int main () { GLFWwindow* window = NULL; const GLubyte* renderer; const GLubyte* version; GLuint vao; GLuint vbo; GLuint colours_vbo; /* geometry to use. these are 3 xyz points (9 floats total) to make a triangle */ GLfloat points[] = { 0.0f, 0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.00f, 0.8f, 0.0f, -0.5f, -0.2f, 0.0f, 0.5f, -0.2f, 0.0f }; GLfloat colours[] = { 1.0f, 1.0f, 0.0f, //yellow rgb(255,255,0) 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, //red rgb(255,0,0) 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, }; /* these are the strings of code for the shaders the vertex shader positions each vertex point */ const char* vertex_shader = "#version 400\n" "layout(location = 0) in vec3 vertex_position;" "layout(location = 1) in vec3 vertex_colour;" "out vec3 color;" "uniform mat4 matrix;" "void main () {" " color = vertex_colour;" " gl_Position=matrix * vec4(vertex_position, 1.0);" "}"; /* the fragment shader colours each fragment (pixel-sized area of the triangle) */ const char* fragment_shader = "#version 400\n" "in vec3 color;" "out vec4 frag_colour;" "void main () {" " frag_colour = vec4 (color, 1.0);" "}"; /* GL shader objects for vertex and fragment shader [components] */ GLuint vs, fs; /* GL shader programme object [combined, to link] */ GLuint shader_programme; /* start GL context and O/S window using the GLFW helper library */ if (!glfwInit ()) { fprintf (stderr, "ERROR: could not start GLFW3\n"); return 1; } /* change to 3.2 if on Apple OS X */ glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow ( 640, 480, "Hello Triangle", NULL, NULL ); if (!window) { fprintf (stderr, "ERROR: could not open window with GLFW3\n"); glfwTerminate(); return 1; } glfwMakeContextCurrent (window); /* start GLEW extension handler */ glewExperimental = GL_TRUE; glewInit (); /* get version info */ renderer = glGetString (GL_RENDERER); /* get renderer string */ version = glGetString (GL_VERSION); /* version as a string */ printf ("Renderer: %s\n", renderer); printf ("OpenGL version supported %s\n", version); /* tell GL to only draw onto a pixel if the shape is closer to the viewer */ glEnable (GL_DEPTH_TEST); /* enable depth-testing */ glDepthFunc (GL_LESS);/*depth-testing interprets a smaller value as "closer"*/ /* a vertex buffer object (VBO) is created here. this stores an array of data on the graphics adapter's memory. in our case - the vertex points */ glGenBuffers (1, &vbo); glBindBuffer (GL_ARRAY_BUFFER, vbo); glBufferData (GL_ARRAY_BUFFER, 9 * sizeof (GLfloat), points, GL_STATIC_DRAW); glGenBuffers (1, &colours_vbo); glBindBuffer (GL_ARRAY_BUFFER, colours_vbo); glBufferData (GL_ARRAY_BUFFER, sizeof (colours), colours, GL_STATIC_DRAW); /* the vertex array object (VAO) is a little descriptor that defines which data from vertex buffer objects should be used as input variables to vertex shaders. in our case - use our only VBO, and say 'every three floats is a variable' */ glGenVertexArrays (1, &vao); glBindVertexArray (vao); glEnableVertexAttribArray (0); glBindBuffer (GL_ARRAY_BUFFER, vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray (1); //enable glBindBuffer (GL_ARRAY_BUFFER, colours_vbo); glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, NULL); /* here we copy the shader strings into GL shaders, and compile them. we then create an executable shader 'program' and attach both of the compiled shaders. we link this, which matches the outputs of the vertex shader to the inputs of the fragment shader, etc. and it is then ready to use */ vs = glCreateShader (GL_VERTEX_SHADER); glShaderSource (vs, 1, &vertex_shader, NULL); glCompileShader (vs); fs = glCreateShader (GL_FRAGMENT_SHADER); glShaderSource (fs, 1, &fragment_shader, NULL); glCompileShader (fs); shader_programme = glCreateProgram (); glAttachShader (shader_programme, fs); glAttachShader (shader_programme, vs); glLinkProgram (shader_programme); double theta=180; GLfloat matrix[] = { 0.5f,0.0f,0.0f,0.00f, 0.0f,0.5f,0.0f,0.00f, 0.0f,0.0f,0.5f,0.00f, 0.25f,0.5f,0.75f,1.0f, }; int matrix_location = glGetUniformLocation (shader_programme, "matrix"); while (!glfwWindowShouldClose (window)) { glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram (shader_programme); glBindVertexArray (vao); glDrawArrays (GL_TRIANGLES, 0, 3); glDrawArrays (GL_TRIANGLES, 3, 6); // update other events like input handling glfwPollEvents (); if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_ESCAPE)) { glfwSetWindowShouldClose (window, 1); } if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_U)) { //return to normal matrix[0] += 0.015f; matrix[5] += 0.005f; } if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_J)) { //return to normal matrix[0] -= 0.015f; matrix[5] -= 0.005f; } //uniformed scaling make smaller if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_D)) { //return to normal matrix[0] -= 0.005f; matrix[5] -= 0.005f; } //uniformed scaling bigger if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_E)) { //return to normal matrix[0] += 0.005f; matrix[5] += 0.005f; matrix[10] += 0.005f; } //non-uniform scaling if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_X)) { //return to normal matrix[5] = cos(theta); matrix[6] = sin(theta); matrix[9] = -sin(theta); matrix[10] =cos(theta); theta+=0.025; } //rotation around Y axis if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_Y)) { //return to normal matrix[0] = cos(theta); matrix[2] = sin(theta); matrix[8] = -sin(theta); matrix[10] =cos(theta); theta+=0.025; } //rotation around Z axis if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_Z)) { //return to normal matrix[0] = cos(theta); matrix[1] = -sin(theta); matrix[4] = sin(theta); matrix[5] = cos(theta); theta+=0.025; } //combined transformations if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_C)) { matrix[0] += 0.005f; matrix[5] += 0.005f; matrix[10] +=0.005f; matrix[12] += 0.025f; } if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_V)) { matrix[0] -= 0.005f; matrix[5] -= 0.005f; matrix[10] -=0.005f; matrix[12] -= 0.025f; } // X left if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_LEFT)) { matrix[12] -= 0.025f; } //X Right if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_RIGHT)) { matrix[12] += 0.025f; } //Y Down if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_DOWN)) { matrix[13] -= 0.025f; } //Y UP if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_UP)) { matrix[13] += 0.025f; } glUniformMatrix4fv (matrix_location, 1, GL_FALSE, matrix); //control triangle seperately // draw points 0-3 from the currently bound VAO with current in-use shader // put the stuff we've been drawing onto the display glfwSwapBuffers (window); } /* close GL context and any other GLFW resources */ glfwTerminate(); return 0; }
int main(void) { GLFWwindow* window; // Initialize the library if (!glfwInit()) return -1; // Activate supersampling glfwWindowHint(GLFW_SAMPLES, 8); // Ensure that we get at least a 3.2 context glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); // On apple we have to load a core profile with forward compatibility #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // Create a windowed mode window and its OpenGL context window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } // Make the window's context current glfwMakeContextCurrent(window); #ifndef __APPLE__ glewExperimental = true; GLenum err = glewInit(); if(GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); } glGetError(); // pull and savely ignonre unhandled errors like GL_INVALID_ENUM fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); #endif int major, minor, rev; major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev); printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION)); printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION)); // Initialize the VAO // A Vertex Array Object (or VAO) is an object that describes how the vertex // attributes are stored in a Vertex Buffer Object (or VBO). This means that // the VAO is not the actual object storing the vertex data, // but the descriptor of the vertex data. VertexArrayObject VAO; VAO.init(); VAO.bind(); // Initialize the VBO with the vertices data // A VBO is a data container that lives in the GPU memory VBO.init(); V.resize(2,6); V << 0, 0.5, -0.5, 0.1, 0.6, -0.4, 0.5, -0.5, -0.5, 0.6, -0.4, -0.4; VBO.update(V); // Initialize the OpenGL Program // A program controls the OpenGL pipeline and it must contains // at least a vertex shader and a fragment shader to be valid Program program; const GLchar* vertex_shader = "#version 150 core\n" "in vec2 position;" "void main()" "{" " gl_Position = vec4(position, 0.0, 1.0);" "}"; const GLchar* fragment_shader = "#version 150 core\n" "out vec4 outColor;" "uniform vec4 triangleColor;" "void main()" "{" " outColor = vec4(triangleColor);" "}"; // Compile the two shaders and upload the binary to the GPU // Note that we have to explicitly specify that the output "slot" called outColor // is the one that we want in the fragment buffer (and thus on screen) program.init(vertex_shader,fragment_shader,"outColor"); program.bind(); // The vertex shader wants the position of the vertices as an input. // The following line connects the VBO we defined above with the position "slot" // in the vertex shader program.bindVertexAttribArray("position",VBO); // Register the keyboard callback glfwSetKeyCallback(window, key_callback); // Register the mouse callback glfwSetMouseButtonCallback(window, mouse_button_callback); // Update viewport glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // Loop until the user closes the window while (!glfwWindowShouldClose(window)) { // Bind your VAO (not necessary if you have only one) VAO.bind(); // Bind your program program.bind(); // Clear the framebuffer glClearColor(0.5f, 0.5f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Enable blending test glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Draw a triangle (red) glUniform4f(program.uniform("triangleColor"), 1.0f, 0.0f, 0.0f, 1.0f); glDrawArrays(GL_TRIANGLES, 0, 3); // Draw a triangle (green) glUniform4f(program.uniform("triangleColor"), 0.0f, 1.0f, 0.0f, 0.5f); glDrawArrays(GL_TRIANGLES, 3, 3); // Swap front and back buffers glfwSwapBuffers(window); // Poll for and process events glfwPollEvents(); } // Deallocate opengl memory program.free(); VAO.free(); VBO.free(); // Deallocate glfw internals glfwTerminate(); return 0; }
int main(int argc, char **argv) { srand(time(NULL)); rand(); if (!glfwInit()) { return -1; } #ifdef __APPLE__ glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #endif if (!glfwOpenWindow(800, 600, 8, 8, 8, 0, 24, 0, GLFW_WINDOW)) { return -1; } glfwSwapInterval(VSYNC); glfwDisable(GLFW_MOUSE_CURSOR); glfwSetWindowTitle("Modern GL"); glfwSetKeyCallback(on_key); glfwSetMouseButtonCallback(on_mouse_button); #ifndef __APPLE__ if (glewInit() != GLEW_OK) { return -1; } #endif if (db_init()) { return -1; } glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_LINE_SMOOTH); glLogicOp(GL_INVERT); glClearColor(0.53, 0.81, 0.92, 1.00); GLuint vertex_array; glGenVertexArrays(1, &vertex_array); glBindVertexArray(vertex_array); GLuint texture; glGenTextures(1, &texture); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glfwLoadTexture2D("texture.tga", 0); GLuint block_program = load_program( "shaders/block_vertex.glsl", "shaders/block_fragment.glsl"); GLuint matrix_loc = glGetUniformLocation(block_program, "matrix"); GLuint camera_loc = glGetUniformLocation(block_program, "camera"); GLuint sampler_loc = glGetUniformLocation(block_program, "sampler"); GLuint timer_loc = glGetUniformLocation(block_program, "timer"); GLuint position_loc = glGetAttribLocation(block_program, "position"); GLuint normal_loc = glGetAttribLocation(block_program, "normal"); GLuint uv_loc = glGetAttribLocation(block_program, "uv"); GLuint line_program = load_program( "shaders/line_vertex.glsl", "shaders/line_fragment.glsl"); GLuint line_matrix_loc = glGetUniformLocation(line_program, "matrix"); GLuint line_position_loc = glGetAttribLocation(line_program, "position"); Chunk chunks[MAX_CHUNKS]; int chunk_count = 0; FPS fps = {0, 0}; float matrix[16]; float x = (rand_double() - 0.5) * 10000; float z = (rand_double() - 0.5) * 10000; float y = 0; float dy = 0; float rx = 0; float ry = 0; int px = 0; int py = 0; int loaded = db_load_state(&x, &y, &z, &rx, &ry); ensure_chunks(chunks, &chunk_count, floorf(roundf(x) / CHUNK_SIZE), floorf(roundf(z) / CHUNK_SIZE), 1); if (!loaded) { y = highest_block(chunks, chunk_count, x, z) + 2; } glfwGetMousePos(&px, &py); double previous = glfwGetTime(); while (glfwGetWindowParam(GLFW_OPENED)) { update_fps(&fps, SHOW_FPS); double now = glfwGetTime(); double dt = MIN(now - previous, 0.2); previous = now; if (exclusive) { int mx, my; glfwGetMousePos(&mx, &my); float m = 0.0025; rx += (mx - px) * m; ry -= (my - py) * m; if (rx < 0) { rx += RADIANS(360); } if (rx >= RADIANS(360)){ rx -= RADIANS(360); } ry = MAX(ry, -RADIANS(90)); ry = MIN(ry, RADIANS(90)); px = mx; py = my; } else { glfwGetMousePos(&px, &py); } if (left_click) { left_click = 0; int hx, hy, hz; if (hit_test(chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz)) { if (hy > 0) { set_block(chunks, chunk_count, hx, hy, hz, 0); } } } if (right_click) { right_click = 0; int hx, hy, hz; if (hit_test(chunks, chunk_count, 1, x, y, z, rx, ry, &hx, &hy, &hz)) { if (!player_intersects_block(2, x, y, z, hx, hy, hz)) { set_block(chunks, chunk_count, hx, hy, hz, block_type); } } } int sz = 0; int sx = 0; ortho = glfwGetKey(GLFW_KEY_LSHIFT); if (glfwGetKey('Q')) break; if (glfwGetKey('W')) sz--; if (glfwGetKey('S')) sz++; if (glfwGetKey('A')) sx--; if (glfwGetKey('D')) sx++; if (dy == 0 && glfwGetKey(GLFW_KEY_SPACE)) { dy = 8; } float vx, vy, vz; get_motion_vector(flying, sz, sx, rx, ry, &vx, &vy, &vz); float speed = flying ? 20 : 5; int step = 8; float ut = dt / step; vx = vx * ut * speed; vy = vy * ut * speed; vz = vz * ut * speed; for (int i = 0; i < step; i++) { if (flying) { dy = 0; } else { dy -= ut * 25; dy = MAX(dy, -250); } x += vx; y += vy + dy * ut; z += vz; if (collide(chunks, chunk_count, 2, &x, &y, &z)) { dy = 0; } } int p = floorf(roundf(x) / CHUNK_SIZE); int q = floorf(roundf(z) / CHUNK_SIZE); ensure_chunks(chunks, &chunk_count, p, q, 0); update_matrix_3d(matrix, x, y, z, rx, ry); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // render chunks glUseProgram(block_program); glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix); glUniform3f(camera_loc, x, y, z); glUniform1i(sampler_loc, 0); glUniform1f(timer_loc, glfwGetTime()); for (int i = 0; i < chunk_count; i++) { Chunk *chunk = chunks + i; if (chunk_distance(chunk, p, q) > RENDER_CHUNK_RADIUS) { continue; } if (!chunk_visible(chunk, matrix)) { continue; } draw_chunk(chunk, position_loc, normal_loc, uv_loc); } // render focused block wireframe int hx, hy, hz; if (hit_test(chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz)) { glUseProgram(line_program); glLineWidth(1); glEnable(GL_COLOR_LOGIC_OP); glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix); GLuint buffer = make_cube_buffer(hx, hy, hz, 0.51); draw_lines(buffer, line_position_loc, 3, 48); glDeleteBuffers(1, &buffer); glDisable(GL_COLOR_LOGIC_OP); } update_matrix_2d(matrix); // render crosshairs glUseProgram(line_program); glLineWidth(4); glEnable(GL_COLOR_LOGIC_OP); glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix); GLuint buffer = make_line_buffer(); draw_lines(buffer, line_position_loc, 2, 4); glDeleteBuffers(1, &buffer); glDisable(GL_COLOR_LOGIC_OP); glfwSwapBuffers(); } db_save_state(x, y, z, rx, ry); db_close(); glfwTerminate(); return 0; }
int main(int argc, char** argv) { int ch, i, window_count; GLboolean auto_iconify = GL_TRUE, fullscreen = GL_FALSE, all_monitors = GL_FALSE; GLFWwindow** windows; while ((ch = getopt(argc, argv, "afhn")) != -1) { switch (ch) { case 'a': all_monitors = GL_TRUE; break; case 'h': usage(); exit(EXIT_SUCCESS); case 'f': fullscreen = GL_TRUE; break; case 'n': auto_iconify = GL_FALSE; break; default: usage(); exit(EXIT_FAILURE); } } glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); glfwWindowHint(GLFW_AUTO_ICONIFY, auto_iconify); if (fullscreen && all_monitors) { int monitor_count; GLFWmonitor** monitors = glfwGetMonitors(&monitor_count); window_count = monitor_count; windows = calloc(window_count, sizeof(GLFWwindow*)); for (i = 0; i < monitor_count; i++) { windows[i] = create_window(monitors[i]); if (!windows[i]) break; } } else { GLFWmonitor* monitor = NULL; if (fullscreen) monitor = glfwGetPrimaryMonitor(); window_count = 1; windows = calloc(window_count, sizeof(GLFWwindow*)); windows[0] = create_window(monitor); } for (i = 0; i < window_count; i++) { glfwSetKeyCallback(windows[i], key_callback); glfwSetFramebufferSizeCallback(windows[i], framebuffer_size_callback); glfwSetWindowSizeCallback(windows[i], window_size_callback); glfwSetWindowFocusCallback(windows[i], window_focus_callback); glfwSetWindowIconifyCallback(windows[i], window_iconify_callback); glfwSetWindowRefreshCallback(windows[i], window_refresh_callback); window_refresh_callback(windows[i]); printf("Window is %s and %s\n", glfwGetWindowAttrib(windows[i], GLFW_ICONIFIED) ? "iconified" : "restored", glfwGetWindowAttrib(windows[i], GLFW_FOCUSED) ? "focused" : "defocused"); } for (;;) { glfwPollEvents(); for (i = 0; i < window_count; i++) { if (glfwWindowShouldClose(windows[i])) break; } if (i < window_count) break; // Workaround for an issue with msvcrt and mintty fflush(stdout); } glfwTerminate(); exit(EXIT_SUCCESS); }
void Screen::begin(const std::string& path) { batb->log << "batb->screen->begin( " << path << " )" << std::endl; LogIndent indent( batb->log, "* " ); if ( init_empty() ) { // set configuration file config( path ); //////////////////////////////////////////////////////////////////////////////// // setup GLFW // glfwSetErrorCallback( glfw_error_callback ); if ( !glfwInit() ) { batb->log << "ERROR: could not initialize GLFW" << std::endl; throw std::runtime_error( "Screen: Could not init GLFW" ); } //////////////////////////////////////////////////////////////////////////////// // screen bool debugctx = yaml["debug"].as<bool>( false ); glfwWindowHint( GLFW_OPENGL_DEBUG_CONTEXT, debugctx ); // debug symbols (?) batb->log << "debug context = " << debugctx << std::endl; // multisamples uint samples = 0; if ( YAML::Node node = yaml[ "multisamples" ] ) { samples = node.as<uint>( samples ); glfwWindowHint( GLFW_SAMPLES, samples ); } batb->log << "multisamples = " << samples << std::endl; // size uint wth = 640; uint hth = 480; if ( YAML::Node node = yaml[ "size" ] ) { wth = node[ "wth" ].as<uint>( wth ); hth = node[ "hth" ].as<uint>( hth ); } batb->log << "window size = " << wth << "x" << hth << std::endl; // fullscreen bool fullscreen = false; if ( YAML::Node node = yaml[ "fullscreen" ] ) { glfw_monitor = node.as<bool>( fullscreen ) ? glfwGetPrimaryMonitor() : 0; // if we create a fullscreen window, let us use the display's resolution if ( glfw_monitor ) { if ( auto mode = glfwGetVideoMode( glfw_monitor ) ) { // save before we set fullscreen nonfullscreen_wth_ = wth; nonfullscreen_hth_ = hth; wth = mode->width; hth = mode->height; } } } batb->log << "window fullscreen = " << fullscreen; if ( fullscreen ) batb->log << " (overriding window size with display resolution (" << wth << "x" << hth << ")"; batb->log->endl(); // title std::string title = ""; if ( YAML::Node node = yaml[ "title" ] ) { title = node.as<std::string>( title ); } batb->log << "window title = " << title << std::endl; // set addioninal windown hints // http://www.glfw.org/docs/latest/window.html#window_hints if ( YAML::Node node = yaml[ "glfw-hints" ] ) { batb->log << "GLFW hints:" << std::endl; LogIndent indent( batb->log, "- " ); for (auto p : node) { auto hint = p.first.as<std::string>(); auto value = p.second.as<std::string>(""); constexpr uint padding = 30; std::string pad( hint.size() < padding ? (padding - hint.size()) : 0, ' ' ); batb->log << hint << pad << " = " << value; if ( glfw_set_windowhint( hint, value ) ) { batb->log->endl(); } else { batb->log << " (WARNING: could not set)" << std::endl; } } } // NOTE: error in implementation of glfw, according to valgrind: glfw_window = glfwCreateWindow( wth, hth, title.c_str(), glfw_monitor, 0 ); // set GL context as 'theWindow_' glfwMakeContextCurrent( glfw_window ); if ( !glfw_window ) { batb->log << "ERROR: could not create GLFW window" << std::endl; throw std::runtime_error( "Screen: could not create GLFW window" ); } // we now have a context, init GLEW // or other, see // * http://www.glfw.org/docs/latest/context_guide.html#context_glext_auto // * https://www.khronos.org/opengl/wiki/OpenGL_Loading_Library GLenum err = glewInit(); if ( err != GLEW_OK ) { batb->log << "ERROR: could not initialize the OpenGL loading library (GLEW): " << glewGetErrorString( err ) << std::endl; std::ostringstream os; os << "Screen: could not init GLEW (" << glewGetErrorString( err ) << ")"; throw std::runtime_error( os.str() ); } // print verbose GL info if ( YAML::Node node = yaml[ "info" ] ) { if ( node.as<bool>() ) { printGLInfo(); } } } init( true ); }
int main() { glfwInit(); 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); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "LearnOpenGL", nullptr, nullptr); glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // Options glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // Initialize GLEW to setup the OpenGL Function pointers glewExperimental = GL_TRUE; glewInit(); // Define the viewport dimensions glViewport(0, 0, screenWidth, screenHeight); // Setup some OpenGL options glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); // Setup and compile our shaders Shader shader("./advanced.vs", "./advanced.frag"); Shader skyboxShader("./skybox.vs", "./skybox.frag"); #pragma region "object_initialization" // Set the object data (buffers, vertex attributes) GLfloat vertices[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f }; 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 }; // Setup cube VAO GLuint cubeVAO, cubeVBO; glGenVertexArrays(1, &cubeVAO); glGenBuffers(1, &cubeVBO); glBindVertexArray(cubeVAO); glBindBuffer(GL_ARRAY_BUFFER, cubeVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glBindVertexArray(0); // Setup skybox VAO GLuint skyboxVAO, skyboxVBO; glGenVertexArrays(1, &skyboxVAO); glGenBuffers(1, &skyboxVBO); glBindVertexArray(skyboxVAO); glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), &skyboxVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); glBindVertexArray(0); // Load textures GLuint cubeTexture = loadTexture("./container.jpg"); #pragma endregion // Cubemap (Skybox) vector<const GLchar*> faces; faces.push_back("skybox/right.jpg"); faces.push_back("skybox/left.jpg"); faces.push_back("skybox/top.jpg"); faces.push_back("skybox/bottom.jpg"); faces.push_back("skybox/back.jpg"); faces.push_back("skybox/front.jpg"); GLuint cubemapTexture = loadCubemap(faces); while (!glfwWindowShouldClose(window)) { // Set frame time GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check and call events glfwPollEvents(); Do_Movement(); // Clear buffers glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw skybox first glDepthMask(GL_FALSE);// Remember to turn depth writing off skyboxShader.Use(); glm::mat4 view = glm::mat4(glm::mat3(camera.GetViewMatrix())); // Remove any translation component of the view matrix glm::mat4 projection = glm::perspective(camera.Zoom, (float)screenWidth/(float)screenHeight, 0.1f, 100.0f); glUniformMatrix4fv(glGetUniformLocation(skyboxShader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(glGetUniformLocation(skyboxShader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); // skybox cube glBindVertexArray(skyboxVAO); glActiveTexture(GL_TEXTURE0); glUniform1i(glGetUniformLocation(shader.Program, "skybox"), 0); glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); glDepthMask(GL_TRUE); // Then draw scene as normal shader.Use(); glm::mat4 model; view = camera.GetViewMatrix(); 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)); // Cubes glBindVertexArray(cubeVAO); glActiveTexture(GL_TEXTURE0); glUniform1i(glGetUniformLocation(shader.Program, "skybox"), 0); glUniform3f(glGetUniformLocation(shader.Program, "cameraPos"), camera.Position.x, camera.Position.y, camera.Position.z); glBindTexture(GL_TEXTURE_2D, cubeTexture); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); // Swap the buffers glfwSwapBuffers(window); } return 0; }
int main() { int width = 640; int height = 480; if(glfwInit() == GL_FALSE) { std::cerr << "failed to init GLFW" << std::endl; return 1; } // sadly glew doesn't play nice with core profiles... glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3); // create a window if(glfwOpenWindow(width, height, 0, 0, 0, 8, 24, 8, GLFW_WINDOW) == GL_FALSE) { std::cerr << "failed to open window" << std::endl; glfwTerminate(); return 1; } // setup windows close callback glfwSetWindowCloseCallback(closedWindow); // this time we disable the mouse cursor since we want differential // mouse input glfwDisable(GLFW_MOUSE_CURSOR); if (gl3wInit()) { std::cerr << "failed to init GL3W" << std::endl; glfwCloseWindow(); glfwTerminate(); return 1; } // draw shader std::string vertex_source = "#version 330\n" "uniform mat4 ViewProjection;\n" "layout(location = 0) in vec4 vposition;\n" "layout(location = 1) in vec3 normal;\n" "out vec4 fcolor;\n" "void main() {\n" " float brightness = dot(normal,normalize(vec3(1,2,3)));\n" " brightness = 0.3+((brightness>0)?0.7*brightness:0.3*brightness);\n" " fcolor = vec4(brightness,brightness,brightness,1);\n" " gl_Position = ViewProjection*vposition;\n" "}\n"; std::string fragment_source = "#version 330\n" "in vec4 fcolor;\n" "layout(location = 0) out vec4 FragColor;\n" "void main() {\n" " FragColor = abs(fcolor);\n" "}\n"; // program and shader handles GLuint shader_program, vertex_shader, fragment_shader; // we need these to properly pass the strings const char *source; int length; // create and compiler vertex shader vertex_shader = glCreateShader(GL_VERTEX_SHADER); source = vertex_source.c_str(); length = vertex_source.size(); glShaderSource(vertex_shader, 1, &source, &length); glCompileShader(vertex_shader); if(!check_shader_compile_status(vertex_shader)) { return 1; } // create and compiler fragment shader fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); source = fragment_source.c_str(); length = fragment_source.size(); glShaderSource(fragment_shader, 1, &source, &length); glCompileShader(fragment_shader); if(!check_shader_compile_status(fragment_shader)) { return 1; } // create program shader_program = glCreateProgram(); // attach shaders glAttachShader(shader_program, vertex_shader); glAttachShader(shader_program, fragment_shader); // link the program and check for errors glLinkProgram(shader_program); check_program_link_status(shader_program); // obtain location of projection uniform GLint DrawViewProjection_location = glGetUniformLocation(shader_program, "ViewProjection"); // trivial shader for occlusion queries std::string query_vertex_source = "#version 330\n" "uniform mat4 ViewProjection;\n" "layout(location = 0) in vec4 vposition;\n" "void main() {\n" " gl_Position = ViewProjection*vposition;\n" "}\n"; std::string query_fragment_source = "#version 330\n" "void main() {\n" "}\n"; // program and shader handles GLuint query_shader_program, query_vertex_shader, query_fragment_shader; // create and compiler vertex shader query_vertex_shader = glCreateShader(GL_VERTEX_SHADER); source = query_vertex_source.c_str(); length = query_vertex_source.size(); glShaderSource(query_vertex_shader, 1, &source, &length); glCompileShader(query_vertex_shader); if(!check_shader_compile_status(query_vertex_shader)) { return 1; } // create and compiler fragment shader query_fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); source = query_fragment_source.c_str(); length = query_fragment_source.size(); glShaderSource(query_fragment_shader, 1, &source, &length); glCompileShader(query_fragment_shader); if(!check_shader_compile_status(query_fragment_shader)) { return 1; } // create program query_shader_program = glCreateProgram(); // attach shaders glAttachShader(query_shader_program, query_vertex_shader); glAttachShader(query_shader_program, query_fragment_shader); // link the program and check for errors glLinkProgram(query_shader_program); check_program_link_status(query_shader_program); // obtain location of projection uniform GLint QueryViewProjection_location = glGetUniformLocation(query_shader_program, "ViewProjection"); // chunk container and chunk parameters std::vector<Chunk> chunks; int chunkrange = 4; int chunksize = 32; // chunk extraction std::cout << "generating chunks, this may take a while." << std::endl; // iterate over all chunks we want to extract for(int i = -chunkrange;i<chunkrange;++i) for(int j = -chunkrange;j<chunkrange;++j) for(int k = -chunkrange;k<chunkrange;++k) { Chunk chunk; // chunk data // generate and bind the vao glGenVertexArrays(1, &chunk.vao); glBindVertexArray(chunk.vao); // generate and bind the vertex buffer object glGenBuffers(1, &chunk.vbo); glBindBuffer(GL_ARRAY_BUFFER, chunk.vbo); std::vector<glm::vec3> vertexData; glm::vec3 offset = static_cast<float>(chunksize) * glm::vec3(i,j,k); float threshold = 0.0f; // iterate over all blocks within the chunk for(int x = 0;x<chunksize;++x) for(int y = 0;y<chunksize;++y) for(int z = 0;z<chunksize;++z) { glm::vec3 pos = glm::vec3(x,y,z) + offset; // insert quads if current block is solid and neighbors are not if(world_function(pos)<threshold) { if(world_function(pos+glm::vec3(1,0,0))>=threshold) { vertexData.push_back(pos+0.5f*glm::vec3( 1, 1, 1)); vertexData.push_back(glm::vec3( 1, 0, 0)); vertexData.push_back(pos+0.5f*glm::vec3( 1,-1, 1)); vertexData.push_back(glm::vec3( 1, 0, 0)); vertexData.push_back(pos+0.5f*glm::vec3( 1, 1,-1)); vertexData.push_back(glm::vec3( 1, 0, 0)); vertexData.push_back(pos+0.5f*glm::vec3( 1,-1,-1)); vertexData.push_back(glm::vec3( 1, 0, 0)); } if(world_function(pos+glm::vec3(0,1,0))>=threshold) { vertexData.push_back(pos+0.5f*glm::vec3( 1, 1, 1)); vertexData.push_back(glm::vec3( 0, 1, 0)); vertexData.push_back(pos+0.5f*glm::vec3( 1, 1,-1)); vertexData.push_back(glm::vec3( 0, 1, 0)); vertexData.push_back(pos+0.5f*glm::vec3(-1, 1, 1)); vertexData.push_back(glm::vec3( 0, 1, 0)); vertexData.push_back(pos+0.5f*glm::vec3(-1, 1,-1)); vertexData.push_back(glm::vec3( 0, 1, 0)); } if(world_function(pos+glm::vec3(0,0,1))>=threshold) { vertexData.push_back(pos+0.5f*glm::vec3( 1, 1, 1)); vertexData.push_back(glm::vec3( 0, 0, 1)); vertexData.push_back(pos+0.5f*glm::vec3(-1, 1, 1)); vertexData.push_back(glm::vec3( 0, 0, 1)); vertexData.push_back(pos+0.5f*glm::vec3( 1,-1, 1)); vertexData.push_back(glm::vec3( 0, 0, 1)); vertexData.push_back(pos+0.5f*glm::vec3(-1,-1, 1)); vertexData.push_back(glm::vec3( 0, 0, 1)); } if(world_function(pos-glm::vec3(1,0,0))>=threshold) { vertexData.push_back(pos+0.5f*glm::vec3(-1, 1, 1)); vertexData.push_back(glm::vec3(-1, 0, 0)); vertexData.push_back(pos+0.5f*glm::vec3(-1, 1,-1)); vertexData.push_back(glm::vec3(-1, 0, 0)); vertexData.push_back(pos+0.5f*glm::vec3(-1,-1, 1)); vertexData.push_back(glm::vec3(-1, 0, 0)); vertexData.push_back(pos+0.5f*glm::vec3(-1,-1,-1)); vertexData.push_back(glm::vec3(-1, 0, 0)); } if(world_function(pos-glm::vec3(0,1,0))>=threshold) { vertexData.push_back(pos+0.5f*glm::vec3( 1,-1, 1)); vertexData.push_back(glm::vec3( 0,-1, 0)); vertexData.push_back(pos+0.5f*glm::vec3(-1,-1, 1)); vertexData.push_back(glm::vec3( 0,-1, 0)); vertexData.push_back(pos+0.5f*glm::vec3( 1,-1,-1)); vertexData.push_back(glm::vec3( 0,-1, 0)); vertexData.push_back(pos+0.5f*glm::vec3(-1,-1,-1)); vertexData.push_back(glm::vec3( 0,-1, 0)); } if(world_function(pos-glm::vec3(0,0,1))>=threshold) { vertexData.push_back(pos+0.5f*glm::vec3( 1, 1,-1)); vertexData.push_back(glm::vec3( 0, 0,-1)); vertexData.push_back(pos+0.5f*glm::vec3( 1,-1,-1)); vertexData.push_back(glm::vec3( 0, 0,-1)); vertexData.push_back(pos+0.5f*glm::vec3(-1, 1,-1)); vertexData.push_back(glm::vec3( 0, 0,-1)); vertexData.push_back(pos+0.5f*glm::vec3(-1,-1,-1)); vertexData.push_back(glm::vec3( 0, 0,-1)); } } } // upload glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)*vertexData.size(), &vertexData[0], GL_STATIC_DRAW); // set up generic attrib pointers glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6*sizeof(GLfloat), (char*)0 + 0*sizeof(GLfloat)); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6*sizeof(GLfloat), (char*)0 + 3*sizeof(GLfloat)); // generate and bind the index buffer object glGenBuffers(1, &chunk.ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, chunk.ibo); chunk.quadcount = vertexData.size()/8; std::vector<GLuint> indexData(6*chunk.quadcount); for(int i = 0;i<chunk.quadcount;++i) { indexData[6*i + 0] = 4*i + 0; indexData[6*i + 1] = 4*i + 1; indexData[6*i + 2] = 4*i + 2; indexData[6*i + 3] = 4*i + 2; indexData[6*i + 4] = 4*i + 1; indexData[6*i + 5] = 4*i + 3; } // upload glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*indexData.size(), &indexData[0], GL_STATIC_DRAW); // chunk bounding box // generate and bind the vao glGenVertexArrays(1, &chunk.bounding_vao); glBindVertexArray(chunk.bounding_vao); // generate and bind the vertex buffer object glGenBuffers(1, &chunk.bounding_vbo); glBindBuffer(GL_ARRAY_BUFFER, chunk.bounding_vbo); // data for the bounding cube GLfloat boundingVertexData[] = { // X Y Z // face 0: offset.x+chunksize-0.5f, offset.y+chunksize-0.5f, offset.z+chunksize-0.5f, offset.x-0.5f, offset.y+chunksize-0.5f, offset.z+chunksize-0.5f, offset.x+chunksize-0.5f, offset.y-0.5f, offset.z+chunksize-0.5f, offset.x-0.5f, offset.y-0.5f, offset.z+chunksize-0.5f, // face 1: offset.x+chunksize-0.5f, offset.y+chunksize-0.5f, offset.z+chunksize-0.5f, offset.x+chunksize-0.5f, offset.y-0.5f, offset.z+chunksize-0.5f, offset.x+chunksize-0.5f, offset.y+chunksize-0.5f, offset.z-0.5f, offset.x+chunksize-0.5f, offset.y-0.5f, offset.z-0.5f, // face 2: offset.x+chunksize-0.5f, offset.y+chunksize-0.5f, offset.z+chunksize-0.5f, offset.x+chunksize-0.5f, offset.y+chunksize-0.5f, offset.z-0.5f, offset.x-0.5f, offset.y+chunksize-0.5f, offset.z+chunksize-0.5f, offset.x-0.5f, offset.y+chunksize-0.5f, offset.z-0.5f, // face 3: offset.x+chunksize-0.5f, offset.y+chunksize-0.5f, offset.z-0.5f, offset.x+chunksize-0.5f, offset.y-0.5f, offset.z-0.5f, offset.x-0.5f, offset.y+chunksize-0.5f, offset.z-0.5f, offset.x-0.5f, offset.y-0.5f, offset.z-0.5f, // face 4: offset.x-0.5f, offset.y+chunksize-0.5f, offset.z+chunksize-0.5f, offset.x-0.5f, offset.y+chunksize-0.5f, offset.z-0.5f, offset.x-0.5f, offset.y-0.5f, offset.z+chunksize-0.5f, offset.x-0.5f, offset.y-0.5f, offset.z-0.5f, // face 5: offset.x+chunksize-0.5f, offset.y-0.5f, offset.z+chunksize-0.5f, offset.x-0.5f, offset.y-0.5f, offset.z+chunksize-0.5f, offset.x+chunksize-0.5f, offset.y-0.5f, offset.z-0.5f, offset.x-0.5f, offset.y-0.5f, offset.z-0.5f, }; // 6 faces with 4 vertices with 6 components (floats) // fill with data glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*6*4*3, boundingVertexData, GL_STATIC_DRAW); // set up generic attrib pointers glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(GLfloat), (char*)0 + 0*sizeof(GLfloat)); // generate and bind the index buffer object glGenBuffers(1, &chunk.bounding_ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, chunk.bounding_ibo); GLuint boundingIndexData[] = { 0, 1, 2, 2, 1, 3, 4, 5, 6, 6, 5, 7, 8, 9,10,10, 9,11, 12,13,14,14,13,15,16,17,18,18,17,19,20,21,22,22,21,23, }; // fill with data glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*6*2*3, boundingIndexData, GL_STATIC_DRAW); // generate the query object for the occlusion query glGenQueries(1, &chunk.query); // set the center location of the chunk chunk.center = offset + 0.5f*chunksize; // add to container chunks.push_back(chunk); } // "unbind" vao glBindVertexArray(0); // timer query setup // use multiple queries to avoid stalling on getting the results const int querycount = 5; GLuint queries[querycount]; int current_query = 0; glGenQueries(querycount, queries); // we are drawing 3d objects so we want depth testing glEnable(GL_DEPTH_TEST); // camera position and orientation glm::vec3 position; glm::mat4 rotation = glm::mat4(1.0f); running = true; float t = glfwGetTime(); bool occlusion_cull = true; bool space_down = false; // mouse position int mousex, mousey; glfwGetMousePos(&mousex, &mousey); while(running) { // calculate timestep float new_t = glfwGetTime(); float dt = new_t - t; t = new_t; // update mouse differential int tmpx, tmpy; glfwGetMousePos(&tmpx, &tmpy); glm::vec2 mousediff(tmpx-mousex, tmpy-mousey); mousex = tmpx; mousey = tmpy; // find up, forward and right vector glm::mat3 rotation3(rotation); glm::vec3 up = glm::transpose(rotation3)*glm::vec3(0.0f, 1.0f, 0.0f); glm::vec3 right = glm::transpose(rotation3)*glm::vec3(1.0f, 0.0f, 0.0f); glm::vec3 forward = glm::transpose(rotation3)*glm::vec3(0.0f, 0.0f,-1.0f); // apply mouse rotation rotation = glm::rotate(rotation, 0.2f*mousediff.x, up); rotation = glm::rotate(rotation, 0.2f*mousediff.y, right); // roll if(glfwGetKey('Q')) { rotation = glm::rotate(rotation, 180.0f*dt, forward); } if(glfwGetKey('E')) { rotation = glm::rotate(rotation,-180.0f*dt, forward); } // movement if(glfwGetKey('W')) { position += 10.0f*dt*forward; } if(glfwGetKey('S')) { position -= 10.0f*dt*forward; } if(glfwGetKey('D')) { position += 10.0f*dt*right; } if(glfwGetKey('A')) { position -= 10.0f*dt*right; } // toggle occlusion culling if(glfwGetKey(GLFW_KEY_SPACE) && !space_down) { occlusion_cull = !occlusion_cull; } space_down = glfwGetKey(GLFW_KEY_SPACE); // terminate on escape if(glfwGetKey(GLFW_KEY_ESC)) { running = false; } // calculate ViewProjection matrix glm::mat4 Projection = glm::perspective(90.0f, 4.0f / 3.0f, 0.1f, 200.f); glm::mat4 View = rotation*glm::translate(glm::mat4(1.0f), -position); glm::mat4 ViewProjection = Projection*View; // set matrices for both shaders glUseProgram(query_shader_program); glUniformMatrix4fv(QueryViewProjection_location, 1, GL_FALSE, glm::value_ptr(ViewProjection)); glUseProgram(shader_program); glUniformMatrix4fv(DrawViewProjection_location, 1, GL_FALSE, glm::value_ptr(ViewProjection)); // set clear color to sky blue glClearColor(0.5f,0.8f,1.0f,1.0f); // clear glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // sort chunks by distance std::sort(chunks.begin(), chunks.end(), DistancePred(position)); size_t i = 0; float maxdist = chunksize; // start timer query glBeginQuery(GL_TIME_ELAPSED, queries[current_query]); // peel chunks while(i!=chunks.size()) { size_t j = i; if(occlusion_cull) { // start occlusion queries and render for the current slice glDisable(GL_CULL_FACE); // we don't want the queries to actually render something glDepthMask(GL_FALSE); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glUseProgram(query_shader_program); for(;j<chunks.size() && glm::distance(chunks[j].center, position)<maxdist;++j) { // frustum culling glm::vec4 projected = ViewProjection*glm::vec4(chunks[j].center,1); if( (glm::distance(chunks[j].center,position) > chunksize) && (std::max(std::abs(projected.x), std::abs(projected.y)) > projected.w+chunksize)) continue; // begin occlusion query glBeginQuery(GL_ANY_SAMPLES_PASSED, chunks[j].query); // draw bounding box glBindVertexArray(chunks[j].bounding_vao); glDrawElements(GL_TRIANGLES, 6*6, GL_UNSIGNED_INT, 0); // end occlusion query glEndQuery(GL_ANY_SAMPLES_PASSED); } j = i; } // render the current slice glEnable(GL_CULL_FACE); // turn rendering back on glDepthMask(GL_TRUE); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glUseProgram(shader_program); for(;j<chunks.size() && glm::distance(chunks[j].center, position)<maxdist;++j) { // frustum culling glm::vec4 projected = ViewProjection*glm::vec4(chunks[j].center,1); if( (glm::distance(chunks[j].center,position) > chunksize) && (std::max(std::abs(projected.x), std::abs(projected.y)) > projected.w+chunksize)) continue; // begin conditional render if(occlusion_cull) glBeginConditionalRender(chunks[j].query, GL_QUERY_BY_REGION_WAIT); // draw chunk glBindVertexArray(chunks[j].vao); glDrawElements(GL_TRIANGLES, 6*chunks[j].quadcount, GL_UNSIGNED_INT, 0); // end conditional render if(occlusion_cull) glEndConditionalRender(); } i = j; maxdist += 2*chunksize; } // end timer query glEndQuery(GL_TIME_ELAPSED); // display timer query results from querycount frames before if(GL_TRUE == glIsQuery(queries[(current_query+1)%querycount])) { GLuint64 result; glGetQueryObjectui64v(queries[(current_query+1)%querycount], GL_QUERY_RESULT, &result); std::cout << result*1.e-6 << " ms/frame" << std::endl; } // advance query counter current_query = (current_query + 1)%querycount; // check for errors GLenum error = glGetError(); if(error != GL_NO_ERROR) { std::cerr << gluErrorString(error); running = false; } // finally swap buffers glfwSwapBuffers(); } // delete the created objects for(size_t i = 0;i<chunks.size();++i) { glDeleteVertexArrays(1, &chunks[i].vao); glDeleteBuffers(1, &chunks[i].vbo); glDeleteBuffers(1, &chunks[i].ibo); glDeleteVertexArrays(1, &chunks[i].bounding_vao); glDeleteBuffers(1, &chunks[i].bounding_vbo); glDeleteBuffers(1, &chunks[i].bounding_ibo); glDeleteQueries(1, &chunks[i].query); } glDeleteQueries(querycount, queries); glDetachShader(shader_program, vertex_shader); glDetachShader(shader_program, fragment_shader); glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); glDeleteProgram(shader_program); glDetachShader(query_shader_program, query_vertex_shader); glDetachShader(query_shader_program, query_fragment_shader); glDeleteShader(query_vertex_shader); glDeleteShader(query_fragment_shader); glDeleteProgram(query_shader_program); glfwCloseWindow(); glfwTerminate(); return 0; }
int main() { int width, height; int frame = 0; bool running = true; glfwInit(); if( !glfwOpenWindow( 512, 512, 0, 0, 0, 0, 0, 0, GLFW_WINDOW ) ) { glfwTerminate(); return 0; } glfwSetWindowTitle("GLFW Application"); while(running) { frame++; glfwGetWindowSize( &width, &height ); height = height > 0 ? height : 1; glViewport( 0, 0, width, height ); glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); glClear( GL_COLOR_BUFFER_BIT ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( 65.0f, (GLfloat)width/(GLfloat)height, 1.0f, 100.0f ); // Draw some rotating garbage glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); gluLookAt(0.0f, -10.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); //glTranslatef( 1.0f, 1.0f, 0.0f ); glRotatef(frame, 0.25f, 1.0f, 0.75f); glBegin( GL_TRIANGLES ); glColor3f(0.1f, 0.0f, 0.0f ); glVertex3f(0.0f, 3.0f, -4.0f); glColor3f(0.0f, 1.0f, 0.0f ); glVertex3f(3.0f, -2.0f, -4.0f); glColor3f(0.0f, 0.0f, 1.0f ); glVertex3f(-3.0f, -2.0f, -4.0f); glEnd(); glBegin( GL_TRIANGLES ); glColor3f(0.0f, 0.1f, 0.0f ); glVertex3f(0.0f, 3.0f, -3.0f); glColor3f(0.0f, 0.0f, 1.0f ); glVertex3f(3.0f, -2.0f, -2.0f); glColor3f(1.0f, 0.0f, 0.0f ); glVertex3f(-3.0f, -2.0f, 2.0f); glEnd(); glfwSwapBuffers(); // exit if ESC was pressed or window was closed running = !glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam( GLFW_OPENED); } glfwTerminate(); return 0; }
int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X #endif // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state // ----------------------------- glEnable(GL_DEPTH_TEST); // build and compile our shader zprogram // ------------------------------------ Shader ourShader("7.4.camera.vs", "7.4.camera.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ float vertices[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; // world space positions of our cubes glm::vec3 cubePositions[] = { glm::vec3( 0.0f, 0.0f, 0.0f), glm::vec3( 2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3( 2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3( 1.3f, -2.0f, -2.5f), glm::vec3( 1.5f, 2.0f, -2.5f), glm::vec3( 1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; unsigned int VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // texture coord attribute glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // load and create a texture // ------------------------- unsigned int texture1, texture2; // texture 1 // --------- glGenTextures(1, &texture1); glBindTexture(GL_TEXTURE_2D, texture1); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps int width, height, nrChannels; stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis. unsigned char *data = stbi_load(FileSystem::getPath("resources/textures/container.jpg").c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); // texture 2 // --------- glGenTextures(1, &texture2); glBindTexture(GL_TEXTURE_2D, texture2); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps data = stbi_load(FileSystem::getPath("resources/textures/awesomeface.png").c_str(), &width, &height, &nrChannels, 0); if (data) { // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); // tell opengl for each sampler to which texture unit it belongs to (only has to be done once) // ------------------------------------------------------------------------------------------- ourShader.use(); ourShader.setInt("texture1", 0); ourShader.setInt("texture2", 1); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // per-frame time logic // -------------------- float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // bind textures on corresponding texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); // activate shader ourShader.use(); // pass projection matrix to shader (note that in this case it could change every frame) glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); // camera/view transformation glm::mat4 view = camera.GetViewMatrix(); ourShader.setMat4("view", view); // render boxes glBindVertexArray(VAO); for (unsigned int i = 0; i < 10; i++) { // calculate the model matrix for each object and pass it to shader before drawing glm::mat4 model = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first model = glm::translate(model, cubePositions[i]); float angle = 20.0f * i; model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; }
int main( ) { int running = GL_TRUE; CDLGetCurrentDirectory(); // Initialize GLFW if( !glfwInit() ) { exit( EXIT_FAILURE ); } glShadeModel(GL_SMOOTH); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glDisable(GL_DEPTH_TEST); //glEnable(GL_TEXTURE_2D); // Finally we can Open an OpenGL window if(!glfwOpenWindow ( 1024, 768, 1,0,0,0,0,0, GLFW_WINDOW )) { glfwTerminate(); exit( EXIT_FAILURE ); } glfwSetWindowTitle( TITLE );//Sets the Windows Name glfwSetWindowSizeCallback(handleResize); //callback function of GLFW to handle window resize glfwSetKeyCallback(handleKeypress); //callback function to handle key press glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); //clear background screen to black // Main loop while( running ) { //Clear information from last draw glClear( GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT); glPushAttrib(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); //Switch to the drawing perspective glLoadIdentity(); //Reset the drawing perspective glBegin(GL_QUADS); glTexCoord2f(0,1); glVertex3f(-1, 1, -1); glTexCoord2f(1,1); glVertex3f( 1, 1, -1); glTexCoord2f(1,0); glVertex3f( 1,-1, -1); glTexCoord2f(0,0); glVertex3f(-1,-1, -1); glEnd(); //glDisable(GL_TEXTURE_2D); glPopAttrib(); glFlush(); glfwSwapBuffers(); // Check if ESC key was pressed or window was closed running = glfwGetWindowParam( GLFW_OPENED ); } // Close window and terminate GLFW glfwTerminate(); // Exit program exit( EXIT_SUCCESS ); }
bool World::Initialize(unsigned int windowWidth, unsigned int windowHeight, String windowName, bool antiAliasing, bool fullScreen, bool resizable) { if (_initialized) { return false; } _running = true; // Windows DLL locations #if defined(WIN32) && defined(NDEBUG) String bitsPath = "bits"; char currentDir[MAX_PATH]; _getcwd(currentDir, MAX_PATH); String currDir(currentDir); StringList libs; #if !ANGEL_DISABLE_DEVIL libs.push_back("DevIL.dll"); libs.push_back("ILU.dll"); libs.push_back("ILUT.dll"); #endif #if ANGEL_DISABLE_FMOD libs.push_back("OpenAL32.dll"); #else libs.push_back("fmodex.dll"); #endif for (int i=0; i < libs.size(); i++) { String libstring = currDir + "\\" + bitsPath + "\\" + libs[i]; HMODULE work = LoadLibrary(libstring.c_str()); if (work == 0) { DWORD err = GetLastError(); _com_error error(err); LPCSTR errorText = error.ErrorMessage(); sysLog.Printf("ERROR: Couldn't load DLL (%s); %s", libs[i].c_str(), errorText); } } // does bits directory exist? DWORD dwAttrib = GetFileAttributes(bitsPath.c_str()); if (dwAttrib != INVALID_FILE_ATTRIBUTES && dwAttrib & FILE_ATTRIBUTE_DIRECTORY) { _chdir(bitsPath.c_str()); } #endif // General windowing initialization #if !ANGEL_MOBILE glfwInit(); #endif #if defined(__APPLE__) // Set up paths correctly in the .app bundle #if !ANGEL_MOBILE CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle); char path[PATH_MAX]; if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX)) { sysLog.Log("ERROR: Problem setting up working directory! Probably nothing will work!"); } CFRelease(resourcesURL); chdir(path); chdir(".."); #if DEBUG // set paths to the local resources rather than the copied ones String fileName = __FILE__; String dirPath = fileName.substr(0, fileName.size() - String("Angel/Infrastructure/World.cpp").size()); CFURLRef exeURL = CFBundleCopyExecutableURL(mainBundle); char exePath[PATH_MAX]; if (!CFURLGetFileSystemRepresentation(exeURL, TRUE, (UInt8 *)exePath, PATH_MAX)) { sysLog.Log("ERROR: Problem setting up working directory! Probably nothing will work!"); } CFRelease(exeURL); chdir(dirPath.c_str()); StringList pathElements = SplitString(exePath, "/"); String exeName = pathElements[pathElements.size()-1]; chdir(exeName.c_str()); #endif #else CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle); char path[PATH_MAX]; if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX)) { std::cout << "Problem setting up working directory! Probably nothing will work!" << std::endl; } CFRelease(resourcesURL); chdir(path); chdir("Angel"); // the iPhone doesn't like having a "Resources" directory in the root of the .app bundle #endif #endif //Start scripting LuaScriptingModule::Prep(); //Reset values based on preferences antiAliasing = thePrefs.OverrideInt("WindowSettings", "antiAliasing", antiAliasing); fullScreen = thePrefs.OverrideInt("WindowSettings", "fullScreen", fullScreen); resizable = thePrefs.OverrideInt("WindowSettings", "resizable", resizable); windowHeight = thePrefs.OverrideInt("WindowSettings", "height", windowHeight); windowWidth = thePrefs.OverrideInt("WindowSettings", "width", windowWidth); windowName = thePrefs.OverrideString("WindowSettings", "name", windowName); //Windowing system setup #if !ANGEL_MOBILE if (antiAliasing) { glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); //4x looks pretty good _antiAliased = true; } else { _antiAliased = false; } int windowMode = GLFW_WINDOW; if (fullScreen) { windowMode = GLFW_FULLSCREEN; } if (resizable) { glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_FALSE); } else { glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE); } glfwOpenWindow(windowWidth, windowHeight, 8, 8, 8, 8, 8, 1, windowMode); glfwSetWindowTitle(windowName.c_str()); glfwSetWindowPos(50, 50); #if defined(WIN32) glfwSwapInterval(0); // because double-buffering and Windows don't get along apparently #else glfwSwapInterval(1); #endif glfwSetWindowSizeCallback(Camera::ResizeCallback); glfwSetKeyCallback(keyboardInput); glfwSetCharCallback(charInput); glfwDisable(GLFW_KEY_REPEAT); glfwSetMousePosCallback(MouseMotion); glfwSetMouseButtonCallback(MouseButton); glfwSetMouseWheelCallback(MouseWheel); glfwSetWindowCloseCallback(windowClosed); _prevTime = glfwGetTime(); #else struct timeval tv; gettimeofday(&tv, NULL); _currTime = _startTime = tv.tv_sec + (double) tv.tv_usec / 1000000.0; #endif //OpenGL state setup #if !ANGEL_MOBILE glClearDepth(1.0f); glPolygonMode(GL_FRONT, GL_FILL); #else glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(1.0f, -1.0f); #endif glShadeModel(GL_FLAT); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glEnable(GL_CULL_FACE); glFrontFace(GL_CCW); glCullFace(GL_BACK); glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearStencil(0); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); theCamera.ResizeCallback(windowWidth, windowHeight); //Get textures going InitializeTextureLoading(); //Subscribe to camera changes theSwitchboard.SubscribeTo(this, "CameraChange"); //initialize singletons #if !ANGEL_MOBILE theInput; theControllerManager.Setup(); #endif theSound; theSpatialGraph; #if !ANGEL_MOBILE RegisterConsole(new TestConsole()); #else // register fonts, since we don't have the console doing it for us on the phone RegisterFont("Resources/Fonts/Inconsolata.otf", 24, "Console"); RegisterFont("Resources/Fonts/Inconsolata.otf", 18, "ConsoleSmall"); #endif LuaScriptingModule::Initialize(); return _initialized = true; }
int main(int argc, char* argv[]) { // Define our variables. FILE* load; uint16_t flash[0x10000]; char leading[0x100]; unsigned int i; bool uread = true; vm_t* vm; int nerrors; bstring ss, st; host_context_t* dtemu = malloc(sizeof(host_context_t)); struct errinfo* errval; const char* prepend = "error: "; const char* warnprefix = "no-"; int msglen; char* msg; // Define arguments. struct arg_lit* show_help = arg_lit0("h", "help", "Show this help."); struct arg_file* input_file = arg_file1(NULL, NULL, "<file>", "The input file, or - to read from standard input."); struct arg_file* execution_dump_file = arg_file0("e", "execution-dump", "<file>", "Produce a very large execution dump file."); struct arg_lit* debug_mode = arg_lit0("d", "debug", "Show each executed instruction."); struct arg_lit* terminate_mode = arg_lit0("t", "show-on-terminate", "Show state of machine when program is terminated."); struct arg_lit* legacy_mode = arg_lit0("l", "legacy", "Automatically initialize hardware to legacy values."); struct arg_str* warning_policies = arg_strn("W", NULL, "policy", 0, _WARN_COUNT * 2 + 10, "Modify warning policies."); struct arg_lit* little_endian_mode = arg_lit0(NULL, "little-endian", "Use little endian serialization (for compatibility with older versions)."); struct arg_lit* verbose = arg_litn("v", NULL, 0, LEVEL_EVERYTHING - LEVEL_DEFAULT, "Increase verbosity."); struct arg_lit* quiet = arg_litn("q", NULL, 0, LEVEL_DEFAULT - LEVEL_SILENT, "Decrease verbosity."); struct arg_int* radiation = arg_intn("r", NULL, "<n>", 0, 1, "Radiation factor (higher is less radiation)"); struct arg_lit* catch_fire = arg_lit0("c", "catch-fire", "The virtual machine should catch fire instead of halting."); struct arg_end* end = arg_end(20); void* argtable[] = { input_file, warning_policies, debug_mode, execution_dump_file, terminate_mode, legacy_mode, little_endian_mode, radiation, catch_fire, verbose, quiet, end }; // Parse arguments. nerrors = arg_parse(argc, argv, argtable); if (nerrors != 0 || show_help->count != 0) { if (show_help->count != 0) arg_print_errors(stdout, end, "emulator"); printd(LEVEL_DEFAULT, "syntax:\n dtemu"); arg_print_syntax(stderr, argtable, "\n"); printd(LEVEL_DEFAULT, "options:\n"); arg_print_glossary(stderr, argtable, " %-25s %s\n"); arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return 1; } // Set verbosity level. debug_setlevel(LEVEL_DEFAULT + verbose->count - quiet->count); // Show version information. version_print(bautofree(bfromcstr("Emulator"))); // Set global path variable. osutil_setarg0(bautofree(bfromcstr(argv[0]))); // Set endianness. isetmode(little_endian_mode->count == 0 ? IMODE_BIG : IMODE_LITTLE); // Set up warning policies. dsetwarnpolicy(warning_policies); // Set up error handling. if (dsethalt()) { errval = derrinfo(); // FIXME: Use bstrings here. msglen = strlen(derrstr[errval->errid]) + strlen(prepend) + 1; msg = malloc(msglen); memset(msg, '\0', msglen); strcat(msg, prepend); strcat(msg, derrstr[errval->errid]); printd(LEVEL_ERROR, msg, errval->errdata); // Handle the error. printd(LEVEL_ERROR, "emulator: error occurred.\n"); arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return 1; } // Zero out the flash space. for (i = 0; i < 0x10000; i++) flash[i] = 0x0; // Zero out the leading space. for (i = 0; i < 0x100; i++) leading[i] = 0x0; // Load from either file or stdin. if (strcmp(input_file->filename[0], "-") != 0) { // Open file. load = fopen(input_file->filename[0], "rb"); if (load == NULL) dhalt(ERR_EMU_LOAD_FILE_FAILED, input_file->filename[0]); } else { // Windows needs stdin in binary mode. #ifdef _WIN32 _setmode(_fileno(stdin), _O_BINARY); #endif // Set load to stdin. load = stdin; } // Read leading component. for (i = 0; i < strlen(ldata_objfmt); i++) leading[i] = fgetc(load); fseek(load, 0, SEEK_SET); // Read up to 0x10000 words. for (i = 0; i < 0x10000 && !feof(load); i++) iread(&flash[i], load); fclose(load); // Check to see if the first X bytes matches the header // for intermediate code and stop if it does. ss = bfromcstr(""); st = bfromcstr(ldata_objfmt); for (i = 0; i < strlen(ldata_objfmt); i++) bconchar(ss, leading[i]); if (biseq(ss, st)) dhalt(ERR_INTERMEDIATE_EXECUTION, NULL); // Set up the host context. glfwInit(); dtemu->create_context = &dtemu_create_context; dtemu->activate_context = &dtemu_activate_context; dtemu->swap_buffers = &dtemu_swap_buffers; dtemu->destroy_context = &dtemu_destroy_context; dtemu->get_ud = &dtemu_get_ud; // And then use the VM. vm = vm_create(); vm->debug = (debug_mode->count > 0); vm_flash(vm, flash); // Set radiation and catch fire settings. if (radiation->count == 1) vm->radiation_factor = radiation->ival[0]; if (catch_fire->count == 1) vm->can_fire = true; // Init hardware. vm_hw_timer_init(vm); vm->host = dtemu; vm_hw_sped3_init(vm); vm_hw_lem1802_init(vm); vm_hw_m35fd_init(vm); vm_hw_lua_init(vm); if (legacy_mode->count > 0) { for (i = 0; i < vm_hw_count(vm); i++) if (vm_hw_get_device(vm, i).id == 0x7349F615 && vm_hw_get_device(vm, i).manufacturer == 0x1C6C8B36) { vm_hw_lem1802_mem_set_screen((struct lem1802_hardware*)vm_hw_get_device(vm, i).userdata, 0x8000); break; } } vm_execute(vm, execution_dump_file->count > 0 ? execution_dump_file->filename[0] : NULL); if (terminate_mode->count > 0) { fprintf(stderr, "\n"); fprintf(stderr, "A: 0x%04X [A]: 0x%04X\n", vm->registers[REG_A], vm->ram[vm->registers[REG_A]]); fprintf(stderr, "B: 0x%04X [B]: 0x%04X\n", vm->registers[REG_B], vm->ram[vm->registers[REG_B]]); fprintf(stderr, "C: 0x%04X [C]: 0x%04X\n", vm->registers[REG_C], vm->ram[vm->registers[REG_C]]); fprintf(stderr, "X: 0x%04X [X]: 0x%04X\n", vm->registers[REG_X], vm->ram[vm->registers[REG_X]]); fprintf(stderr, "Y: 0x%04X [Y]: 0x%04X\n", vm->registers[REG_Y], vm->ram[vm->registers[REG_Y]]); fprintf(stderr, "Z: 0x%04X [Z]: 0x%04X\n", vm->registers[REG_Z], vm->ram[vm->registers[REG_Z]]); fprintf(stderr, "I: 0x%04X [I]: 0x%04X\n", vm->registers[REG_I], vm->ram[vm->registers[REG_I]]); fprintf(stderr, "J: 0x%04X [J]: 0x%04X\n", vm->registers[REG_J], vm->ram[vm->registers[REG_J]]); fprintf(stderr, "PC: 0x%04X SP: 0x%04X\n", vm->pc, vm->sp); fprintf(stderr, "EX: 0x%04X IA: 0x%04X\n", vm->ex, vm->ia); } vm_hw_lua_free(vm); vm_hw_free_all(vm); vm_free(vm); arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); glfwTerminate(); return 0; }
int main(int argc, char** argv) { if (!glewInit()) return EXIT_FAILURE; GLFWwindow* window; /* Initialize the library */ if (!glfwInit()) return EXIT_FAILURE; /* Create a windowed mode window and its OpenGL context */ glfwHints(); window = glfwCreateWindow( g_windowWidth, g_windowHeight, "Dunjun", nullptr, nullptr); if (!window) { glfwTerminate(); return EXIT_FAILURE; } /* Make the window's context current */ glfwMakeContextCurrent(window); glewInit(); float vertices[] = { +0.0f, +0.5f, //Vertex 1 -0.5f, -0.5f, //Vertex 2 +0.5f, -0.5f, //Vertex 3 }; GLuint vbo; // Vertex Buffer Object glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); const char* vertexShaderText = { "#version 120\n" "\n" "attribute vec2 position;" "void main()" "{" " gl_Position = vec4(position, 0.0, 1.0);" "}" }; const char* fragmentShaderText = { "#version 120\n" "\n" "void main()" "{" " gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);" "}" }; GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderText, nullptr); glCompileShader(vertexShader); GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderText, nullptr); glCompileShader(fragmentShader); GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glBindAttribLocation(shaderProgram, 0, "position"); glLinkProgram(shaderProgram); glUseProgram(shaderProgram); bool running = true; bool fullscreen = false; /* Loop until the user closes the window */ while (running) { /* Render here */ glClearColor(0.5f, 0.69f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); /* Draw Things*/ { glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr); glDrawArrays(GL_TRIANGLES, 0, 3); glDisableVertexAttribArray(0); } /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); if (glfwWindowShouldClose(window) || glfwGetKey(window, GLFW_KEY_ESCAPE)) running = false; /*if (glfwGetKey(window, GLFW_KEY_F11)) { fullscreen = !fullscreen; GLFWwindow* newWindow; glfwHints(); if (fullscreen) { int count; const GLFWvidmode* modes = glfwGetVideoModes(glfwGetPrimaryMonitor(), &count); newWindow = glfwCreateWindow(modes[count - 1].width, modes[count - 1].height, "Dunjun", glfwGetPrimaryMonitor(), window); } else { newWindow = glfwCreateWindow( g_windowWidth, g_windowHeight, "Dunjun", nullptr, window); } glfwDestroyWindow(window); window = newWindow; glfwMakeContextCurrent(window); }*/ } glfwDestroyWindow(window); glfwTerminate(); return EXIT_SUCCESS; }
int _tmain(int argc, _TCHAR* argv[]) { GLFWwindow* window = 0; glfwSetErrorCallback(glfw_error_callback_func); // Initialise GLFW if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); getchar(); return -1; } //----------------------------------------------------------------------------- glfwWindowHint(GLFW_SAMPLES, 4); // GL3.3 Core profile 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); glfwWindowHint(GLFW_VISIBLE, 0); //オフスクリーン // Open a window and create its OpenGL context window = glfwCreateWindow(1, 1, "GPGPU Test", NULL, NULL); if (window == NULL){ fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n"); getchar(); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); #if defined _WIN32 // Initialize GLEW glewExperimental = GL_TRUE; ///!!!! important for core profile // コアプロファイルで必要となります if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); getchar(); glfwTerminate(); return -1; } #endif { cout << "GL_VENDOR:" << glGetString(GL_VENDOR) << endl; cout << "GL_RENDERER:" << glGetString(GL_RENDERER) << endl; cout << "GL_VERSION:" << glGetString(GL_VERSION) << endl; cout << "GL_SHADING_LANGUAGE_VERSION:" << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl; } // Mat imgSrc = Mat(Size(32, 24), CV_32FC1); Mat imgSrc = Mat(Size(8, 4), CV_32FC1); Mat imgDst = Mat::zeros(imgSrc.size(), imgSrc.type()); //--------------------------------- //init Src image { const int width = imgSrc.cols; const int height = imgSrc.rows; for (int y = 0; y < height; y++){ for (int x = 0; x < width; x++){ imgSrc.at<float>(y,x) = y*100.0f + x; } } } //--------------------------------- //Execute GPGPU { const int width = imgSrc.cols; const int height = imgSrc.rows; // Create and compile our GLSL program from the shaders GLuint programID = LoadShaders("GpGpuVertexShader.vertexshader", "GpGpuFragmentShader.fragmentshader"); // FBO identifier GLuint fbo = 0; //--------------------------------- // FBO // create FBO (off-screen framebuffer) glGenFramebuffers(1, &fbo); // bind offscreen framebuffer (that is, skip the window-specific render target) glBindFramebuffer(GL_FRAMEBUFFER, fbo); // texture enum E_TextureID{ SRC, DST, SIZEOF, }; unsigned int textureID[E_TextureID::SIZEOF]; //src dst //--------------------------------- // CreateTexture { GLenum format = GL_RED; //single channel GLenum type = GL_FLOAT; //float GLenum internalFormat = GL_R32F; //single channel float glGenTextures(sizeof(textureID) / sizeof(textureID[0]), textureID); // create (reference to) a new texture for (int i = 0; i < sizeof(textureID) / sizeof(textureID[0]); i++){ glBindTexture(GL_TEXTURE_2D, textureID[i]); // (set texture parameters here) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); //create the texture glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, type, 0); glBindTexture(GL_TEXTURE_2D, 0); } } //upload imgSrc to texture { GLenum format = GL_RED; //single channel GLenum type = GL_FLOAT; //float void* data = imgSrc.data; glBindTexture(GL_TEXTURE_2D, textureID[E_TextureID::SRC]); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, data); glBindTexture(GL_TEXTURE_2D, 0); } //Execute { glUseProgram(programID); GLuint vao; GLuint vbo; // [-1, 1] の正方形 static GLfloat position[][2] = { { -1.0f, -1.0f }, { 1.0f, -1.0f }, { 1.0f, 1.0f }, { -1.0f, 1.0f } }; // create vao&vbo glGenVertexArrays(1, &vao); glGenBuffers(1, &vbo); // bind vao & vbo glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); // upload vbo data glBufferData(GL_ARRAY_BUFFER, (int)sizeof(position), position, GL_STATIC_DRAW); // Set VertexAttribute GLint attrLoc = glGetAttribLocation(programID, "position"); glEnableVertexAttribArray(attrLoc); //enable attribute Location glVertexAttribPointer( attrLoc, // attribute 0. No particular reason for 0, but must match the layout in the shader. 2, // size (Specifies the number of components) x,y GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (Specifies the byte offset between consecutive generic vertex attributes) (void*)0 // array buffer offset (Specifies a pointer to the first generic vertex attribute in the array) ); //Bind Texture & Fbo const int textureUnit = 0; glActiveTexture(GL_TEXTURE0 + textureUnit); glBindTexture(GL_TEXTURE_2D, textureID[E_TextureID::SRC]); glUniform1i(glGetUniformLocation(programID, "texSrc"), textureUnit); glUniform2f(glGetUniformLocation(programID, "texSrcSize"),width,height); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureID[E_TextureID::DST], 0); //Viewport glViewport(0, 0, width, height); //Render!! glDrawArrays(GL_TRIANGLE_FAN, 0, (int)(sizeof(position) / sizeof(position[0]))); glFlush(); // delete vao&vbo glBindVertexArray(0); glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); } { //download from framebuffer GLenum format = GL_RED; //single channel GLenum type = GL_FLOAT; //float void* data = imgDst.data; int width = imgDst.cols; int height = imgDst.rows; //wait for Rendering glFinish(); // ReadBuffer glReadBuffer(GL_COLOR_ATTACHMENT0); // ReadPixels glReadPixels(0, 0, width, height, format, type, data); } //clean up glDeleteFramebuffers(1, &fbo); glDeleteTextures(sizeof(textureID) / sizeof(textureID[0]), textureID); glDeleteProgram(programID); } //dump { cout << "imgSrc" << endl; cout << imgSrc << endl; cout << "imgDst" << endl; cout << imgDst << endl; } //verify int errNum = 0; { //verify int width = imgSrc.cols; int height = imgSrc.rows; for (int y = 0; y < height; y++){ for (int x = 0; x < width; x++){ float src = imgSrc.at<float>(y, x); float dst = imgDst.at<float>(y, x); if (src != dst) errNum++; } } cout << "ErrNum:" << errNum << endl; } #if 0 //visualize { imshow("src", imgSrc); imshow("dst", imgDst); waitKey(); } #endif // Close OpenGL window and terminate GLFW glfwTerminate(); cout << "Hit return key" << endl; cin.get(); return errNum; }
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(800, 600, "triangle", nullptr, nullptr); glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll); glewExperimental = GL_TRUE; glewInit(); glViewport(0, 0, 800, 600); glEnable(GL_DEPTH_TEST); GLint vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vertexshader, NULL); GLint fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fragmentshader, NULL); glCompileShader(vertex); glCompileShader(fragment); GLint program = glCreateProgram(); glAttachShader(program, vertex); glAttachShader(program, fragment); glLinkProgram(program); GLint fragment1 = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment1, 1, &fragmentshader1, NULL); glCompileShader(fragment1); GLint program1 = glCreateProgram(); glAttachShader(program1, vertex); glAttachShader(program1, fragment1); glLinkProgram(program1); GLfloat vertices[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f }; glm::vec3 cubePositions[] = { glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, -4.0f), glm::vec3(0.0f, 0.0f, -10.f), glm::vec3(0.0f, 0.0f, -22.0f), glm::vec3(0.0f, 0.0f, -35.0f), glm::vec3(0.0f, 0.0f, -55.0f), glm::vec3(0.0f, 0.0f, -80.0f), }; GLfloat angle[7] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; GLfloat size[7] = { 0.3f, 1.0f, 1.2f, 0.7, 5.0f, 4.0f, 3.0f }; GLuint vbo, vaoc, vaol; glGenBuffers(1, &vbo); glGenVertexArrays(1, &vaoc); glGenVertexArrays(1, &vaol); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindVertexArray(vaoc); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glBindVertexArray(0); glBindVertexArray(vaol); glBindBuffer(GL_ARRAY_BUFFER, vbo); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glBindVertexArray(0); while (!glfwWindowShouldClose(window)) { glfwPollEvents(); movement(); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(program); glm::mat4 model; glm::mat4 view; glm::mat4 projection; view = glm::lookAt(camerapos, camerapos - cameramove, cameraup); projection = glm::perspective(aspect, (GLfloat)800 / (GLfloat)600, 0.1f, 200.0f); GLint modelLoc = glGetUniformLocation(program, "model"); GLint viewLoc = glGetUniformLocation(program, "view"); GLint projLoc = glGetUniformLocation(program, "projection"); GLint objectcolorLoc = glGetUniformLocation(program, "objectcolor"); GLint lightcolorLoc = glGetUniformLocation(program, "lightcolor"); GLint lightPosLoc = glGetUniformLocation(program, "lightPos"); GLint viewPosLoc = glGetUniformLocation(program, "viewPos"); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); glUniform3f(lightcolorLoc, 1.0f, 1.0f, 1.0f); glUniform3f(lightPosLoc, lightPos.x, lightPos.y, lightPos.z); glUniform3f(viewPosLoc, camerapos.x, camerapos.y, camerapos.z); glBindVertexArray(vaoc); for (GLint i = 0; i < 7; i++) { model = glm::mat4(); model = glm::translate(model, cubePositions[i]); angle[i] = angle[i] + ((7 - i)* 0.00002); GLfloat radius = (20.0f + -1 * cubePositions[i].z); GLfloat x = sin(angle[i]) * radius; GLfloat z = (1 - cos(angle[i])) * radius; model = glm::translate(model, glm::vec3(x, 0.0f, z)); model = glm::rotate(model, (GLfloat)glfwGetTime() / (i + 1) * 2, glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::scale(model, glm::vec3(size[i])); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); glUniform3f(objectcolorLoc, 1.0f - (GLfloat)0.14f * i, 0.0f + (GLfloat)0.1f * i, 0.0f + (GLfloat)0.1f * i); glDrawArrays(GL_TRIANGLES, 0, 36); } glBindVertexArray(0); glUseProgram(program1); modelLoc = glGetUniformLocation(program1, "model"); viewLoc = glGetUniformLocation(program1, "view"); projLoc = glGetUniformLocation(program1, "projection"); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); model = glm::mat4(); model = glm::translate(model, lightPos); model = glm::scale(model, glm::vec3(10.0f)); model = glm::rotate(model, (GLfloat)glfwGetTime() *0.2f, glm::vec3(0.0f, 1.0f, 0.0f)); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); glBindVertexArray(vaol); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); glfwSwapBuffers(window); } glfwTerminate(); return 0; }
void AnalyzeSequence_GLSL(std::shared_ptr<DatasetUtils::Segm::Video::Sequence> pCurrSequence) { srand(0); // for now, assures that two consecutive runs on the same data return the same results //srand((unsigned int)time(NULL)); size_t nCurrFrameIdx = 0; size_t nNextFrameIdx = nCurrFrameIdx+1; bool bGPUContextInitialized = false; try { glfwSetErrorCallback(GLFWErrorCallback); CV_Assert(pCurrSequence.get() && pCurrSequence->GetTotalImageCount()>1); if(pCurrSequence->m_pEvaluator==nullptr && EVALUATE_OUTPUT) throw std::runtime_error(cv::format("Missing evaluation impl for video segmentation dataset '%s'",g_pDatasetInfo->m_sDatasetName.c_str())); const std::string sCurrSeqName = pCurrSequence->m_sName.size()>12?pCurrSequence->m_sName.substr(0,12):pCurrSequence->m_sName; const size_t nFrameCount = pCurrSequence->GetTotalImageCount(); const cv::Mat oROI = LIMIT_MODEL_TO_SEQUENCE_ROI?pCurrSequence->GetROI():cv::Mat(); cv::Mat oCurrInputFrame = pCurrSequence->GetInputFromIndex(nCurrFrameIdx).clone(); CV_Assert(!oCurrInputFrame.empty()); CV_Assert(oCurrInputFrame.isContinuous()); #if NEED_GT_MASK cv::Mat oCurrGTMask = pCurrSequence->GetGTFromIndex(nCurrFrameIdx).clone(); CV_Assert(!oCurrGTMask.empty() && oCurrGTMask.isContinuous()); #endif //NEED_GT_MASK #if DISPLAY_OUTPUT cv::Mat oLastInputFrame = oCurrInputFrame.clone(); #endif //DISPLAY_OUTPUT cv::Mat oNextInputFrame = pCurrSequence->GetInputFromIndex(nNextFrameIdx); #if NEED_GT_MASK #if NEED_LAST_GT_MASK cv::Mat oLastGTMask = oCurrGTMask.clone(); #endif // NEED_LAST_GT_MASK cv::Mat oNextGTMask = pCurrSequence->GetGTFromIndex(nNextFrameIdx); #endif //NEED_GT_MASK #if NEED_FG_MASK cv::Mat oLastFGMask(oCurrInputFrame.size(),CV_8UC1,cv::Scalar_<uchar>(0)); #endif //NEED_FG_MASK #if DISPLAY_OUTPUT cv::Mat oLastBGImg; #endif //DISPLAY_OUTPUT glAssert(oCurrInputFrame.channels()==1 || oCurrInputFrame.channels()==4); cv::Size oWindowSize = oCurrInputFrame.size(); // note: never construct GL classes before context initialization if(glfwInit()==GL_FALSE) glError("Failed to init GLFW"); bGPUContextInitialized = true; glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,TARGET_GL_VER_MAJOR); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,TARGET_GL_VER_MINOR); glfwWindowHint(GLFW_RESIZABLE,GL_FALSE); #if !DISPLAY_OUTPUT glfwWindowHint(GLFW_VISIBLE,GL_FALSE); #endif //!DISPLAY_OUTPUT std::unique_ptr<GLFWwindow,void(*)(GLFWwindow*)> pWindow(glfwCreateWindow(oWindowSize.width,oWindowSize.height,(pCurrSequence->m_sRelativePath+" [GPU]").c_str(),nullptr,nullptr),glfwDestroyWindow); if(!pWindow) glError("Failed to create window via GLFW"); glfwMakeContextCurrent(pWindow.get()); glewInitErrorCheck; #if USE_LOBSTER std::shared_ptr<BackgroundSubtractorLOBSTER_GLSL> pAlgo(new BackgroundSubtractorLOBSTER_GLSL()); const double dDefaultLearningRate = BGSLOBSTER_DEFAULT_LEARNING_RATE; pAlgo->initialize(oCurrInputFrame,oROI); #elif USE_SUBSENSE #error "Missing glsl impl." // ... @@@@@ std::shared_ptr<BackgroundSubtractorSuBSENSE_GLSL> pAlgo(new BackgroundSubtractorSuBSENSE_GLSL()); const double dDefaultLearningRate = 0; pAlgo->initialize(oCurrInputFrame,oROI); #elif USE_PAWCS #error "Missing glsl impl." // ... @@@@@ std::shared_ptr<BackgroundSubtractorPAWCS_GLSL> pAlgo(new BackgroundSubtractorPAWCS_GLSL()); const double dDefaultLearningRate = 0; pAlgo->initialize(oCurrInputFrame,oROI); #else //USE_VIBE || USE_PBAS #error "Missing glsl impl." // ... @@@@@ const size_t m_nInputChannels = (size_t)oCurrInputFrame.channels(); #if USE_VIBE std::shared_ptr<cv::BackgroundSubtractorViBe_GLSL> pAlgo; if(m_nInputChannels==3) pAlgo = std::shared_ptr<cv::BackgroundSubtractorViBe_GLSL>(new BackgroundSubtractorViBe_GLSL_3ch()); else pAlgo = std::shared_ptr<cv::BackgroundSubtractorViBe_GLSL>(new BackgroundSubtractorViBe_GLSL_1ch()); const double dDefaultLearningRate = BGSVIBE_DEFAULT_LEARNING_RATE; #else //USE_PBAS std::shared_ptr<cv::BackgroundSubtractorPBAS_GLSL> pAlgo; if(m_nInputChannels==3) pAlgo = std::shared_ptr<cv::BackgroundSubtractorPBAS_GLSL>(new BackgroundSubtractorPBAS_GLSL_3ch()); else pAlgo = std::shared_ptr<cv::BackgroundSubtractorPBAS_GLSL>(new BackgroundSubtractorPBAS_GLSL_1ch()); const double dDefaultLearningRate = BGSPBAS_DEFAULT_LEARNING_RATE_OVERRIDE; #endif //USE_PBAS pAlgo->initialize(oCurrInputFrame); #endif //USE_VIBE || USE_PBAS #if DISPLAY_OUTPUT bool bContinuousUpdates = false; std::string sDisplayName = pCurrSequence->m_sRelativePath; cv::namedWindow(sDisplayName); #endif //DISPLAY_OUTPUT #if (WRITE_IMG_OUTPUT || WRITE_AVI_OUTPUT) #if WRITE_AVI_OUTPUT cv::VideoWriter oSegmWriter(pCurrSequence->m_sResultsPath+"../"+pCurrSequence->m_sName+"_segm.avi",CV_FOURCC('F','F','V','1'),30,pCurrSequence->GetImageSize(),false); #endif //WRITE_AVI_OUTPUT #endif //(WRITE_IMG_OUTPUT || WRITE_AVI_OUTPUT) std::shared_ptr<GLImageProcAlgo> pGLSLAlgo = std::dynamic_pointer_cast<GLImageProcAlgo>(pAlgo); if(pGLSLAlgo==nullptr) glError("Segmentation algorithm has no GLImageProcAlgo interface"); pGLSLAlgo->setOutputFetching(NEED_FG_MASK); if(!pGLSLAlgo->getIsUsingDisplay() && DISPLAY_OUTPUT) // @@@@ determine in advance to hint window to hide? or just always hide, and show when needed? glfwHideWindow(pWindow.get()); #if USE_GLSL_EVALUATION std::shared_ptr<DatasetUtils::EvaluatorBase::GLEvaluatorBase> pGLSLAlgoEvaluator; if(pCurrSequence->m_pEvaluator!=nullptr) pGLSLAlgoEvaluator = std::dynamic_pointer_cast<DatasetUtils::EvaluatorBase::GLEvaluatorBase>(pCurrSequence->m_pEvaluator->CreateGLEvaluator(pGLSLAlgo,nFrameCount)); if(pGLSLAlgoEvaluator==nullptr) glError("Segmentation evaluation algorithm has no GLSegmEvaluator interface"); pGLSLAlgoEvaluator->initialize(oCurrGTMask,oROI.empty()?cv::Mat(oCurrInputFrame.size(),CV_8UC1,cv::Scalar_<uchar>(255)):oROI); oWindowSize.width *= pGLSLAlgoEvaluator->m_nSxSDisplayCount; #else //!USE_GLSL_EVALUATION oWindowSize.width *= pGLSLAlgo->m_nSxSDisplayCount; #endif //!USE_GLSL_EVALUATION glfwSetWindowSize(pWindow.get(),oWindowSize.width,oWindowSize.height); glViewport(0,0,oWindowSize.width,oWindowSize.height); TIMER_TIC(MainLoop); while(nNextFrameIdx<=nFrameCount) { if(!((nCurrFrameIdx+1)%100)) std::cout << "\t\t" << std::setfill(' ') << std::setw(12) << sCurrSeqName << " @ F:" << std::setfill('0') << std::setw(PlatformUtils::decimal_integer_digit_count((int)nFrameCount)) << nCurrFrameIdx+1 << "/" << nFrameCount << " [GPU]" << std::endl; const double dCurrLearningRate = (BOOTSTRAP_100_FIRST_FRAMES&&nCurrFrameIdx<=100)?1:dDefaultLearningRate; TIMER_INTERNAL_TIC(OverallLoop); TIMER_INTERNAL_TIC(PipelineUpdate); pAlgo->apply_async(oNextInputFrame,dCurrLearningRate); TIMER_INTERNAL_TOC(PipelineUpdate); #if USE_GLSL_EVALUATION pGLSLAlgoEvaluator->apply_async(oNextGTMask); #endif //USE_GLSL_EVALUATION TIMER_INTERNAL_TIC(VideoQuery); #if DISPLAY_OUTPUT oCurrInputFrame.copyTo(oLastInputFrame); oNextInputFrame.copyTo(oCurrInputFrame); #endif //DISPLAY_OUTPUT if(++nNextFrameIdx<nFrameCount) oNextInputFrame = pCurrSequence->GetInputFromIndex(nNextFrameIdx); #if DEBUG_OUTPUT cv::imshow(sMouseDebugDisplayName,oNextInputFrame); #endif //DEBUG_OUTPUT #if NEED_GT_MASK #if NEED_LAST_GT_MASK oCurrGTMask.copyTo(oLastGTMask); oNextGTMask.copyTo(oCurrGTMask); #endif //NEED_LAST_GT_MASK if(nNextFrameIdx<nFrameCount) oNextGTMask = pCurrSequence->GetGTFromIndex(nNextFrameIdx); #endif //NEED_GT_MASK TIMER_INTERNAL_TOC(VideoQuery); glErrorCheck; if(glfwWindowShouldClose(pWindow.get())) break; glfwPollEvents(); #if DISPLAY_OUTPUT if(glfwGetKey(pWindow.get(),GLFW_KEY_ESCAPE) || glfwGetKey(pWindow.get(),GLFW_KEY_Q)) break; glfwSwapBuffers(pWindow.get()); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); #endif //DISPLAY_OUTPUT #if NEED_FG_MASK pAlgo->getLatestForegroundMask(oLastFGMask); if(!oROI.empty()) cv::bitwise_or(oLastFGMask,UCHAR_MAX/2,oLastFGMask,oROI==0); #endif //NEED_FG_MASK #if DISPLAY_OUTPUT pAlgo->getBackgroundImage(oLastBGImg); if(!oROI.empty()) cv::bitwise_or(oLastBGImg,UCHAR_MAX/2,oLastBGImg,oROI==0); cv::Mat oDisplayFrame = DatasetUtils::GetDisplayImage(oLastInputFrame,oLastBGImg,pCurrSequence->m_pEvaluator?pCurrSequence->m_pEvaluator->GetColoredSegmMaskFromResult(oLastFGMask,oLastGTMask,oROI):oLastFGMask,nCurrFrameIdx); cv::Mat oDisplayFrameResized; if(oDisplayImage.cols>1920 || oDisplayImage.rows>1080) cv::resize(oDisplayFrame,oDisplayFrameResized,cv::Size(oDisplayFrame.cols/2,oDisplayFrame.rows/2)); else oDisplayFrameResized = oDisplayFrame; cv::imshow(sDisplayName,oDisplayFrameResized); int nKeyPressed; if(bContinuousUpdates) nKeyPressed = cv::waitKey(1); else nKeyPressed = cv::waitKey(0); if(nKeyPressed!=-1) nKeyPressed %= (UCHAR_MAX+1); // fixes return val bug in some opencv versions if(nKeyPressed==' ') bContinuousUpdates = !bContinuousUpdates; else if(nKeyPressed==(int)'q') break; #endif //DISPLAY_OUTPUT #if WRITE_AVI_OUTPUT oSegmWriter.write(oLastFGMask); #endif //WRITE_AVI_OUTPUT #if WRITE_IMG_OUTPUT pCurrSequence->WriteResult(nCurrFrameIdx,oLastFGMask); #endif //WRITE_IMG_OUTPUT #if (EVALUATE_OUTPUT && (!USE_GLSL_EVALUATION || VALIDATE_GPU_EVALUATION)) if(pCurrSequence->m_pEvaluator) pCurrSequence->m_pEvaluator->AccumulateMetricsFromResult(oCurrFGMask,oCurrGTMask,oROI); #endif //(EVALUATE_OUTPUT && (!USE_GLSL_EVALUATION || VALIDATE_GPU_EVALUATION)) TIMER_INTERNAL_TOC(OverallLoop); #if DISPLAY_TIMERS std::cout << "VideoQuery=" << TIMER_INTERNAL_ELAPSED_MS(VideoQuery) << "ms, " << "PipelineUpdate=" << TIMER_INTERNAL_ELAPSED_MS(PipelineUpdate) << "ms, " << "OverallLoop=" << TIMER_INTERNAL_ELAPSED_MS(OverallLoop) << "ms" << std::endl; #endif //ENABLE_INTERNAL_TIMERS ++nCurrFrameIdx; } TIMER_TOC(MainLoop); const double dTimeElapsed = TIMER_ELAPSED_MS(MainLoop)/1000; const double dAvgFPS = (double)nCurrFrameIdx/dTimeElapsed; std::cout << "\t\t" << std::setfill(' ') << std::setw(12) << sCurrSeqName << " @ end, " << int(dTimeElapsed) << " sec in-thread (" << (int)floor(dAvgFPS+0.5) << " FPS)" << std::endl; #if EVALUATE_OUTPUT if(pCurrSequence->m_pEvaluator) { #if USE_GLSL_EVALUATION #if VALIDATE_GPU_EVALUATION printf("cpu eval:\n\tnTP=%" PRIu64 ", nTN=%" PRIu64 ", nFP=%" PRIu64 ", nFN=%" PRIu64 ", nSE=%" PRIu64 ", tot=%" PRIu64 "\n",pCurrSequence->m_pEvaluator->m_oBasicMetrics.nTP,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nTN,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nFP,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nFN,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nSE,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nTP+pCurrSequence->m_pEvaluator->m_oBasicMetrics.nTN+pCurrSequence->m_pEvaluator->m_oBasicMetrics.nFP+pCurrSequence->m_pEvaluator->m_oBasicMetrics.nFN); #endif //VALIDATE_USE_GLSL_EVALUATION pCurrSequence->m_pEvaluator->FetchGLEvaluationResults(pGLSLAlgoEvaluator); #if VALIDATE_GPU_EVALUATION printf("gpu eval:\n\tnTP=%" PRIu64 ", nTN=%" PRIu64 ", nFP=%" PRIu64 ", nFN=%" PRIu64 ", nSE=%" PRIu64 ", tot=%" PRIu64 "\n",pCurrSequence->m_pEvaluator->m_oBasicMetrics.nTP,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nTN,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nFP,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nFN,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nSE,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nTP+pCurrSequence->m_pEvaluator->m_oBasicMetrics.nTN+pCurrSequence->m_pEvaluator->m_oBasicMetrics.nFP+pCurrSequence->m_pEvaluator->m_oBasicMetrics.nFN); #endif //VALIDATE_USE_GLSL_EVALUATION #endif //USE_GLSL_EVALUATION pCurrSequence->m_pEvaluator->dTimeElapsed_sec = dTimeElapsed; } #endif //EVALUATE_OUTPUT #if DISPLAY_OUTPUT cv::destroyWindow(sDisplayName); #endif //DISPLAY_OUTPUT } catch(const CxxUtils::Exception& e) { std::cout << "\nAnalyzeSequence caught Exception:\n" << e.what(); if(!g_sLatestGLFWErrorMessage.empty()) { std::cout << " (" << g_sLatestGLFWErrorMessage << ")" << "\n" << std::endl; g_sLatestGLFWErrorMessage = std::string(); } else std::cout << "\n" << std::endl; } catch(const cv::Exception& e) { std::cout << "\nAnalyzeSequence caught cv::Exception:\n" << e.what() << "\n" << std::endl; } catch(const std::exception& e) { std::cout << "\nAnalyzeSequence caught std::exception:\n" << e.what() << "\n" << std::endl; } catch(...) { std::cout << "\nAnalyzeSequence caught unhandled exception\n" << std::endl; } if(bGPUContextInitialized) glfwTerminate(); if(pCurrSequence.get()) { #if DATASET_PRECACHING pCurrSequence->StopPrecaching(); #endif //DATASET_PRECACHING pCurrSequence->m_nImagesProcessed.set_value(nCurrFrameIdx); } }
int main(int argc, char **argv) #endif { const GLFWvidmode *video_mode; int c; while ((c = fz_getopt(argc, argv, "p:r:W:H:S:U:")) != -1) { switch (c) { default: usage(argv[0]); break; case 'p': password = fz_optarg; break; case 'r': currentzoom = fz_atof(fz_optarg); break; case 'W': layout_w = fz_atof(fz_optarg); break; case 'H': layout_h = fz_atof(fz_optarg); break; case 'S': layout_em = fz_atof(fz_optarg); break; case 'U': layout_css = fz_optarg; break; } } if (fz_optind < argc) { fz_strlcpy(filename, argv[fz_optind], sizeof filename); } else { #ifdef _WIN32 win_install(); if (!win_open_file(filename, sizeof filename)) exit(0); #else usage(argv[0]); #endif } title = strrchr(filename, '/'); if (!title) title = strrchr(filename, '\\'); if (title) ++title; else title = filename; memset(&ui, 0, sizeof ui); search_input.p = search_input.text; search_input.q = search_input.p; search_input.end = search_input.p; glfwSetErrorCallback(on_error); if (!glfwInit()) { fprintf(stderr, "cannot initialize glfw\n"); exit(1); } video_mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); screen_w = video_mode->width; screen_h = video_mode->height; window = glfwCreateWindow(DEFAULT_WINDOW_W, DEFAULT_WINDOW_H, filename, NULL, NULL); if (!window) { fprintf(stderr, "cannot create glfw window\n"); exit(1); } glfwMakeContextCurrent(window); ctx = fz_new_context(NULL, NULL, 0); fz_register_document_handlers(ctx); if (layout_css) { fz_buffer *buf = fz_read_file(ctx, layout_css); fz_set_user_css(ctx, fz_string_from_buffer(ctx, buf)); fz_drop_buffer(ctx, buf); } has_ARB_texture_non_power_of_two = glfwExtensionSupported("GL_ARB_texture_non_power_of_two"); if (!has_ARB_texture_non_power_of_two) fz_warn(ctx, "OpenGL implementation does not support non-power of two texture sizes"); glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size); ui.fontsize = DEFAULT_UI_FONTSIZE; ui.baseline = DEFAULT_UI_BASELINE; ui.lineheight = DEFAULT_UI_LINEHEIGHT; ui_init_fonts(ctx, ui.fontsize); reload(); shrinkwrap(); glfwSetFramebufferSizeCallback(window, on_reshape); glfwSetCursorPosCallback(window, on_mouse_motion); glfwSetMouseButtonCallback(window, on_mouse_button); glfwSetScrollCallback(window, on_scroll); glfwSetCharModsCallback(window, on_char); glfwSetKeyCallback(window, on_key); glfwSetWindowRefreshCallback(window, on_display); glfwGetFramebufferSize(window, &window_w, &window_h); ui_needs_update = 1; while (!glfwWindowShouldClose(window)) { glfwWaitEvents(); if (ui_needs_update) run_main_loop(); } ui_finish_fonts(ctx); fz_drop_link(ctx, links); fz_drop_page(ctx, page); fz_drop_outline(ctx, outline); fz_drop_document(ctx, doc); fz_drop_context(ctx); glfwTerminate(); return 0; }
// the program starts here void AppMain() { // initialise GLFW glfwSetErrorCallback(OnError); if(!glfwInit()) throw std::runtime_error("glfwInit failed"); // open a window with GLFW glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); gWindow = glfwCreateWindow((int)SCREEN_SIZE.x, (int)SCREEN_SIZE.y, "Mek", NULL /*glfwGetPrimaryMonitor()*/, NULL); if (!gWindow) throw std::runtime_error("glfwCreateWindow failed. Can your hardware handle OpenGL 3.3?"); // GLFW settings glfwSetInputMode(gWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPos(gWindow, 0, 0); glfwSetScrollCallback(gWindow, OnScroll); glfwMakeContextCurrent(gWindow); // required or we crash on VAO creation glewExperimental = GL_TRUE; // initialise GLEW if (glewInit() != GLEW_OK) { throw std::runtime_error("glewInit failed"); } // GLEW throws some errors so discard all the errors so far while(glGetError() != GL_NO_ERROR) {} // Init DevIL ilInit(); // enable vsync using windows only code #ifdef _WIN32 // Turn on vertical screen sync under Windows. typedef BOOL(WINAPI *PFNWGLSWAPINTERVALEXTPROC)(int interval); PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = NULL; wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); if (wglSwapIntervalEXT) wglSwapIntervalEXT(1); #endif // print out some info about the graphics drivers std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl; std::cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl; std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl; // make sure OpenGL version 3.2 API is available if(!GLEW_VERSION_3_3) throw std::runtime_error("OpenGL 3.3 API is not available."); // OpenGL settings glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // initialise the gWoodenCrate asset LoadWoodenCrateAsset(); // create all the instances in the 3D scene based on the gWoodenCrate asset CreateInstances(); // setup Camera::getInstance() Camera::getInstance().setPosition(glm::vec3(1100, 75, 0)); Camera::getInstance().setViewportAspectRatio(SCREEN_SIZE.x / SCREEN_SIZE.y); Camera::getInstance().setNearAndFarPlanes(1.f, 500.0f); Camera::getInstance().setFieldOfView(179); crosshair = new twodOverlay("crosshair.png", 0, 0, 1); skull = new twodOverlayAnim("killSkull.png", 5, 0.5); startscreen = new twodOverlay("pressStart.png", 0, 0, 10); skull->updatePos(-0.85f, -0.75f, 4); skull ->cycle = true; //MODEL INITS prepProjectiles(); model = new GameObject(0); model->SetName("Moving"); gModel = new ComponentGraphics(); gModel->setOwner(model); gModel->loadModel("models/TallCube.dae"); Component* gp = gModel; model->AddComponent(GRAPHICS, gp); gCol = new ComponentCollision(); gCol->setCollisionMask(gModel->getScene()); gCol->setOwner(model); model->pos = glm::vec3(7.5, 0.5, -11); model->vel = 0.01; model->dir = glm::vec3(1, 0, 0); model->scale = glm::vec3(5, 5, 5); gCol->type = MOVING; gCol->createHitboxRender(); gp = gCol; model->AddComponent(PHYSICS, gp); ComponentInput* ci = new ComponentInput(0.05,0.05); gp = ci; model->AddComponent(CONTROLLER, gp); //PROPER INIT for (int i = 0; i < 22; i++) { if (i != 3 && i != 0 && i != 4 && i != 8 && i != 18 && i != 19 && i != 20 && i !=21) { GameObject *gObject = new GameObject(goVec.size()); ComponentGraphics *cModel = new ComponentGraphics(); ComponentCollision *cCollision = new ComponentCollision(); Component *c; if (i == 0) { gObject->SetName("Spawn Container 1"); cModel->loadModel("models/Container.dae"); gObject->scale = glm::vec3(0.7, 0.7, 0.7); gObject->pos = glm::vec3(60, 0, -110); } else if (i == 1) { gObject->SetName("Water Tower"); cModel->loadModel("models/Watertower.dae"); gObject->scale = glm::vec3(3, 3, 3); gObject->pos = glm::vec3(-65, 0, -90); } else if (i == 2) { gObject->SetName("MenuScene"); cModel->loadModel("models/Warehouse_One_mesh_No_roof.dae"); gObject->scale = glm::vec3(1, 1, 1);// glm::vec3(1.6, 1.6, 1.6); gObject->pos = glm::vec3(10000, 0, 0); } else if (i == 3) { gObject->SetName("Spawn Container 2"); cModel->loadModel("models/Container90.dae"); gObject->scale = glm::vec3(0.7, 0.7, 0.7); gObject->pos = glm::vec3(85, 0, -75); } else if (i == 4) { gObject->SetName("Middle Plus"); cModel->loadModel("models/Container.dae"); gObject->scale = glm::vec3(0.7, 0.7, 0.7); gObject->pos = glm::vec3(15, 0, -20); } else if (i == 5) { gObject->SetName("North Wall"); cModel->loadModel("models/Container_Wal_LPl.dae"); gObject->scale = glm::vec3(0.7, 0.70, 0.70); gObject->pos = glm::vec3(100, 0, 165); } else if (i == 6) { gObject->SetName("Dumbster");//Crane cModel->loadModel("models/Dumspter2.dae"); gObject->pos = glm::vec3(0, 0, -140); gObject->scale = glm::vec3(0.4, 0.4, 0.4); } else if (i == 7) { gObject->SetName("Shack"); cModel->loadModel("models/Shack.dae"); gObject->scale = glm::vec3(0.75, 0.75, 0.75); gObject->pos = glm::vec3(0, 0, 120); } else if (i == 8) { gObject->SetName("Middle Plus"); cModel->loadModel("models/Container.dae"); gObject->scale = glm::vec3(0.7, 0.7, 0.7); gObject->pos = glm::vec3(-5, 0, -20); } else if (i == 9) { gObject->SetName("Container 2"); cModel->loadModel("models/Container.dae"); gObject->scale = glm::vec3(0.70, 0.70, 0.70); gObject->pos = glm::vec3(80, 0, 100); } else if (i == 10) { gObject->SetName("South Wall"); cModel->loadModel("models/Container_Wal_LPl.dae"); gObject->scale = glm::vec3(0.7, 0.70, 0.70); gObject->pos = glm::vec3(-100, 0, 165); } else if (i == 11) { gObject->SetName("East Wall"); cModel->loadModel("models/Container_Wal_LP90.dae"); gObject->scale = glm::vec3(0.7, 0.70, 0.70); gObject->pos = glm::vec3(50, 0, 145); } else if (i == 12) { gObject->SetName("West Wall"); cModel->loadModel("models/Container_Wal_LP90.dae"); gObject->scale = glm::vec3(0.7, 0.70, 0.70); gObject->pos = glm::vec3(50, 0, -125); } else if (i == 13) { gObject->SetName("Container 2"); cModel->loadModel("models/Container.dae"); gObject->scale = glm::vec3(0.70, 0.70, 0.70); gObject->pos = glm::vec3(60, 0, 100); } else if (i == 14) { gObject->SetName("Container 90"); cModel->loadModel("models/Container90.dae"); gObject->scale = glm::vec3(0.70, 0.70, 0.70); gObject->pos = glm::vec3(70, 0, 70); } else if (i == 15) { gObject->SetName("Shack"); cModel->loadModel("models/Shack.dae"); gObject->scale = glm::vec3(0.75, 0.75, 0.75); gObject->pos = glm::vec3(-30, 0, 120); } else if (i == 16) { gObject->SetName("Shack"); cModel->loadModel("models/Shack.dae"); gObject->scale = glm::vec3(0.75, 0.75, 0.75); gObject->pos = glm::vec3(30, 0, 120); } else if (i == 17) { gObject->SetName("Shack"); cModel->loadModel("models/Shack.dae"); gObject->scale = glm::vec3(0.75, 0.75, 0.75); gObject->pos = glm::vec3(-60, 0, 120); } else if (i == 18) { gObject->SetName("Middle Plus North"); cModel->loadModel("models/Container90.dae"); gObject->scale = glm::vec3(0.7, 0.7, 0.7); gObject->pos = glm::vec3(27, 0, -5); } else if (i == 19) { gObject->SetName("Middle Plus North"); cModel->loadModel("models/Container90.dae"); gObject->scale = glm::vec3(0.7, 0.7, 0.7); gObject->pos = glm::vec3(27, 0, 15); } else if (i == 20) { gObject->SetName("Middle Plus North"); cModel->loadModel("models/Container90.dae"); gObject->scale = glm::vec3(0.7, 0.7, 0.7); gObject->pos = glm::vec3(-20, 0, 15); } else if (i == 21) { gObject->SetName("Middle Plus North"); cModel->loadModel("models/Container90.dae"); gObject->scale = glm::vec3(0.7, 0.7, 0.7); gObject->pos = glm::vec3(-20, 0, -5); } gObject->pos /= 10.f; cModel->setOwner(gObject); c = cModel; gObject->AddComponent(GRAPHICS, c); cCollision->setOwner(gObject); cCollision->setCollisionMask(cModel->getScene()); cCollision->type = STATIC; cCollision->setCollisionElip(glm::vec3(1, 1, 1)); cCollision->createHitboxRender(); gObject->AddComponent(PHYSICS, cCollision); goVec.push_back(gObject); } } LoadTargets(); spotLightColour = glm::normalize(spotLightColour); for (int i = 0; i < 6; i++) { LightComponent* light; if (i == 0) { light = new LightComponent(lSPOT); SpotLight* lc = new SpotLight; lc->Base.Base.Color = spotLightColour; lc->Base.Base.AmbientIntensity = 0.1f; lc->Base.Base.DiffuseIntensity = 0.1f; lc->Base.Atten.Constant = 0.1f; lc->Base.Atten.Exp = 0.1f; lc->Base.Atten.Linear = 0.1f; lc->Cutoff = 0.75f; lc->Base.Position = glm::vec3(-6, 1, 11); lc->Direction = glm::vec3(0, 0, -1); light->SetVars(lSPOT, lc); } if (i == 1) { light = new LightComponent(lSPOT); SpotLight* lc = new SpotLight; lc->Base.Base.Color = spotLightColour; lc->Base.Base.AmbientIntensity = 0.5f; lc->Base.Base.DiffuseIntensity = 0.5f; lc->Base.Atten.Constant = 0.5f; lc->Base.Atten.Exp = 0.5f; lc->Base.Atten.Linear = 0.5f; lc->Cutoff = 0.75f; lc->Base.Position = glm::vec3(3, 1, 11); lc->Direction = (glm::vec3(0, 0, 10)); light->SetVars(lSPOT, lc); } if (i == 2) { //light = new LightComponent(lSPOT); //SpotLight* lc = new SpotLight; //lc->Base.Base.Color = glm::vec3(0,0.1,0); //lc->Base.Base.AmbientIntensity = 0.5f; //lc->Base.Base.DiffuseIntensity = 0.5f; // //lc->Base.Atten.Constant = 0.5f; //lc->Base.Atten.Exp = 0.5f; //lc->Base.Atten.Linear = 0.5f; // //lc->Cutoff = 0.75f; //lc->Base.Position = glm::vec3(-3, 1, 11); //lc->Direction = (glm::vec3(-3, 0, 12)); // //light->SetVars(lSPOT, lc); } if (i == 3) { //light = new LightComponent(lSPOT); //SpotLight* lc = new SpotLight; //lc->Base.Base.Color = spotLightColour; //lc->Base.Base.AmbientIntensity = 0.5f; //lc->Base.Base.DiffuseIntensity = 0.5f; // //lc->Base.Atten.Constant = 0.5f; //lc->Base.Atten.Exp = 0.5f; //lc->Base.Atten.Linear = 0.5f; // //lc->Cutoff = 0.75f; //lc->Base.Position = glm::vec3(-6, 1, 11); //lc->Direction = (glm::vec3(-6, 1, 12)); // //light->SetVars(lSPOT, lc); } if (i == 4) { //light = new LightComponent(lSPOT); //SpotLight* lc = new SpotLight; //lc->Base.Base.Color = spotLightColour; //lc->Base.Base.AmbientIntensity = 0.1f; //lc->Base.Base.DiffuseIntensity = 0.1f; // //lc->Base.Atten.Constant = 0.1f; //lc->Base.Atten.Exp = 0.1f; //lc->Base.Atten.Linear = 0.1f; // //lc->Cutoff = 0.75f; //lc->Base.Position = glm::vec3(0, 1, 0); //lc->Direction = glm::vec3(0, -1, 0); // //light->SetVars(lSPOT, lc); } if (i == 5) { light = new LightComponent(lSPOT); SpotLight* lc = new SpotLight; lc->Base.Base.Color = spotLightColour; lc->Base.Base.AmbientIntensity = 0.5f; lc->Base.Base.DiffuseIntensity = 0.5f; lc->Base.Atten.Constant = 0.5f; lc->Base.Atten.Exp = 0.5f; lc->Base.Atten.Linear = 0.5f; lc->Cutoff = 0.5f; lc->Base.Position = glm::vec3(1000, 1, 0);//4 1 0 lc->Direction = glm::vec3(0, -1, 0);// 5 0 0 light->SetVars(lSPOT, lc); } } animatedMech = new GameObject(100); animatedMechGC = new ComponentGraphics(); animatedMechGC->loadModel("models/Test_Animation_DAE.dae"); Component* c = animatedMechGC; animatedMech->AddComponent(GRAPHICS, c); animatedMech->pos = glm::vec3(0, 0, 0); animatedMech->scale = glm::vec3(1, 1, 1); //END MODEL INITS camInterp.points.push_back(glm::vec3(1025, 1, 0)); camInterp.points.push_back(glm::vec3(1000, 1, 25)); camInterp.points.push_back(glm::vec3(975, 1, 0)); camInterp.points.push_back(glm::vec3(1000, 1, -25)); camInterp.points.push_back(glm::vec3(1025, 1, 0)); camInterp.state = SLERP; camInterp.buildCurve(); TextRendering::getInstance().initText2D("MekFont.bmp"); fontColour = glm::normalize(fontColour); wglSwapIntervalEXT(1); // run while the window is open double lastTime = glfwGetTime(); while(!glfwWindowShouldClose(gWindow)){ // process pending events glfwPollEvents(); // update the scene based on the time elapsed since last update double thisTime = glfwGetTime(); Update((float)(thisTime - lastTime)); lastTime = thisTime; // draw one frame Render(); // check for errors GLenum error = glGetError(); if (error != GL_NO_ERROR) { std::cerr << "OpenGL Error " << error << " - " << glewGetErrorString(error) << std::endl; } //exit program if escape key is pressed if(glfwGetKey(gWindow, GLFW_KEY_ESCAPE)) glfwSetWindowShouldClose(gWindow, GL_TRUE); } // clean up and exit glfwTerminate(); }
int main(int argc, char* argv[]) { if(argc>1) { mainScript=argv[1]; } //glfw if(!glfwInit()) { std::cout << "GLFW init error.\n"; return 1; } window = glfwCreateWindow(1280, 600, "Demo", 0, 0); if(!window) { glfwTerminate(); std::cout << "GLFW window creation error.\n"; return 2; } glfwMakeContextCurrent(window); glfwSwapInterval(1); //glfw callbacks glfwSetKeyCallback(window, onKey); glfwSetMouseButtonCallback(window, onMouseButton); glfwSetCursorPosCallback(window, onCursor); glfwSetScrollCallback(window, onScroll); glfwSetWindowIconifyCallback(window,onIconify); glfwSetWindowFocusCallback(window,onFocus); glfwSetCursorEnterCallback(window, onCursorEnter); glfwSetCharCallback(window, onChar); //glew GLenum glewErr = glewInit(); if(GLEW_OK != glewErr) { std::cout << "GLEW Error " << glewGetErrorString(glewErr) << std::endl; glfwTerminate(); return 3; } // printVers(); // int majorVer,minorVer; glGetIntegerv(GL_MAJOR_VERSION,&majorVer); glGetIntegerv(GL_MINOR_VERSION,&minorVer); //std::cout << majorVer<<" "<<minorVer << std::endl; // programManager=new ProgramManager(); // if(majorVer>3 || minorVer>=3) { geometryShaderSupport=true; programManager->setGeometryShaderSupport(true); glPrimitiveRestartIndex(-1); } // initDeferred(); //inits textureManager=new TextureManager(); geometryVaoManager=new GeometryVaoManager(); scene=new Scene(mainScript); // UpdateListener *fileListener=new UpdateListener(); FW::FileWatcher fileWatcher; fileWatcher.addWatch("data/shader/geometry", fileListener); fileWatcher.addWatch("data/shader/deferred", fileListener); fileWatcher.addWatch("data/shader", fileListener); fileWatcher.addWatch("data/texture", fileListener); fileWatcher.addWatch("data/geometry", fileListener); fileWatcher.addWatch("data", fileListener); // int lastClientWidth=0,lastClientHeight=0; // while(!glfwWindowShouldClose(window)) { fileWatcher.update(); double time = glfwGetTime(); int clientWidth,clientHeight; glfwGetWindowSize(window, &clientWidth, &clientHeight); scene->run(time,clientWidth,clientHeight); glfwSetInputMode(window,GLFW_CURSOR, scene->isLockCursor()?GLFW_CURSOR_DISABLED:GLFW_CURSOR_NORMAL); if(lastClientWidth != clientWidth || lastClientHeight != clientHeight) { setupDeferred(clientWidth?clientWidth:128, clientHeight?clientHeight:128); } render(clientWidth,clientHeight); glfwSwapBuffers(window); glfwPollEvents(); // lastClientWidth=clientWidth; lastClientHeight=clientHeight; } //uninits delete programManager; delete textureManager; delete geometryVaoManager; delete scene; uninitDeferred(); // glfwTerminate(); return 0; }
int main(int argc, char** argv){ cl_int err; // START OPENGL INIT Magick::InitializeMagick(argv[0]); // start GL context and O/S window using the GLFW helper library if (!glfwInit ()) { fprintf (stderr, "ERROR: could not start GLFW3\n"); return 1; } // Demand OpenGL 4.1 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); #ifdef __APPLE__ // Use Core profile to obtain a context for the latest OpenGL spec. // Otherwise we're stuck at 2.1 std::cout<<"Apple FTW\n"; glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif window = glfwCreateWindow (WIDTH, HEIGHT, "Hello Triangle", NULL, NULL); if (!window) { fprintf (stderr, "ERROR: could not open window with GLFW3\n"); glfwTerminate(); return 1; } glfwSetWindowSize( window, WIDTH/2 , HEIGHT/2); //glfwWindowHint(GLFW_SAMPLES, 4); //glEnable( GL_MULTISAMPLE ); glfwMakeContextCurrent (window); checkGLErr( "glfwMakeContextCurrent" ); // start GLEW extension handler glewExperimental = GL_TRUE; glewInit(); glGetError(); //checkGLErr( "GLEW init" ); // END OPENGL INIT.. // START OPENCL.. std::vector<cl::Platform> platformList; cl::Platform::get(&platformList); checkErr(platformList.size()!=0 ? CL_SUCCESS : -1, "cl::Platform::get"); std::cerr << "Platform number is: " << platformList.size() << std::endl; std::string platformVendor; platformList[0].getInfo((cl_platform_info)CL_PLATFORM_VENDOR, &platformVendor); std::cerr << "Platform is by: " << platformVendor << "\n"; #ifdef __APPLE__ CGLContextObj kCGLContext = CGLGetCurrentContext(); CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext); cl_context_properties cprops[6] = {CL_CONTEXT_PLATFORM, (cl_context_properties)(platformList[0])(),CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE , (cl_context_properties) kCGLShareGroup, 0, 0}; cl::Context context( CL_DEVICE_TYPE_CPU, cprops, NULL, NULL, &err); #endif #ifdef __linux__ cl_platform_id platform; err = clGetPlatformIDs(1, &platform, NULL); cl_context_properties props[] = { CL_GL_CONTEXT_KHR, (cl_context_properties)glfwGetGLXContext( window ), CL_GLX_DISPLAY_KHR, (cl_context_properties)glfwGetX11Display(), CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 }; cl::Context context( CL_DEVICE_TYPE_CPU, props, NULL, NULL, &err); //cl::Context context = clCreateContextFromType(props, CL_DEVICE_TYPE_CPU, NULL, NULL, &err); #endif checkErr(err, "Context::Context()"); std::cout<<"Created context."<< std::endl; // Create shared texture. pCLTarget = new RenderTarget( WIDTH, HEIGHT, GL_RGBA , GL_RGBA, GL_FLOAT, 0, false ); checkGLErr( "RenderTarget::RenderTarget" ); pAccumulator = new RenderTarget( WIDTH, HEIGHT, GL_RGBA, GL_RGBA, GL_FLOAT, 0, false ); checkGLErr( "RenderTarget::RenderTarget" ); const int inSizeS = 3; const int inSizeP = 0; const int inSizeT = 12; const int inSurf = 5; /* float* outH = new float[inSize]; cl::Buffer outCL( context, CL_MEM_WRITE_ONLY, inSize * sizeof( float ) ); */ Sphere* spheres = new Sphere[inSizeS]; std::cout<<"Sphere: "<< spheres[0].radius << "\n"; spheres[1].uSurf = 0; spheres[1].center = glm::vec4( 0.0f, -2.0f, 0.0f, 0.0f ); spheres[1].radius = 1.0f; /*spheres[1].uSurf = 0; spheres[1].center = glm::vec4( +1.0f, 0.0f, +1.0f, 0.0f); spheres[1].radius = 1.0f;*/ spheres[0].uSurf = 2; spheres[0].center = glm::vec4( 0.0f, +1.50f, 0.0f, 0.0f); spheres[0].radius = 0.2f; /*spheres[2].uSurf = 0; spheres[2].center = glm::vec4( +0.0f, 0.0f, -0.0f, 0.0f); spheres[2].radius = 1.0f;*/ spheres[2].uSurf = 0; spheres[2].center = glm::vec4( -2.0f, -2.0f, -2.0f, 0.0f); spheres[2].radius = 1.0f; /*spheres[4].uSurf = 0; spheres[4].center = glm::vec4( -1.0f, -0.0f, +1.0f, 0.0f); spheres[4].radius = 1.0f;*/ Plane* planes = new Plane[inSizeP]; int planeSize = 3.0f; //std::cout<<"Sphere: "<< planes[0].radius << "\n"; /*planes[0].normal = glm::vec4( 0.0f, 1.0f, 0.0f, 0.0f ); planes[0].point = glm::vec4( 0.0f, -planeSize, 0.0f, 0.0f ); planes[0].uSurf = 1; planes[1].normal = glm::vec4( 0.0f, -1.0f, 0.0f, 0.0f ); planes[1].point = glm::vec4( 0.0f, planeSize, 0.0f, 0.0f ); planes[1].uSurf = 1; planes[2].normal = glm::vec4( 1.0f, 0.0f, 0.0f, 0.0f ); planes[2].point = glm::vec4( -planeSize, 0.0f, 0.0f, 0.0f ); planes[2].uSurf = 1; planes[3].normal = glm::vec4( -1.0f, 0.0f, 0.0f, 0.0f ); planes[3].point = glm::vec4( planeSize, 0.0f, 0.0f, 0.0f ); planes[3].uSurf = 1; planes[4].normal = glm::vec4( 0.0f, 0.0f, +1.0f, +0.0f ); planes[4].point = glm::vec4( 0.0f, 0.0f, -planeSize, 0.0f ); planes[4].uSurf = 1; planes[5].normal = glm::vec4( 0.0f, 0.0f, -1.0f, 0.0f ); planes[5].point = glm::vec4( 0.0f, 0.0f, +planeSize, 0.0f ); planes[5].uSurf = 1;*/ Triangle* triangles = new Triangle[inSizeT]; //std::cout<<"Sphere: "<< spheres[0].radius << "\n"; float boxSize = 3.0f; triangles[0].uSurf = 1; triangles[0].p0 = glm::vec4( -boxSize, -boxSize, -boxSize, 0.0f); triangles[0].p1 = glm::vec4( -boxSize, boxSize, -boxSize, 0.0f); triangles[0].p2 = glm::vec4( -boxSize, -boxSize, boxSize, 0.0f); triangles[1].uSurf = 1; triangles[1].p0 = glm::vec4( -boxSize, boxSize, boxSize, 0.0f); triangles[1].p2 = glm::vec4( -boxSize, boxSize, -boxSize, 0.0f); triangles[1].p1 = glm::vec4( -boxSize, -boxSize, boxSize, 0.0f); triangles[2].uSurf = 1; triangles[2].p0 = glm::vec4( boxSize, -boxSize, -boxSize, 0.0f); triangles[2].p2 = glm::vec4( boxSize, boxSize, -boxSize, 0.0f); triangles[2].p1 = glm::vec4( boxSize, -boxSize, boxSize, 0.0f); triangles[3].uSurf = 1; triangles[3].p0 = glm::vec4( boxSize, boxSize, boxSize, 0.0f); triangles[3].p1 = glm::vec4( boxSize, boxSize, -boxSize, 0.0f); triangles[3].p2 = glm::vec4( boxSize, -boxSize, boxSize, 0.0f); triangles[4].uSurf = 1; triangles[4].p0 = glm::vec4( -boxSize, -boxSize, -boxSize, 0.0f); triangles[4].p2 = glm::vec4( boxSize, -boxSize, -boxSize, 0.0f); triangles[4].p1 = glm::vec4( -boxSize, -boxSize, boxSize, 0.0f); triangles[5].uSurf = 1; triangles[5].p0 = glm::vec4( boxSize, -boxSize, boxSize, 0.0f); triangles[5].p1 = glm::vec4( boxSize, -boxSize, -boxSize, 0.0f); triangles[5].p2 = glm::vec4( -boxSize, -boxSize, boxSize, 0.0f); triangles[6].uSurf = 1; triangles[6].p0 = glm::vec4( -boxSize, boxSize, -boxSize, 0.0f); triangles[6].p1 = glm::vec4( boxSize, boxSize, -boxSize, 0.0f); triangles[6].p2 = glm::vec4( -boxSize, boxSize, boxSize, 0.0f); triangles[7].uSurf = 1; triangles[7].p0 = glm::vec4( boxSize, boxSize, boxSize, 0.0f); triangles[7].p2 = glm::vec4( boxSize, boxSize, -boxSize, 0.0f); triangles[7].p1 = glm::vec4( -boxSize, boxSize, boxSize, 0.0f); triangles[8].uSurf = 3; triangles[8].p0 = glm::vec4( -boxSize, -boxSize, -boxSize, 0.0f); triangles[8].p1 = glm::vec4( boxSize, -boxSize, -boxSize, 0.0f); triangles[8].p2 = glm::vec4( -boxSize, boxSize, -boxSize, 0.0f); triangles[9].uSurf = 3; triangles[9].p0 = glm::vec4( boxSize, boxSize, -boxSize, 0.0f); triangles[9].p2 = glm::vec4( boxSize, -boxSize, -boxSize, 0.0f); triangles[9].p1 = glm::vec4( -boxSize, boxSize, -boxSize, 0.0f); triangles[10].uSurf = 4; triangles[10].p0 = glm::vec4( -boxSize, -boxSize, boxSize, 0.0f); triangles[10].p2 = glm::vec4( boxSize, -boxSize, boxSize, 0.0f); triangles[10].p1 = glm::vec4( -boxSize, boxSize, boxSize, 0.0f); triangles[11].uSurf = 4; triangles[11].p0 = glm::vec4( boxSize, boxSize, boxSize, 0.0f); triangles[11].p1 = glm::vec4( boxSize, -boxSize, boxSize, 0.0f); triangles[11].p2 = glm::vec4( -boxSize, boxSize, boxSize, 0.0f); /*triangles[12].uSurf = 1; triangles[12].p0 = glm::vec4( -boxSize/4.0f, boxSize, -boxSize/4.0f, 0.0f); triangles[12].p1 = glm::vec4( boxSize/4.0f, boxSize, -boxSize/4.0f, 0.0f); triangles[12].p2 = glm::vec4( -boxSize/4.0f, boxSize, boxSize/4.0f, 0.0f); triangles[13].uSurf = 1; triangles[13].p0 = glm::vec4( boxSize/4.0f, boxSize, boxSize/4.0f, 0.0f); triangles[13].p2 = glm::vec4( boxSize/4.0f, boxSize, -boxSize/4.0f, 0.0f); triangles[13].p1 = glm::vec4( -boxSize/4.0f, boxSize, boxSize/4.0f, 0.0f);*/ GeometryDescriptor* geometry = new GeometryDescriptor( inSizeS, inSizeP, inSizeT ); Surface* pSurf = new Surface[inSurf]; pSurf[0].vColor = glm::vec4( 1.0f, 1.0f, 0.0f, 1.0f ); pSurf[1].vColor = glm::vec4( 1.0f, 1.0f, 1.0f, 1.0f ); pSurf[2].vColor = glm::vec4( 1.0f, 1.0f, 1.0f, 1.0f ); float lPower = 5.0f; pSurf[2].vEmissive = glm::vec4( lPower, lPower, lPower, lPower ); pSurf[3].vColor = glm::vec4( 1.0f, 0.0f, 0.0f, 1.0f ); pSurf[4].vColor = glm::vec4( 0.0f, 1.0f, 0.0f, 1.0f ); cl::Buffer clSpheres( context, CL_MEM_READ_ONLY, inSizeS * sizeof( Sphere )); checkErr(err, "Buffer::Buffer()"); cl::Buffer clPlanes( context, CL_MEM_READ_ONLY, inSizeP * sizeof( Plane ) ); checkErr(err, "Buffer::Buffer()"); cl::Buffer clTriangles( context, CL_MEM_READ_ONLY, inSizeT * sizeof( Triangle ) ); checkErr(err, "Buffer::Buffer()"); cl::Buffer clCamera( context, CL_MEM_READ_ONLY, 1 * sizeof( CLCamera ) ); checkErr(err, "Buffer::Buffer()"); cl::Buffer clGeom( context, CL_MEM_READ_ONLY, 1 * sizeof( GeometryDescriptor ) ); checkErr(err, "Buffer::Buffer()"); cl::Buffer clImgDesc( context, CL_MEM_READ_ONLY, 1 * sizeof( ImageDescriptor ) ); checkErr(err, "Buffer::Buffer()"); cl::Buffer clSeed( context, CL_MEM_READ_WRITE, WIDTH * HEIGHT * 4 * sizeof( uint ) ); checkErr(err, "Buffer::Buffer()"); cl::Buffer clSurf( context, CL_MEM_READ_WRITE, inSurf * sizeof( Surface ) ); checkErr(err, "Buffer::Buffer()"); cl::ImageGL imgGL( context, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, pCLTarget->getColorTexture()->glGetInternalTexture(), &err ); checkErr(err, "ImageGL::ImageGL()"); cl::ImageGL accGL( context, CL_MEM_READ_ONLY, GL_TEXTURE_2D, 0, pAccumulator->getColorTexture()->glGetInternalTexture(), &err ); checkErr(err, "ImageGL::ImageGL()"); std::cout<<"Created buffers."<< std::endl; srand( time( NULL ) ); uint *pSeeds = new uint[WIDTH * HEIGHT * 4]; for( int i = 0; i < WIDTH * HEIGHT * 4; i++ ){ pSeeds[i] = rand(); } std::vector<cl::Device> devices; devices = context.getInfo<CL_CONTEXT_DEVICES>(); checkErr(devices.size() > 0 ? CL_SUCCESS : -1, "devices.size() > 0"); std::cout<<"Num available devices: "<< devices.size()<< std::endl; std::ifstream file("src/kernel/kernel0.cl"); checkErr(file.is_open() ? CL_SUCCESS:-1, "src/kernel/kernel0.cl"); std::string prog( std::istreambuf_iterator<char>(file), (std::istreambuf_iterator<char>())); cl::Program::Sources source(1, std::make_pair(prog.c_str(), prog.length()+1)); std::cout<<"Source obtained."<< std::endl; cl::Program program(context, source); err = program.build(devices,"-cl-opt-disable"); std::cout<<"Source obtained."<< std::endl; std::string buildLog; program.getBuildInfo( devices[0], CL_PROGRAM_BUILD_LOG, &buildLog ); std::cout<<"Build log:" << buildLog<< std::endl; checkErr(err, "Program::build()"); std::cout<<"Built program"<< std::endl; cl::Kernel kernel(program, "bi_directional_path_trace", &err); checkErr(err, "Kernel::Kernel()"); err = kernel.setArg(0, clCamera); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(1, imgGL); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(2, accGL); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(3, clSpheres); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(4, clPlanes); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(5, clTriangles); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(6, clGeom); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(7, clImgDesc); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(8, clSeed); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(9, clSurf); checkErr(err, "Kernel::setArg()"); std::cout<<"Built Kernel"<< std::endl; pCamera = new ModelCamera( window ); pCamera->setSpeedX( 0.03f ); pCamera->setSpeedY( 0.03f ); pCamera->setRadius( 8.0f ); pCamera->setOrientation( glm::vec3( 0.0f, -1.0f, 0.0f ) ); pCamera->reset( glm::vec3( 1.0f, 0.1f, -0.1f ) ); cl::CommandQueue queue(context, devices[0], 0, &err); checkErr(err, "CommandQueue::CommandQueue()"); CLCamera* cam = pCamera->getCLCamera(); std::cout<<cam->vPos.x<<","<<cam->vPos.y<<","<<cam->vPos.z<<std::endl; std::cout<<cam->vLookAt.x<<","<<cam->vLookAt.y<<","<<cam->vLookAt.z<<std::endl; std::cout<<cam->vUp.x<<","<<cam->vUp.y<<","<<cam->vUp.z<<std::endl; std::cout<< sizeof( Plane )<< std::endl; queue.enqueueWriteBuffer( clCamera, CL_TRUE, 0, 1 * sizeof(CLCamera), (const void*)cam ); queue.enqueueWriteBuffer( clSpheres, CL_TRUE, 0, inSizeS * sizeof(Sphere), (const void*)spheres); queue.enqueueWriteBuffer( clPlanes, CL_TRUE, 0, inSizeP * sizeof(Plane), (const void*)planes); queue.enqueueWriteBuffer( clTriangles, CL_TRUE, 0, inSizeT * sizeof(Triangle), (const void*)triangles); queue.enqueueWriteBuffer( clGeom, CL_TRUE, 0, 1 * sizeof(GeometryDescriptor), (const void*)geometry); queue.enqueueWriteBuffer( clSeed, CL_TRUE, 0, WIDTH * HEIGHT * 4 * sizeof(uint), (const void*)pSeeds); queue.enqueueWriteBuffer( clSurf, CL_TRUE, 0, inSurf * sizeof(Surface), (const void*)pSurf); vSharedUnits = new std::vector<cl::Memory>(); vSharedUnits->push_back( imgGL ); vSharedUnits->push_back( accGL ); //Initialise counter. imgDesc.numSamples = 0; imgDesc.sampleRate = SAMPLES; cLast = clock(); while( !glfwWindowShouldClose( window ) ){ //usleep( 1000000 ); mainLoop( queue, context, kernel, clImgDesc, clCamera ); } /* Previous Program. Remove these if you think they are not required. float *fout = new float[inSize]; err = queue.enqueueReadBuffer( clSpheres, CL_TRUE, 0, inSize * sizeof(Sphere), fout); */ checkErr(err, "ComamndQueue::enqueueReadBuffer()"); std::cout<<"Kernel finished executing."<< std::endl; delete vSharedUnits; return EXIT_SUCCESS; }
int main(void) #endif { assert(copy_file(GAME_DLL_FILENAME, GAME_TEMP_DLL_FILENAME)); assert(copy_file(GAME_DLL_FILENAME, GAME_TEMP_2_DLL_FILENAME)); platform_game_code gameCode = platform_load_game_code("game_temp.so"); gameCode.useTemp = true; if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); return 1; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_SAMPLES, 16); glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); glfwWindowHint(GLFW_AUTO_ICONIFY, GL_FALSE); #if GAME_DEBUG int32 numMonitors = 0; GLFWmonitor **monitors = glfwGetMonitors(&numMonitors); if (numMonitors < 2) { fprintf(stderr, "failed to find secondary monitor"); return 1; } const GLFWvidmode *mode = glfwGetVideoMode(monitors[1]); glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); glfwWindowHint(GLFW_FLOATING, GL_TRUE); GLFWwindow *window = glfwCreateWindow(mode->width, mode->height, "ProCo", monitors[1], NULL); #else GLFWwindow *window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "ProCo", NULL, NULL); #endif if (!window) { printf("failed to create window\n"); return 1; } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_position_callback); glfwSetMouseButtonCallback(window, mouse_button_callback); game_memory gameMemory = {}; gameMemory.debugReadEntireFile = DEBUGPlatformReadEntireFile; gameMemory.debugWriteEntireFile = DEBUGPlatformWriteEntireFile; gameMemory.debugFreeFileMemory = DEBUGPlatformFreeFileMemory; game_state *gameState = NULL; if (window == NULL) { fprintf(stderr, "ERROR: Could not create window: \n"); return 0; } if (!gameCode.gameInitialization(window, &gameMemory, &gameState)) { fprintf(stderr, "Failed to initialize game\n"); return 0; } uint32 prevTime = 0; newTime = glfwGetTime(); glfwSetWindowUserPointer(window, &gameState->input); int32 gameCodeReloadTimer = 0; #if GAME_DEBUG printf("Initialization successful. Starting main loop\n"); #endif while (!glfwWindowShouldClose(window)) { newTime = glfwGetTime(); real32 frameTime = (newTime - prevTime); prevTime = newTime; #if GAME_DEBUG ++gameCodeReloadTimer; if (gameCodeReloadTimer >= 300) { if (platform_reload_game_code(&gameCode)) { if (!gameCode.gameInitializeRenderer(window, &gameMemory, gameState)) { printf("Failed to initialize renderer\n"); return 0; } } gameCodeReloadTimer = 0; } #endif glfwPollEvents(); if (gameState->input.keys.escape) break; gameCode.gameUpdateAndRender(window, &gameMemory, &gameState, g_fixedDeltaTime, frameTime); gameState->input.mouse.justPressedMask = 0; } gameCode.freeGameMemory(&g_gameMemory, gameState); glfwTerminate(); return 0; }
int main(int argc, char** argv) { int ch, width, height; thrd_t physics_thread = 0; GLFWwindow* window; GLFWmonitor* monitor = NULL; if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); exit(EXIT_FAILURE); } while ((ch = getopt(argc, argv, "fhs")) != -1) { switch (ch) { case 'f': monitor = glfwGetPrimaryMonitor(); break; case 'h': usage(); exit(EXIT_SUCCESS); } } if (monitor) { const GLFWvidmode* mode = glfwGetVideoMode(monitor); glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); width = mode->width; height = mode->height; } else { width = 640; height = 480; } window = glfwCreateWindow(width, height, "Particle Engine", monitor, NULL); if (!window) { fprintf(stderr, "Failed to create GLFW window\n"); glfwTerminate(); exit(EXIT_FAILURE); } if (monitor) glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwMakeContextCurrent(window); glfwSwapInterval(1); glfwSetWindowSizeCallback(window, resize_callback); glfwSetKeyCallback(window, key_callback); // Set initial aspect ratio glfwGetWindowSize(window, &width, &height); resize_callback(window, width, height); // Upload particle texture glGenTextures(1, &particle_tex_id); glBindTexture(GL_TEXTURE_2D, particle_tex_id); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, P_TEX_WIDTH, P_TEX_HEIGHT, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, particle_texture); // Upload floor texture glGenTextures(1, &floor_tex_id); glBindTexture(GL_TEXTURE_2D, floor_tex_id); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, F_TEX_WIDTH, F_TEX_HEIGHT, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, floor_texture); if (glfwExtensionSupported("GL_EXT_separate_specular_color")) { glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT, GL_SEPARATE_SPECULAR_COLOR_EXT); } // Set filled polygon mode as default (not wireframe) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); wireframe = 0; // Set initial times thread_sync.t = 0.0; thread_sync.dt = 0.001f; thread_sync.p_frame = 0; thread_sync.d_frame = 0; mtx_init(&thread_sync.particles_lock, mtx_timed); cnd_init(&thread_sync.p_done); cnd_init(&thread_sync.d_done); if (thrd_create(&physics_thread, physics_thread_main, window) != thrd_success) { glfwTerminate(); exit(EXIT_FAILURE); } glfwSetTime(0.0); while (!glfwWindowShouldClose(window)) { draw_scene(window, glfwGetTime()); glfwSwapBuffers(window); glfwPollEvents(); } thrd_join(physics_thread, NULL); glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); }
BOOL View::CreateGLWindow(const char * title, int width, int height, int bits) { glfwSetErrorCallback(error_callback); if (!glfwInit()) { exit(EXIT_FAILURE); } glfwWindowHint(GLFW_SAMPLES, 4); //Request 4x antialiasing glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //Request a specific OpenGL version glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //Request a specific OpenGL version glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL if (m_bFullScreen) { m_window = glfwCreateWindow(width, height, title, glfwGetPrimaryMonitor(), NULL); } else { m_window = glfwCreateWindow(width, height, title, NULL, NULL); } if (!m_window) { fprintf(stderr, "Failed to open GLFW window.\n"); glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(m_window); // For redirecting the callback from InputHandler glfwSetWindowUserPointer(m_window, m_cInputHandler); // For setting keyboard callback auto InputHandler_Key_CallBack = [](GLFWwindow * window, int key, int scancode, int action ,int mods) { static_cast<InputHandler*>(glfwGetWindowUserPointer(window))->Key_Callback(key, scancode, action, mods); }; // For setting mouse callback auto InputHandler_Mouse_CallBack = [](GLFWwindow * window, int button, int action, int mods) { static_cast<InputHandler*>(glfwGetWindowUserPointer(window))->Mouse_Callback(button, action, mods); }; // Sets the callbacks glfwSetKeyCallback(m_window, InputHandler_Key_CallBack); glfwSetMouseButtonCallback(m_window, InputHandler_Mouse_CallBack); glfwSetWindowSizeCallback(m_window, resize_callback); glfwSetScrollCallback(m_window, scroll_callback); glGetIntegerv(GL_VIEWPORT, m_viewPort); m_iWindow_Width = width; m_iWindow_Height = height; glViewport(0, 0, m_iWindow_Width, m_iWindow_Height); glewExperimental = true; GLenum err = glewInit(); if (err != GLEW_OK) { fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); } if (!InitGL()) { return FALSE; } // Move the screen to the middle glfwSetWindowPos(m_window, ((float)(glfwGetVideoMode(glfwGetPrimaryMonitor())->width) * 0.5f) - ((float)(this->m_iWindow_Width) * 0.5f), ((float)(glfwGetVideoMode(glfwGetPrimaryMonitor())->height) * 0.5f) - ((float)(this->m_iWindow_Height) * 0.5f)); return TRUE; }
int main(int argc, char** argv) { #if defined(_WIN32) LOG_INFO("Windows build."); #elif defined(_LINUX) LOG_INFO("Linux build."); LOG_INFO("DISPLAY=%s", getenv("DISPLAY")); #elif defined(_MACOS) LOG_INFO("MacOS build."); #endif bool useOpenGLCoreContext = false; #ifdef USE_CORE_CONTEXT useOpenGLCoreContext = true; #endif g_renderMode.outputType = RenderingMode::OVR_SDK; LOG_INFO("Using GLFW3 backend."); LOG_INFO("Compiled against GLFW %i.%i.%i", GLFW_VERSION_MAJOR, GLFW_VERSION_MINOR, GLFW_VERSION_REVISION); int major, minor, revision; glfwGetVersion(&major, &minor, &revision); LOG_INFO("Running against GLFW %i.%i.%i", major, minor, revision); LOG_INFO("glfwGetVersionString: %s", glfwGetVersionString()); // Command line options for (int i=0; i<argc; ++i) { const std::string a = argv[i]; LOG_INFO("argv[%d]: %s", i, a.c_str()); if (!a.compare("-sdk")) { g_renderMode.outputType = RenderingMode::OVR_SDK; } else if (!a.compare("-client")) { g_renderMode.outputType = RenderingMode::OVR_Client; } else if (!a.compare("-core")) { useOpenGLCoreContext = true; } else if (!a.compare("-compat")) { useOpenGLCoreContext = false; } } #ifdef USE_OCULUSSDK g_app.initHMD(); #else g_renderMode.outputType = RenderingMode::Mono_Buffered; #endif GLFWwindow* l_Window = NULL; glfwSetErrorCallback(ErrorCallback); if (!glfwInit()) { exit(EXIT_FAILURE); } // Log system monitor information const GLFWmonitor* pPrimary = glfwGetPrimaryMonitor(); int monitorCount = 0; GLFWmonitor** ppMonitors = glfwGetMonitors(&monitorCount); for (int i=0; i<monitorCount; ++i) { GLFWmonitor* pCur = ppMonitors[i]; const GLFWvidmode* mode = glfwGetVideoMode(pCur); if (mode != NULL) { (void)pPrimary; LOG_INFO("Monitor #%d: %dx%d @ %dHz %s", i, mode->width, mode->height, mode->refreshRate, pCur==pPrimary ? "Primary":""); } } bool swapBackBufferDims = false; // Context setup - before window creation glfwWindowHint(GLFW_DEPTH_BITS, 16); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, useOpenGLCoreContext ? GLFW_OPENGL_CORE_PROFILE : GLFW_OPENGL_COMPAT_PROFILE); //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #ifdef _DEBUG glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif #if defined(USE_OSVR) LOG_INFO("USE_OSVR=1"); std::string windowTitle = ""; windowTitle = PROJECT_NAME "-GLFW-Osvr"; if (g_app.UsingDebugHmd()) { const hmdRes sz = { 800, 600 }; // Create a normal, decorated application window LOG_INFO("Using Debug HMD mode."); windowTitle = PROJECT_NAME "-GLFW-DebugHMD"; g_renderMode.outputType = RenderingMode::Mono_Buffered; l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); } else { const hmdRes sz = { g_app.getHmdResolution().h, g_app.getHmdResolution().w }; const winPos pos = g_app.getHmdWindowPos(); g_renderMode.outputType = RenderingMode::SideBySide_Undistorted; LOG_INFO("Using Extended desktop mode."); windowTitle = PROJECT_NAME "-GLFW-Extended"; LOG_INFO("Creating GLFW_DECORATED window %dx%d@%d,%d", sz.w, sz.h, pos.x, pos.y); glfwWindowHint(GLFW_DECORATED, 0); l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); glfwWindowHint(GLFW_DECORATED, 1); glfwSetInputMode(l_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetWindowPos(l_Window, pos.x, pos.y); } #elif defined(USE_OCULUSSDK) LOG_INFO("USE_OCULUSSDK=1"); ovrSizei sz = g_app.getHmdResolution(); const ovrVector2i pos = g_app.getHmdWindowPos(); std::string windowTitle = ""; if (g_app.UsingDebugHmd() == true) { // Create a normal, decorated application window LOG_INFO("Using Debug HMD mode."); windowTitle = PROJECT_NAME "-GLFW-DebugHMD"; g_renderMode.outputType = RenderingMode::Mono_Buffered; l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); } else if (g_app.UsingDirectMode()) { // HMD active - position undecorated window to fill HMD viewport LOG_INFO("Using Direct to Rift mode."); windowTitle = PROJECT_NAME "-GLFW-Direct"; GLFWmonitor* monitor = glfwGetPrimaryMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(monitor); sz.w = mode->width; sz.h = mode->height; LOG_INFO("Creating window %dx%d@%d,%d", sz.w, sz.h, pos.x, pos.y); l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), monitor, NULL); glfwSetInputMode(l_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); #ifdef _LINUX swapBackBufferDims = true; #endif #if defined(_WIN32) g_app.AttachToWindow((void*)glfwGetWin32Window(l_Window)); #endif } else { LOG_INFO("Using Extended desktop mode."); windowTitle = PROJECT_NAME "-GLFW-Extended"; LOG_INFO("Creating GLFW_DECORATED window %dx%d@%d,%d", sz.w, sz.h, pos.x, pos.y); glfwWindowHint(GLFW_DECORATED, 0); l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); glfwWindowHint(GLFW_DECORATED, 1); glfwSetInputMode(l_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetWindowPos(l_Window, pos.x, pos.y); } resize(l_Window, sz.w, sz.h); // inform AppSkeleton of window size #else const glm::vec2 sz(800, 600); // Create a normal, decorated application window LOG_INFO("Using No VR SDK."); const std::string windowTitle = PROJECT_NAME "-GLFW-NoVRSDK"; g_renderMode.outputType = RenderingMode::Mono_Buffered; l_Window = glfwCreateWindow(sz.x, sz.y, windowTitle.c_str(), NULL, NULL); #endif //USE_OSVR|USE_OCULUSSDK if (!l_Window) { LOG_INFO("Glfw failed to create a window. Exiting."); glfwTerminate(); exit(EXIT_FAILURE); } // Required for SDK rendering (to do the buffer swap on its own) #ifdef OVRSDK05 #if defined(_WIN32) g_app.setWindow(glfwGetWin32Window(l_Window)); #elif defined(__linux__) g_app.setWindow(NULL);//glfwGetX11Display()); #endif #endif //USE_OCULUSSDK glfwMakeContextCurrent(l_Window); glfwSetWindowSizeCallback(l_Window, resize); glfwSetMouseButtonCallback(l_Window, mouseDown); glfwSetCursorPosCallback(l_Window, mouseMove); glfwSetScrollCallback(l_Window, mouseWheel); glfwSetKeyCallback(l_Window, keyboard); memset(m_keyStates, 0, GLFW_KEY_LAST*sizeof(int)); // joysticks for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; ++i) { if (GL_FALSE == glfwJoystickPresent(i)) continue; const char* pJoyName = glfwGetJoystickName(i); if (pJoyName == NULL) continue; int numAxes = 0; int numButtons = 0; glfwGetJoystickAxes(i, &numAxes); glfwGetJoystickButtons(i, &numButtons); LOG_INFO("Glfw opened Joystick #%d: %s w/ %d axes, %d buttons", i, pJoyName, numAxes, numButtons); if (g_joystickIdx == -1) g_joystickIdx = i; } printGLContextInfo(l_Window); glfwMakeContextCurrent(l_Window); g_pHMDWindow = l_Window; // Don't forget to initialize Glew, turn glewExperimental on to // avoid problems fetching function pointers... glewExperimental = GL_TRUE; const GLenum l_Result = glewInit(); if (l_Result != GLEW_OK) { LOG_INFO("glewInit() error."); exit(EXIT_FAILURE); } #ifdef _DEBUG // Debug callback initialization // Must be done *after* glew initialization. glDebugMessageCallback(myCallback, NULL); glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE); glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_MARKER, 0, GL_DEBUG_SEVERITY_NOTIFICATION, -1 , "Start debugging"); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); #endif #ifdef USE_ANTTWEAKBAR LOG_INFO("Using AntTweakbar."); TwInit(useOpenGLCoreContext ? TW_OPENGL_CORE : TW_OPENGL, NULL); InitializeBar(); #endif LOG_INFO("Calling initGL..."); g_app.initGL(); LOG_INFO("Calling initVR..."); g_app.initVR(swapBackBufferDims); LOG_INFO("initVR(%d) complete.", swapBackBufferDims); while (!glfwWindowShouldClose(l_Window)) { g_app.CheckForTapToDismissHealthAndSafetyWarning(); glfwPollEvents(); joystick(); timestep(); g_fps.OnFrame(); if (g_dynamicallyScaleFBO) { DynamicallyScaleFBO(); } #ifdef USE_ANTTWEAKBAR TwRefreshBar(g_pTweakbar); #endif displayToHMD(); #ifndef _LINUX // Indicate FPS in window title // This is absolute death for performance in Ubuntu Linux 12.04 { std::ostringstream oss; oss << windowTitle << " " << static_cast<int>(g_fps.GetFPS()) << " fps"; glfwSetWindowTitle(l_Window, oss.str().c_str()); if (g_AuxWindow != NULL) glfwSetWindowTitle(g_AuxWindow, oss.str().c_str()); } #endif const float dumpInterval = 1.f; if (g_logDumpTimer.seconds() > dumpInterval) { LOG_INFO("Frame rate: %d fps", static_cast<int>(g_fps.GetFPS())); g_logDumpTimer.reset(); } // Optionally display to auxiliary mono view if (g_AuxWindow != NULL) { glfwMakeContextCurrent(g_AuxWindow); glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ///@note VAOs *cannot* be shared between contexts. ///@note GLFW windows are inextricably tied to their own unique context. /// For these two reasons, calling draw a third time for the auxiliary window /// is not possible. Furthermore, it is not strictly desirable for the extra /// rendering cost. /// Instead, we share the render target texture from the stereo render and present /// just the left eye to the aux window. if (g_drawToAuxWindow) { presentSharedFboTexture(); } #ifdef USE_ANTTWEAKBAR TwDraw(); ///@todo Should this go first? Will it write to a depth buffer? #endif glfwSwapBuffers(g_AuxWindow); if (glfwWindowShouldClose(g_AuxWindow)) { destroyAuxiliaryWindow(g_AuxWindow); } // Set context to Rift window when done glfwMakeContextCurrent(l_Window); } } g_app.exitVR(); glfwDestroyWindow(l_Window); glfwTerminate(); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]){ if(!glfwInit()){ throw std::runtime_error("glfwInit failed"); } glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); glfwOpenWindowHint(0, GLFW_OPENGL_CORE_PROFILE); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 1); glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE); if(!glfwOpenWindow(800, 600, 0, 0, 0, 0, 32, 0, GLFW_WINDOW)){ throw std::runtime_error("glfwOpenWindow failed. does this hardware work with 3.1"); } glewExperimental = GL_TRUE; if(glewInit() != GLEW_OK){ throw std::runtime_error("glewInit failed"); } if(!GLEW_VERSION_3_1){ throw std::runtime_error("OpenGL 3.1 API is not available"); } LoadGeometry(); LoadTexture(); PrepVertexUniforms(); camera.setPosition(glm::vec3(0,0,8)); camera.setViewportAspectRatio(screenwidth/screenheight); light.position = camera.position(); light.intensities = glm::vec3(1,1,1); glfwDisable(GLFW_MOUSE_CURSOR); glfwSetMousePos(0, 0); glfwSetMouseWheel(0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); while(glfwGetWindowParam(GLFW_OPENED)){ update(); display(); //check for errors GLenum error = glGetError(); if(error != GL_NO_ERROR){ glPrintError(); } //esc == close if(glfwGetKey(GLFW_KEY_ESC)){ glfwCloseWindow(); } } glfwTerminate(); return 0; }
int GLSL::enter() { 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_TRUE); GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "Advanced GLSL LearnOpenGL", nullptr, nullptr); glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); //glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glewExperimental = GL_TRUE; glewInit(); glViewport(0, 0, screenWidth, screenHeight); glEnable(GL_DEPTH_TEST); glEnable(GL_PROGRAM_POINT_SIZE); Shader shaderRed("../_ShaderSource/advanced/ubo.vs", "../_ShaderSource/advanced/uboRed.frag"); Shader shaderGreen("../_ShaderSource/advanced/ubo.vs", "../_ShaderSource/advanced/uboGreen.frag"); Shader shaderBlue("../_ShaderSource/advanced/ubo.vs", "../_ShaderSource/advanced/uboBlue.frag"); Shader shaderYellow("../_ShaderSource/advanced/ubo.vs", "../_ShaderSource/advanced/uboYellow.frag"); #pragma region "object_initialization" GLfloat cubeVertices[] = { -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f }; // 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, 3 * sizeof(GLfloat), (GLvoid*)0); glBindVertexArray(0); #pragma endregion // create a uniform buffer object // first we get the relevant block indices GLuint uniformBlockIndexRed = glGetUniformBlockIndex(shaderRed.Program, "Matrices"); GLuint uniformBlockIndexGreen = glGetUniformBlockIndex(shaderGreen.Program, "Matrices"); GLuint uniformBlockIndexBlue = glGetUniformBlockIndex(shaderBlue.Program, "Matrices"); GLuint uniformBlockIndexYellow = glGetUniformBlockIndex(shaderYellow.Program, "Matrices"); // then we link each shader's uniform block to this uniform binding point glUniformBlockBinding(shaderRed.Program, uniformBlockIndexRed, 0); glUniformBlockBinding(shaderGreen.Program, uniformBlockIndexGreen, 0); glUniformBlockBinding(shaderBlue.Program, uniformBlockIndexBlue, 0); glUniformBlockBinding(shaderYellow.Program, uniformBlockIndexYellow, 0); // now actually create the buffer GLuint uboMatrices; glGenBuffers(1, &uboMatrices); glBindBuffer(GL_UNIFORM_BUFFER, uboMatrices); glBufferData(GL_UNIFORM_BUFFER, 2 * sizeof(glm::mat4), NULL, GL_STATIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); // define the range of the buffer that links to a uniform binding point... glBindBufferRange(GL_UNIFORM_BUFFER, 0, uboMatrices, 0, 2 * sizeof(glm::mat4)); // store the projection matrix glm::mat4 projection = glm::perspective(45.0f, (float)screenWidth / (float)screenHeight, 0.1f, 100.0f); glBindBuffer(GL_UNIFORM_BUFFER, uboMatrices); glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(glm::mat4), glm::value_ptr(projection)); glBindBuffer(GL_UNIFORM_BUFFER, 0); //glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); // game loop while (!glfwWindowShouldClose(window)) { // Set frame time GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check and call events glfwPollEvents(); Do_Movement(); // Clear buffers glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ////////////////////////////////////////////////////////////////////////// // set the view and projection matrix in the uniform block glm::mat4 view = camera.GetViewMatrix(); glBindBuffer(GL_UNIFORM_BUFFER, uboMatrices); glBufferSubData(GL_UNIFORM_BUFFER, sizeof(glm::mat4), sizeof(glm::mat4), glm::value_ptr(view)); glBindBuffer(GL_UNIFORM_BUFFER, 0); // draw 4 cubes //RED glBindVertexArray(cubeVAO); shaderRed.Use(); glm::mat4 model; model = glm::translate(model, glm::vec3(-0.75f, 0.75f, 0.0f)); glUniformMatrix4fv(glGetUniformLocation(shaderRed.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); ////GREEN //shaderGreen.Use(); //model = glm::mat4(); //model = glm::translate(model, glm::vec3(0.75f, 0.75f, 0.0f)); //glUniformMatrix4fv(glGetUniformLocation(shaderGreen.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); //glDrawArrays(GL_TRIANGLES, 0, 36); ////BLUE //shaderBlue.Use(); //model = glm::mat4(); //model = glm::translate(model, glm::vec3(-0.75f, -0.75f, 0.0f)); //glUniformMatrix4fv(glGetUniformLocation(shaderBlue.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); //glDrawArrays(GL_TRIANGLES, 0, 36); //// //shaderYellow.Use(); //model = glm::mat4(); //model = glm::translate(model, glm::vec3(0.75f, -0.75f, 0.0f)); //glUniformMatrix4fv(glGetUniformLocation(shaderYellow.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); //glDrawArrays(GL_TRIANGLES, 0, 36); // glfwSwapBuffers(window); } glfwTerminate(); return 0; }
// The MAIN function, from here we start our application and run our Game loop int main() { // Initializing Window // Init GLFW glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "Project Helios", 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); // Shaders - - - - // Setup and compile our shaders Shader lightingShader("resources/shaders/lighting.vs", "resources/shaders/lighting.frag"); Shader lampShader("resources/shaders/lamp.vs", "resources/shaders/lamp.frag"); // Models - - - - while(KEY!=GLFW_KEY_ENTER) { glfwSetWindowTitle(window, "Home"); glfwPollEvents(); // Clear the colorbuffer glClearColor(0.2f, 0.3f, 0.4f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glfwSwapBuffers(window); } glfwSetWindowTitle(window, "Project Helios"); // Load Models Model Map("resources/models/Mapa.obj"); Model Lamp("resources/models/Lamp.obj"); Model Bat1("resources/models/Huge Battery.obj"); Model Bat2("resources/models/Huge Battery.obj"); Model Bat3("resources/models/Huge Battery.obj"); Model Bat4("resources/models/Huge Battery.obj"); Model Keycard("resources/models/Keycard.obj"); Model KeyExit("resources/models/Keycard.obj"); Model Gun("resources/models/The Gun.obj"); // Draw in wireframe //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //LOOP - - - - // 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.0f, 0.2f, 0.8f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); lampShader.Use(); // Transformation matrices glm::mat4 projection = glm::perspective(camera.Zoom, (float)screenWidth/(float)screenHeight, 0.1f, 100.0f); glm::mat4 view = camera.GetViewMatrix(); glUniformMatrix4fv(glGetUniformLocation(lampShader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(lampShader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); glUniform3f(glGetUniformLocation(lampShader.Program, "lightColor"), lightColor.x, lightColor.y, lightColor.z); lightingShader.Use(); // Set lights properties glUniform3f(glGetUniformLocation(lightingShader.Program, "light.position"), lightPos.x, lightPos.y, lightPos.z); glUniform3f(glGetUniformLocation(lightingShader.Program, "viewPos"), camera.Position.x, camera.Position.y, camera.Position.z); glUniform3f(glGetUniformLocation(lightingShader.Program, "light.color"), lightColor.x, lightColor.y, lightColor.z); glUniform3f(glGetUniformLocation(lightingShader.Program, "light.ambient"), 0.1f, 0.1f, 0.1f); // Transformation matrices glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); // Draw the loaded model glm::mat4 model_map; glm::mat4 model_lamp; glm::mat4 model_bat1; glm::mat4 model_bat2; glm::mat4 model_bat3; glm::mat4 model_bat4; glm::mat4 model_key; glm::mat4 model_keyExit; glm::mat4 model_gun; // Prepare Matrices model_lamp = glm::translate(model_lamp, glm::vec3(0.0f, 3.93f, 0.0f)); model_lamp = glm::rotate(model_lamp, glm::radians(180.0f), glm::vec3(0.0f, 0.0f, 1.0f)); model_bat1 = glm::translate(model_bat1, glm::vec3(6.5f, 0.0f, 4.0f)); model_bat1 = glm::rotate(model_bat1, glm::radians(-135.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model_bat2 = glm::translate(model_bat2, glm::vec3(6.5f, 0.0f, -4.0f)); model_bat2 = glm::rotate(model_bat2, glm::radians(-45.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model_bat3 = glm::translate(model_bat3, glm::vec3(6.5f, 0.0f, 0.0f)); model_bat3 = glm::rotate(model_bat3, glm::radians(-90.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model_bat4 = glm::translate(model_bat4, glm::vec3(-6.5f, 0.0f, 4.0f)); model_bat4 = glm::rotate(model_bat4, glm::radians(135.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model_key = glm::translate(model_key, glm::vec3(1.6f, 1.32f, -0.3f)); model_key = glm::rotate(model_key, glm::radians(90.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model_keyExit = glm::translate(model_keyExit, glm::vec3(-6.25f, 1.2f, -4.99f)); model_keyExit = glm::rotate(model_keyExit, glm::radians(0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); // Draw lampShader.Use(); glUniformMatrix4fv(glGetUniformLocation(lampShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model_lamp)); Lamp.Draw(lampShader); lightingShader.Use(); glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model_map)); glUniform3f(glGetUniformLocation(lightingShader.Program, "material.ambient"), 1.0f, 1.0f, 1.0f); glUniform3f(glGetUniformLocation(lightingShader.Program, "material.diffuse"), 0.8f, 0.8f, 0.8f); glUniform3f(glGetUniformLocation(lightingShader.Program, "material.specular"), 0.7f, 0.7f, 0.7f); glUniform1f(glGetUniformLocation(lightingShader.Program, "material.shininess"), 32.0f); Map.Draw(lightingShader); glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model_bat1)); glUniform3f(glGetUniformLocation(lightingShader.Program, "material.specular"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(lightingShader.Program, "material.shininess"), 2.0f); Bat1.Draw(lightingShader); glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model_bat2)); Bat2.Draw(lightingShader); glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model_bat3)); Bat3.Draw(lightingShader); glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model_bat4)); Bat4.Draw(lightingShader); // Verify if the key was taken if(enableKey){ glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model_key)); glUniform3f(glGetUniformLocation(lightingShader.Program, "material.diffuse"), 1.0f, 1.0f, 1.0f); glUniform3f(glGetUniformLocation(lightingShader.Program, "material.specular"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(lightingShader.Program, "material.shininess"), 8.0f); Keycard.Draw(lightingShader); } if(enableExitKey){ glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model_keyExit)); KeyExit.Draw(lightingShader); } colorOffsetR = 0.5 * sin(glm::radians(alpha)) + 0.5; colorOffsetG = 0.5 * sin(glm::radians(2*alpha)) + 0.5; colorOffsetB = 0.5 * sin(glm::radians(4*alpha)) + 0.5; //lightColor = glm::vec3(colorOffsetR, colorOffsetG, colorOffsetB); if(alpha > 360) alpha = 0; else alpha += 0.05; // Swap the buffers glfwSwapBuffers(window); } glfwTerminate(); return 0; }
int main(int argc, char* argv[]) { glfwSetErrorCallback(error_callback); if (!glfwInit()) { fprintf(stderr, "Could not initialize GLFW.\n"); return EXIT_FAILURE; } glfwWindowHint(GLFW_RED_BITS, 8); glfwWindowHint(GLFW_GREEN_BITS, 8); glfwWindowHint(GLFW_BLUE_BITS, 8); glfwWindowHint(GLFW_ALPHA_BITS, 8); glfwWindowHint(GLFW_DEPTH_BITS, 32); glfwWindowHint(GLFW_STENCIL_BITS, GLFW_DONT_CARE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); glfwWindowHint(GLFW_SAMPLES, 4); GLFWwindow *window = glfwCreateWindow(1024, 768, "Lightmapping Example", NULL, NULL); if (!window) { fprintf(stderr, "Could not create window.\n"); glfwTerminate(); return EXIT_FAILURE; } glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); glfwSwapInterval(1); scene_t scene = {0}; if (!initScene(&scene)) { fprintf(stderr, "Could not initialize scene.\n"); glfwDestroyWindow(window); glfwTerminate(); return EXIT_FAILURE; } printf("Ambient Occlusion Baking Example.\n"); printf("Use your mouse and the W, A, S, D, E, Q keys to navigate.\n"); printf("Press SPACE to start baking one light bounce!\n"); printf("This will take a few seconds and bake a lightmap illuminated by:\n"); printf("1. The mesh itself (initially black)\n"); printf("2. A white sky (1.0f, 1.0f, 1.0f)\n"); while (!glfwWindowShouldClose(window)) { mainLoop(window, &scene); } destroyScene(&scene); glfwDestroyWindow(window); glfwTerminate(); return EXIT_SUCCESS; }
// 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); // Setup OpenGL options glEnable(GL_DEPTH_TEST); // Build and compile our shader program Shader ourShader("coordinate_systems.vs", "coordinate_systems.frag"); // Set up vertex data (and buffer(s)) and attribute pointers GLfloat vertices[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; // World space positions of our cubes glm::vec3 cubePositions[] = { glm::vec3( 0.0f, 0.0f, 0.0f), glm::vec3( 2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3( 2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3( 1.3f, -2.0f, -2.5f), glm::vec3( 1.5f, 2.0f, -2.5f), glm::vec3( 1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; GLuint VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // TexCoord attribute glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * 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 | GL_DEPTH_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 view; glm::mat4 projection; view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f)); projection = glm::perspective(45.0f, (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 100.0f); // Get their uniform location GLint modelLoc = glGetUniformLocation(ourShader.Program, "model"); GLint viewLoc = glGetUniformLocation(ourShader.Program, "view"); GLint projLoc = glGetUniformLocation(ourShader.Program, "projection"); // Pass the matrices to the shader glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); // 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. glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); glBindVertexArray(VAO); for (GLuint i = 0; i < 10; i++) { // Calculate the model matrix for each object and pass it to shader before drawing glm::mat4 model; model = glm::translate(model, cubePositions[i]); GLfloat angle = 20.0f * i; model = glm::rotate(model, 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 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; }
glfw_helper() { if (!glfwInit()) exit(EXIT_FAILURE); }