// The MAIN function, from here we start our application and run our Game loop void depthTesting() { // 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(screenWidth, screenHeight, "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, 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)) // Setup and compile our shaders Shader shader(vertexShaderSource, fragmentShaderSource); #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 planeVertices[] = { // 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 }; // 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 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(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glBindVertexArray(0); // Load textures GLuint cubeTexture = loadTexture("/Users/cc_xueqin/programming/learning/opengl/project/learn_opengl/res/container2.png"); GLuint floorTexture = loadTexture("/Users/cc_xueqin/programming/learning/opengl/project/learn_opengl/res/awesomeface.png"); #pragma endregion // 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 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)); // Cubes glBindVertexArray(cubeVAO); glBindTexture(GL_TEXTURE_2D, cubeTexture); // We omit the glActiveTexture part since TEXTURE0 is already the default active texture unit. (sampler used in fragment is set to 0 as well as default) model = glm::translate(model, glm::vec3(-1.0f, 0.01f, -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); // Floor glBindVertexArray(planeVAO); 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); // Swap the buffers glfwSwapBuffers(window); } glfwTerminate(); }
int main(int argc, const char *argv[]) { if(!glfwInit()) { std::cerr << "Failed to initialize GLFW3." << std::endl; return -1; } glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); GLFWwindow *window = glfwCreateWindow(640, 480, "Compute Shader Test", NULL, NULL); if(!window) { std::cerr << "Failed to create a GLFW window." << std::endl; return -1; } glfwMakeContextCurrent(window); glewExperimental = 1; glewInit(); std::cout << "Vendor:" << glGetString(GL_VENDOR) << std::endl; std::cout << "Renderer:" << glGetString(GL_RENDERER) << std::endl; std::cout << "Version:" << glGetString(GL_VERSION) << std::endl; std::cout << "Shader Language Version:" << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; if(GLEW_ARB_compute_shader) { std::cerr << "ARB_compute_shader extension supported." << std::endl; } else { std::cerr << "ARB_compute_shader extension not supported." << std::endl; return -1; } if(GLEW_ARB_shader_image_load_store) { std::cerr << "ARB_shader_image_load_store extension supported." << std::endl; } else { std::cerr << "ARB_shader_image_load_store extension not supported." << std::endl; return -1; } glEnable(GL_TEXTURE_2D); GLuint vertex_array; glGenVertexArrays(1, &vertex_array); glBindVertexArray(vertex_array); std::cout << "X = " << ComputeShader::get_max_localsize_x() << std::endl; std::cout << "Y = " << ComputeShader::get_max_localsize_y() << std::endl; std::cout << "Z = " << ComputeShader::get_max_localsize_z() << std::endl; { ComputeShader compute_shader("shader.comp"); Shader shader("shader.vert", "shader.frag"); //Texture input("opengl_logo.bmp"); Texture output(512, 512); while(!glfwWindowShouldClose(window)) { //glClearColor(1, 1, 1, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); compute_shader.use(); glUniform1i(0, 0); //input.bind_image(0, GL_READ_ONLY); output.bind_image(0, GL_WRITE_ONLY); glDispatchCompute(32, 32, 1); glMemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT); shader.use(); glUniform1i(0, 0); output.render(); glfwSwapBuffers(window); glfwPollEvents(); } } glfwTerminate(); return 0; }
int main(int argc, char** argv) { int ch, client, context, major, minor, revision, profile; GLint redbits, greenbits, bluebits, alphabits, depthbits, stencilbits; int list_extensions = GLFW_FALSE, list_layers = GLFW_FALSE; GLenum error; GLFWwindow* window; enum { CLIENT, CONTEXT, BEHAVIOR, DEBUG, FORWARD, HELP, EXTENSIONS, LAYERS, MAJOR, MINOR, PROFILE, ROBUSTNESS, VERSION, REDBITS, GREENBITS, BLUEBITS, ALPHABITS, DEPTHBITS, STENCILBITS, ACCUMREDBITS, ACCUMGREENBITS, ACCUMBLUEBITS, ACCUMALPHABITS, AUXBUFFERS, SAMPLES, STEREO, SRGB, SINGLEBUFFER, NOERROR_SRSLY }; const struct option options[] = { { "behavior", 1, NULL, BEHAVIOR }, { "client-api", 1, NULL, CLIENT }, { "context-api", 1, NULL, CONTEXT }, { "debug", 0, NULL, DEBUG }, { "forward", 0, NULL, FORWARD }, { "help", 0, NULL, HELP }, { "list-extensions", 0, NULL, EXTENSIONS }, { "list-layers", 0, NULL, LAYERS }, { "major", 1, NULL, MAJOR }, { "minor", 1, NULL, MINOR }, { "profile", 1, NULL, PROFILE }, { "robustness", 1, NULL, ROBUSTNESS }, { "version", 0, NULL, VERSION }, { "red-bits", 1, NULL, REDBITS }, { "green-bits", 1, NULL, GREENBITS }, { "blue-bits", 1, NULL, BLUEBITS }, { "alpha-bits", 1, NULL, ALPHABITS }, { "depth-bits", 1, NULL, DEPTHBITS }, { "stencil-bits", 1, NULL, STENCILBITS }, { "accum-red-bits", 1, NULL, ACCUMREDBITS }, { "accum-green-bits", 1, NULL, ACCUMGREENBITS }, { "accum-blue-bits", 1, NULL, ACCUMBLUEBITS }, { "accum-alpha-bits", 1, NULL, ACCUMALPHABITS }, { "aux-buffers", 1, NULL, AUXBUFFERS }, { "samples", 1, NULL, SAMPLES }, { "stereo", 0, NULL, STEREO }, { "srgb", 0, NULL, SRGB }, { "singlebuffer", 0, NULL, SINGLEBUFFER }, { "no-error", 0, NULL, NOERROR_SRSLY }, { NULL, 0, NULL, 0 } }; // Initialize GLFW and create window if (!valid_version()) exit(EXIT_FAILURE); glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); while ((ch = getopt_long(argc, argv, "a:b:dfhlm:n:p:s:v", options, NULL)) != -1) { switch (ch) { case 'a': case CLIENT: if (strcasecmp(optarg, API_NAME_OPENGL) == 0) glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); else if (strcasecmp(optarg, API_NAME_OPENGL_ES) == 0) glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API); else { usage(); exit(EXIT_FAILURE); } break; case 'b': case BEHAVIOR: if (strcasecmp(optarg, BEHAVIOR_NAME_NONE) == 0) { glfwWindowHint(GLFW_CONTEXT_RELEASE_BEHAVIOR, GLFW_RELEASE_BEHAVIOR_NONE); } else if (strcasecmp(optarg, BEHAVIOR_NAME_FLUSH) == 0) { glfwWindowHint(GLFW_CONTEXT_RELEASE_BEHAVIOR, GLFW_RELEASE_BEHAVIOR_FLUSH); } else { usage(); exit(EXIT_FAILURE); } break; case 'c': case CONTEXT: if (strcasecmp(optarg, API_NAME_NATIVE) == 0) glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_NATIVE_CONTEXT_API); else if (strcasecmp(optarg, API_NAME_EGL) == 0) glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API); else { usage(); exit(EXIT_FAILURE); } break; case 'd': case DEBUG: glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE); break; case 'f': case FORWARD: glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); break; case 'h': case HELP: usage(); exit(EXIT_SUCCESS); case 'l': case EXTENSIONS: list_extensions = GLFW_TRUE; break; case LAYERS: list_layers = GLFW_TRUE; break; case 'm': case MAJOR: glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, atoi(optarg)); break; case 'n': case MINOR: glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, atoi(optarg)); break; case 'p': case PROFILE: if (strcasecmp(optarg, PROFILE_NAME_CORE) == 0) { glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); } else if (strcasecmp(optarg, PROFILE_NAME_COMPAT) == 0) { glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE); } else { usage(); exit(EXIT_FAILURE); } break; case 's': case ROBUSTNESS: if (strcasecmp(optarg, STRATEGY_NAME_NONE) == 0) { glfwWindowHint(GLFW_CONTEXT_ROBUSTNESS, GLFW_NO_RESET_NOTIFICATION); } else if (strcasecmp(optarg, STRATEGY_NAME_LOSE) == 0) { glfwWindowHint(GLFW_CONTEXT_ROBUSTNESS, GLFW_LOSE_CONTEXT_ON_RESET); } else { usage(); exit(EXIT_FAILURE); } break; case 'v': case VERSION: print_version(); exit(EXIT_SUCCESS); case REDBITS: if (strcmp(optarg, "-") == 0) glfwWindowHint(GLFW_RED_BITS, GLFW_DONT_CARE); else glfwWindowHint(GLFW_RED_BITS, atoi(optarg)); break; case GREENBITS: if (strcmp(optarg, "-") == 0) glfwWindowHint(GLFW_GREEN_BITS, GLFW_DONT_CARE); else glfwWindowHint(GLFW_GREEN_BITS, atoi(optarg)); break; case BLUEBITS: if (strcmp(optarg, "-") == 0) glfwWindowHint(GLFW_BLUE_BITS, GLFW_DONT_CARE); else glfwWindowHint(GLFW_BLUE_BITS, atoi(optarg)); break; case ALPHABITS: if (strcmp(optarg, "-") == 0) glfwWindowHint(GLFW_ALPHA_BITS, GLFW_DONT_CARE); else glfwWindowHint(GLFW_ALPHA_BITS, atoi(optarg)); break; case DEPTHBITS: if (strcmp(optarg, "-") == 0) glfwWindowHint(GLFW_DEPTH_BITS, GLFW_DONT_CARE); else glfwWindowHint(GLFW_DEPTH_BITS, atoi(optarg)); break; case STENCILBITS: if (strcmp(optarg, "-") == 0) glfwWindowHint(GLFW_STENCIL_BITS, GLFW_DONT_CARE); else glfwWindowHint(GLFW_STENCIL_BITS, atoi(optarg)); break; case ACCUMREDBITS: if (strcmp(optarg, "-") == 0) glfwWindowHint(GLFW_ACCUM_RED_BITS, GLFW_DONT_CARE); else glfwWindowHint(GLFW_ACCUM_RED_BITS, atoi(optarg)); break; case ACCUMGREENBITS: if (strcmp(optarg, "-") == 0) glfwWindowHint(GLFW_ACCUM_GREEN_BITS, GLFW_DONT_CARE); else glfwWindowHint(GLFW_ACCUM_GREEN_BITS, atoi(optarg)); break; case ACCUMBLUEBITS: if (strcmp(optarg, "-") == 0) glfwWindowHint(GLFW_ACCUM_BLUE_BITS, GLFW_DONT_CARE); else glfwWindowHint(GLFW_ACCUM_BLUE_BITS, atoi(optarg)); break; case ACCUMALPHABITS: if (strcmp(optarg, "-") == 0) glfwWindowHint(GLFW_ACCUM_ALPHA_BITS, GLFW_DONT_CARE); else glfwWindowHint(GLFW_ACCUM_ALPHA_BITS, atoi(optarg)); break; case AUXBUFFERS: if (strcmp(optarg, "-") == 0) glfwWindowHint(GLFW_AUX_BUFFERS, GLFW_DONT_CARE); else glfwWindowHint(GLFW_AUX_BUFFERS, atoi(optarg)); break; case SAMPLES: if (strcmp(optarg, "-") == 0) glfwWindowHint(GLFW_SAMPLES, GLFW_DONT_CARE); else glfwWindowHint(GLFW_SAMPLES, atoi(optarg)); break; case STEREO: glfwWindowHint(GLFW_STEREO, GLFW_TRUE); break; case SRGB: glfwWindowHint(GLFW_SRGB_CAPABLE, GLFW_TRUE); break; case SINGLEBUFFER: glfwWindowHint(GLFW_DOUBLEBUFFER, GLFW_FALSE); break; case NOERROR_SRSLY: glfwWindowHint(GLFW_CONTEXT_NO_ERROR, GLFW_TRUE); break; default: usage(); exit(EXIT_FAILURE); } } print_version(); glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); window = glfwCreateWindow(200, 200, "Version", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); error = glGetError(); if (error != GL_NO_ERROR) printf("*** OpenGL error after make current: 0x%08x ***\n", error); // Report client API version client = glfwGetWindowAttrib(window, GLFW_CLIENT_API); context = glfwGetWindowAttrib(window, GLFW_CONTEXT_CREATION_API); major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); revision = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); profile = glfwGetWindowAttrib(window, GLFW_OPENGL_PROFILE); printf("%s context version string: \"%s\"\n", get_api_name(client), glGetString(GL_VERSION)); printf("%s context version parsed by GLFW: %u.%u.%u\n", get_api_name(client), major, minor, revision); // Report client API context properties if (client == GLFW_OPENGL_API) { if (major >= 3) { GLint flags; glGetIntegerv(GL_CONTEXT_FLAGS, &flags); printf("%s context flags (0x%08x):", get_api_name(client), flags); if (flags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT) printf(" forward-compatible"); if (flags & 2/*GL_CONTEXT_FLAG_DEBUG_BIT*/) printf(" debug"); if (flags & GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB) printf(" robustness"); if (flags & 8/*GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR*/) printf(" no-error"); putchar('\n'); printf("%s context flags parsed by GLFW:", get_api_name(client)); if (glfwGetWindowAttrib(window, GLFW_OPENGL_FORWARD_COMPAT)) printf(" forward-compatible"); if (glfwGetWindowAttrib(window, GLFW_OPENGL_DEBUG_CONTEXT)) printf(" debug"); if (glfwGetWindowAttrib(window, GLFW_CONTEXT_ROBUSTNESS) == GLFW_LOSE_CONTEXT_ON_RESET) printf(" robustness"); if (glfwGetWindowAttrib(window, GLFW_CONTEXT_NO_ERROR)) printf(" no-error"); putchar('\n'); } if (major >= 4 || (major == 3 && minor >= 2)) { GLint mask; glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &mask); printf("%s profile mask (0x%08x): %s\n", get_api_name(client), mask, get_profile_name_gl(mask)); printf("%s profile mask parsed by GLFW: %s\n", get_api_name(client), get_profile_name_glfw(profile)); } if (glfwExtensionSupported("GL_ARB_robustness")) { const int robustness = glfwGetWindowAttrib(window, GLFW_CONTEXT_ROBUSTNESS); GLint strategy; glGetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_ARB, &strategy); printf("%s robustness strategy (0x%08x): %s\n", get_api_name(client), strategy, get_strategy_name_gl(strategy)); printf("%s robustness strategy parsed by GLFW: %s\n", get_api_name(client), get_strategy_name_glfw(robustness)); } } printf("%s context renderer string: \"%s\"\n", get_api_name(client), glGetString(GL_RENDERER)); printf("%s context vendor string: \"%s\"\n", get_api_name(client), glGetString(GL_VENDOR)); if (major >= 2) { printf("%s context shading language version: \"%s\"\n", get_api_name(client), glGetString(GL_SHADING_LANGUAGE_VERSION)); } printf("%s framebuffer:\n", get_api_name(client)); if (client == GLFW_OPENGL_API && profile == GLFW_OPENGL_CORE_PROFILE) { glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_BACK_LEFT, GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE, &redbits); glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_BACK_LEFT, GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, &greenbits); glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_BACK_LEFT, GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, &bluebits); glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_BACK_LEFT, GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, &alphabits); glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_DEPTH, GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, &depthbits); glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_STENCIL, GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, &stencilbits); } else { glGetIntegerv(GL_RED_BITS, &redbits); glGetIntegerv(GL_GREEN_BITS, &greenbits); glGetIntegerv(GL_BLUE_BITS, &bluebits); glGetIntegerv(GL_ALPHA_BITS, &alphabits); glGetIntegerv(GL_DEPTH_BITS, &depthbits); glGetIntegerv(GL_STENCIL_BITS, &stencilbits); } printf(" red: %u green: %u blue: %u alpha: %u depth: %u stencil: %u\n", redbits, greenbits, bluebits, alphabits, depthbits, stencilbits); if (client == GLFW_OPENGL_ES_API || glfwExtensionSupported("GL_ARB_multisample") || major > 1 || minor >= 3) { GLint samples, samplebuffers; glGetIntegerv(GL_SAMPLES, &samples); glGetIntegerv(GL_SAMPLE_BUFFERS, &samplebuffers); printf(" samples: %u sample buffers: %u\n", samples, samplebuffers); } if (client == GLFW_OPENGL_API && profile != GLFW_OPENGL_CORE_PROFILE) { GLint accumredbits, accumgreenbits, accumbluebits, accumalphabits; GLint auxbuffers; glGetIntegerv(GL_ACCUM_RED_BITS, &accumredbits); glGetIntegerv(GL_ACCUM_GREEN_BITS, &accumgreenbits); glGetIntegerv(GL_ACCUM_BLUE_BITS, &accumbluebits); glGetIntegerv(GL_ACCUM_ALPHA_BITS, &accumalphabits); glGetIntegerv(GL_AUX_BUFFERS, &auxbuffers); printf(" accum red: %u accum green: %u accum blue: %u accum alpha: %u aux buffers: %u\n", accumredbits, accumgreenbits, accumbluebits, accumalphabits, auxbuffers); } if (list_extensions) list_context_extensions(client, major, minor); printf("Vulkan loader: %s\n", glfwVulkanSupported() ? "available" : "missing"); if (glfwVulkanSupported()) { uint32_t i, re_count, pd_count; const char** re; VkApplicationInfo ai = {VK_STRUCTURE_TYPE_APPLICATION_INFO}; VkInstanceCreateInfo ici = {VK_STRUCTURE_TYPE_APPLICATION_INFO}; VkInstance instance; VkPhysicalDevice* pd; PFN_vkCreateInstance vkCreateInstance = (PFN_vkCreateInstance) glfwGetInstanceProcAddress(NULL, "vkCreateInstance"); PFN_vkDestroyInstance vkDestroyInstance; PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices; PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties; re = glfwGetRequiredInstanceExtensions(&re_count); printf("Vulkan required instance extensions:"); for (i = 0; i < re_count; i++) printf(" %s", re[i]); putchar('\n'); if (list_extensions) list_vulkan_instance_extensions(); if (list_layers) list_vulkan_instance_layers(); ai.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; ai.pApplicationName = "glfwinfo"; ai.applicationVersion = GLFW_VERSION_MAJOR; ai.pEngineName = "GLFW"; ai.engineVersion = GLFW_VERSION_MAJOR; ai.apiVersion = VK_API_VERSION_1_0; ici.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; ici.pApplicationInfo = &ai; ici.enabledExtensionCount = re_count; ici.ppEnabledExtensionNames = re; if (vkCreateInstance(&ici, NULL, &instance) != VK_SUCCESS) { glfwTerminate(); exit(EXIT_FAILURE); } vkDestroyInstance = (PFN_vkDestroyInstance) glfwGetInstanceProcAddress(instance, "vkDestroyInstance"); vkEnumeratePhysicalDevices = (PFN_vkEnumeratePhysicalDevices) glfwGetInstanceProcAddress(instance, "vkEnumeratePhysicalDevices"); vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties) glfwGetInstanceProcAddress(instance, "vkGetPhysicalDeviceProperties"); if (vkEnumeratePhysicalDevices(instance, &pd_count, NULL) != VK_SUCCESS) { vkDestroyInstance(instance, NULL); glfwTerminate(); exit(EXIT_FAILURE); } pd = (VkPhysicalDevice*) calloc(pd_count, sizeof(VkPhysicalDevice)); if (vkEnumeratePhysicalDevices(instance, &pd_count, pd) != VK_SUCCESS) { free(pd); vkDestroyInstance(instance, NULL); glfwTerminate(); exit(EXIT_FAILURE); } for (i = 0; i < pd_count; i++) { VkPhysicalDeviceProperties pdp; vkGetPhysicalDeviceProperties(pd[i], &pdp); printf("Vulkan %s device: \"%s\"\n", get_device_type_name(pdp.deviceType), pdp.deviceName); if (list_extensions) list_vulkan_device_extensions(instance, pd[i]); if (list_layers) list_vulkan_device_layers(instance, pd[i]); } free(pd); vkDestroyInstance(instance, NULL); } glfwTerminate(); exit(EXIT_SUCCESS); }
// program entry int32_t main(int32_t argc, char *argv[]) { GLFWwindow* window; int32_t width, height; NvAssetLoaderInit(NULL); sWindowIsFocused = true; sForcedRenderCount = 0; if( !glfwInit() ) { fprintf( stderr, "Failed to initialize GLFW\n" ); exit( EXIT_FAILURE ); } NvMacPlatformContext* platform = new NvMacPlatformContext; // add command line arguments for (int i = 1; i < argc; i++) { platform->m_commandLine.push_back(argv[i]); } sApp = NvAppFactory(platform); NvEGLConfiguration config(NvGfxAPIVersionGL4(), 8, 8, 8, 8, 16, 0); sApp->configurationCallback(config); // Set Mac hints to get a core profile context... 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); // Does not seem to work... /* if (config.api == GLAppContext::Configuration::API_ES) glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, config.majVer); //glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); */ NvGLMacAppContext* context = new NvGLMacAppContext(config); window = glfwCreateWindow( 1280, 720, "Mac SDK Application", NULL, NULL ); if (!window) { fprintf( stderr, "Failed to open GLFW window\n" ); glfwTerminate(); exit( EXIT_FAILURE ); } platform->setWindow(window); context->setWindow(window); sApp->setGLContext(context); // Set callback functions glfwSetFramebufferSizeCallback(window, reshape); glfwSetWindowFocusCallback(window, focus); setInputCallbacksGLFW(window); context->bindContext(); glfwSwapInterval( 1 ); glfwGetFramebufferSize(window, &width, &height); int32_t major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); int32_t minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); config.apiVer = NvGfxAPIVersion(NvGfxAPI::GL, major, minor); glGetIntegerv(GL_RED_BITS, (GLint*)&config.redBits); glGetIntegerv(GL_GREEN_BITS, (GLint*)&config.greenBits); glGetIntegerv(GL_BLUE_BITS, (GLint*)&config.blueBits); glGetIntegerv(GL_ALPHA_BITS, (GLint*)&config.alphaBits); glGetIntegerv(GL_DEPTH_BITS, (GLint*)&config.depthBits); glGetIntegerv(GL_STENCIL_BITS, (GLint*)&config.stencilBits); context->setConfiguration(config); #if 1 // get extensions (need for ES2.0) GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); exit(-1); } fprintf(stdout, "Using GLEW %s\n", glewGetString(GLEW_VERSION)); #endif // Parse command-line options initGL(argc, argv); reshape(window, width, height); sApp->mainLoop(); // Shut down the app before shutting down GL delete sApp; // Terminate GLFW glfwTerminate(); NvAssetLoaderShutdown(); // Exit program 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); // build and compile shaders // ------------------------- Shader shader("5.3.parallax_mapping.vs", "5.3.parallax_mapping.fs"); // load textures // ------------- unsigned int diffuseMap = loadTexture(FileSystem::getPath("resources/textures/bricks2.jpg").c_str()); unsigned int normalMap = loadTexture(FileSystem::getPath("resources/textures/bricks2_normal.jpg").c_str()); unsigned int heightMap = loadTexture(FileSystem::getPath("resources/textures/bricks2_disp.jpg").c_str()); /*unsigned int diffuseMap = loadTexture(FileSystem::getPath("resources/textures/toy_box_diffuse.png").c_str()); unsigned int normalMap = loadTexture(FileSystem::getPath("resources/textures/toy_box_normal.png").c_str()); unsigned int heightMap = loadTexture(FileSystem::getPath("resources/textures/toy_box_disp.png").c_str());*/ // shader configuration // -------------------- shader.use(); shader.setInt("diffuseMap", 0); shader.setInt("normalMap", 1); shader.setInt("depthMap", 2); // lighting info // ------------- glm::vec3 lightPos(0.5f, 1.0f, 0.3f); // 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); // configure view/projection matrices glm::mat4 projection = glm::perspective(camera.Zoom, (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); glm::mat4 view = camera.GetViewMatrix(); shader.use(); shader.setMat4("projection", projection); shader.setMat4("view", view); // render parallax-mapped quad glm::mat4 model; model = glm::rotate(model, glm::radians((float)glfwGetTime() * -10.0f), glm::normalize(glm::vec3(1.0, 0.0, 1.0))); // rotate the quad to show parallax mapping from multiple directions shader.setMat4("model", model); shader.setVec3("viewPos", camera.Position); shader.setVec3("lightPos", lightPos); shader.setFloat("heightScale", heightScale); // adjust with Q and E keys std::cout << heightScale << std::endl; glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, diffuseMap); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, normalMap); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, heightMap); renderQuad(); // render light source (simply re-renders a smaller plane at the light's position for debugging/visualization) model = glm::mat4(); model = glm::translate(model, lightPos); model = glm::scale(model, glm::vec3(0.1f)); shader.setMat4("model", model); renderQuad(); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; }
int main() { 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(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); std::cout << "RUNNING VERSION " << glGetString(GL_VERSION); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cout << "Failed to initialize GLEW" << std::endl; return -1; } glViewport(0, 0, WIDTH, HEIGHT); // Initialize callback listeners glfwSetKeyCallback(window, key_callback); // Build and compile our shader program Shader ourShader( "resources/shaders/textures.vs", // Vertex shader "resources/shaders/textures.frag" // Fragment shader ); // Set up vertex data (and buffer(s)) and attribute pointers GLfloat vertices[] = { // Positions // Texture1 Coords // Texture2 Coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 1.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, }; // Cube positions in the game world std::array<glm::vec3, 10> 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) }; GLuint VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // 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 0 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // Texture attribute 2 glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(2); // Texture attribute 3 glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), (GLvoid*)(5 * sizeof(GLfloat))); glEnableVertexAttribArray(3); glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs), remember: do NOT unbind the EBO, keep it bound to this VAO // Generate textures GLuint textures[2]; glGenTextures(2, textures); // -- Prepare texture 1 -- // glBindTexture(GL_TEXTURE_2D, textures[0]); // All upcoming GL_TEXTURE_2D operations now have effect on this texture object // Set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture wrapping to GL_REPEAT (usually basic wrapping method) 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; unsigned char* image = SOIL_load_image("resources/textures/container.jpg", &width, &height, 0, SOIL_LOAD_RGB); 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); // -- Prepare texture 2 -- // glBindTexture(GL_TEXTURE_2D, textures[1]); // All upcoming GL_TEXTURE_2D operations now have effect on this texture object // Set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); // Set texture wrapping to GL_REPEAT (usually basic wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); // 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 image = SOIL_load_image("resources/textures/dataart.jpg", &width, &height, 0, SOIL_LOAD_RGB); 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); glBindTexture(GL_TEXTURE_2D, 0); glEnable(GL_DEPTH_TEST); // Run game loop while (!glfwWindowShouldClose(window)) { // Check events glfwPollEvents(); update_camera_positions(0.05f); // Rendering glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Activate shader ourShader.Use(); // Create transformations glm::mat4 view; // view matrix glm::mat4 projection; // projection matrix view = glm::translate(view, glm::vec3(cameraDistanceX, cameraDistanceY, cameraDistanceZ)); // Note that we're translating the scene in the reverse direction of where we want to move projection = glm::perspective(45.0f, (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 100.0f); // Pass matrixes to their uniform variables in fragment shader GLint modelLoc = glGetUniformLocation(ourShader.Program, "model"); GLint viewLoc = glGetUniformLocation(ourShader.Program, "view"); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); GLint projectionLoc = glGetUniformLocation(ourShader.Program, "projection"); glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection)); // Note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once. // Bind Textures using texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textures[0]); glUniform1i(glGetUniformLocation(ourShader.Program, "customTexture1"), 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textures[1]); glUniform1i(glGetUniformLocation(ourShader.Program, "customTexture2"), 1); // Draw glBindVertexArray(VAO); for (GLuint i = 0; i < cubePositions.size(); i++) { glm::mat4 model; model = glm::translate(model, cubePositions[i]); GLfloat angle = 20.0f * (i + 1); model = glm::rotate(model, (GLfloat)glfwGetTime() * angle, glm::vec3(1.0f, 0.3f, 0.5f)); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); } glBindVertexArray(0); // Swap double buffers glfwSwapBuffers(window); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; }
int main(int argc, char *argv[]){ 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(SCREEN_WIDTH, SCREEN_HEIGHT, "Solar", nullptr, nullptr); glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); glfwSetCursorEnterCallback(window, cursor_enter_callback); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glewExperimental = GL_TRUE; glewInit(); glGetError(); glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); glEnable(GL_DEPTH_TEST); glEnable(GL_MULTISAMPLE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_PROGRAM_POINT_SIZE); //---------------------------test code---------------------------- //---------------------------------------------------------------- solar.Init(); GLfloat deltaTime = 0.0f; GLfloat lastFrame = 0.0f; while (!glfwWindowShouldClose(window)) { GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; glfwPollEvents(); glClearColor(0.05f, 0.05f, 0.068f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); solar.ProcessInput(deltaTime); solar.Update(deltaTime); solar.Render(); //-------------------------test code------------------------------- //------------------------------------------------------------------ InputManager::ClearMouseMovement(); InputManager::ClearMouseScroll(); glfwSwapBuffers(window); } ResourceManager::Clear(); glfwTerminate(); return 0; }
unsigned int Renderer::Initialize() { if (m_initialized) return CS_ERR_NONE; unsigned int err = CS_ERR_NONE; #ifdef PLATFORM_WINDOWS if (!glfwInit()) return CS_ERR_WINDOW_FAILED; glfwWindowHint(GLFW_SAMPLES, CSSET_GLFW_SAMPLES_VALUE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); Engine* engine = System::GetInstance()->GetEngineData(); m_window = glfwCreateWindow(CSSET_WINDOW_WIDTH_DEFAULT, CSSET_WINDOW_HEIGHT_DEFAULT, CSSET_WINDOW_NAME, nullptr, nullptr); engine->width = CSSET_WINDOW_WIDTH_DEFAULT; engine->height = CSSET_WINDOW_HEIGHT_DEFAULT; m_screenRatio = (float)engine->height / (float)engine->width; if (m_window == nullptr) { glfwTerminate(); return CS_ERR_WINDOW_FAILED; } glfwMakeContextCurrent(m_window); glewExperimental = true; if (glewInit() != GLEW_OK) return CS_ERR_WINDOW_FAILED; glfwSwapInterval(CSSET_VSYNC_ENALBED); #else // initialize OpenGL ES and EGL EGLint w, h, format; EGLint numConfigs; EGLConfig config; EGLSurface surface; EGLContext context; Engine* engine = System::GetInstance()->GetEngineData(); EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(display, 0, 0); /* Here, the application chooses the configuration it desires. In this * sample, we have a very simplified selection process, where we pick * the first EGLConfig that matches our criteria */ eglChooseConfig(display, attribs, &config, 1, &numConfigs); /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is * guaranteed to be accepted by ANativeWindow_setBuffersGeometry(). * As soon as we picked a EGLConfig, we can safely reconfigure the * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */ eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format); ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format); surface = eglCreateWindowSurface(display, config, engine->app->window, NULL); context = eglCreateContext(display, config, NULL, attribsContext); if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) { LOGW("Unable to eglMakeCurrent"); return -1; } eglQuerySurface(display, surface, EGL_WIDTH, &w); eglQuerySurface(display, surface, EGL_HEIGHT, &h); m_screenRatio = (float)w / (float)h; engine->display = display; engine->context = context; engine->surface = surface; engine->width = w; engine->height = h; eglSwapInterval(engine->display, CSSET_VSYNC_ENALBED); AConfiguration_setNavigation(engine->app->config, ACONFIGURATION_NAVHIDDEN_YES); #endif // Shaders Loading m_basicShader = ResourceManager::GetInstance()->LoadShader(&SN_BASIC); m_wireframeShader = ResourceManager::GetInstance()->LoadShader(&SN_WIREFRAME); m_basicWireframeShader = ResourceManager::GetInstance()->LoadShader(&SN_BASICWIREFRAME); m_fontShader = ResourceManager::GetInstance()->LoadShader(&SN_FONT); m_shaderID = m_basicShader; m_mode = BASIC; //////////// options go here glClearColor(CSSET_CLEAR_COLORS[0], CSSET_CLEAR_COLORS[1], CSSET_CLEAR_COLORS[2], CSSET_CLEAR_COLORS[3]); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); if (CSSET_BACKFACE_CULLING) { glEnable(GL_CULL_FACE); } glCullFace(GL_BACK); glFrontFace(GL_CCW); glEnable(GL_DITHER); //glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST); /* glEnable(GL_STENCIL); glStencilFunc(GL_LEQUAL, 0, 0xFF); glStencilOp(GL_REPLACE, GL_KEEP, GL_KEEP); */ glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); ///////////////////////// m_initialized = true; return err; }
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 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 SetUpOpenGL(GLFWwindow **window, const int xRes, const int yRes, GLuint *vertexShader, GLuint *fragmentShader, GLuint *shaderProgram, GLuint *vao, GLuint *vbo, GLuint *ebo, GLuint *tex) { // Initialise GLFW if( !glfwInit() ) { fprintf(stderr, "Error in SetUpOpenGL(), failed to initialize GLFW. Line: %d\n", __LINE__); return -1; } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create a GFLW window and create its OpenGL context #ifdef FULLSCREEN *window = glfwCreateWindow( xRes, yRes, "Mandelbrot Set", glfwGetPrimaryMonitor(), NULL); #else *window = glfwCreateWindow( xRes, yRes, "Mandelbrot Set", NULL, NULL); #endif if(*window == NULL ){ fprintf(stderr, "Error in SetUpOpenGL(), failed to open GLFW window. Line: %d\n", __LINE__); glfwTerminate(); return -1; } glfwMakeContextCurrent(*window); // vsync glfwSwapInterval(1); // Initialize GLEW glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { fprintf(stderr, "Error in SetUpOpenGL(), failed to initialize GLEW. Line: %d\n", __LINE__); return -1; } // Ensure we can capture the escape key being pressed below glfwSetInputMode(*window, GLFW_STICKY_KEYS, GL_TRUE); // Include shader strings from file #include "shaders.glsl" // Define rectangle, on which we'll draw the texture float rectangleVertices[] = { // Position Texcoords -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 1.0f }; // vertex array object glGenVertexArrays(1, vao); glBindVertexArray(*vao); // vertex buffer object for rectangle glGenBuffers(1,vbo); glBindBuffer(GL_ARRAY_BUFFER, *vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(rectangleVertices), rectangleVertices, GL_STATIC_DRAW); // rectangle formed of two triangles, use ebo to re-use vertices glGenBuffers(1, ebo); GLuint elements[] = { 0, 1, 2, 2, 3, 0}; glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW); // define and compile shaders // vertex *vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(*vertexShader, 1, &vertexSource, NULL); glCompileShader(*vertexShader); GLint status; glGetShaderiv(*vertexShader, GL_COMPILE_STATUS, &status); if (status != GL_TRUE) { printf("Vertex shader compilation error, line %d\n", __LINE__); } // fragment *fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(*fragmentShader, 1, &fragmentSource, NULL); glCompileShader(*fragmentShader); glGetShaderiv(*fragmentShader, GL_COMPILE_STATUS, &status); if (status != GL_TRUE) { printf("Vertex shader compilation error, line %d\n", __LINE__); } *shaderProgram = glCreateProgram(); glAttachShader(*shaderProgram, *vertexShader); glAttachShader(*shaderProgram, *fragmentShader); glLinkProgram(*shaderProgram); glUseProgram(*shaderProgram); // set attributes GLint posAttrib = glGetAttribLocation(*shaderProgram, "position"); glEnableVertexAttribArray(posAttrib); glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0); GLint texAttrib = glGetAttribLocation(*shaderProgram, "texcoord"); glEnableVertexAttribArray(texAttrib); glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float))); // define texture glGenTextures(1, tex); glBindTexture(GL_TEXTURE_2D, *tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); return 0; }
// APPLICATION ENTRY // ----------------- int main() { int width = 1024; int height = 768; sim_ptr = NULL; int c = 0; GLFWmonitor** m = glfwGetMonitors(&c); // init glfwSetErrorCallback(error_callback); if(!glfwInit()) { printf("ERROR: cannot initialize GLFW.\n"); exit(EXIT_FAILURE); } // glfwWindowHint(GLFW_DEPTH_BITS, 16); glfwWindowHint(GLFW_SAMPLES, 4);; #if defined(ROXLU_GL_CORE3) glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, 1); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #endif GLFWwindow* window = glfwCreateWindow(width, height, "Simulation", NULL, NULL); if(!window) { printf("ERROR: cannot open window.\n"); exit(EXIT_FAILURE); } glfwSetWindowSizeCallback(window, window_size_callback); glfwSetWindowCloseCallback(window, window_close_callback); glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetCursorPosCallback(window, cursor_callback); glfwSetScrollCallback(window, scroll_callback); glfwSetKeyCallback(window, key_callback); glfwSetCharCallback(window, char_callback); glfwMakeContextCurrent(window); #if defined(ROXLU_GL_CORE3) if(glxwInit() != 0) { printf("ERROR: cannot init glxw\n"); return EXIT_FAILURE; } #else glewExperimental = true; GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err)); exit(EXIT_FAILURE); } #endif Simulation sim; sim_ptr = ∼ sim.window = window; sim.window_w = width; sim.window_h = height; sim.setup(); bool running = true; while(running) { glfwPollEvents(); sim.update(); sim.draw(); glfwSwapBuffers(window); running = !(glfwGetKey(window, GLFW_KEY_ESC)); } glfwTerminate(); return EXIT_SUCCESS; };
// ------------------------------------------------------------------- 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 typedef struct { float x,y,z; } xyz; typedef struct { float r,g,b,a; } rgba; typedef struct { xyz position, normal; rgba color; } vertex; xyz v[] = { { 1, 1, 1}, {-1, 1, 1}, {-1,-1, 1}, { 1,-1, 1}, { 1,-1,-1}, { 1, 1,-1}, {-1, 1,-1}, {-1,-1,-1} }; xyz n[] = { { 0, 0, 1}, { 1, 0, 0}, { 0, 1, 0} , {-1, 0, 1}, { 0,-1, 0}, { 0, 0,-1} }; rgba c[] = { {1, 1, 1, 1}, {1, 1, 0, 1}, {1, 0, 1, 1}, {0, 1, 1, 1}, {1, 0, 0, 1}, {0, 0, 1, 1}, {0, 1, 0, 1}, {0, 0, 0, 1} }; vertex vertices[24] = { {v[0],n[0],c[0]}, {v[1],n[0],c[1]}, {v[2],n[0],c[2]}, {v[3],n[0],c[3]}, {v[0],n[1],c[0]}, {v[3],n[1],c[3]}, {v[4],n[1],c[4]}, {v[5],n[1],c[5]}, {v[0],n[2],c[0]}, {v[5],n[2],c[5]}, {v[6],n[2],c[6]}, {v[1],n[2],c[1]}, {v[1],n[3],c[1]}, {v[6],n[3],c[6]}, {v[7],n[3],c[7]}, {v[2],n[3],c[2]}, {v[7],n[4],c[7]}, {v[4],n[4],c[4]}, {v[3],n[4],c[3]}, {v[2],n[4],c[2]}, {v[4],n[5],c[4]}, {v[7],n[5],c[7]}, {v[6],n[5],c[6]}, {v[5],n[5],c[5]} }; GLuint indices[24] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11, 12,13,14,15, 16,17,18,19, 20,21,22,23 }; cube = vertex_buffer_new( "vertex:3f,normal:3f,color:4f" ); vertex_buffer_push_back( cube, vertices, 24, indices, 24 ); shader = shader_load("shaders/cube.vert","shaders/cube.frag"); init( ); glfwSetWindowSize( window, 400, 400 ); glfwShowWindow( window ); glfwSetTime(0.0); while(!glfwWindowShouldClose( window )) { display( window ); glfwPollEvents( ); } glfwDestroyWindow( window ); glfwTerminate( ); return EXIT_SUCCESS; }
int main(void) { GLFWwindow* window; GLuint vertex_buffer, vertex_shader, fragment_shader, program; GLint mvp_location, vpos_location, vcol_location; glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); glfwSwapInterval(1); // NOTE: OpenGL error checks have been omitted for brevity glGenBuffers(1, &vertex_buffer); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL); glCompileShader(vertex_shader); fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL); glCompileShader(fragment_shader); program = glCreateProgram(); glAttachShader(program, vertex_shader); glAttachShader(program, fragment_shader); glLinkProgram(program); mvp_location = glGetUniformLocation(program, "MVP"); vpos_location = glGetAttribLocation(program, "vPos"); vcol_location = glGetAttribLocation(program, "vCol"); glEnableVertexAttribArray(vpos_location); glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE, sizeof(vertices[0]), (void*) 0); glEnableVertexAttribArray(vcol_location); glVertexAttribPointer(vcol_location, 3, GL_FLOAT, GL_FALSE, sizeof(vertices[0]), (void*) (sizeof(float) * 2)); while (!glfwWindowShouldClose(window)) { float ratio; int width, height; mat4x4 m, p, mvp; glfwGetFramebufferSize(window, &width, &height); ratio = width / (float) height; glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT); mat4x4_identity(m); mat4x4_rotate_Z(m, m, (float) glfwGetTime()); mat4x4_ortho(p, -ratio, ratio, -1.f, 1.f, 1.f, -1.f); mat4x4_mul(mvp, p, m); glUseProgram(program); glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp); glDrawArrays(GL_TRIANGLES, 0, 3); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); }
// 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 shader("parallax_mapping.vs", "parallax_mapping.frag"); // Load textures GLuint diffuseMap = loadTexture(FileSystem::getPath("resources/textures/bricks2.jpg").c_str()); GLuint normalMap = loadTexture(FileSystem::getPath("resources/textures/bricks2_normal.jpg").c_str()); GLuint heightMap = loadTexture(FileSystem::getPath("resources/textures/bricks2_disp.jpg").c_str()); //GLuint diffuseMap = loadTexture(FileSystem::getPath("resources/textures/wood.png").c_str(); //GLuint normalMap = loadTexture(FileSystem::getPath("resources/textures/toy_box_normal.png").c_str()); //GLuint heightMap = loadTexture(FileSystem::getPath("resources/textures/toy_box_disp.png").c_str()); // Set texture units shader.Use(); glUniform1i(glGetUniformLocation(shader.Program, "diffuseMap"), 0); glUniform1i(glGetUniformLocation(shader.Program, "normalMap"), 1); glUniform1i(glGetUniformLocation(shader.Program, "depthMap"), 2); // Light position glm::vec3 lightPos(0.5f, 1.0f, 0.3f); // 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); // Configure view/projection matrices shader.Use(); glm::mat4 view = camera.GetViewMatrix(); glm::mat4 projection = glm::perspective(camera.Zoom, (GLfloat)SCR_WIDTH / (GLfloat)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)); // Render normal-mapped quad glm::mat4 model; //model = glm::rotate(model, (GLfloat)glfwGetTime() * -10, glm::normalize(glm::vec3(1.0, 0.0, 1.0))); // Rotates the quad to show parallax mapping works in all directions glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glUniform3fv(glGetUniformLocation(shader.Program, "lightPos"), 1, &lightPos[0]); glUniform3fv(glGetUniformLocation(shader.Program, "viewPos"), 1, &camera.Position[0]); glUniform1f(glGetUniformLocation(shader.Program, "height_scale"), height_scale); glUniform1i(glGetUniformLocation(shader.Program, "parallax"), parallax_mapping); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, diffuseMap); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, normalMap); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, heightMap); RenderQuad(); // render light source (simply renders a smaller plane at the light's position for debugging/visualization) model = glm::mat4(); model = glm::translate(model, lightPos); model = glm::scale(model, glm::vec3(0.1f)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); //RenderQuad(); // Swap the buffers glfwSwapBuffers(window); } glfwTerminate(); return 0; }
int main() { GLFWwindow* window; struct DemoData data; struct NVGcontext* vg = NULL; struct GPUtimer gpuTimer; struct PerfGraph fps, cpuGraph, gpuGraph; double prevt = 0, cpuTime = 0; if (!glfwInit()) { printf("Failed to init GLFW."); return -1; } initGraph(&fps, GRAPH_RENDER_FPS, "Frame Time"); initGraph(&cpuGraph, GRAPH_RENDER_MS, "CPU Time"); initGraph(&gpuGraph, GRAPH_RENDER_MS, "GPU Time"); glfwSetErrorCallback(errorcb); #ifndef _WIN32 // don't require this on win32, and works with more cards 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); #endif #ifdef DEMO_MSAA glfwWindowHint(GLFW_SAMPLES, 4); #endif window = glfwCreateWindow(1000, 600, "NanoVG", NULL, NULL); // window = glfwCreateWindow(1000, 600, "NanoVG", glfwGetPrimaryMonitor(), NULL); if (!window) { glfwTerminate(); return -1; } glfwSetKeyCallback(window, key); glfwMakeContextCurrent(window); #ifdef NANOVG_GLEW glewExperimental = GL_TRUE; if(glewInit() != GLEW_OK) { printf("Could not init glew.\n"); return -1; } #endif #ifdef DEMO_MSAA vg = nvgCreateGL3(512, 512, 0); #else vg = nvgCreateGL3(512, 512, NVG_ANTIALIAS); #endif if (vg == NULL) { printf("Could not init nanovg.\n"); return -1; } if (loadDemoData(vg, &data) == -1) return -1; glfwSwapInterval(0); initGPUTimer(&gpuTimer); glfwSetTime(0); prevt = glfwGetTime(); while (!glfwWindowShouldClose(window)) { double mx, my, t, dt; int winWidth, winHeight; int fbWidth, fbHeight; float pxRatio; float gpuTimes[3]; int i, n; t = glfwGetTime(); dt = t - prevt; prevt = t; startGPUTimer(&gpuTimer); glfwGetCursorPos(window, &mx, &my); glfwGetWindowSize(window, &winWidth, &winHeight); glfwGetFramebufferSize(window, &fbWidth, &fbHeight); // Calculate pixel ration for hi-dpi devices. pxRatio = (float)fbWidth / (float)winWidth; // Update and render glViewport(0, 0, fbWidth, fbHeight); glClearColor(0.3f, 0.3f, 0.32f, 1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); nvgBeginFrame(vg, winWidth, winHeight, pxRatio); renderDemo(vg, mx,my, winWidth,winHeight, t, blowup, &data); renderGraph(vg, 5,5, &fps); renderGraph(vg, 5+200+5,5, &cpuGraph); if (gpuTimer.supported) renderGraph(vg, 5+200+5+200+5,5, &gpuGraph); nvgEndFrame(vg); glEnable(GL_DEPTH_TEST); // Measure the CPU time taken excluding swap buffers (as the swap may wait for GPU) cpuTime = glfwGetTime() - t; updateGraph(&fps, dt); updateGraph(&cpuGraph, cpuTime); // We may get multiple results. n = stopGPUTimer(&gpuTimer, gpuTimes, 3); for (i = 0; i < n; i++) updateGraph(&gpuGraph, gpuTimes[i]); glfwSwapBuffers(window); glfwPollEvents(); } freeDemoData(vg, &data); nvgDeleteGL3(vg); printf("Average Frame Time: %.2f ms\n", getGraphAverage(&fps) * 1000.0f); printf(" CPU Time: %.2f ms\n", getGraphAverage(&cpuGraph) * 1000.0f); printf(" GPU Time: %.2f ms\n", getGraphAverage(&gpuGraph) * 1000.0f); glfwTerminate(); return 0; }
void setup(int argc, char** argv) { size_t filenameidx = 1; for(size_t i = 1; i < argc; ++i) { if(!strcmp(argv[i], "--")) { filenameidx = i+1; break; } if(!strcmp(argv[i], "--width")) { if(argc == i+1) FATAL("%s: expected argument after %s\n", argv[0], argv[i]); width = strtol(argv[i+1], NULL, 0); ++i; continue; } if(!strcmp(argv[i], "--height")) { if(argc == i+1) FATAL("%s: expected argument after %s\n", argv[0], argv[i]); height = strtol(argv[i+1], NULL, 0); ++i; continue; } if(!strcmp(argv[i], "--interval")) { if(argc == i+1) FATAL("%s: expected argument after %s\n", argv[0], argv[i]); interval = strtol(argv[i+1], NULL, 0); ++i; continue; } if(!strcmp(argv[i], "--fullscreen")) { fullscreen = true; continue; } if(!strcmp(argv[i], "--device") || !strcmp(argv[i], "--buffer-size") || !strcmp(argv[i], "--period-size") || !strcmp(argv[i], "--rate") || !strcmp(argv[i], "--format")) { ++i; continue; } filenameidx = i; break; } if(filenameidx+1 != argc) { usage(argv[0]); exit(1); } glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow(width, height, argv[0], fullscreen ? glfwGetPrimaryMonitor() : NULL, NULL); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); glfwMakeContextCurrent(window); glfwSwapInterval(interval); printf("Using GL renderer: %s %s\n", glGetString(GL_VENDOR), glGetString(GL_RENDERER)); glGenBuffers(1, &vertexn); glBindBuffer(GL_ARRAY_BUFFER, vertexn); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glGenBuffers(1, &elementn); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementn); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glGenVertexArrays(1, &varrayn); glBindVertexArray(varrayn); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0); /* XXX: wtf? */ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementn); GLuint vsn, fsn; const char* src; GLint status; progn = glCreateProgram(); #include "vs.h" src = vs; vsn = glCreateShader(GL_VERTEX_SHADER); glAttachShader(progn, vsn); glShaderSource(vsn, 1, &src, NULL); glCompileShader(vsn); glGetShaderiv(vsn, GL_COMPILE_STATUS, &status); if(status != GL_TRUE) { char msg[1024]; glGetShaderInfoLog(vsn, 1024, NULL, msg); fprintf(stderr, "VS:%s", msg); exit(1); } #include "fs.h" src = fs; fsn = glCreateShader(GL_FRAGMENT_SHADER); glAttachShader(progn, fsn); glShaderSource(fsn, 1, &src, NULL); glCompileShader(fsn); glGetShaderiv(fsn, GL_COMPILE_STATUS, &status); if(status != GL_TRUE) { char msg[1024]; glGetShaderInfoLog(fsn, 1024, NULL, msg); fprintf(stderr, "FS:%s", msg); exit(1); } glLinkProgram(progn); glGetProgramiv(progn, GL_LINK_STATUS, &status); if(status != GL_TRUE) { char msg[1024]; glGetProgramInfoLog(progn, 1024, NULL, msg); fprintf(stderr, "PROG:%s", msg); exit(1); } xmdatau = glGetUniformLocation(progn, "xmdata"); glUseProgram(progn); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); init_alsa_device(argc, argv, 64, 2048, SND_PCM_NONBLOCK, &device, &period_size, &rate, &format); create_context_from_file(&xmctx, rate, argv[filenameidx]); if(xmctx == NULL) exit(1); xm_set_max_loop_count(xmctx, 1); channels = xm_get_number_of_channels(xmctx); instruments = xm_get_number_of_instruments(xmctx); CHECK_ALSA_CALL(snd_pcm_prepare(device)); }
Screen::Screen(const Vector2i &size, const std::string &caption, bool resizable, bool fullscreen) : Widget(nullptr), mGLFWWindow(nullptr), mNVGContext(nullptr), mCursor(Cursor::Arrow), mCaption(caption) { memset(mCursors, 0, sizeof(GLFWcursor *) * (int) Cursor::CursorCount); /* Request a forward compatible OpenGL 3.3 core profile context */ glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); /* Request a RGBA8 buffer without MSAA */ glfwWindowHint(GLFW_SAMPLES, 0); 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, 24); glfwWindowHint(GLFW_VISIBLE, GL_FALSE); glfwWindowHint(GLFW_RESIZABLE, resizable ? GL_TRUE : GL_FALSE); if (fullscreen) { GLFWmonitor *monitor = glfwGetPrimaryMonitor(); const GLFWvidmode *mode = glfwGetVideoMode(monitor); mGLFWWindow = glfwCreateWindow(mode->width, mode->height, caption.c_str(), monitor, nullptr); } else { mGLFWWindow = glfwCreateWindow(size.x(), size.y(), caption.c_str(), nullptr, nullptr); } if (!mGLFWWindow) throw std::runtime_error("Could not create an OpenGL 3.3 context!"); glfwMakeContextCurrent(mGLFWWindow); #if defined(_WIN32) if (!glewInitialized) { glewExperimental = GL_TRUE; glewInitialized = true; if (glewInit() != GLEW_NO_ERROR) throw std::runtime_error("Could not initialize GLEW!"); glGetError(); // pull and ignore unhandled errors like GL_INVALID_ENUM } #endif glfwGetFramebufferSize(mGLFWWindow, &mFBSize[0], &mFBSize[1]); glViewport(0, 0, mFBSize[0], mFBSize[1]); glClearColor(mBackground[0], mBackground[1], mBackground[2], 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glfwSwapInterval(0); glfwSwapBuffers(mGLFWWindow); #if defined(__APPLE__) /* Poll for events once before starting a potentially lengthy loading process. This is needed to be classified as "interactive" by other software such as iTerm2 */ glfwPollEvents(); #endif /* Propagate GLFW events to the appropriate Screen instance */ glfwSetCursorPosCallback(mGLFWWindow, [](GLFWwindow *w,double x,double y) { auto it = __nanogui_screens.find(w); if (it == __nanogui_screens.end()) return; Screen *s = it->second; if (!s->mProcessEvents) return; s->cursorPosCallbackEvent(x, y); } ); glfwSetMouseButtonCallback(mGLFWWindow, [](GLFWwindow *w, int button, int action, int modifiers) { auto it = __nanogui_screens.find(w); if (it == __nanogui_screens.end()) return; Screen *s = it->second; if (!s->mProcessEvents) return; s->mouseButtonCallbackEvent(button, action, modifiers); } ); glfwSetKeyCallback(mGLFWWindow, [](GLFWwindow *w, int key, int scancode, int action, int mods) { auto it = __nanogui_screens.find(w); if (it == __nanogui_screens.end()) return; Screen *s = it->second; if (!s->mProcessEvents) return; s->keyCallbackEvent(key, scancode, action, mods); } ); glfwSetCharCallback(mGLFWWindow, [](GLFWwindow *w, unsigned int codepoint) { auto it = __nanogui_screens.find(w); if (it == __nanogui_screens.end()) return; Screen *s = it->second; if (!s->mProcessEvents) return; s->charCallbackEvent(codepoint); } ); glfwSetDropCallback(mGLFWWindow, [](GLFWwindow *w,int count,const char **filenames) { auto it = __nanogui_screens.find(w); if (it == __nanogui_screens.end()) return; Screen *s = it->second; if (!s->mProcessEvents) return; s->dropCallbackEvent(count, filenames); } ); glfwSetScrollCallback(mGLFWWindow, [](GLFWwindow *w, double x, double y) { auto it = __nanogui_screens.find(w); if (it == __nanogui_screens.end()) return; Screen *s = it->second; if (!s->mProcessEvents) return; s->scrollCallbackEvent(x, y); } ); initialize(mGLFWWindow); }
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 PBO(asynchronous DMA transfer)", NULL, NULL); if (!window) { std::cout << "Error::GLFW could not create winddow!" << std::endl; glfwTerminate(); return -1; } glfwSetWindowPos(window, 300, 100); // 创建的窗口的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(); return -1; } // 设置视口参数 glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); // Section1 准备顶点数据 setupQuadVAO(); preparePBO(); initColorBuffer(); // Section2 加载字体 FontResourceManager::getInstance().loadFont("arial", "../../resources/fonts/arial.ttf"); FontResourceManager::getInstance().loadASCIIChar("arial", 38, unicodeCharacters); // Section3 加载纹理 cubeTextId = TextureHelper::load2DTexture("../../resources/textures/wood.png"); initPixelText(); // Section4 准备着色器程序 Shader shader("scene.vertex", "scene.frag"); Shader textShader("text.vertex", "text.frag"); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // 开始游戏主循环 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); glm::mat4 projection; glm::mat4 view; glm::mat4 model; // 这里填写场景绘制代码 // 先绘制纹理图片 shader.use(); glUniformMatrix4fv(glGetUniformLocation(shader.programId, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(shader.programId, "view"), 1, GL_FALSE, glm::value_ptr(view)); model = glm::mat4(); glUniformMatrix4fv(glGetUniformLocation(shader.programId, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!isFirstRendered) { renderInitScene(shader); isFirstRendered = true; } else { renderScene(shader); } // 在右侧绘制信息文字 否则左侧文字会复制到右侧 textShader.use(); projection = glm::ortho(0.0f, (GLfloat)(SINGLE_SCREEN_WIDTH), 0.0f, (GLfloat)SINGLE_SCREEN_HEIGHT); view = glm::mat4(); glUniformMatrix4fv(glGetUniformLocation(textShader.programId, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(textShader.programId, "view"), 1, GL_FALSE, glm::value_ptr(view)); model = glm::mat4(); glUniformMatrix4fv(glGetUniformLocation(textShader.programId, "model"), 1, GL_FALSE, glm::value_ptr(model)); renderInfo(textShader); printTransferRate(); glBindVertexArray(0); glUseProgram(0); glfwSwapBuffers(window); // 交换缓存 } // 释放资源 glDeleteVertexArrays(1, &quadVAOId); glDeleteBuffers(1, &quadVBOId); glDeleteVertexArrays(1, &textVAOId); glDeleteBuffers(1, &textVBOId); glDeleteBuffers(2, PBOIds); // 注意释放PBO releaseColorBuffer(); 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); // 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); // 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); // Build and compile our shader program Shader ourShader("transform.vs", "transform.frag"); // Set up vertex data (and buffer(s)) and attribute pointers GLfloat vertices[] = { // Positions // Colors // Texture Coords 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // Top Right 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Bottom Right -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Left -0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // Top Left }; GLuint indices[] = { // Note that we start from 0! 0, 1, 3, // First Triangle 1, 2, 3 // Second Triangle }; GLuint 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, 8 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // Color attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); // TexCoord attribute glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); glEnableVertexAttribArray(2); glBindVertexArray(0); // Unbind VAO // Load and create a texture GLuint texture1; GLuint texture2; // ==================== // Texture 1 // ==================== glGenTextures(1, &texture1); glBindTexture(GL_TEXTURE_2D, texture1); // All upcoming GL_TEXTURE_2D operations now have effect on our texture object // Set our texture parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture wrapping to GL_REPEAT glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Load, create texture and generate mipmaps int width, height; unsigned char* image = SOIL_load_image("../../../resources/textures/container.jpg", &width, &height, 0, SOIL_LOAD_RGB); 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); glBindTexture(GL_TEXTURE_2D, 0); // Unbind texture when done, so we won't accidentily mess up our texture. // =================== // Texture 2 // =================== glGenTextures(1, &texture2); glBindTexture(GL_TEXTURE_2D, texture2); // Set our texture parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Load, create texture and generate mipmaps image = SOIL_load_image("../../../resources/textures/awesomeface.png", &width, &height, 0, SOIL_LOAD_RGB); 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); glBindTexture(GL_TEXTURE_2D, 0); // Game loop while (!glfwWindowShouldClose(window)) { // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions glfwPollEvents(); // Render // Clear the colorbuffer glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Bind Textures using texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glUniform1i(glGetUniformLocation(ourShader.Program, "ourTexture1"), 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); glUniform1i(glGetUniformLocation(ourShader.Program, "ourTexture2"), 1); // Activate shader ourShader.Use(); // Create transformations glm::mat4 transform; // 先平移 (0.5f, -0.5f, 0.0f); 注意,当前是normalized device coordinate。 GLuint time = (GLuint)glfwGetTime(); GLuint transFlag = time & 0x3; transform = glm::translate(transform, glm::vec3((GLfloat)transFlag*0.2f, - (GLfloat)transFlag*0.1f, 0.0f)); // 利用时间信息rotate,这是角度。最后一个参数是沿着什么方向rotate,这里是z 轴。 transform = glm::rotate(transform, (GLfloat)glfwGetTime() * 50.0f, glm::vec3(0.0f, 0.0f, 1.0f)); // Get matrix's uniform location and set matrix // 获取shader 中uniform 的变量 GLint transformLoc = glGetUniformLocation(ourShader.Program, "transform"); // 将transform 矩阵复制到uniform 变量上。 glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(transform)); // Draw container glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glBindVertexArray(0); // Swap the screen buffers glfwSwapBuffers(window); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; }
Window::Window(CString name, uint32 width, uint32 height) { // Initialize GLFW if this is the first window created if (!GLFWInitialized) { if (!glfwInit()) { Console::Error("GLFW could not be initialized."); Application::Terminate(EXIT_FAILURE); } else { // Indicate that GLFW has been initialized, and add deinitialize function to run at program exit GLFWInitialized = true; std::atexit([] { glfwTerminate(); }); } } // Get the primary monitor auto monitor = glfwGetPrimaryMonitor(); if (!monitor) { Console::WriteLine("GLFW failed to get primary monitor."); Application::Terminate(EXIT_FAILURE); } // Get the primary monitor's video mode auto videoMode = glfwGetVideoMode(monitor); if (!videoMode) { Console::WriteLine("GLFW failed to get primary monitor video mode."); Application::Terminate(EXIT_FAILURE); } // Set the new window to be invisible glfwWindowHint(GLFW_VISIBLE, false); // Set the OpenGL context to version 4.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // Create the window this->_window = glfwCreateWindow(width, height, name, nullptr, nullptr); if (!_window) { Console::WriteLine("GLFW failed to create window."); Application::Terminate(EXIT_FAILURE); } // Register this window with the window table WindowTable[this->_window] = this; // Set the window gain/lose focus function glfwSetWindowFocusCallback(this->_window, [](GLFWwindow* window, int hasFocus) { // Reset the cursor position if the window has gained focus if (hasFocus) { WindowTable[window]->center_cursor(); } }); // Center the window in the screen int32 centerX = (videoMode->width - this->get_width()) / 2; int32 centerY = (videoMode->height - this->get_height()) / 2; glfwSetWindowPos(this->_window, centerX, centerY); // Make the window visible glfwShowWindow(this->_window); // Make the cursor invisible and move it to the center of the window glfwSetInputMode(this->_window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); glfwSetCursorPos(this->_window, this->get_width() / 2, this->get_height() / 2); // Make an OpenGL context in window glfwMakeContextCurrent(this->_window); }
// The MAIN function, from here we start our application and run our Game loop int main() { // Init GLFW glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); 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); //glEnable(GL_FRAMEBUFFER_SRGB); // This enables OpenGL's built-in sRGB support. Once enabled, all subsequent fragment outputs (into framebuffer's color buffer(s)) are first gamma corrected. // Setup and compile our shaders Shader shader("gamma_correction.vs", "gamma_correction.frag"); GLfloat planeVertices[] = { // Positions // Normals // Texture Coords 5.0f, -0.5f, 5.0f, 0.0f, 1.0f, 0.0f, 5.0f, 0.0f, -5.0f, -0.5f, 5.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -5.0f, -0.5f, -5.0f, 0.0f, 1.0f, 0.0f, 0.0f, 5.0f, 5.0f, -0.5f, 5.0f, 0.0f, 1.0f, 0.0f, 5.0f, 0.0f, -5.0f, -0.5f, -5.0f, 0.0f, 1.0f, 0.0f, 0.0f, 5.0f, 5.0f, -0.5f, -5.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 sources 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) }; // Load textures GLuint floorTexture = loadTexture(FileSystem::getPath("resources/textures/wood.png").c_str(), false); GLuint floorTextureGammaCorrected = loadTexture(FileSystem::getPath("resources/textures/wood.png").c_str(), true); // 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, "lightPositions"), 4, &lightPositions[0][0]); glUniform3fv(glGetUniformLocation(shader.Program, "lightColors"), 4, &lightColors[0][0]); glUniform3fv(glGetUniformLocation(shader.Program, "viewPos"), 1, &camera.Position[0]); glUniform1i(glGetUniformLocation(shader.Program, "gamma"), gammaEnabled); // Floor glBindVertexArray(planeVAO); glBindTexture(GL_TEXTURE_2D, gammaEnabled ? floorTextureGammaCorrected : floorTexture); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); std::cout << (gammaEnabled ? "Gamma enabled" : "Gamma disabled") << std::endl; // Swap the buffers glfwSwapBuffers(window); } glfwTerminate(); return 0; }
void call(int target, int hint) { glfwWindowHint(target, hint); }
// The MAIN function, from here we start our application and run our Game loop int main() { if(!glfwInit()){ return -1; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); auto window = glfwCreateWindow(WIDTH, HEIGHT, "Cube maps", nullptr, nullptr); if (nullptr == window) { std::cout << "Failed to create GLFW windows" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); int actualWidth; int actualHeight; glfwGetFramebufferSize(window, &actualWidth, &actualHeight); glViewport(0, 0, actualWidth, actualHeight); // 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); // Setup some OpenGL options glEnable(GL_DEPTH_TEST); // Setup and compile our shaders Shader shader("vertex.vsh", "fragment.fsh"); // Load models Model nanosuit("nanosuit/nanosuit.obj"); vector<const GLchar*> faces; faces.push_back("right.jpg"); faces.push_back("left.jpg"); faces.push_back("top.jpg"); faces.push_back("bottom.jpg"); faces.push_back("back.jpg"); faces.push_back("front.jpg"); GLuint cubemapTexture = loadCubemap(faces); GLfloat skyboxVertices[] = { // Positions -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f }; GLuint skyboxVAO; glGenVertexArrays(1, &skyboxVAO); glBindVertexArray(skyboxVAO); GLuint skyboxVBO; glGenBuffers(1, &skyboxVBO); glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), &skyboxVertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glBindVertexArray(0); Shader skyboxShader("skybox.vsh", "skybox.fsh"); // 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); // Draw scene as normal shader.Use(); 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 glm::mat4 view = camera.GetViewMatrix(); glm::mat4 projection = glm::perspective(camera.Zoom, (float)screenWidth/(float)screenHeight, 0.1f, 100.0f); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniform3f(glGetUniformLocation(shader.Program, "cameraPos"), camera.Position.x, camera.Position.y, camera.Position.z); glActiveTexture(GL_TEXTURE3); // We already have 3 texture units active (in this shader) so set the skybox as the 4th texture unit (texture units are 0 based so index number 3) glUniform1i(glGetUniformLocation(shader.Program, "skybox"), 3); // Now draw the nanosuit glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture); nanosuit.Draw(shader); glDepthFunc(GL_LEQUAL); skyboxShader.Use(); // Transformation matrices glUniformMatrix4fv(glGetUniformLocation(skyboxShader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); view = glm::mat4(glm::mat3(camera.GetViewMatrix())); glUniformMatrix4fv(glGetUniformLocation(skyboxShader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); 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); // 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, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // 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); // 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 int width, height; glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); // Build and compile our shader program Shader ourShader("basic.vs", "basic.frag"); // Set up vertex data (and buffer(s)) and attribute pointers GLfloat vertices[] = { // Positions // Colors 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Right -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // Bottom Left 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f // Top }; GLuint VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // 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 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // Color attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glBindVertexArray(0); // Unbind VAO // Game loop while (!glfwWindowShouldClose(window)) { // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions glfwPollEvents(); // Render // Clear the colorbuffer glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Draw the triangle ourShader.Use(); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); // Swap the screen buffers glfwSwapBuffers(window); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; }
// The MAIN function, from here we start our application and run our Game loop int main() { if(!glfwInit()){ return -1; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); auto window = glfwCreateWindow(screenWidth, screenHeight, "Depth Testing", nullptr, nullptr); if (nullptr == window) { std::cout << "Failed to create GLFW windows" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); int actualWidth; int actualHeight; glfwGetFramebufferSize(window, &actualWidth, &actualHeight); glViewport(0, 0, actualWidth, actualHeight); // 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); // 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)) // Setup and compile our shaders GLuint shaderProgram = createShaderProgramWithFilenames("vertex.vsh", "fragment.fsh"); // 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 planeVertices[] = { // 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 }; // 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 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(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glBindVertexArray(0); // Load textures GLuint cubeTexture = loadTexture("marble.jpg"); GLuint floorTexture = loadTexture("metal.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 glUseProgram(shaderProgram); 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(shaderProgram, "view"), 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); // Cubes glBindVertexArray(cubeVAO); // We omit the glActiveTexture part since TEXTURE0 is already the default active texture unit. (sampler used in fragment is set to 0 as well as default) glBindTexture(GL_TEXTURE_2D, cubeTexture); model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f)); glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "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(shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); // Floor glBindVertexArray(planeVAO); glBindTexture(GL_TEXTURE_2D, floorTexture); model = glm::mat4(); glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); // Swap the buffers glfwSwapBuffers(window); } glfwTerminate(); return 0; }
int main() { 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(800, 600, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, keyCallback); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cout << "Failed to initialize GLEW" << std::endl; return -1; } int framebufferWidth, framebufferHeight; glfwGetFramebufferSize(window, &framebufferWidth, &framebufferHeight); glViewport(0, 0, framebufferWidth, framebufferHeight); // Create, Compile, and Validate Vertex Shader GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glCompileShader(vertexShader); GLint success; GLchar infoLog[512]; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if(!success) { glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::__1::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::__1::endl; } // Create, Compile, and Validate Fragment Shader GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSourceOne, NULL); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if(!success) { glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog); std::__1::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::__1::endl; } // Create, Link Shaders, and Validate Shader Program GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if(!success) { glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog); std::__1::cout << "ERROR::SHADER::PROGRAM::LINKAGE_FAILED\n" << infoLog << std::__1::endl; } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); GLuint vertexArrayObject[2], vertexBufferObject[2]; GLfloat vertices1[] = { // Triangle 1 -1.0f, -0.5f, 0.0f, // Left-Point 0.0f, -0.5f, 0.0f, // Center -0.5f, 0.5f, 0.0f // Left-Top }; GLfloat vertices2[] = { // Triangle 2 1.0f, -0.5f, 0.0f, // Right-Point 0.0f, -0.5f, 0.0f, // Center 0.5f, 0.5f, 0.0f // Right-Top }; glGenVertexArrays(2, vertexArrayObject); glGenBuffers(2, vertexBufferObject); // ROUND 1 // Bind Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s). glBindVertexArray(vertexArrayObject[0]); // Copy triangleVertices array in a buffer for OpenGL to use glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices1), vertices1, GL_STATIC_DRAW); // Set our vertex attributes pointers glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); // Unbind the Vertex Array Object; glBindVertexArray(0); // ROUND 2 glBindVertexArray(vertexArrayObject[1]); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject[1]); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices2), vertices2, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); while(!glfwWindowShouldClose(window)) { glfwPollEvents(); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(shaderProgram); glBindVertexArray(vertexArrayObject[0]); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); glBindVertexArray(vertexArrayObject[1]); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); glfwSwapBuffers(window); } glDeleteVertexArrays(2, vertexArrayObject); glDeleteBuffers(2, vertexBufferObject); 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); // 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("ourTexture", 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); shader.setMat4("view", view); shader.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)); shader.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)); shader.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; }
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); // 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); glDepthFunc(GL_LEQUAL); // set depth function to less than AND equal for skybox depth trick. // build and compile shaders // ------------------------- Shader pbrShader("2.1.2.pbr.vs", "2.1.2.pbr.fs"); Shader equirectangularToCubemapShader("2.1.2.cubemap.vs", "2.1.2.equirectangular_to_cubemap.fs"); Shader irradianceShader("2.1.2.cubemap.vs", "2.1.2.irradiance_convolution.fs"); Shader backgroundShader("2.1.2.background.vs", "2.1.2.background.fs"); pbrShader.use(); pbrShader.setInt("irradianceMap", 0); pbrShader.setVec3("albedo", 0.5f, 0.0f, 0.0f); pbrShader.setFloat("ao", 1.0f); backgroundShader.use(); backgroundShader.setInt("environmentMap", 0); // 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; // pbr: setup framebuffer // ---------------------- unsigned int captureFBO; unsigned int captureRBO; glGenFramebuffers(1, &captureFBO); glGenRenderbuffers(1, &captureRBO); glBindFramebuffer(GL_FRAMEBUFFER, captureFBO); glBindRenderbuffer(GL_RENDERBUFFER, captureRBO); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, 512, 512); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, captureRBO); // pbr: load the HDR environment map // --------------------------------- stbi_set_flip_vertically_on_load(true); int width, height, nrComponents; float *data = stbi_loadf(FileSystem::getPath("resources/textures/hdr/newport_loft.hdr").c_str(), &width, &height, &nrComponents, 0); unsigned int hdrTexture; if (data) { glGenTextures(1, &hdrTexture); glBindTexture(GL_TEXTURE_2D, hdrTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, width, height, 0, GL_RGB, GL_FLOAT, data); // note how we specify the texture's data value to be float glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cout << "Failed to load HDR image." << std::endl; } // pbr: setup cubemap to render to and attach to framebuffer // --------------------------------------------------------- unsigned int envCubemap; glGenTextures(1, &envCubemap); glBindTexture(GL_TEXTURE_CUBE_MAP, envCubemap); for (unsigned int i = 0; i < 6; ++i) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB16F, 512, 512, 0, GL_RGB, GL_FLOAT, nullptr); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // pbr: set up projection and view matrices for capturing data onto the 6 cubemap face directions // ---------------------------------------------------------------------------------------------- glm::mat4 captureProjection = glm::perspective(glm::radians(90.0f), 1.0f, 0.1f, 10.0f); glm::mat4 captureViews[] = { glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)), glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)), glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)), glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f)), glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, -1.0f, 0.0f)), glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f), glm::vec3(0.0f, -1.0f, 0.0f)) }; // pbr: convert HDR equirectangular environment map to cubemap equivalent // ---------------------------------------------------------------------- equirectangularToCubemapShader.use(); equirectangularToCubemapShader.setInt("equirectangularMap", 0); equirectangularToCubemapShader.setMat4("projection", captureProjection); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, hdrTexture); glViewport(0, 0, 512, 512); // don't forget to configure the viewport to the capture dimensions. glBindFramebuffer(GL_FRAMEBUFFER, captureFBO); for (unsigned int i = 0; i < 6; ++i) { equirectangularToCubemapShader.setMat4("view", captureViews[i]); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, envCubemap, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); renderCube(); } glBindFramebuffer(GL_FRAMEBUFFER, 0); // pbr: create an irradiance cubemap, and re-scale capture FBO to irradiance scale. // -------------------------------------------------------------------------------- unsigned int irradianceMap; glGenTextures(1, &irradianceMap); glBindTexture(GL_TEXTURE_CUBE_MAP, irradianceMap); for (unsigned int i = 0; i < 6; ++i) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB16F, 32, 32, 0, GL_RGB, GL_FLOAT, nullptr); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindFramebuffer(GL_FRAMEBUFFER, captureFBO); glBindRenderbuffer(GL_RENDERBUFFER, captureRBO); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, 32, 32); // pbr: solve diffuse integral by convolution to create an irradiance (cube)map. // ----------------------------------------------------------------------------- irradianceShader.use(); irradianceShader.setInt("environmentMap", 0); irradianceShader.setMat4("projection", captureProjection); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, envCubemap); glViewport(0, 0, 32, 32); // don't forget to configure the viewport to the capture dimensions. glBindFramebuffer(GL_FRAMEBUFFER, captureFBO); for (unsigned int i = 0; i < 6; ++i) { irradianceShader.setMat4("view", captureViews[i]); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, irradianceMap, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); renderCube(); } glBindFramebuffer(GL_FRAMEBUFFER, 0); // initialize static shader uniforms before rendering // -------------------------------------------------- glm::mat4 projection = glm::perspective(camera.Zoom, (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); pbrShader.use(); pbrShader.setMat4("projection", projection); backgroundShader.use(); backgroundShader.setMat4("projection", projection); // then before rendering, configure the viewport to the original framebuffer's screen dimensions int scrWidth, scrHeight; glfwGetFramebufferSize(window, &scrWidth, &scrHeight); glViewport(0, 0, scrWidth, scrHeight); // 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); // render scene, supplying the convoluted irradiance map to the final shader. // ------------------------------------------------------------------------------------------ pbrShader.use(); glm::mat4 view = camera.GetViewMatrix(); pbrShader.setMat4("view", view); pbrShader.setVec3("camPos", camera.Position); // bind pre-computed IBL data glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, irradianceMap); // render rows*column number of spheres with material properties defined by textures (they all have the same material properties) glm::mat4 model; for (int row = 0; row < nrRows; ++row) { pbrShader.setFloat("metallic", (float)row / (float)nrRows); for (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. pbrShader.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, -2.0f )); pbrShader.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]; pbrShader.setVec3("lightPositions[" + std::to_string(i) + "]", newPos); pbrShader.setVec3("lightColors[" + std::to_string(i) + "]", lightColors[i]); model = glm::mat4(); model = glm::translate(model, newPos); model = glm::scale(model, glm::vec3(0.5f)); pbrShader.setMat4("model", model); renderSphere(); } // render skybox (render as last to prevent overdraw) backgroundShader.use(); backgroundShader.setMat4("view", view); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, envCubemap); //glBindTexture(GL_TEXTURE_CUBE_MAP, irradianceMap); // display irradiance map renderCube(); // 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; }
int main() { //Initialize GLFW glewExperimental = true; if (!glfwInit()) exit(EXIT_FAILURE); //Set the GLFW window creation hints - these are optional glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //Request a specific OpenGL version glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //Request a specific OpenGL version glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow(1024, 640, "Planet Raycasting", NULL, NULL); if (!window) { fprintf( stderr, "Failed to open GLFW window.\n" ); glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); GLenum err = glewInit(); if (err != GLEW_OK) { fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); return -1; } int width, height; glfwGetWindowSize(window, &width, &height); scene.init(width, height); glClearColor(0.45f, 0.6f, 0.73f, 1.0f); glDisable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); //Main Loop while(!glfwWindowShouldClose(window)) { static double lastTime = glfwGetTime(); double time = glfwGetTime(); double dt = time - lastTime; lastTime = time; float speed = (float)dt; dz = (float)(glfwGetKey(window, GLFW_KEY_W)==GLFW_PRESS) - (glfwGetKey(window, GLFW_KEY_S)==GLFW_PRESS); dx = (float)(glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) - (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS); if(glfwGetKey(window, GLFW_KEY_LEFT_SHIFT)==GLFW_PRESS) speed*=10.0f; if(glfwGetKey(window, GLFW_KEY_LEFT_CONTROL)==GLFW_PRESS) speed*=0.1f; scene.move(dx*speed, dy*speed, dz*speed); static bool mouseLocked = false; static double prevX, prevY; if(glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT)==GLFW_PRESS) { if(!mouseLocked) { mouseLocked = true; glfwGetCursorPos(window, &prevX, &prevY); } else { double mX, mY; glfwGetCursorPos(window, &mX, &mY); scene.rotate(float(mX - prevX)/width, float(mY - prevY)/height); prevX = mX; prevY = mY; } } else { mouseLocked = false; } scene.draw(); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); }
int main(int argc, char** argv) { int ch, width, height; float position; unsigned long frame_count = 0; double last_time, current_time; GLboolean fullscreen = GL_FALSE; GLFWmonitor* monitor = NULL; GLFWwindow* window; while ((ch = getopt(argc, argv, "fh")) != -1) { switch (ch) { case 'h': usage(); exit(EXIT_SUCCESS); case 'f': fullscreen = GL_TRUE; break; } } glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); if (fullscreen) { const GLFWvidmode* mode; monitor = glfwGetPrimaryMonitor(); 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, "", monitor, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); set_swap_interval(window, 0); last_time = glfwGetTime(); frame_rate = 0.0; swap_tear = (glfwExtensionSupported("WGL_EXT_swap_control_tear") || glfwExtensionSupported("GLX_EXT_swap_control_tear")); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetKeyCallback(window, key_callback); glMatrixMode(GL_PROJECTION); glOrtho(-1.f, 1.f, -1.f, 1.f, 1.f, -1.f); glMatrixMode(GL_MODELVIEW); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT); position = cosf((float) glfwGetTime() * 4.f) * 0.75f; glRectf(position - 0.25f, -1.f, position + 0.25f, 1.f); glfwSwapBuffers(window); glfwPollEvents(); frame_count++; current_time = glfwGetTime(); if (current_time - last_time > 1.0) { frame_rate = frame_count / (current_time - last_time); frame_count = 0; last_time = current_time; update_window_title(window); } } glfwTerminate(); exit(EXIT_SUCCESS); }