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); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // build and compile our shader zprogram // ------------------------------------ Shader ourShader("5.2.transform.vs", "5.2.transform.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ float vertices[] = { // positions // texture coords 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, // top right 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, // bottom right -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, // bottom left -0.5f, 0.5f, 0.0f, 0.0f, 1.0f // top left }; unsigned int indices[] = { 0, 1, 3, // first triangle 1, 2, 3 // second triangle }; unsigned int VBO, VAO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // texture coord attribute glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // load and create a texture // ------------------------- unsigned int texture1, texture2; // texture 1 // --------- glGenTextures(1, &texture1); glBindTexture(GL_TEXTURE_2D, texture1); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps int width, height, nrChannels; stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis. unsigned char *data = stbi_load(FileSystem::getPath("resources/textures/container.jpg").c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); // texture 2 // --------- glGenTextures(1, &texture2); glBindTexture(GL_TEXTURE_2D, texture2); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps data = stbi_load(FileSystem::getPath("resources/textures/awesomeface.png").c_str(), &width, &height, &nrChannels, 0); if (data) { // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); // tell opengl for each sampler to which texture unit it belongs to (only has to be done once) // ------------------------------------------------------------------------------------------- ourShader.use(); ourShader.setInt("texture1", 0); ourShader.setInt("texture2", 1); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // bind textures on corresponding texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); glm::mat4 transform; // first container // --------------- transform = glm::translate(transform, glm::vec3(0.5f, -0.5f, 0.0f)); transform = glm::rotate(transform, (float)glfwGetTime(), glm::vec3(0.0f, 0.0f, 1.0f)); // get their uniform location and set matrix (using glm::value_ptr) unsigned int transformLoc = glGetUniformLocation(ourShader.ID, "transform"); glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(transform)); // with the uniform matrix set, draw the first container glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // second transformation // --------------------- transform = glm::mat4(); // reset it to an identity matrix transform = glm::translate(transform, glm::vec3(-0.5f, 0.5f, 0.0f)); float scaleAmount = sin(glfwGetTime()); transform = glm::scale(transform, glm::vec3(scaleAmount, scaleAmount, scaleAmount)); glUniformMatrix4fv(transformLoc, 1, GL_FALSE, &transform[0][0]); // this time take the matrix value array's first element as its memory pointer value // now with the uniform matrix being replaced with new transformations, draw it again. glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // 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, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; }
int main(int /* argc */, char ** /* argv */) { // // Setup GLFW, glew and some initial GL state // static const char windowTitle[] = "CPU Subdivision Example"; if (not glfwInit()) { printf("Failed to initialize GLFW\n"); return 1; } #define CORE_PROFILE #ifdef CORE_PROFILE setGLCoreProfile(); #endif #if GLFW_VERSION_MAJOR>=3 if (not (g_window=glfwCreateWindow(g_width, g_height, windowTitle, NULL, NULL))) { printf("Failed to open window.\n"); glfwTerminate(); return 1; } glfwMakeContextCurrent(g_window); // accommodate high DPI displays (e.g. mac retina displays) glfwGetFramebufferSize(g_window, &g_width, &g_height); glfwSetFramebufferSizeCallback(g_window, reshape); glfwSetWindowCloseCallback(g_window, windowClose); #else if (glfwOpenWindow(g_width, g_height, 8, 8, 8, 8, 24, 8, GLFW_WINDOW) == GL_FALSE) { printf("Failed to open window.\n"); glfwTerminate(); return 1; } glfwSetWindowTitle(windowTitle); glfwSetWindowSizeCallback(reshape); glfwSetWindowCloseCallback(windowClose); #endif #if defined(OSD_USES_GLEW) #ifdef CORE_PROFILE // this is the only way to initialize glew correctly under core profile context. glewExperimental = true; #endif if (GLenum r = glewInit() != GLEW_OK) { printf("Failed to initialize glew. Error = %s\n", glewGetErrorString(r)); exit(1); } #ifdef CORE_PROFILE // clear GL errors which was generated during glewInit() glGetError(); #endif #endif initOsd(); // // Start the main drawing loop // while (g_running) { idle(); display(); #if GLFW_VERSION_MAJOR>=3 glfwPollEvents(); glfwSwapBuffers(g_window); #else glfwSwapBuffers(); #endif glFinish(); } }
// ------------------------------------------------------------------- main --- int main( int argc, char **argv ) { GLFWwindow* window; glfwSetErrorCallback( error_callback ); if (!glfwInit( )) { exit( EXIT_FAILURE ); } glfwWindowHint( GLFW_VISIBLE, GL_TRUE ); glfwWindowHint( GLFW_RESIZABLE, GL_FALSE ); window = glfwCreateWindow( 1, 1, "Distance fields demo", NULL, NULL ); if (!window) { glfwTerminate( ); exit( EXIT_FAILURE ); } glfwMakeContextCurrent( window ); glfwSwapInterval( 1 ); glfwSetFramebufferSizeCallback( window, reshape ); glfwSetWindowRefreshCallback( window, display ); glfwSetKeyCallback( window, keyboard ); #ifndef __APPLE__ glewExperimental = GL_TRUE; GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf( stderr, "Error: %s\n", glewGetErrorString(err) ); exit( EXIT_FAILURE ); } fprintf( stderr, "Using GLEW %s\n", glewGetString(GLEW_VERSION) ); #endif init(); glfwSetWindowSize( window, 512, 512 ); glfwShowWindow( window ); glfwSetTime(0.0); while(!glfwWindowShouldClose( window )) { display( window ); angle += 30 * glfwGetTime(); glfwSetTime(0.0); glfwPollEvents( ); } glfwDestroyWindow( window ); glfwTerminate( ); return EXIT_SUCCESS; }
// ------------------------------------------------------------------- main --- int main( int argc, char **argv ) { GLFWwindow* window; char* screenshot_path = NULL; if (argc > 1) { if (argc == 3 && 0 == strcmp( "--screenshot", argv[1] )) screenshot_path = argv[2]; else { fprintf( stderr, "Unknown or incomplete parameters given\n" ); exit( EXIT_FAILURE ); } } glfwSetErrorCallback( error_callback ); if (!glfwInit( )) { exit( EXIT_FAILURE ); } glfwWindowHint( GLFW_VISIBLE, GL_FALSE ); glfwWindowHint( GLFW_RESIZABLE, GL_FALSE ); window = glfwCreateWindow( 600,400, argv[0], NULL, NULL ); if (!window) { glfwTerminate( ); exit( EXIT_FAILURE ); } glfwMakeContextCurrent( window ); glfwSwapInterval( 1 ); glfwSetFramebufferSizeCallback( window, reshape ); glfwSetWindowRefreshCallback( window, display ); glfwSetKeyCallback( window, keyboard ); glfwSetCharCallback( window, char_input ); #ifndef __APPLE__ glewExperimental = GL_TRUE; GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf( stderr, "Error: %s\n", glewGetErrorString(err) ); exit( EXIT_FAILURE ); } fprintf( stderr, "Using GLEW %s\n", glewGetString(GLEW_VERSION) ); #endif init(); glfwShowWindow( window ); reshape( window, 600,400 ); while (!glfwWindowShouldClose( window )) { display( window ); glfwPollEvents( ); if (screenshot_path) { screenshot( window, screenshot_path ); glfwSetWindowShouldClose( window, 1 ); } } console_delete( console ); glfwDestroyWindow( window ); glfwTerminate( ); return EXIT_SUCCESS; }
bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable) { setViewName(viewName); _frameZoomFactor = frameZoomFactor; glfwWindowHint(GLFW_RESIZABLE,resizable?GL_TRUE:GL_FALSE); glfwWindowHint(GLFW_RED_BITS,_glContextAttrs.redBits); glfwWindowHint(GLFW_GREEN_BITS,_glContextAttrs.greenBits); glfwWindowHint(GLFW_BLUE_BITS,_glContextAttrs.blueBits); glfwWindowHint(GLFW_ALPHA_BITS,_glContextAttrs.alphaBits); glfwWindowHint(GLFW_DEPTH_BITS,_glContextAttrs.depthBits); glfwWindowHint(GLFW_STENCIL_BITS,_glContextAttrs.stencilBits); int needWidth = rect.size.width * _frameZoomFactor; int neeHeight = rect.size.height * _frameZoomFactor; _mainWindow = glfwCreateWindow(needWidth, neeHeight, _viewName.c_str(), _monitor, nullptr); if (_mainWindow == nullptr) { std::string message = "Can't create window"; if (!_glfwError.empty()) { message.append("\nMore info: \n"); message.append(_glfwError); } MessageBox(message.c_str(), "Error launch application"); return false; } /* * Note that the created window and context may differ from what you requested, * as not all parameters and hints are * [hard constraints](@ref window_hints_hard). This includes the size of the * window, especially for full screen windows. To retrieve the actual * attributes of the created window and context, use queries like @ref * glfwGetWindowAttrib and @ref glfwGetWindowSize. * * see declaration glfwCreateWindow */ int realW = 0, realH = 0; glfwGetWindowSize(_mainWindow, &realW, &realH); if (realW != needWidth) { rect.size.width = realW / _frameZoomFactor; } if (realH != neeHeight) { rect.size.height = realH / _frameZoomFactor; } glfwMakeContextCurrent(_mainWindow); glfwSetMouseButtonCallback(_mainWindow, GLFWEventHandler::onGLFWMouseCallBack); glfwSetCursorPosCallback(_mainWindow, GLFWEventHandler::onGLFWMouseMoveCallBack); glfwSetScrollCallback(_mainWindow, GLFWEventHandler::onGLFWMouseScrollCallback); glfwSetCharCallback(_mainWindow, GLFWEventHandler::onGLFWCharCallback); glfwSetKeyCallback(_mainWindow, GLFWEventHandler::onGLFWKeyCallback); glfwSetWindowPosCallback(_mainWindow, GLFWEventHandler::onGLFWWindowPosCallback); glfwSetFramebufferSizeCallback(_mainWindow, GLFWEventHandler::onGLFWframebuffersize); glfwSetWindowSizeCallback(_mainWindow, GLFWEventHandler::onGLFWWindowSizeFunCallback); glfwSetWindowIconifyCallback(_mainWindow, GLFWEventHandler::onGLFWWindowIconifyCallback); setFrameSize(rect.size.width, rect.size.height); // check OpenGL version at first const GLubyte* glVersion = glGetString(GL_VERSION); if ( utils::atof((const char*)glVersion) < 1.5 ) { char strComplain[256] = {0}; sprintf(strComplain, "OpenGL 1.5 or higher is required (your version is %s). Please upgrade the driver of your video card.", glVersion); MessageBox(strComplain, "OpenGL version too old"); return false; } initGlew(); // Enable point size by default. glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); return true; }
int main() { GLFWwindow *window; char *userptr = "userptr"; glfwSetErrorCallback(errorcb); assert(glfwInit() == GL_TRUE); assert(!strcmp(glfwGetVersionString(), "3.0.0 JS WebGL Emscripten")); { int major, minor, rev; glfwGetVersion(&major, &minor, &rev); assert(major == 3); assert(minor == 0); assert(rev == 0); } { int count, x, y, w, h; GLFWmonitor **monitors = glfwGetMonitors(&count); assert(count == 1); for (int i = 0; i < count; ++i) { assert(monitors[i] != NULL); } assert(glfwGetPrimaryMonitor() != NULL); glfwGetMonitorPos(monitors[0], &x, &y); glfwGetMonitorPhysicalSize(monitors[0], &w, &h); assert(glfwGetMonitorName(monitors[0]) != NULL); glfwSetMonitorCallback(monitcb); // XXX: not implemented // assert(glfwGetVideoModes(monitors[0], &count) != NULL); // assert(glfwGetVideoMode(monitors[0]) != NULL); // glfwSetGamma(monitors[0], 1.0f); // assert(glfwGetGammaRamp(monitors[0]) != NULL); // glfwSetGammaRamp(monitors[0], ramp); } { int x, y, w, h; glfwDefaultWindowHints(); glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API); window = glfwCreateWindow(640, 480, "glfw3.c", NULL, NULL); assert(window != NULL); glfwSetWindowPosCallback(window, wposicb); glfwSetWindowSizeCallback(window, wsizecb); glfwSetWindowCloseCallback(window, wcloscb); glfwSetWindowRefreshCallback(window, wrfrscb); glfwSetWindowFocusCallback(window, wfocucb); glfwSetWindowIconifyCallback(window, wiconcb); glfwSetFramebufferSizeCallback(window, wfsizcb); assert(glfwWindowShouldClose(window) == 0); glfwSetWindowShouldClose(window, 1); assert(glfwWindowShouldClose(window) == 1); glfwSetWindowTitle(window, "test"); glfwSetWindowTitle(window, "glfw3.c"); // XXX: not implemented // glfwSetWindowPos(window, 1, 1); glfwGetWindowPos(window, &x, &y); // stub glfwGetWindowSize(window, &w, &h); assert(w == 640 && h == 480); glfwSetWindowSize(window, 1, 1); glfwGetWindowSize(window, &w, &h); assert(w == 1 && h == 1); glfwSetWindowSize(window, 640, 480); glfwGetFramebufferSize(window, &w, &h); // XXX: not implemented // glfwIconifyWindow(window); // glfwRestoreWindow(window); // glfwShowWindow(window); // glfwHideWindow(window); assert(glfwGetWindowMonitor(window) == NULL); glfwDestroyWindow(window); window = glfwCreateWindow(640, 480, "glfw3.c", glfwGetPrimaryMonitor(), NULL); assert(window != NULL); assert(glfwGetWindowMonitor(window) == glfwGetPrimaryMonitor()); glfwDestroyWindow(window); window = glfwCreateWindow(640, 480, "glfw3.c", NULL, NULL); assert(window != NULL); assert(glfwGetWindowAttrib(window, GLFW_CLIENT_API) == GLFW_OPENGL_ES_API); assert(glfwGetWindowUserPointer(window) == NULL); glfwSetWindowUserPointer(window, userptr); assert(glfwGetWindowUserPointer(window) == userptr); } { double x, y; glfwSetKeyCallback(window, wkeypcb); glfwSetCharCallback(window, wcharcb); glfwSetMouseButtonCallback(window, wmbutcb); glfwSetCursorPosCallback(window, wcurpcb); glfwSetCursorEnterCallback(window, wcurecb); glfwSetScrollCallback(window, wscrocb); // XXX: stub, events come immediatly // glfwPollEvents(); // glfwWaitEvents(); assert(glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_NORMAL); // XXX: not implemented // glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); glfwGetKey(window, GLFW_KEY_A); glfwGetMouseButton(window, 0); glfwGetCursorPos(window, &x, &y); // XXX: not implemented // glfwSetCursorPos(window, 0, 0); } { // XXX: not implemented // glfwJoystickPresent(joy); // glfwGetJoystickAxes(joy, &count); // glfwGetJoystickButtons(joy, &count); // glfwGetJoystickName(joy); } { // XXX: not implemented // glfwSetClipboardString(window, "string"); // glfwGetClipboardString(window); } { glfwGetTime(); glfwSetTime(0); } { glfwMakeContextCurrent(window); // stub assert(glfwGetCurrentContext() == window); glfwSwapBuffers(window); // stub glfwSwapInterval(0); // stub } { assert(glfwExtensionSupported("nonexistant") == 0); assert(glfwGetProcAddress("nonexistant") == NULL); } glfwTerminate(); #ifdef REPORT_RESULT int result = 1; REPORT_RESULT(); #endif 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); // build and compile shaders // ------------------------- Shader shader("11.anti_aliasing.vs", "11.anti_aliasing.fs"); Shader screenShader("11.aa_post.vs", "11.aa_post.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ float cubeVertices[] = { // positions -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 }; float 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 unsigned int 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, 3 * sizeof(float), (void*)0); // setup screen VAO unsigned int 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(float), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float))); // configure MSAA framebuffer // -------------------------- unsigned int framebuffer; glGenFramebuffers(1, &framebuffer); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); // create a multisampled color attachment texture unsigned int textureColorBufferMultiSampled; glGenTextures(1, &textureColorBufferMultiSampled); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, textureColorBufferMultiSampled); glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, 4, GL_RGB, SCR_WIDTH, SCR_HEIGHT, GL_TRUE); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, textureColorBufferMultiSampled, 0); // create a (also multisampled) renderbuffer object for depth and stencil attachments unsigned int rbo; glGenRenderbuffers(1, &rbo); glBindRenderbuffer(GL_RENDERBUFFER, rbo); glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_DEPTH24_STENCIL8, SCR_WIDTH, SCR_HEIGHT); glBindRenderbuffer(GL_RENDERBUFFER, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << endl; glBindFramebuffer(GL_FRAMEBUFFER, 0); // configure second post-processing framebuffer unsigned int intermediateFBO; glGenFramebuffers(1, &intermediateFBO); glBindFramebuffer(GL_FRAMEBUFFER, intermediateFBO); // create a color attachment texture unsigned int screenTexture; glGenTextures(1, &screenTexture); glBindTexture(GL_TEXTURE_2D, screenTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, SCR_WIDTH, SCR_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, screenTexture, 0); // we only need a color buffer if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) cout << "ERROR::FRAMEBUFFER:: Intermediate framebuffer is not complete!" << endl; glBindFramebuffer(GL_FRAMEBUFFER, 0); // shader configuration // -------------------- shader.use(); screenShader.setInt("screenTexture", 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. draw scene as normal in multisampled buffers glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); // set transformation matrices shader.use(); glm::mat4 projection = glm::perspective(camera.Zoom, (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 1000.0f); shader.setMat4("projection", projection); shader.setMat4("view", camera.GetViewMatrix()); shader.setMat4("model", glm::mat4()); glBindVertexArray(cubeVAO); glDrawArrays(GL_TRIANGLES, 0, 36); // 2. now blit multisampled buffer(s) to normal colorbuffer of intermediate FBO. Image is stored in screenTexture glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, intermediateFBO); glBlitFramebuffer(0, 0, SCR_WIDTH, SCR_HEIGHT, 0, 0, SCR_WIDTH, SCR_HEIGHT, GL_COLOR_BUFFER_BIT, GL_NEAREST); // 3. now render quad with scene's visuals as its texture image glBindFramebuffer(GL_FRAMEBUFFER, 0); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glDisable(GL_DEPTH_TEST); // draw Screen quad screenShader.use(); glBindVertexArray(quadVAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, screenTexture); // use the now resolved color attachment as the quad's texture glDrawArrays(GL_TRIANGLES, 0, 6); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; }
GLFWView::GLFWView(bool fullscreen_, bool benchmark_) : fullscreen(fullscreen_), benchmark(benchmark_) { glfwSetErrorCallback(glfwError); std::srand(static_cast<unsigned int>(std::time(nullptr))); if (!glfwInit()) { mbgl::Log::Error(mbgl::Event::OpenGL, "failed to initialize glfw"); exit(1); } GLFWmonitor *monitor = nullptr; if (fullscreen) { monitor = glfwGetPrimaryMonitor(); auto videoMode = glfwGetVideoMode(monitor); width = videoMode->width; height = videoMode->height; } glfwWindowHint(GLFW_COCOA_GRAPHICS_SWITCHING, GL_TRUE); #ifdef DEBUG glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif #ifdef GL_ES_VERSION_2_0 glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); #endif glfwWindowHint(GLFW_RED_BITS, 8); glfwWindowHint(GLFW_GREEN_BITS, 8); glfwWindowHint(GLFW_BLUE_BITS, 8); glfwWindowHint(GLFW_ALPHA_BITS, 8); glfwWindowHint(GLFW_STENCIL_BITS, 8); glfwWindowHint(GLFW_DEPTH_BITS, 16); window = glfwCreateWindow(width, height, "Mapbox GL", monitor, nullptr); if (!window) { glfwTerminate(); mbgl::Log::Error(mbgl::Event::OpenGL, "failed to initialize window"); exit(1); } glfwSetWindowUserPointer(window, this); glfwMakeContextCurrent(window); if (benchmark) { // Disables vsync on platforms that support it. glfwSwapInterval(0); } else { glfwSwapInterval(1); } glfwSetCursorPosCallback(window, onMouseMove); glfwSetMouseButtonCallback(window, onMouseClick); glfwSetWindowSizeCallback(window, onWindowResize); glfwSetFramebufferSizeCallback(window, onFramebufferResize); glfwSetScrollCallback(window, onScroll); glfwSetKeyCallback(window, onKey); glfwGetWindowSize(window, &width, &height); glfwGetFramebufferSize(window, &fbWidth, &fbHeight); pixelRatio = static_cast<float>(fbWidth) / width; glfwMakeContextCurrent(nullptr); printf("\n"); printf("================================================================================\n"); printf("\n"); printf("- Press `S` to cycle through bundled styles\n"); printf("- Press `X` to reset the transform\n"); printf("- Press `N` to reset north\n"); printf("- Press `R` to enable the route demo\n"); printf("- Press `E` to insert an example building extrusion layer\n"); printf("- Press `Z` to cycle through north orientations\n"); printf("- Prezz `X` to cycle through the viewport modes\n"); printf("- Press `A` to cycle through Mapbox offices in the world + dateline monument\n"); printf("- Press `B` to cycle through the color, stencil, and depth buffer\n"); printf("\n"); printf("- Press `1` through `6` to add increasing numbers of point annotations for testing\n"); printf("- Press `7` through `0` to add increasing numbers of shape annotations for testing\n"); printf("\n"); printf("- Press `Q` to remove annotations\n"); printf("- Press `K` to add a random custom runtime imagery annotation\n"); printf("- Press `L` to add a random line annotation\n"); printf("- Press `W` to pop the last-added annotation off\n"); printf("\n"); printf("- Press `P` to pause tile requests\n"); printf("- `Control` + mouse drag to rotate\n"); printf("- `Shift` + mouse drag to tilt\n"); printf("\n"); printf("- Press `Tab` to cycle through the map debug options\n"); printf("- Press `Esc` to quit\n"); printf("\n"); printf("================================================================================\n"); printf("\n"); }
bool Window:: open(int width, int height, int sample_count, bool windowed, int gl_major_version, int gl_minor_version) { const int MAX_MAJOR_VERSION = 4; if (gl_major_version > MAX_MAJOR_VERSION) { return false; } const int MAX_MINOR_VERSION[] = { 5, 1, 3, 3 }; if (gl_minor_version > MAX_MINOR_VERSION[gl_major_version-1]) { return false; } int tgl_extension_index = 0; for (int i=0; i<(gl_major_version-1); ++i) { tgl_extension_index += MAX_MINOR_VERSION[i] + 1; } tgl_extension_index += gl_minor_version; TGLEXTENSION tgl_extension = (TGLEXTENSION)tgl_extension_index; if (glfwInit() != GL_TRUE) { return false; } glfwSetErrorCallback(onError); glfwWindowHint(GLFW_RED_BITS, 8); glfwWindowHint(GLFW_GREEN_BITS, 8); glfwWindowHint(GLFW_BLUE_BITS, 8); glfwWindowHint(GLFW_ALPHA_BITS, 0); glfwWindowHint(GLFW_DEPTH_BITS, 24); glfwWindowHint(GLFW_STENCIL_BITS, 8); glfwWindowHint(GLFW_SAMPLES, sample_count); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, gl_major_version); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, gl_minor_version); if (gl_major_version >= 3 && gl_minor_version >= 3) { glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); } #ifdef _DEBUG glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif GLFWmonitor* monitor = windowed ? NULL : glfwGetPrimaryMonitor(); glfw_handle_ = glfwCreateWindow(width, height, "TyGrA", monitor, NULL); if (glfw_handle_ == nullptr) { glfwTerminate(); return false; } glfwMakeContextCurrent(glfw_handle_); glfwSwapInterval(-1); glfwShowWindow(glfw_handle_); tglInit(); if (tglIsAvailable(tgl_extension) != GL_TRUE) { glfwTerminate(); return false; } if (view_ != nullptr) { view_->windowViewWillStart(shared_from_this()); } glfwSetFramebufferSizeCallback(glfw_handle_, onResize); glfwSetWindowCloseCallback(glfw_handle_, onClose); glfwSetCursorPosCallback(glfw_handle_, onMouseMove); glfwSetScrollCallback(glfw_handle_, onMouseWheel); glfwSetMouseButtonCallback(glfw_handle_, onMouseButton); glfwSetKeyCallback(glfw_handle_, onKeyEvent); fakeResizeCallback(); if (controller_ != nullptr) { controller_->windowControlWillStart(shared_from_this()); } return true; }
int main(int argc, char** argv) { int ch, i, window_count; GLboolean auto_iconify = GL_TRUE, fullscreen = GL_FALSE, all_monitors = GL_FALSE; GLFWwindow** windows; while ((ch = getopt(argc, argv, "afhn")) != -1) { switch (ch) { case 'a': all_monitors = GL_TRUE; break; case 'h': usage(); exit(EXIT_SUCCESS); case 'f': fullscreen = GL_TRUE; break; case 'n': auto_iconify = GL_FALSE; break; default: usage(); exit(EXIT_FAILURE); } } glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); glfwWindowHint(GLFW_AUTO_ICONIFY, auto_iconify); if (fullscreen && all_monitors) { int monitor_count; GLFWmonitor** monitors = glfwGetMonitors(&monitor_count); window_count = monitor_count; windows = calloc(window_count, sizeof(GLFWwindow*)); for (i = 0; i < monitor_count; i++) { windows[i] = create_window(monitors[i]); if (!windows[i]) break; } } else { GLFWmonitor* monitor = NULL; if (fullscreen) monitor = glfwGetPrimaryMonitor(); window_count = 1; windows = calloc(window_count, sizeof(GLFWwindow*)); windows[0] = create_window(monitor); } for (i = 0; i < window_count; i++) { glfwSetKeyCallback(windows[i], key_callback); glfwSetFramebufferSizeCallback(windows[i], framebuffer_size_callback); glfwSetWindowSizeCallback(windows[i], window_size_callback); glfwSetWindowFocusCallback(windows[i], window_focus_callback); glfwSetWindowIconifyCallback(windows[i], window_iconify_callback); glfwSetWindowRefreshCallback(windows[i], window_refresh_callback); window_refresh_callback(windows[i]); printf("Window is %s and %s\n", glfwGetWindowAttrib(windows[i], GLFW_ICONIFIED) ? "iconified" : "restored", glfwGetWindowAttrib(windows[i], GLFW_FOCUSED) ? "focused" : "defocused"); } for (;;) { glfwPollEvents(); for (i = 0; i < window_count; i++) { if (glfwWindowShouldClose(windows[i])) break; } if (i < window_count) break; // Workaround for an issue with msvcrt and mintty fflush(stdout); } glfwTerminate(); exit(EXIT_SUCCESS); }
int main(void) { GLFWwindow* window; // Initialize the library if (!glfwInit()) return -1; // Activate supersampling glfwWindowHint(GLFW_SAMPLES, 8); // Ensure that we get at least a 3.2 context glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); // On apple we have to load a core profile with forward compatibility #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // Create a windowed mode window and its OpenGL context window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } // Make the window's context current glfwMakeContextCurrent(window); #ifndef __APPLE__ glewExperimental = true; GLenum err = glewInit(); if(GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); } glGetError(); // pull and savely ignonre unhandled errors like GL_INVALID_ENUM fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); #endif int major, minor, rev; major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev); printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION)); printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION)); // Initialize the VAO // A Vertex Array Object (or VAO) is an object that describes how the vertex // attributes are stored in a Vertex Buffer Object (or VBO). This means that // the VAO is not the actual object storing the vertex data, // but the descriptor of the vertex data. VertexArrayObject VAO; VAO.init(); VAO.bind(); // Initialize the VBO with the vertices data // A VBO is a data container that lives in the GPU memory VBO.init(); V.resize(2,6); V << 0, 0.5, -0.5, 0.1, 0.6, -0.4, 0.5, -0.5, -0.5, 0.6, -0.4, -0.4; VBO.update(V); // Initialize the OpenGL Program // A program controls the OpenGL pipeline and it must contains // at least a vertex shader and a fragment shader to be valid Program program; const GLchar* vertex_shader = "#version 150 core\n" "in vec2 position;" "void main()" "{" " gl_Position = vec4(position, 0.0, 1.0);" "}"; const GLchar* fragment_shader = "#version 150 core\n" "out vec4 outColor;" "uniform vec4 triangleColor;" "void main()" "{" " outColor = vec4(triangleColor);" "}"; // Compile the two shaders and upload the binary to the GPU // Note that we have to explicitly specify that the output "slot" called outColor // is the one that we want in the fragment buffer (and thus on screen) program.init(vertex_shader,fragment_shader,"outColor"); program.bind(); // The vertex shader wants the position of the vertices as an input. // The following line connects the VBO we defined above with the position "slot" // in the vertex shader program.bindVertexAttribArray("position",VBO); // Register the keyboard callback glfwSetKeyCallback(window, key_callback); // Register the mouse callback glfwSetMouseButtonCallback(window, mouse_button_callback); // Update viewport glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // Loop until the user closes the window while (!glfwWindowShouldClose(window)) { // Bind your VAO (not necessary if you have only one) VAO.bind(); // Bind your program program.bind(); // Clear the framebuffer glClearColor(0.5f, 0.5f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Enable blending test glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Draw a triangle (red) glUniform4f(program.uniform("triangleColor"), 1.0f, 0.0f, 0.0f, 1.0f); glDrawArrays(GL_TRIANGLES, 0, 3); // Draw a triangle (green) glUniform4f(program.uniform("triangleColor"), 0.0f, 1.0f, 0.0f, 0.5f); glDrawArrays(GL_TRIANGLES, 3, 3); // Swap front and back buffers glfwSwapBuffers(window); // Poll for and process events glfwPollEvents(); } // Deallocate opengl memory program.free(); VAO.free(); VBO.free(); // Deallocate glfw internals glfwTerminate(); return 0; }
int main(int argc, char **argv) #endif { const GLFWvidmode *video_mode; int c; while ((c = fz_getopt(argc, argv, "p:r:W:H:S:U:")) != -1) { switch (c) { default: usage(argv[0]); break; case 'p': password = fz_optarg; break; case 'r': currentzoom = fz_atof(fz_optarg); break; case 'W': layout_w = fz_atof(fz_optarg); break; case 'H': layout_h = fz_atof(fz_optarg); break; case 'S': layout_em = fz_atof(fz_optarg); break; case 'U': layout_css = fz_optarg; break; } } if (fz_optind < argc) { fz_strlcpy(filename, argv[fz_optind], sizeof filename); } else { #ifdef _WIN32 win_install(); if (!win_open_file(filename, sizeof filename)) exit(0); #else usage(argv[0]); #endif } title = strrchr(filename, '/'); if (!title) title = strrchr(filename, '\\'); if (title) ++title; else title = filename; memset(&ui, 0, sizeof ui); search_input.p = search_input.text; search_input.q = search_input.p; search_input.end = search_input.p; glfwSetErrorCallback(on_error); if (!glfwInit()) { fprintf(stderr, "cannot initialize glfw\n"); exit(1); } video_mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); screen_w = video_mode->width; screen_h = video_mode->height; window = glfwCreateWindow(DEFAULT_WINDOW_W, DEFAULT_WINDOW_H, filename, NULL, NULL); if (!window) { fprintf(stderr, "cannot create glfw window\n"); exit(1); } glfwMakeContextCurrent(window); ctx = fz_new_context(NULL, NULL, 0); fz_register_document_handlers(ctx); if (layout_css) { fz_buffer *buf = fz_read_file(ctx, layout_css); fz_set_user_css(ctx, fz_string_from_buffer(ctx, buf)); fz_drop_buffer(ctx, buf); } has_ARB_texture_non_power_of_two = glfwExtensionSupported("GL_ARB_texture_non_power_of_two"); if (!has_ARB_texture_non_power_of_two) fz_warn(ctx, "OpenGL implementation does not support non-power of two texture sizes"); glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size); ui.fontsize = DEFAULT_UI_FONTSIZE; ui.baseline = DEFAULT_UI_BASELINE; ui.lineheight = DEFAULT_UI_LINEHEIGHT; ui_init_fonts(ctx, ui.fontsize); reload(); shrinkwrap(); glfwSetFramebufferSizeCallback(window, on_reshape); glfwSetCursorPosCallback(window, on_mouse_motion); glfwSetMouseButtonCallback(window, on_mouse_button); glfwSetScrollCallback(window, on_scroll); glfwSetCharModsCallback(window, on_char); glfwSetKeyCallback(window, on_key); glfwSetWindowRefreshCallback(window, on_display); glfwGetFramebufferSize(window, &window_w, &window_h); ui_needs_update = 1; while (!glfwWindowShouldClose(window)) { glfwWaitEvents(); if (ui_needs_update) run_main_loop(); } ui_finish_fonts(ctx); fz_drop_link(ctx, links); fz_drop_page(ctx, page); fz_drop_outline(ctx, outline); fz_drop_document(ctx, doc); fz_drop_context(ctx); 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 ourShader("7.4.camera.vs", "7.4.camera.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ float vertices[] = { -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 }; // world space positions of our cubes 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) }; unsigned int VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // texture coord attribute glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // load and create a texture // ------------------------- unsigned int texture1, texture2; // texture 1 // --------- glGenTextures(1, &texture1); glBindTexture(GL_TEXTURE_2D, texture1); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps int width, height, nrChannels; stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis. unsigned char *data = stbi_load(FileSystem::getPath("resources/textures/container.jpg").c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); // texture 2 // --------- glGenTextures(1, &texture2); glBindTexture(GL_TEXTURE_2D, texture2); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps data = stbi_load(FileSystem::getPath("resources/textures/awesomeface.png").c_str(), &width, &height, &nrChannels, 0); if (data) { // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); // tell opengl for each sampler to which texture unit it belongs to (only has to be done once) // ------------------------------------------------------------------------------------------- ourShader.use(); ourShader.setInt("texture1", 0); ourShader.setInt("texture2", 1); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // per-frame time logic // -------------------- float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // bind textures on corresponding texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); // activate shader ourShader.use(); // pass projection matrix to shader (note that in this case it could change every frame) glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); // camera/view transformation glm::mat4 view = camera.GetViewMatrix(); ourShader.setMat4("view", view); // render boxes glBindVertexArray(VAO); for (unsigned int i = 0; i < 10; i++) { // calculate the model matrix for each object and pass it to shader before drawing glm::mat4 model = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first model = glm::translate(model, cubePositions[i]); float angle = 20.0f * i; model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model); 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, &VAO); glDeleteBuffers(1, &VBO); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; }
WindowGL33::FramebufferResizeEventType::DelegatePtr WindowGL33::addFramebufferResizeCallback( FramebufferResizeCallbackType const& callback) { glfwSetFramebufferSizeCallback(m_pWndHandle, WindowGL33::framebufferResizeCallback); return m_framebufferResizeCallbacks.addListener(callback); }
int main(int argc, char** argv) { //! The pointer to the GLFW window GLFWwindow* window; //! Setting up the GLFW Error callback glfwSetErrorCallback(csX75::error_callback); //! Initialize GLFW if (!glfwInit()) return -1; //We want OpenGL 4.0 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //This is for MacOSX - can be omitted otherwise //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); //We don't want the old OpenGL //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //! Create a windowed mode window and its OpenGL context window = glfwCreateWindow(720, 720, "Assignment3:Star Wars", NULL, NULL); if (!window) { glfwTerminate(); return -1; } //! Make the window's context current glfwMakeContextCurrent(window); //Initialize GLEW //Turn this on to get Shader based OpenGL glewExperimental = GL_TRUE; GLenum err = glewInit(); if (GLEW_OK != err) { //Problem: glewInit failed, something is seriously wrong. std::cerr<<"GLEW Init Failed : %s"<<std::endl; } //Keyboard Callback glfwSetKeyCallback(window, csX75::key_callback); //Framebuffer resize callback glfwSetFramebufferSizeCallback(window, csX75::framebuffer_size_callback); // Ensure we can capture the escape key being pressed below //glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); glfwSetInputMode(window, GLFW_STICKY_MOUSE_BUTTONS, GL_TRUE); //glfwSetCursorPosCallback(window, csX75::cursor_callback); //Initialize GL state csX75::initGL(); initBuffersGL(); // Loop until the user closes the window while (glfwWindowShouldClose(window) == 0) { // Render here renderGL(); // Swap front and back buffers glfwSwapBuffers(window); // Poll for and process events glfwPollEvents(); } glfwTerminate(); return 0; }
int main(int argc, char *argv[]) { glfwSetErrorCallback(err); if (!glfwInit()) { exit(1); } /* create the window and its associated OpenGL context */ wd = glfwCreateWindow(width, height, "Whoot 2", NULL, NULL); if (!wd) { glfwTerminate(); exit(1); } /* make the window's context the current context */ glfwMakeContextCurrent(wd); GLenum err = glewInit(); if (GLEW_OK != err) { std::cout << "glewInit failed!" << std::endl; std::cout << glewGetErrorString(err) << std::endl; } glfwGetFramebufferSize(wd, &fbwidth, &fbheight); /* shape view port */ fbreshape(wd, fbwidth, fbheight); /* --- register callbacks with GLFW --- */ /* register function to handle window resizes */ glfwSetFramebufferSizeCallback(wd, fbreshape); glfwSetWindowSizeCallback(wd, reshape); /* register function to handle window close */ glfwSetWindowCloseCallback(wd, quit); /* register function to handle keyboard input */ glfwSetKeyCallback(wd, kbd); // general keyboard input glfwSetCharCallback(wd, charhd); // simpler specific character handling initgl(); FullScreenPass myFSP = FullScreenPass(); ParticlePass myPP = ParticlePass(10000); typedef std::chrono::high_resolution_clock Clock; typedef std::chrono::milliseconds milliseconds; Clock::time_point currentTime, newTime; milliseconds frameTime; do { currentTime = Clock::now(); /* color buffer must be cleared each time */ glClear(GL_COLOR_BUFFER_BIT); myFSP.draw(); myPP.draw(); /* GLFW is ALWAYS double buffered; will call glFlush() */ glfwSwapBuffers(wd); glfwPollEvents(); newTime = Clock::now(); frameTime = std::chrono::duration_cast<milliseconds>(newTime - currentTime); if(frameTime.count() < 16) { std::this_thread::sleep_for(milliseconds(16 - frameTime.count())); } } while (!glfwWindowShouldClose(wd)); exit(0); }
int main(int argc, char** argv) { int width, height, ch; GLFWmonitor* monitor = NULL; GLFWwindow* window; glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); while ((ch = getopt(argc, argv, "fh")) != -1) { switch (ch) { case 'h': usage(); exit(EXIT_SUCCESS); case 'f': monitor = glfwGetPrimaryMonitor(); break; default: usage(); exit(EXIT_FAILURE); } } if (monitor) { const GLFWvidmode* mode = glfwGetVideoMode(monitor); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); width = mode->width; height = mode->height; } else { width = 200; height = 200; } window = glfwCreateWindow(width, height, "Gamma Test", monitor, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } set_gamma(window, 1.f); glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); glfwSwapInterval(1); glfwSetKeyCallback(window, key_callback); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glMatrixMode(GL_PROJECTION); glOrtho(-1.f, 1.f, -1.f, 1.f, -1.f, 1.f); glMatrixMode(GL_MODELVIEW); glClearColor(0.5f, 0.5f, 0.5f, 0); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.8f, 0.2f, 0.4f); glRectf(-0.5f, -0.5f, 0.5f, 0.5f); glfwSwapBuffers(window); glfwWaitEvents(); } glfwTerminate(); exit(EXIT_SUCCESS); }
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); glDepthFunc(GL_LESS); glEnable(GL_STENCIL_TEST); glStencilFunc(GL_NOTEQUAL, 1, 0xFF); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); // build and compile shaders // ------------------------- Shader shader("2.stencil_testing.vs", "2.stencil_testing.fs"); Shader shaderSingleColor("2.stencil_testing.vs", "2.stencil_single_color.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ float 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 }; float planeVertices[] = { // positions // texture Coords (note we set these higher than 1 (together with GL_REPEAT as texture wrapping mode). this 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 }; // cube VAO unsigned int 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(float), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); glBindVertexArray(0); // 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, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); glBindVertexArray(0); // load textures // ------------- unsigned int cubeTexture = loadTexture(FileSystem::getPath("resources/textures/marble.jpg").c_str()); unsigned int floorTexture = loadTexture(FileSystem::getPath("resources/textures/metal.png").c_str()); // shader configuration // -------------------- shader.use(); shader.setInt("texture1", 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 | GL_STENCIL_BUFFER_BIT); // don't forget to clear the stencil buffer! // set uniforms shaderSingleColor.use(); glm::mat4 model; glm::mat4 view = camera.GetViewMatrix(); glm::mat4 projection = glm::perspective(camera.Zoom, (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); shaderSingleColor.setMat4("view", view); shaderSingleColor.setMat4("projection", projection); shader.use(); shader.setMat4("view", view); shader.setMat4("projection", projection); // draw floor as normal, but don't write the floor to the stencil buffer, we only care about the containers. We set its mask to 0x00 to not write to the stencil buffer. glStencilMask(0x00); // floor glBindVertexArray(planeVAO); glBindTexture(GL_TEXTURE_2D, floorTexture); shader.setMat4("model", glm::mat4()); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); // 1st. render pass, draw objects as normal, writing to the stencil buffer // -------------------------------------------------------------------- glStencilFunc(GL_ALWAYS, 1, 0xFF); glStencilMask(0xFF); // cubes glBindVertexArray(cubeVAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, cubeTexture); model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f)); shader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); model = glm::mat4(); model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f)); shader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); // 2nd. render pass: now draw slightly scaled versions of the objects, this time disabling stencil writing. // Because the stencil buffer is now filled with several 1s. The parts of the buffer that are 1 are not drawn, thus only drawing // the objects' size differences, making it look like borders. // ----------------------------------------------------------------------------------------------------------------------------- glStencilFunc(GL_NOTEQUAL, 1, 0xFF); glStencilMask(0x00); glDisable(GL_DEPTH_TEST); shaderSingleColor.use(); float scale = 1.1; // cubes glBindVertexArray(cubeVAO); glBindTexture(GL_TEXTURE_2D, cubeTexture); model = glm::mat4(); model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f)); model = glm::scale(model, glm::vec3(scale, scale, scale)); shaderSingleColor.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); model = glm::mat4(); model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f)); model = glm::scale(model, glm::vec3(scale, scale, scale)); shaderSingleColor.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); glStencilMask(0xFF); glEnable(GL_DEPTH_TEST); // 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, &planeVAO); glDeleteBuffers(1, &cubeVBO); glDeleteBuffers(1, &planeVBO); glfwTerminate(); return 0; }
// ------------------------------------------------------------------- main --- int main( int argc, char **argv ) { GLFWwindow* window; char* screenshot_path = NULL; if (argc > 1) { if (argc == 3 && 0 == strcmp( "--screenshot", argv[1] )) screenshot_path = argv[2]; else { fprintf( stderr, "Unknown or incomplete parameters given\n" ); exit( EXIT_FAILURE ); } } glfwSetErrorCallback( error_callback ); if (!glfwInit( )) { exit( EXIT_FAILURE ); } glfwWindowHint( GLFW_VISIBLE, GL_FALSE ); glfwWindowHint( GLFW_RESIZABLE, GL_FALSE ); window = glfwCreateWindow( 1000, 500, argv[0], NULL, NULL ); if (!window) { glfwTerminate( ); exit( EXIT_FAILURE ); } glfwMakeContextCurrent( window ); glfwSwapInterval( 1 ); glfwSetFramebufferSizeCallback( window, reshape ); glfwSetWindowRefreshCallback( window, display ); glfwSetKeyCallback( window, keyboard ); #ifndef __APPLE__ GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf( stderr, "Error: %s\n", glewGetErrorString(err) ); exit( EXIT_FAILURE ); } fprintf( stderr, "Using GLEW %s\n", glewGetString(GLEW_VERSION) ); #endif float start=(float)(glfwGetTime()*1000.0f); init(); ////printf("init waste_time: %f\n", (float)(glfwGetTime()*1000.0f)-start); glfwShowWindow( window ); reshape( window, 1000, 500 ); while(!glfwWindowShouldClose( window )) { start=(float)(glfwGetTime()*1000.0f); display( window ); glfwPollEvents( ); ///printf("waste_time: %f\n", (float)(glfwGetTime()*1000.0f)-start); if (screenshot_path) { screenshot( window, (const char*)screenshot_path ); glfwSetWindowShouldClose( window, 1 ); } } glDeleteProgram( bounds_shader ); glDeleteProgram( text_shader ); glDeleteTextures( 1, &font_manager->atlas->id ); font_manager->atlas->id = 0; text_buffer_delete( buffer ); font_manager_delete( font_manager ); glfwDestroyWindow( window ); glfwTerminate( ); return EXIT_SUCCESS; }
static void test_modes(GLFWmonitor* monitor) { int i, count; GLFWwindow* window; const GLFWvidmode* modes = glfwGetVideoModes(monitor, &count); for (i = 0; i < count; i++) { const GLFWvidmode* mode = modes + i; GLFWvidmode current; glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); printf("Testing mode %u on monitor %s: %s\n", (unsigned int) i, glfwGetMonitorName(monitor), format_mode(mode)); window = glfwCreateWindow(mode->width, mode->height, "Video Mode Test", glfwGetPrimaryMonitor(), NULL); if (!window) { printf("Failed to enter mode %u: %s\n", (unsigned int) i, format_mode(mode)); continue; } glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); glfwSwapInterval(1); glfwSetTime(0.0); while (glfwGetTime() < 5.0) { glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(window); glfwPollEvents(); if (glfwWindowShouldClose(window)) { printf("User terminated program\n"); glfwTerminate(); exit(EXIT_SUCCESS); } } glGetIntegerv(GL_RED_BITS, ¤t.redBits); glGetIntegerv(GL_GREEN_BITS, ¤t.greenBits); glGetIntegerv(GL_BLUE_BITS, ¤t.blueBits); glfwGetWindowSize(window, ¤t.width, ¤t.height); if (current.redBits != mode->redBits || current.greenBits != mode->greenBits || current.blueBits != mode->blueBits) { printf("*** Color bit mismatch: (%i %i %i) instead of (%i %i %i)\n", current.redBits, current.greenBits, current.blueBits, mode->redBits, mode->greenBits, mode->blueBits); } if (current.width != mode->width || current.height != mode->height) { printf("*** Size mismatch: %ix%i instead of %ix%i\n", current.width, current.height, mode->width, mode->height); } printf("Closing window\n"); glfwDestroyWindow(window); window = NULL; glfwPollEvents(); } }
GLFWframebuffersizefun call(GLFWwindow* window, GLFWframebuffersizefun cbfun) { return glfwSetFramebufferSizeCallback(window, cbfun); }
int main( void ) { GLFWwindow* window; int width, height; // init GLFW if( !glfwInit() ) exit( EXIT_FAILURE ); glfwWindowHint(GLFW_DEPTH_BITS, 16); window = glfwCreateWindow( 800, 600, WINDOW_TITLE, NULL, NULL ); if (!window) { glfwTerminate(); exit( EXIT_FAILURE ); } glfwSetFramebufferSizeCallback(window, reshape); glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); glfwSwapInterval( 1 ); glfwGetFramebufferSize(window, &width, &height); reshape(window, width, height); glfwSetTime( 0.0 ); init(); // main loop double t; double t_old = 0.f; double dt; int titleBufferLength = strlen(WINDOW_TITLE)+20; char *windowTitle = new char[titleBufferLength]; for (;;) { // calculate delta t = glfwGetTime(); dt = t - t_old; t_old = t; // render update(window, dt); display(); // update fps counter in window title sprintf_s(windowTitle, titleBufferLength, "%s FPS: %d", WINDOW_TITLE, fps); glfwSetWindowTitle(window, windowTitle); glfwSwapBuffers(window); glfwPollEvents(); // check if we should stop running if (glfwWindowShouldClose(window)) break; } delete[] windowTitle; close(); glfwTerminate(); exit( EXIT_SUCCESS ); }
int main(int argc, char** argv) { Slot* slots; GLFWmonitor* monitor = NULL; int ch, i, width, height, count = 1; setlocale(LC_ALL, ""); glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); printf("Library initialized\n"); glfwSetMonitorCallback(monitor_callback); glfwSetJoystickCallback(joystick_callback); while ((ch = getopt(argc, argv, "hfn:")) != -1) { switch (ch) { case 'h': usage(); exit(EXIT_SUCCESS); case 'f': monitor = glfwGetPrimaryMonitor(); break; case 'n': count = (int) strtol(optarg, NULL, 10); break; default: usage(); exit(EXIT_FAILURE); } } if (monitor) { const GLFWvidmode* mode = glfwGetVideoMode(monitor); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); width = mode->width; height = mode->height; } else { width = 640; height = 480; } if (!count) { fprintf(stderr, "Invalid user\n"); exit(EXIT_FAILURE); } slots = calloc(count, sizeof(Slot)); for (i = 0; i < count; i++) { char title[128]; slots[i].closeable = GLFW_TRUE; slots[i].number = i + 1; snprintf(title, sizeof(title), "Event Linter (Window %i)", slots[i].number); if (monitor) { printf("Creating full screen window %i (%ix%i on %s)\n", slots[i].number, width, height, glfwGetMonitorName(monitor)); } else { printf("Creating windowed mode window %i (%ix%i)\n", slots[i].number, width, height); } slots[i].window = glfwCreateWindow(width, height, title, monitor, NULL); if (!slots[i].window) { free(slots); glfwTerminate(); exit(EXIT_FAILURE); } glfwSetWindowUserPointer(slots[i].window, slots + i); glfwSetWindowPosCallback(slots[i].window, window_pos_callback); glfwSetWindowSizeCallback(slots[i].window, window_size_callback); glfwSetFramebufferSizeCallback(slots[i].window, framebuffer_size_callback); glfwSetWindowContentScaleCallback(slots[i].window, window_content_scale_callback); glfwSetWindowCloseCallback(slots[i].window, window_close_callback); glfwSetWindowRefreshCallback(slots[i].window, window_refresh_callback); glfwSetWindowFocusCallback(slots[i].window, window_focus_callback); glfwSetWindowIconifyCallback(slots[i].window, window_iconify_callback); glfwSetWindowMaximizeCallback(slots[i].window, window_maximize_callback); glfwSetMouseButtonCallback(slots[i].window, mouse_button_callback); glfwSetCursorPosCallback(slots[i].window, cursor_position_callback); glfwSetCursorEnterCallback(slots[i].window, cursor_enter_callback); glfwSetScrollCallback(slots[i].window, scroll_callback); glfwSetKeyCallback(slots[i].window, key_callback); glfwSetCharCallback(slots[i].window, char_callback); glfwSetCharModsCallback(slots[i].window, char_mods_callback); glfwSetDropCallback(slots[i].window, drop_callback); glfwMakeContextCurrent(slots[i].window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); glfwSwapInterval(1); } printf("Main loop starting\n"); for (;;) { for (i = 0; i < count; i++) { if (glfwWindowShouldClose(slots[i].window)) break; } if (i < count) break; glfwWaitEvents(); // Workaround for an issue with msvcrt and mintty fflush(stdout); } free(slots); glfwTerminate(); exit(EXIT_SUCCESS); }
int main( void ) { //------------------------------------------------------ //Ex 23 GLM:llä matriisi laskemista //glm::mat4 matrix1(1.0f, 0.0f, 2.0f, 2.0f, // 0.0f, 1.0f, 0.0f, 0.0f, // 1.0f, 1.0f, 1.0f, 2.0f, // 0.0f, 0.0f, 1.0f, 0.0f); //glm::mat4 matrix2(0.0f, 0.0f, 0.0f, 2.0f, // 1.0f, 1.0f, 0.0f, 0.0f, // 1.0f, 1.0f, 0.0f, 2.0f, // 0.0f, 0.0f, 1.0f, 0.0f); //glm::vec4 multiplyVector(3.0f, 4.0f, -2.0f, 1.0f); //glm::vec4 xTulos; //xTulos = (matrix1 * matrix2) * multiplyVector; ///*for (int j = 0; j < sizeof(xTulos); j++) //{ // std::cout << xTulos[j] << std::endl; //}*/ //std::cout << xTulos[0] << ", " << xTulos[1] << ", " << xTulos[2] << ", " << xTulos[3] << std::endl; //-------------------------------------------------------- //Test //------------------------------------------------------ std::cout << "Ex 25-------------------------------------------------------\n" << std::endl; glm::vec4 P1(0.0f, 0.0f, 0.0f, 1.0f); glm::vec4 P2(1.0f, 0.0f, 0.0f, 1.0f); glm::vec4 P3(0.0f, 1.0f, 0.0f, 1.0f); glm::vec3 x_axis(1.0f, 0.0f, 0.0f); glm::vec3 y_axis(0.0f, 1.0f, 0.0f); glm::vec3 z_axis(0.0f, 0.0f, 1.0f); glm::vec3 s(0.3f); //skaalaus glm::vec3 t(-2.0f, -1.0f, 0.0f); //siirto glm::vec3 r = z_axis; //kierto glm::mat4 R = rotate(3.14159265f / 6.0f, r); glm::mat4 S = scale(s); glm::mat4 T = translate(t); glm::mat4 T_total = T*S*R; PrintVec(T_total*P1); PrintVec(T_total*P2); PrintVec(T_total*P3); PrintMatrix(T_total); std::cout << "\nEx 26--------------------------------------------------------" << std::endl; glm::vec3 cam_pos(1.2f, 0.1f, 0.0); glm::vec3 cam_up = y_axis; glm::vec3 cam_right = x_axis; glm::vec3 cam_front = z_axis; //oikeakätinen koordinaatisto glm::mat4 C = lookAt(cam_pos, cam_pos + cam_front, cam_up); T_total = C*T_total; PrintVec(T_total*P1); PrintVec(T_total*P2); PrintVec(T_total*P3); PrintMatrix(T_total); std::cout << "\nEx 27---------------------------------------------------------" << std::endl; float v_width = 6.0; //viewport in camera coord float v_height = 6.0; glm::mat4 T_projection = glm::ortho(-0.5f*v_width, 0.5f*v_width, -0.5f*v_height, 0.5f*v_height); T_total = T_projection*T_total; PrintVec(T_total*P1); PrintVec(T_total*P2); PrintVec(T_total*P3); PrintMatrix(T_total); //------------------------------------------------------ std::cout << "\n Ex 30--------------------------------------------------------" << std::endl; if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); return -1; } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); int w = 1024; int h = 768; window = glfwCreateWindow(w, h, "Tutorial 02 - Red triangle", NULL, NULL); if (window == NULL){ fprintf(stderr, "Failed to open GLFW window."); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, renderer::FramebufferSizeCallback); renderer::FramebufferSizeCallback(window, w, h); glewExperimental = true; // Needed for core profile if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); return -1; } glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); renderer::Init(window); do{ renderer::Render(); glfwPollEvents(); } while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0); renderer::Uninit(); glfwTerminate(); //------------------------------------------------------ // TESTI KOLMIO //if (!glfwInit()) //{ // fprintf(stderr, "Failed to initialize GLFW\n"); // return -1; //} //glfwWindowHint(GLFW_SAMPLES, 4); //glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //glfwWindowHint(GLFW_OPENGL_PROFILE, // GLFW_OPENGL_CORE_PROFILE); //window = glfwCreateWindow(1024, 768, // "Tutorial 02 - Red triangle", NULL, NULL); //if (window == NULL){ // fprintf(stderr, "Failed to open GLFW window."); // glfwTerminate(); // return -1; //} //glfwMakeContextCurrent(window); //glewExperimental = true; // Needed for core profile //if (glewInit() != GLEW_OK) { // fprintf(stderr, "Failed to initialize GLEW\n"); // return -1; //} //glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); //Init(); //do{ // Render(); // glfwPollEvents(); //} while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && // glfwWindowShouldClose(window) == 0); //glfwTerminate(); //--------------------------------------------------------- system("pause"); return 0; }
// ------------------------------------------------------------------- main --- int main( int argc, char **argv ) { GLFWwindow* window; glfwSetErrorCallback( error_callback ); if (!glfwInit( )) { exit( EXIT_FAILURE ); } glfwWindowHint( GLFW_VISIBLE, GL_TRUE ); glfwWindowHint( GLFW_RESIZABLE, GL_FALSE ); window = glfwCreateWindow( 1, 1, "Freetype OpenGL / LCD filtering", NULL, NULL ); if (!window) { glfwTerminate( ); exit( EXIT_FAILURE ); } glfwMakeContextCurrent( window ); glfwSwapInterval( 1 ); glfwSetFramebufferSizeCallback( window, reshape ); glfwSetWindowRefreshCallback( window, display ); glfwSetKeyCallback( window, keyboard ); #ifndef __APPLE__ glewExperimental = GL_TRUE; GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf( stderr, "Error: %s\n", glewGetErrorString(err) ); exit( EXIT_FAILURE ); } fprintf( stderr, "Using GLEW %s\n", glewGetString(GLEW_VERSION) ); #endif size_t i; texture_font_t *font = 0; atlas = texture_atlas_new( 512, 512, 3 ); const char * filename = "fonts/Vera.ttf"; wchar_t *text = L"A Quick Brown Fox Jumps Over The Lazy Dog 0123456789"; buffer = vertex_buffer_new( "vertex:3f,tex_coord:2f,color:4f,ashift:1f,agamma:1f" ); vec2 pen = {{0,0}}; vec4 color = {{0,0,0,1}}; for( i=7; i < 27; ++i) { font = texture_font_new_from_file( atlas, i, filename ); pen.x = 0; pen.y -= font->height; texture_font_load_glyphs( font, text ); add_text( buffer, font, text, &color, &pen ); texture_font_delete( font ); } glBindTexture( GL_TEXTURE_2D, atlas->id ); shader = shader_load( "shaders/text.vert", "shaders/text.frag" ); mat4_set_identity( &projection ); mat4_set_identity( &model ); mat4_set_identity( &view ); glfwSetWindowSize( window, 800, 500 ); glfwShowWindow( window ); while(!glfwWindowShouldClose( window )) { display( window ); glfwPollEvents( ); } glfwDestroyWindow( window ); 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); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // build and compile our shader program // ------------------------------------ // we skipped compile log checks this time for readability (if you do encounter issues, add the compile-checks! see previous code samples) unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER); unsigned int fragmentShaderOrange = glCreateShader(GL_FRAGMENT_SHADER); // the first fragment shader that outputs the color orange unsigned int fragmentShaderYellow = glCreateShader(GL_FRAGMENT_SHADER); // the second fragment shader that outputs the color yellow unsigned int shaderProgramOrange = glCreateProgram(); unsigned int shaderProgramYellow = glCreateProgram(); // the second shader program glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glCompileShader(vertexShader); glShaderSource(fragmentShaderOrange, 1, &fragmentShader1Source, NULL); glCompileShader(fragmentShaderOrange); glShaderSource(fragmentShaderYellow, 1, &fragmentShader2Source, NULL); glCompileShader(fragmentShaderYellow); // link the first program object glAttachShader(shaderProgramOrange, vertexShader); glAttachShader(shaderProgramOrange, fragmentShaderOrange); glLinkProgram(shaderProgramOrange); // then link the second program object using a different fragment shader (but same vertex shader) // this is perfectly allowed since the inputs and outputs of both the vertex and fragment shaders are equally matched. glAttachShader(shaderProgramYellow, vertexShader); glAttachShader(shaderProgramYellow, fragmentShaderYellow); glLinkProgram(shaderProgramYellow); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ float firstTriangle[] = { -0.9f, -0.5f, 0.0f, // left -0.0f, -0.5f, 0.0f, // right -0.45f, 0.5f, 0.0f, // top }; float secondTriangle[] = { 0.0f, -0.5f, 0.0f, // left 0.9f, -0.5f, 0.0f, // right 0.45f, 0.5f, 0.0f // top }; unsigned int VBOs[2], VAOs[2]; glGenVertexArrays(2, VAOs); // we can also generate multiple VAOs or buffers at the same time glGenBuffers(2, VBOs); // first triangle setup // -------------------- glBindVertexArray(VAOs[0]); glBindBuffer(GL_ARRAY_BUFFER, VBOs[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(firstTriangle), firstTriangle, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); // Vertex attributes stay the same glEnableVertexAttribArray(0); // glBindVertexArray(0); // no need to unbind at all as we directly bind a different VAO the next few lines // second triangle setup // --------------------- glBindVertexArray(VAOs[1]); // note that we bind to a different VAO now glBindBuffer(GL_ARRAY_BUFFER, VBOs[1]); // and a different VBO glBufferData(GL_ARRAY_BUFFER, sizeof(secondTriangle), secondTriangle, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); // because the vertex data is tightly packed we can also specify 0 as the vertex attribute's stride to let OpenGL figure it out glEnableVertexAttribArray(0); // glBindVertexArray(0); // not really necessary as well, but beware of calls that could affect VAOs while this one is bound (like binding element buffer objects, or enabling/disabling vertex attributes) // uncomment this call to draw in wireframe polygons. //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // now when we draw the triangle we first use the vertex and orange fragment shader from the first program glUseProgram(shaderProgramOrange); // draw the first triangle using the data from our first VAO glBindVertexArray(VAOs[0]); glDrawArrays(GL_TRIANGLES, 0, 3); // this call should output an orange triangle // then we draw the second triangle using the data from the second VAO // when we draw the second triangle we want to use a different shader program so we switch to the shader program with our yellow fragment shader. glUseProgram(shaderProgramYellow); glBindVertexArray(VAOs[1]); glDrawArrays(GL_TRIANGLES, 0, 3); // this call should output a yellow triangle // 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(2, VAOs); glDeleteBuffers(2, VBOs); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; }
int main(void) { // Create window and load extensions glfwSetErrorCallback(errorCallback); if (!glfwInit()) { std::exit(EXIT_FAILURE); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow(globals.width, globals.height, "Toon shading", NULL, NULL); if (!window) { glfwTerminate(); std::exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glfwSwapInterval(1); glewExperimental = GL_TRUE; GLenum status = glewInit(); if (status != GLEW_OK) { std::cerr << "Error: " << glewGetErrorString(status) << std::endl; std::exit(EXIT_FAILURE); } std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl; glfwSetKeyCallback(window, keyCallback); glfwSetMouseButtonCallback(window, mouseButtonCallback); glfwSetCursorPosCallback(window, cursorPosCallback); glfwSetFramebufferSizeCallback(window, framebufferSizeCallback); glfwSetScrollCallback(window, scrollCallback); TwInit(TW_OPENGL_CORE, NULL); TwWindowSize(globals.width, globals.height); TwBar *myBar; myBar = TwNewBar("Toon config"); TwAddVarCB(myBar, "X pos", TW_TYPE_FLOAT, setLightXpos, getLightXpos , &globals.lightdir_x, " step=0.5 group=Light label='x-pos' "); TwAddVarCB(myBar, "Y pos", TW_TYPE_FLOAT, setLightYpos, getLightYpos , &globals.lightdir_y, " step=0.5 group=Light label='y-pos' "); TwAddVarCB(myBar, "Z pos", TW_TYPE_FLOAT, setLightZpos, getLightZpos , &globals.lightdir_z, " step=0.01 group=Light label='z-pos' "); TwAddVarRW(myBar, "Ambient color", TW_TYPE_COLOR3F, &globals.ambientColor, "group=Material colormode=hls"); TwAddVarRW(myBar, "Diffuse color", TW_TYPE_COLOR3F, &globals.diffuseColor, "group=Material colormode=hls"); TwAddVarCB(myBar, "Diffuse intensity", TW_TYPE_FLOAT,setDifflvl, getDifflvl, &globals.material_kd, "group=Material step=0.01"); TwAddVarRW(myBar, "Outline color", TW_TYPE_COLOR3F, &globals.outlineColor, "group=Material colormode=hls"); TwAddVarCB(myBar, "Outline intensity", TW_TYPE_FLOAT, setOutlinelvl, getOutlinelvl , &globals.outline_intensity, " step=0.01 min=0.0 max=1.0 group=Material"); TwAddVarCB(myBar, "Background color", TW_TYPE_COLOR3F, setBgcolorCallBack, getBgcolorCallBack, &globals.bg_color[0], "group=Misc colormode=hls"); TwAddVarCB(myBar, "Color levels", TW_TYPE_INT8, setColorlvl, getColorlvl , &globals.colorlvl, " step=1 min=2 max=6 group=Material"); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); // Initialize rendering init(); // Start rendering loop while (!glfwWindowShouldClose(window)) { display(); TwDraw(); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); }
int main() { curl_global_init(CURL_GLOBAL_ALL); glfwSetErrorCallback(error_callback); if(!glfwInit()) { printf("Error: cannot setup glfw.\n"); exit(EXIT_FAILURE); } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* win = NULL; int w = 1280; int h = 768; win = glfwCreateWindow(w, h, "KankerFont v0.0.0.2", NULL, NULL); if(!win) { glfwTerminate(); exit(EXIT_FAILURE); } glfwSetFramebufferSizeCallback(win, resize_callback); glfwSetKeyCallback(win, key_callback); glfwSetCharCallback(win, char_callback); glfwSetCursorPosCallback(win, cursor_callback); glfwSetMouseButtonCallback(win, button_callback); glfwMakeContextCurrent(win); glfwSwapInterval(1); if (!gladLoadGL()) { printf("Cannot load GL.\n"); exit(1); } // ---------------------------------------------------------------- // THIS IS WHERE YOU START CALLING OPENGL FUNCTIONS, NOT EARLIER!! // ---------------------------------------------------------------- rx_log_init(); KankerApp app; if (0 != app.init()) { printf("error: cannot init the app.\n"); exit(EXIT_FAILURE); } app_ptr = &app; while(!glfwWindowShouldClose(win)) { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); app.update(); app.draw(); glfwSwapBuffers(win); glfwPollEvents(); } glfwTerminate(); return EXIT_SUCCESS; }
int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_SAMPLES, 4); 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); glfwMakeContextCurrent(window); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } 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("1.1.pbr.vs", "1.1.pbr.fs"); shader.use(); shader.setVec3("albedo", 0.5f, 0.0f, 0.0f); shader.setFloat("ao", 1.0f); // lights // ------ glm::vec3 lightPositions[] = { glm::vec3(-10.0f, 10.0f, 10.0f), glm::vec3( 10.0f, 10.0f, 10.0f), glm::vec3(-10.0f, -10.0f, 10.0f), glm::vec3( 10.0f, -10.0f, 10.0f), }; glm::vec3 lightColors[] = { glm::vec3(300.0f, 300.0f, 300.0f), glm::vec3(300.0f, 300.0f, 300.0f), glm::vec3(300.0f, 300.0f, 300.0f), glm::vec3(300.0f, 300.0f, 300.0f) }; int nrRows = 7; int nrColumns = 7; float spacing = 2.5; // initialize static shader uniforms before rendering // -------------------------------------------------- glm::mat4 projection = glm::perspective(camera.Zoom, (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); shader.use(); shader.setMat4("projection", projection); // 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); shader.use(); glm::mat4 view = camera.GetViewMatrix(); shader.setMat4("view", view); shader.setVec3("camPos", camera.Position); // render rows*column number of spheres with varying metallic/roughness values scaled by rows and columns respectively glm::mat4 model; for (unsigned int row = 0; row < nrRows; ++row) { shader.setFloat("metallic", (float)row / (float)nrRows); for (unsigned int col = 0; col < nrColumns; ++col) { // we clamp the roughness to 0.025 - 1.0 as perfectly smooth surfaces (roughness of 0.0) tend to look a bit off // on direct lighting. shader.setFloat("roughness", glm::clamp((float)col / (float)nrColumns, 0.05f, 1.0f)); model = glm::mat4(); model = glm::translate(model, glm::vec3( (float)(col - (nrColumns / 2)) * spacing, (float)(row - (nrRows / 2)) * spacing, 0.0f )); shader.setMat4("model", model); renderSphere(); } } // render light source (simply re-render sphere at light positions) // this looks a bit off as we use the same shader, but it'll make their positions obvious and // keeps the codeprint small. for (unsigned int i = 0; i < sizeof(lightPositions) / sizeof(lightPositions[0]); ++i) { glm::vec3 newPos = lightPositions[i] + glm::vec3(sin(glfwGetTime() * 5.0) * 5.0, 0.0, 0.0); newPos = lightPositions[i]; shader.setVec3("lightPositions[" + std::to_string(i) + "]", newPos); shader.setVec3("lightColors[" + std::to_string(i) + "]", lightColors[i]); model = glm::mat4(); model = glm::translate(model, newPos); model = glm::scale(model, glm::vec3(0.5f)); shader.setMat4("model", model); renderSphere(); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; }
/* Register a callback that runs after the window gets resized */ void GLWrapper::setReshapeCallback(void(*func)(GLFWwindow* window, int w, int h)) { reshape = func; glfwSetFramebufferSizeCallback(window, reshape); }