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(int argc, char *argv[]) { GLFWwindow* window; if(!glfwInit()) { return -1; } GLFWmonitor* monitor = glfwGetPrimaryMonitor(); const GLFWvidmode* vidmode = glfwGetVideoMode(monitor); window = glfwCreateWindow(vidmode->width, vidmode->height, "Pentigree", monitor, NULL); if(!window) { glfwTerminate(); return -1; } glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); int width, height; glfwGetFramebufferSize(window, &width, &height); float x = 0.0f; float y = 0.0f; glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0f, width, 0.0f, height, 0.0, 1.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); std::string lrep = pentigreelSystemRepresentation(); while(!glfwWindowShouldClose(window)) { x = width / 2.0f; y = height / 16.0f; glClear(GL_COLOR_BUFFER_BIT); glPushMatrix(); for(std::string::iterator it = lrep.begin(); it != lrep.end(); it++) { if(*it == 'F') { glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glLineWidth(3.0f); GLfloat vertices[] = {x, y, x + LINE_LENGTH, y}; glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 0, vertices); glDrawArrays(GL_LINES, 0, 4); glDisableClientState(GL_VERTEX_ARRAY); x = x + LINE_LENGTH; } if(*it == '-' || *it == '+') { glTranslatef(x, y, 0.0f); x = 0.0f; y = 0.0f; float angle = ((*it == '-') ? -72.0f : 72.0f); glRotatef(angle, 0.0f, 0.0f, 1.0f); } } glPopMatrix(); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; }
int main (int argc, char *argv[]) // MAIN { FILE *f; int i=0; if (argc!=3) { print_usage(); exit(0); } coo_file=argv[1]; data_file=argv[2]; load_chr_font("DRFT.CHR"); for (i=0;i<86400;i++) { coord[i][0]=0.0f; coord[i][1]=0.0f; coord[i][2]=0.0f; data[i][0] = 0.0f; data[i][1] = 0.0f; selected[i]=-1; } f = fopen(coo_file,"rt"); if (f == NULL) { printf("Error opening file %s\n",coo_file); exit(0); } i = 0; while (!feof(f)) { int snum; float n; float e; float h; fscanf(f,"%d\t%f\t%f\t%f\n",&snum,&n,&e,&h); coord[snum][0] = n; coord[snum][1] = e; coord[snum][2] = h; if (i == 0) { max_coo_x = n; max_coo_y = e; max_coo_h = h; min_coo_x = n; min_coo_y = e; min_coo_h = h; i = 1; } else { if (max_coo_x < n) max_coo_x = n; if (max_coo_y < e) max_coo_y = e; if (max_coo_h < h) max_coo_h = h; if (min_coo_x > n) min_coo_x = n; if (min_coo_y > e) min_coo_y = e; if (min_coo_h > h) min_coo_h = h; } selected[snum] = 1; } fclose(f); coo_w = max_coo_x - min_coo_x; coo_h = max_coo_y - min_coo_y; coo_a = max_coo_h - min_coo_h; f = fopen(data_file,"rt"); if (f == NULL) { printf("Error opening file %s\n",data_file); exit(0); } i = 0; int j = 0; while (!feof(f)) { fscanf(f,"%f\t%f\n",&data[i][0],&data[i][1]); if (i>=14400) if (selected[i-14400]>=0) { if (j==0) { max_data[0]=data[0][0]; max_data[1]=data[0][1]; min_data[0]=data[0][0]; min_data[1]=data[0][1]; j = 1; } else { if (max_data[0]<data[i][0]) max_data[0]=data[i][0]; if (max_data[1]<data[i][1]) max_data[1]=data[i][1]; if (min_data[0]>data[i][0]) min_data[0]=data[i][0]; if (min_data[1]>data[i][1]) min_data[1]=data[i][1]; } } i++; } fclose(f); data_w[0] = max_data[0]-min_data[0]; data_w[1] = max_data[1]-min_data[1]; if (!glfwInit()) exit(EXIT_FAILURE); current_vmode = glfwGetVideoMode(glfwGetPrimaryMonitor()); screen_width = current_vmode->width; screen_height = current_vmode->height; arat = (float)screen_width / (float)screen_height; px = 2.0F / screen_width; py = 2.0F / screen_height; window = glfwCreateWindow(screen_width, screen_height, "PROFB", glfwGetPrimaryMonitor(), NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); glfwSetMouseButtonCallback(window, mousepress); glfwSetCursorPosCallback(window, mousemove); glfwSetScrollCallback(window, mouseweelscroll); glClearColor(1.0,1.0,1.0,0); glEnable(GL_LINE_SMOOTH); glEnable(GL_POINT_SMOOTH); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); while (!glfwWindowShouldClose(window)) { glfwPollEvents(); if (Redisplay==1) { Draw(); Redisplay=0; } } glfwDestroyWindow(window); glfwTerminate(); return 0; }
int main() { char message[256]; sprintf(message, "staring glfw %s", glfwGetVersionString()); assert(GL_log(message, __FILE__, __LINE__)); glfwSetErrorCallback(glfw_error_callback); //open and OS window using glfw if (!glfwInit()) { fprintf (stderr,"ERROR: could not start GLFW3\n"); return 1; } glfwWindowHint(GLFW_SAMPLES, 4); //get primary monitor GLFWmonitor* mon = glfwGetPrimaryMonitor(); //this lets us use the video mode for the monitor we pass const GLFWvidmode* vmode = glfwGetVideoMode(mon); GLFWwindow* window = glfwCreateWindow(vmode->width, vmode->height, "Extended GL Init", NULL/*mon*/, NULL); glfwSetWindowSize(window, g_gl_width, g_gl_height); if (!window) { fprintf (stderr,"ERROR: could not open window GLFW3\n"); glfwTerminate(); return 1; } glfwMakeContextCurrent(window); //start glew extention handler glewExperimental = GL_TRUE; glewInit(); //get version info const GLubyte * renderer = glGetString (GL_RENDERER); //get renderer string const GLubyte * version = glGetString (GL_VERSION); //get version as a string printf ("Renerer: %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); /* other stuff goes here */ /*float points[] = { 0.0f, 0.5, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, -0.5f, 0.0f }; GLuint VBO = 0; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, 9 * sizeof (float), points, GL_STATIC_DRAW); GLuint VAO = 0; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, VBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); const char* vertex_shader = "#version 330\n" "in vec3 pos;\n" "void main() {" "gl_Position = vec4(pos, 1.0);\n" "}"; const char* fragment_shader = "#version 330\n" "out vec4 frag_colour;\n" "void main() {" "frag_colour = vec4(0.5, 0.0, 0.5, 1.0);\n" "}"; //create a shader GLuint vs = glCreateShader(GL_VERTEX_SHADER); //put the actual cha* int the shader glShaderSource(vs, 1, &vertex_shader, NULL); //compile the shader glCompileShader(vs); PrintShaderInfoLog(vs); GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &fragment_shader, NULL); glCompileShader(fs); PrintShaderInfoLog(fs); //create the container that holds the shaders GLuint shaderProgram = glCreateProgram(); //attach the shaders glAttachShader(shaderProgram, fs); glAttachShader(shaderProgram, vs); //this inks the shaders together, its kinda like a compile glLinkProgram(shaderProgram); PrintProgramInfoLog(shaderProgram); //new object float Spoints[] = { -0.25f, -0.5f, 0.0f, -0.25f, -0.75f, 0.0f, 0.25f, -0.5f, 0.0f, 0.25f, -0.75f, 0.0f }; GLuint VBO2 = 0; glGenBuffers(1, &VBO2); glBindBuffer(GL_ARRAY_BUFFER, VBO2); glBufferData(GL_ARRAY_BUFFER, 12 * sizeof (float), Spoints, GL_STATIC_DRAW); GLuint VAO2 = 0; glGenVertexArrays(1, &VAO2); glBindVertexArray(VAO2); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); const char* vertex_shader2 = "#version 330\n" "in vec3 vp;\n" "void main() {" "gl_position = vec4(vp, 2.0);\n" "}"; const char* fragment_shader2 = "#version 330\n" "out vec4 frag_colour;\n" "void main() {" "frag_colour = vec4(0.5, 0.0, 0.0, 1.0);\n" "}"; //create a shader GLuint vs2 = glCreateShader(GL_VERTEX_SHADER); //put the actual char* in the shader glShaderSource(vs2, 1, &vertex_shader2, NULL); //compile the shader glCompileShader(vs2); PrintShaderInfoLog(vs2); GLuint fs2 = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs2, 1, &fragment_shader2, NULL); glCompileShader(fs2); PrintShaderInfoLog(fs2); //create the container that holds the shaders GLuint secondProgram = glCreateProgram(); //attach the shaders glAttachShader(secondProgram, fs2); glAttachShader(secondProgram, vs2); //this inks the shaders together, its kinda like a compile glLinkProgram(secondProgram); PrintProgramInfoLog(secondProgram); */ Ortho = new Matrix4(); Orthographic(0, g_gl_width, g_gl_height, 0, 0, -1, Ortho); //Quad * tester1 = new Quad(); AnimatedSprite * tester = new AnimatedSprite("../resources/MegamanXSheet.xml", window); tester->SetAnimation("teleport", ONCE); while (!glfwWindowShouldClose(window)) { //_update_fps_counter(window); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.5); glEnable(GL_ALPHA); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CW); //wipe the drawing surface glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //resize window glViewport (0, 0, g_gl_width, g_gl_height); tester->Update(); //tester->Draw(); //tester->Input(); //update other events like input handling glfwPollEvents(); //put the stuff we've been drawing into the display glfwSwapBuffers(window); resetDeltaTime(); if (GLFW_PRESS == glfwGetKey(window, GLFW_KEY_ESCAPE)) { glfwSetWindowShouldClose(window, 1); } } //close GL context and any other GLFW resources //delete Ortho; //delete tester; glfwTerminate(); return 0; }
void init() { #ifdef GRAPHICS if (!glfwInit()) { LOG("Failed to init GLFW."); exit(-1); } initGraph(&fps_graph, GRAPH_RENDER_FPS, "Frame Time"); initGraph(&cpu_graph, GRAPH_RENDER_MS, "CPU Time"); initGraph(&gpu_graph, GRAPH_RENDER_MS, "GPU Time"); glfwSetErrorCallback([](int error, const char* desc) {LOG("GLFW error %d: %s\n", error, desc); }); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, 1); int height = glfwGetVideoMode(glfwGetPrimaryMonitor())->height*0.6, width = height*double(world::width) / double(world::height); window = glfwCreateWindow(width, height, "PedestrianSimulator", NULL, NULL); if (!window) { glfwTerminate(); exit(-1); } glfwSetKeyCallback(window, [](GLFWwindow* window, int key, int scancode, int action, int mods) { NVG_NOTUSED(scancode); NVG_NOTUSED(mods); if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); }); glfwSetMouseButtonCallback(window, [](GLFWwindow* wind, int button, int action, int mods){ static vec_t start_pos; vecd_t pos; glfwGetCursorPos(wind, &pos.x, &pos.y); vec_t world_pos = screen2world({ pos.x, pos.y }); if (action == GLFW_RELEASE) { if (button == GLFW_MOUSE_BUTTON_1) { world::add_objective({ world_pos, 0 }); } else if (button == GLFW_MOUSE_BUTTON_2) { world::add_objective({ world_pos, 1 }); } else if (button==GLFW_MOUSE_BUTTON_3) LOG("click at screen (%.2lf, %.2lf), world (%.2f, %.2f)", pos.x, pos.y, world_pos.x, world_pos.y); } else if (action == GLFW_PRESS) { if (button == GLFW_MOUSE_BUTTON_2) { start_pos = world_pos; } } }); glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { LOG("Could not init glew.\n"); exit(-1); } glGetError(); vg = nvgCreateGL3(512, 512, NVG_ANTIALIAS | NVG_STENCIL_STROKES); if (vg == NULL) { LOG("Could not init nanovg.\n"); exit(-1); } nvgCreateFont(vg, "sans", "roboto.ttf"); glfwSwapInterval(0); initGPUTimer(&gpu_timer); glfwSetTime(0); prev_time = glfwGetTime(); #endif }
int main(int argc, char** argv) { int ch, width, height; float position; unsigned long frame_count = 0; double last_time, current_time; GLboolean fullscreen = GL_FALSE; GLFWmonitor* monitor = NULL; GLFWwindow* window; while ((ch = getopt(argc, argv, "fh")) != -1) { switch (ch) { case 'h': usage(); exit(EXIT_SUCCESS); case 'f': fullscreen = GL_TRUE; break; } } glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); if (fullscreen) { const GLFWvidmode* mode; monitor = glfwGetPrimaryMonitor(); mode = glfwGetVideoMode(monitor); glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); width = mode->width; height = mode->height; } else { width = 640; height = 480; } window = glfwCreateWindow(width, height, "", monitor, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); set_swap_interval(window, 0); last_time = glfwGetTime(); frame_rate = 0.0; swap_tear = (glfwExtensionSupported("WGL_EXT_swap_control_tear") || glfwExtensionSupported("GLX_EXT_swap_control_tear")); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetKeyCallback(window, key_callback); glMatrixMode(GL_PROJECTION); glOrtho(-1.f, 1.f, -1.f, 1.f, 1.f, -1.f); glMatrixMode(GL_MODELVIEW); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT); position = cosf((float) glfwGetTime() * 4.f) * 0.75f; glRectf(position - 0.25f, -1.f, position + 0.25f, 1.f); glfwSwapBuffers(window); glfwPollEvents(); frame_count++; current_time = glfwGetTime(); if (current_time - last_time > 1.0) { frame_rate = frame_count / (current_time - last_time); frame_count = 0; last_time = current_time; update_window_title(window); } } glfwTerminate(); exit(EXIT_SUCCESS); }
Screen::Screen(const Vector2i &size, const std::string &caption, bool resizable, bool fullscreen) : Widget(nullptr), mGLFWWindow(nullptr), mNVGContext(nullptr), mCursor(Cursor::Arrow), mCaption(caption) { memset(mCursors, 0, sizeof(GLFWcursor *) * (int) Cursor::CursorCount); /* Request a forward compatible OpenGL 3.3 core profile context */ glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); /* Request a RGBA8 buffer without MSAA */ glfwWindowHint(GLFW_SAMPLES, 0); glfwWindowHint(GLFW_RED_BITS, 8); glfwWindowHint(GLFW_GREEN_BITS, 8); glfwWindowHint(GLFW_BLUE_BITS, 8); glfwWindowHint(GLFW_ALPHA_BITS, 8); glfwWindowHint(GLFW_STENCIL_BITS, 8); glfwWindowHint(GLFW_DEPTH_BITS, 24); glfwWindowHint(GLFW_VISIBLE, GL_FALSE); glfwWindowHint(GLFW_RESIZABLE, resizable ? GL_TRUE : GL_FALSE); if (fullscreen) { GLFWmonitor *monitor = glfwGetPrimaryMonitor(); const GLFWvidmode *mode = glfwGetVideoMode(monitor); mGLFWWindow = glfwCreateWindow(mode->width, mode->height, caption.c_str(), monitor, nullptr); } else { mGLFWWindow = glfwCreateWindow(size.x(), size.y(), caption.c_str(), nullptr, nullptr); } if (!mGLFWWindow) throw std::runtime_error("Could not create an OpenGL 3.3 context!"); glfwMakeContextCurrent(mGLFWWindow); #if defined(_WIN32) if (!glewInitialized) { glewExperimental = GL_TRUE; glewInitialized = true; if (glewInit() != GLEW_NO_ERROR) throw std::runtime_error("Could not initialize GLEW!"); glGetError(); // pull and ignore unhandled errors like GL_INVALID_ENUM } #endif glfwGetFramebufferSize(mGLFWWindow, &mFBSize[0], &mFBSize[1]); glViewport(0, 0, mFBSize[0], mFBSize[1]); glClearColor(mBackground[0], mBackground[1], mBackground[2], 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glfwSwapInterval(0); glfwSwapBuffers(mGLFWWindow); #if defined(__APPLE__) /* Poll for events once before starting a potentially lengthy loading process. This is needed to be classified as "interactive" by other software such as iTerm2 */ glfwPollEvents(); #endif /* Propagate GLFW events to the appropriate Screen instance */ glfwSetCursorPosCallback(mGLFWWindow, [](GLFWwindow *w,double x,double y) { auto it = __nanogui_screens.find(w); if (it == __nanogui_screens.end()) return; Screen *s = it->second; if (!s->mProcessEvents) return; s->cursorPosCallbackEvent(x, y); } ); glfwSetMouseButtonCallback(mGLFWWindow, [](GLFWwindow *w, int button, int action, int modifiers) { auto it = __nanogui_screens.find(w); if (it == __nanogui_screens.end()) return; Screen *s = it->second; if (!s->mProcessEvents) return; s->mouseButtonCallbackEvent(button, action, modifiers); } ); glfwSetKeyCallback(mGLFWWindow, [](GLFWwindow *w, int key, int scancode, int action, int mods) { auto it = __nanogui_screens.find(w); if (it == __nanogui_screens.end()) return; Screen *s = it->second; if (!s->mProcessEvents) return; s->keyCallbackEvent(key, scancode, action, mods); } ); glfwSetCharCallback(mGLFWWindow, [](GLFWwindow *w, unsigned int codepoint) { auto it = __nanogui_screens.find(w); if (it == __nanogui_screens.end()) return; Screen *s = it->second; if (!s->mProcessEvents) return; s->charCallbackEvent(codepoint); } ); glfwSetDropCallback(mGLFWWindow, [](GLFWwindow *w,int count,const char **filenames) { auto it = __nanogui_screens.find(w); if (it == __nanogui_screens.end()) return; Screen *s = it->second; if (!s->mProcessEvents) return; s->dropCallbackEvent(count, filenames); } ); glfwSetScrollCallback(mGLFWWindow, [](GLFWwindow *w, double x, double y) { auto it = __nanogui_screens.find(w); if (it == __nanogui_screens.end()) return; Screen *s = it->second; if (!s->mProcessEvents) return; s->scrollCallbackEvent(x, y); } ); initialize(mGLFWWindow); }
int main(int argc, char** argv) { int width, height, ch; GLFWmonitor* monitor = NULL; GLFWwindow* window; glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); while ((ch = getopt(argc, argv, "fh")) != -1) { switch (ch) { case 'h': usage(); exit(EXIT_SUCCESS); case 'f': monitor = glfwGetPrimaryMonitor(); break; default: usage(); exit(EXIT_FAILURE); } } if (monitor) { GLFWvidmode mode = glfwGetVideoMode(monitor); width = mode.width; height = mode.height; } else { width = 640; height = 480; } window = glfwCreateWindow(width, height, "Iconify", monitor, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glfwSwapInterval(1); glfwSetKeyCallback(window, key_callback); glfwSetWindowSizeCallback(window, window_size_callback); glfwSetWindowCloseCallback(window, window_close_callback); glfwSetWindowFocusCallback(window, window_focus_callback); glfwSetWindowIconifyCallback(window, window_iconify_callback); printf("Window is %s and %s\n", glfwGetWindowParam(window, GLFW_ICONIFIED) ? "iconified" : "restored", glfwGetWindowParam(window, GLFW_FOCUSED) ? "focused" : "defocused"); glEnable(GL_SCISSOR_TEST); while (!closed) { glfwGetWindowSize(window, &width, &height); glScissor(0, 0, width, height); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); glScissor(0, 0, 640, 480); glClearColor(1, 1, 1, 0); glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); exit(EXIT_SUCCESS); }
void BaseApplication::ChooseResolution() { int _resolutionTable[] = { 640, 480, 800, 600, 1024, 768, 1280, 720, 1280, 800, 1280, 1024, 1366, 768, 1400, 1050, 1600, 1200, 1680, 1050, 1920, 1080 }; #define RES_COUNT 21 #define RESIZE_WARNING "<WARNING>: Your resolution has been changed to: %d x %d, because it did not conform to any standard resolution.\n" //Somehow this window hint is causing the glfwCreateWindow func to fail window creation. //I should investigate further once the assigment is over. //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); #ifdef _DEBUG glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif glfwWindowHint(GLFW_SAMPLES, this->m_oApp->APPINFO.m_iSample); GLFWmonitor* _primatyMon = glfwGetPrimaryMonitor(); const GLFWvidmode* _modes = glfwGetVideoMode(_primatyMon); //Simple lambda func to determine if the number is even or not. auto _even = [](unsigned int n){ return (n % 2 == 0) ? n : (n + 1); }; //Return a value if the number is even. auto _isEven_ = [](unsigned int n){return (n % 2 == 0) ? true : false; }; unsigned int _idx = 0; unsigned int _nextIdx = 0; static unsigned int _prevIdx = 99; bool _found = false; if (this->m_oApp->APPINFO.m_viWinSize.x == 0 && this->m_oApp->APPINFO.m_viWinSize.y == 0) { if ((_resolutionTable[20] < _modes->width) && (_resolutionTable[21] < _modes->height)) { this->m_oApp->APPINFO.m_viWinSize = ivec2(_resolutionTable[20], _resolutionTable[21]); _found = !_found; } if (!_found) { for (unsigned int i = 0; i < RES_COUNT; ++i) { if (_prevIdx != i) { _idx = _even(i); _nextIdx = _idx + 1; } else continue; if ((_resolutionTable[_idx] == _modes->width) && (_resolutionTable[_nextIdx] == _modes->height)) { this->m_oApp->APPINFO.m_viWinSize = ivec2(_resolutionTable[_idx], _resolutionTable[_nextIdx]); _found = !_found; } if (!_found && !_isEven_(i)) { _prevIdx = _idx; } if (_found) { printf(RESIZE_WARNING, this->m_oApp->APPINFO.m_viWinSize.x, this->m_oApp->APPINFO.m_viWinSize.y); break; } } } } else if (this->m_oApp->APPINFO.m_viWinSize.x <= 0 && this->m_oApp->APPINFO.m_viWinSize.y > 0) { if ((_resolutionTable[20] < _modes->width) && (_resolutionTable[21] < _modes->height)) { this->m_oApp->APPINFO.m_viWinSize = ivec2(_resolutionTable[20], _resolutionTable[21]); _found = !_found; } if (!_found) { for (unsigned int i = 0; i < RES_COUNT; ++i) { if (_prevIdx != i) { _idx = _even(i); _nextIdx = _idx + 1; } else continue; if (this->m_oApp->APPINFO.m_viWinSize.y == _resolutionTable[_nextIdx]) { this->m_oApp->APPINFO.m_viWinSize.x = _resolutionTable[_idx]; _found = !_found; } if (!_found && !_isEven_(i)) { _prevIdx = _idx; } if (_found) { printf(RESIZE_WARNING, this->m_oApp->APPINFO.m_viWinSize.x, this->m_oApp->APPINFO.m_viWinSize.y); break; } } } } else if (this->m_oApp->APPINFO.m_viWinSize.y <= 0 && this->m_oApp->APPINFO.m_viWinSize.x > 0) { if ((_resolutionTable[20] < _modes->width) && (_resolutionTable[21] < _modes->height)) { this->m_oApp->APPINFO.m_viWinSize = ivec2(_resolutionTable[20], _resolutionTable[21]); _found = !_found; } if (!_found) { for (unsigned int i = 0; i < RES_COUNT; ++i) { if (_prevIdx != i) { _idx = _even(i); _nextIdx = _idx + 1; } else continue; if (this->m_oApp->APPINFO.m_viWinSize.x == _resolutionTable[_idx]) { this->m_oApp->APPINFO.m_viWinSize.y = _resolutionTable[_nextIdx]; _found = !_found; } if (!_found && !_isEven_(i)) { _prevIdx = _idx; } if (_found) { printf(RESIZE_WARNING, this->m_oApp->APPINFO.m_viWinSize.x, this->m_oApp->APPINFO.m_viWinSize.y); break; } } } } if (!_found) { printf(RESIZE_WARNING, this->m_oApp->APPINFO.m_viWinSize.x, this->m_oApp->APPINFO.m_viWinSize.y); this->m_oApp->APPINFO.m_viWinSize = ivec2(_resolutionTable[10], _resolutionTable[11]); } if (this->m_oApp->APPINFO.Flags.m_uiFullScreen) { this->m_oApp->DATA.m_oWin = glfwCreateWindow( this->m_oApp->APPINFO.m_viWinSize.x, this->m_oApp->APPINFO.m_viWinSize.y, this->m_oApp->APPINFO.m_pccTitle, _primatyMon, nullptr); } else { this->m_oApp->DATA.m_oWin = glfwCreateWindow( this->m_oApp->APPINFO.m_viWinSize.x, this->m_oApp->APPINFO.m_viWinSize.y, this->m_oApp->APPINFO.m_pccTitle, nullptr, nullptr); } printf("--------------------------------------------------------------------------------"); printf("-- WINDOW INITIALIZED CORRECTLY. \n"); printf("--------------------------------------------------------------------------------"); }
glm::uvec2 getSize(GLFWmonitor * monitor) { const GLFWvidmode * mode = glfwGetVideoMode(monitor); return glm::uvec2(mode->width, mode->height); }
int main(int argc, char *argv[]) { //start context if (!glfwInit()) { fprintf(stderr, "Error, could not start GLFW3\n"); return 1; } else { fprintf(stderr, "GLFW initialized properly."); } //Forward compatibility from version 3.2. 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_SAMPLES, 4); //Anti aliasing (4 passes) //start logs Logger::restartLog(GL_LOG_FILE); glfwSetErrorCallback(glfwErrorCallback); GLFWmonitor* monitor = glfwGetPrimaryMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(monitor); //init window with primary monitor resolution //Set these modes for a fullscreen window and don't for classic fullscreen: /*glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);*/ //------------------------------------------------ //GLFWwindow * window = glfwCreateWindow(mode->width, mode->height, "Tutorial 1: Draw a triangle", monitor, NULL); //Fullscreen GLFWwindow * window = glfwCreateWindow(800, 600, "Tutorial 1: Draw a triangle", NULL, NULL); //Not Fullscreen //if window initialisation failed if (!window) { fprintf(stderr, "Could not open window with GLFW3\n"); glfwTerminate(); return 1; } glfwMakeContextCurrent(window); glfwSetWindowSizeCallback(window, glfwWindowSizeCallback); //start glew extension handler; glewExperimental = GL_TRUE; glewInit(); //get version info const GLubyte * renderer = glGetString(GL_RENDERER); const GLubyte * version = glGetString(GL_VERSION); //Log informations Logger::printToLog(GL_LOG_FILE, "Starting GLFW: %s \n", glfwGetVersionString()); logGlParams(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); //draw triangle initTriangles(); Shader vertex = Shader("vertex.vert", GL_VERTEX_SHADER); Shader frag_1 = Shader("frag1.frag", GL_FRAGMENT_SHADER); Shader frag_2 = Shader("frag2.frag", GL_FRAGMENT_SHADER); Shader shaders_1[2] = { vertex, frag_1 }; Shader shaders_2[2] = { vertex, frag_2 }; ShaderProgram shader_programme_1 = ShaderProgram(shaders_1, VERT_FRAG); ShaderProgram shader_programme_2 = ShaderProgram(shaders_2, VERT_FRAG); while (!glfwWindowShouldClose(window)) { updateFpsCounter(window); // wipe the drawing surface clear glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport(0, 0, g_gl_width, g_gl_height); glClearColor(0.1f, 0.1f, 0.1f, 0.0f); glUseProgram(shader_programme_1.get_program()); glBindVertexArray(vao_1); // draw points 0-5 from the currently bound VAO with current in-use shader glDrawArrays(GL_TRIANGLES, 0, 6); glUseProgram(shader_programme_2.get_program()); glBindVertexArray(vao_2); // draw points 0-5 from the currently bound VAO with current in-use shader glDrawArrays(GL_TRIANGLES, 0, 3); // update other events like input handling glfwPollEvents(); // put the stuff we've been drawing onto the display glfwSwapBuffers(window); if (GLFW_PRESS == glfwGetKey(window, GLFW_KEY_ESCAPE)) { glfwSetWindowShouldClose(window, 1); } } //close gl context and other glfw resources glfwTerminate(); return 0; }
int main( int argc, char* argv[] ) { // initialize glfw GLFWwindow* window = nullptr; glfwInit(); /*glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 4 ); glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 3 ); //glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );*/ glfwWindowHint( GLFW_RESIZABLE, GL_FALSE ); if( FULL_SCREEN ) { GLFWvidmode* mode = (GLFWvidmode*)glfwGetVideoMode( glfwGetPrimaryMonitor() ); glfwWindowHint( GLFW_RED_BITS, mode->redBits ); glfwWindowHint( GLFW_GREEN_BITS, mode->greenBits ); glfwWindowHint( GLFW_BLUE_BITS, mode->blueBits ); glfwWindowHint( GLFW_REFRESH_RATE, mode->refreshRate ); SCREEN_WIDTH = mode->width; SCREEN_HEIGHT = mode->height; window = glfwCreateWindow( SCREEN_WIDTH, SCREEN_HEIGHT, "Gravity Pong", glfwGetPrimaryMonitor(), nullptr ); } else { window = glfwCreateWindow( SCREEN_WIDTH, SCREEN_HEIGHT, "Gravity Pong", nullptr, nullptr ); } glfwMakeContextCurrent( window ); glfwSwapInterval( 1 ); glewExperimental = GL_TRUE; glewInit(); // check to see if there was a glewInit() bug glGetError(); glfwSetKeyCallback( window, keyCallBack ); // opengl config glViewport( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT ); glEnable( GL_CULL_FACE ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); // initialize the game game = new GravityPong( SCREEN_WIDTH, SCREEN_HEIGHT ); game->init(); // time variables GLfloat dt = 0.0f, lastTime = 0.0f; RetroRenderer renderer; // start the game within the menu state while( !glfwWindowShouldClose( window ) ) { // calculate dt GLfloat currentTime = glfwGetTime(); dt = currentTime - lastTime; lastTime = currentTime; glfwPollEvents(); // keep dt small if( dt > 0.333f ) { dt = 0.333f; } // process input game->processInput( dt ); // update game state game->update( dt ); // render the game glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); glClear( GL_COLOR_BUFFER_BIT ); game->render(); glfwSwapBuffers( window ); } ResourceManager::clear(); //system( "pause" ); glfwDestroyWindow( window ); glfwTerminate(); return 0; }
int main(int argc, char** argv) { #if defined(_WIN32) LOG_INFO("Windows build."); #elif defined(_LINUX) LOG_INFO("Linux build."); #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) 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(OVRSDK06) std::string windowTitle = ""; LOG_INFO("Using SDK 0.6.0.0's direct mode."); windowTitle = PROJECT_NAME "-GLFW-06-Direct"; GLFWmonitor* monitor = glfwGetPrimaryMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(monitor); ovrSizei sz; ovrVector2i pos; sz.w = mode->width/2; sz.h = mode->height/2; pos.x = 100; pos.y = 100; // Create just a regular window for presenting OVR SDK 0.6's mirror texture ///@todo Is it any faster with no mirror at all? 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(), NULL, NULL); g_app.SetAppWindowSize(sz); #else l_Window = glfwCreateWindow(800, 600, "GLFW Oculus Rift Test", NULL, NULL); std::string windowTitle = PROJECT_NAME; #endif //USE_OSVR|OVRSDK06 if (!l_Window) { LOG_INFO("Glfw failed to create a window. Exiting."); glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(l_Window); glfwSetWindowSizeCallback(l_Window, resize_Aux); glfwSetMouseButtonCallback(l_Window, mouseDown_Aux); glfwSetCursorPosCallback(l_Window, mouseMove_Aux); glfwSetScrollCallback(l_Window, mouseWheel_Aux); glfwSetKeyCallback(l_Window, keyboard_Aux); 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); SetVsync(0); // SDK 0.6 requires vsync OFF while (!glfwWindowShouldClose(l_Window)) { g_app.CheckForTapToDismissHealthAndSafetyWarning(); glfwPollEvents(); joystick(); timestep(); g_fps.OnFrame(); if (g_dynamicallyScaleFBO) { DynamicallyScaleFBO(); } #ifdef USE_ANTTWEAKBAR TwRefreshBar(g_pTweakbar); #endif g_app.pre_render_pass(); 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()); } #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(); } } g_app.exitVR(); glfwDestroyWindow(l_Window); glfwTerminate(); exit(EXIT_SUCCESS); }
int main(int argc, char** argv) { int count = 0; double base; GLFWwindow* window; srand((unsigned int) time(NULL)); glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); for (;;) { int width, height; GLFWmonitor* monitor = NULL; GLuint vertex_shader, fragment_shader, program, vertex_buffer; GLint mvp_location, vpos_location; if (count & 1) { int monitorCount; GLFWmonitor** monitors = glfwGetMonitors(&monitorCount); monitor = monitors[rand() % monitorCount]; } if (monitor) { const GLFWvidmode* mode = glfwGetVideoMode(monitor); width = mode->width; height = mode->height; } else { width = 640; height = 480; } base = glfwGetTime(); window = glfwCreateWindow(width, height, "Window Re-opener", monitor, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } if (monitor) { printf("Opening full screen window on monitor %s took %0.3f seconds\n", glfwGetMonitorName(monitor), glfwGetTime() - base); } else { printf("Opening regular window took %0.3f seconds\n", glfwGetTime() - base); } glfwSetWindowCloseCallback(window, window_close_callback); glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); glfwSwapInterval(1); vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL); glCompileShader(vertex_shader); fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL); glCompileShader(fragment_shader); program = glCreateProgram(); glAttachShader(program, vertex_shader); glAttachShader(program, fragment_shader); glLinkProgram(program); mvp_location = glGetUniformLocation(program, "MVP"); vpos_location = glGetAttribLocation(program, "vPos"); glGenBuffers(1, &vertex_buffer); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(vpos_location); glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE, sizeof(vertices[0]), (void*) 0); glfwSetTime(0.0); while (glfwGetTime() < 5.0) { float ratio; int width, height; mat4x4 m, p, mvp; glfwGetFramebufferSize(window, &width, &height); ratio = width / (float) height; glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT); mat4x4_ortho(p, -ratio, ratio, -1.f, 1.f, 0.f, 1.f); mat4x4_identity(m); mat4x4_rotate_Z(m, m, (float) glfwGetTime()); mat4x4_mul(mvp, p, m); glUseProgram(program); glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glfwSwapBuffers(window); glfwPollEvents(); if (glfwWindowShouldClose(window)) { close_window(window); printf("User closed window\n"); glfwTerminate(); exit(EXIT_SUCCESS); } } printf("Closing window\n"); close_window(window); count++; } glfwTerminate(); }
glm::vec2 _getCurrentScreenSize() { const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); return {mode->width, mode->height}; }
int main(int argc, char** argv) { int width, height, ch; GLFWmonitor* monitor = NULL; GLFWwindow* window; glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); while ((ch = getopt(argc, argv, "fh")) != -1) { switch (ch) { case 'h': usage(); exit(EXIT_SUCCESS); case 'f': monitor = glfwGetPrimaryMonitor(); break; default: usage(); exit(EXIT_FAILURE); } } if (monitor) { const GLFWvidmode* mode = glfwGetVideoMode(monitor); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); width = mode->width; height = mode->height; } else { width = 200; height = 200; } window = glfwCreateWindow(width, height, "Gamma Test", monitor, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } set_gamma(window, 1.f); glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); glfwSwapInterval(1); glfwSetKeyCallback(window, key_callback); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glMatrixMode(GL_PROJECTION); glOrtho(-1.f, 1.f, -1.f, 1.f, -1.f, 1.f); glMatrixMode(GL_MODELVIEW); glClearColor(0.5f, 0.5f, 0.5f, 0); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.8f, 0.2f, 0.4f); glRectf(-0.5f, -0.5f, 0.5f, 0.5f); glfwSwapBuffers(window); glfwWaitEvents(); } glfwTerminate(); exit(EXIT_SUCCESS); }
int main(int argc, char** argv) { LOG_INFO("RiftRay version %s", pRiftRayVersion); #if defined(_WIN32) LOG_INFO("Windows build."); #elif defined(_LINUX) LOG_INFO("Linux build."); #elif defined(_MACOS) LOG_INFO("MacOS build."); #endif bool useOpenGLCoreContext = false; g_renderMode.outputType = RenderingMode::OVR_SDK; #ifdef USE_CORE_CONTEXT useOpenGLCoreContext = true; #endif #ifdef _LINUX // Linux driver seems to be lagging a bit useOpenGLCoreContext = false; #endif 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; } } LoadConfigFile(); g_app.initHMD(); GLFWwindow* l_Window = NULL; glfwSetErrorCallback(ErrorCallback); if (!glfwInit()) { exit(EXIT_FAILURE); } #ifdef __APPLE__ // Set the working directory to the Resources dir of the .app bundle CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle); char path[PATH_MAX]; CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX); CFRelease(resourcesURL); strcat( path, "/shaders" ); struct stat sb; if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) chdir(path); #endif #ifndef _LINUX glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); # if defined(_MACOS) glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); # else glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); # endif #endif //ndef _LINUX if (useOpenGLCoreContext) { LOG_INFO("Using OpenGL core context."); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); } else { #ifndef _LINUX glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE); #endif } glfwWindowHint(GLFW_SAMPLES, 0); #ifdef _DEBUG glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif std::string windowTitle = "RiftRay-v" + std::string(pRiftRayVersion); #ifdef USE_OCULUSSDK const ovrSizei sz = g_app.getHmdResolution(); const ovrVector2i pos = g_app.getHmdWindowPos(); if (g_app.UsingDebugHmd() == true) { // Create a normal, decorated application window LOG_INFO("Using Debug HMD mode."); windowTitle += "-GLFW-DebugHMD"; l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); g_app.m_dashScene.m_bDraw = false; g_renderMode.outputType = RenderingMode::Mono_Buffered; } else if (g_app.UsingDirectMode()) { LOG_INFO("Using Direct to Rift mode."); windowTitle += "-GLFW-Direct"; l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); #if defined(_WIN32) g_app.AttachToWindow((void*)glfwGetWin32Window(l_Window)); #endif } else { LOG_INFO("Using Extended desktop mode."); windowTitle += "-GLFW-Extended"; glfwWindowHint(GLFW_DECORATED, 0); l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); glfwWindowHint(GLFW_DECORATED, 1); 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."); windowTitle += "-GLFW-NoVRSDK"; g_renderMode.outputType = RenderingMode::Mono_Buffered; l_Window = glfwCreateWindow(sz.x, sz.y, windowTitle.c_str(), NULL, NULL); resize(l_Window, sz.x, sz.y); // inform AppSkeleton of window size #endif //USE_OSVR|USE_OCULUSSDK if (!l_Window) { LOG_INFO("Glfw failed to create a window. Exiting."); glfwTerminate(); exit(EXIT_FAILURE); } #ifdef USE_OCULUSSDK // Required for SDK rendering (to do the buffer swap on its own) # if defined(_WIN32) g_app.setWindow(glfwGetWin32Window(l_Window)); # elif defined(__linux__) g_app.setWindow(glfwGetX11Display()); # endif #endif 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)); FindPreferredJoystick(); // 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) { LOG_INFO("Monitor #%d: %dx%d @ %dHz %s", i, mode->width, mode->height, mode->refreshRate, pCur==pPrimary ? "Primary":""); } } 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(); LOG_INFO("initVR complete."); SetVsync(1); // default to vsync on StartShaderLoad(); while (!glfwWindowShouldClose(l_Window)) { const bool tapped = g_app.CheckForTapOnHmd(); if (tapped && (g_receivedFirstTap == false)) { g_app.RecenterPose(); g_receivedFirstTap = true; } glfwPollEvents(); joystick(); timestep(); g_fps.OnFrame(); if (g_dynamicallyScaleFBO) { DynamicallyScaleFBO(); } #ifdef USE_ANTTWEAKBAR TwRefreshBar(g_pTweakbar); TwRefreshBar(g_pShaderTweakbar); #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); }
bool initGlfw(int argc, char **argv) { glfwSetErrorCallback(error_callback); if (!glfwInit()) return -1; PrintMonitorInfo(); IdentifyMonitors(); /// Init Control window containing AntTweakBar { const int w = 640; const int h = 480; g_pWindow = glfwCreateWindow(w, h, "GLSkeleton - GLFW 3", NULL, NULL); if (!g_pWindow) { glfwTerminate(); return -1; } glfwMakeContextCurrent(g_pWindow); glfwSetWindowSizeCallback (g_pWindow, resize); glfwSetMouseButtonCallback(g_pWindow, mouseDown); glfwSetCursorPosCallback (g_pWindow, mouseMove); glfwSetScrollCallback (g_pWindow, mouseWheel); glfwSetKeyCallback (g_pWindow, keyboard); glfwSetCharCallback (g_pWindow, charkey); ///@note Bad size errors will be thrown if this is not called at init TwWindowSize(w, h); } /// Init secondary window { g_pWindow2 = glfwCreateWindow( 1280, 800, "Oculus window", ///@note Fullscreen windows cannot be positioned. The fullscreen window over the Oculus /// monitor would be the preferred solution, but on Windows that fullscreen window will disappear /// on the first mouse input occuring outside of it, defeating the purpose of the first window. NULL, //g_pOculusMonitor, g_pWindow); if (!g_pWindow2) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(g_pWindow2); /// Position Oculus secondary monitor pseudo-fullscreen window if (g_pPrimaryMonitor != NULL) { const GLFWvidmode* pMode = glfwGetVideoMode(g_pPrimaryMonitor); if (pMode != NULL) { glfwSetWindowPos(g_pWindow2, pMode->width, 0); } } glfwShowWindow(g_pWindow2); } /// If we are not sharing contexts between windows, make the appropriate one current here. //glfwMakeContextCurrent(g_pWindow); return 1; }
Window::Window(CString name, uint32 width, uint32 height) { // Initialize GLFW if this is the first window created if (!GLFWInitialized) { if (!glfwInit()) { Console::Error("GLFW could not be initialized."); Application::Terminate(EXIT_FAILURE); } else { // Indicate that GLFW has been initialized, and add deinitialize function to run at program exit GLFWInitialized = true; std::atexit([] { glfwTerminate(); }); } } // Get the primary monitor auto monitor = glfwGetPrimaryMonitor(); if (!monitor) { Console::WriteLine("GLFW failed to get primary monitor."); Application::Terminate(EXIT_FAILURE); } // Get the primary monitor's video mode auto videoMode = glfwGetVideoMode(monitor); if (!videoMode) { Console::WriteLine("GLFW failed to get primary monitor video mode."); Application::Terminate(EXIT_FAILURE); } // Set the new window to be invisible glfwWindowHint(GLFW_VISIBLE, false); // Set the OpenGL context to version 4.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // Create the window this->_window = glfwCreateWindow(width, height, name, nullptr, nullptr); if (!_window) { Console::WriteLine("GLFW failed to create window."); Application::Terminate(EXIT_FAILURE); } // Register this window with the window table WindowTable[this->_window] = this; // Set the window gain/lose focus function glfwSetWindowFocusCallback(this->_window, [](GLFWwindow* window, int hasFocus) { // Reset the cursor position if the window has gained focus if (hasFocus) { WindowTable[window]->center_cursor(); } }); // Center the window in the screen int32 centerX = (videoMode->width - this->get_width()) / 2; int32 centerY = (videoMode->height - this->get_height()) / 2; glfwSetWindowPos(this->_window, centerX, centerY); // Make the window visible glfwShowWindow(this->_window); // Make the cursor invisible and move it to the center of the window glfwSetInputMode(this->_window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); glfwSetCursorPos(this->_window, this->get_width() / 2, this->get_height() / 2); // Make an OpenGL context in window glfwMakeContextCurrent(this->_window); }
GameEngine::GameEngine(const std::string& application_name, WindowMode windowMode) { glfwSetErrorCallback(ErrorCallback); if (!glfwInit()) { std::terminate(); } // Window creation GLFWmonitor *monitor = glfwGetPrimaryMonitor(); const GLFWvidmode *vidmode = glfwGetVideoMode(monitor); #ifdef USE_DEBUG_CONTEXT glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE); #else glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); #endif glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true); glfwWindowHint(GLFW_DEPTH_BITS, 24); glfwWindowHint(GLFW_STENCIL_BITS, 8); if (windowMode == WindowMode::kFullScreen) { window_ = glfwCreateWindow(vidmode->width, vidmode->height, application_name.c_str(), monitor, nullptr); } else { window_ = glfwCreateWindow(vidmode->width, vidmode->height, application_name.c_str(), nullptr, nullptr); } if (!window_) { std::cerr << "FATAL: Couldn't create a glfw window. Aborting now." << std::endl; glfwTerminate(); std::terminate(); } // Check the created OpenGL context's version int ogl_major_version = glfwGetWindowAttrib(window_, GLFW_CONTEXT_VERSION_MAJOR); int ogl_minor_version = glfwGetWindowAttrib(window_, GLFW_CONTEXT_VERSION_MINOR); std::cout << "OpenGL version: " << ogl_major_version << '.' << ogl_minor_version << std::endl; int width, height; glfwGetFramebufferSize(window_, &width, &height); std::cout << "Resolution: " << width << " x " << height << std::endl; if (ogl_major_version < 4 || (ogl_major_version == 4 && ogl_minor_version < 5)) { std::cerr << "At least OpenGL version 4.5 is required to run this program\n"; std::terminate(); } glfwMakeContextCurrent(window_); // No V-sync needed. glfwSwapInterval(0); bool success = gladLoadGL(); if (!success) { std::cerr << "gladLoadGL failed" << std::endl; std::terminate(); } #ifdef USE_DEBUG_CONTEXT glDebugMessageCallback(&DebugCallback, nullptr); #endif success = Label::InitializeTextRendering(); if (!success) { std::cerr << "Label::InitializeTextRendering failed" << std::endl; std::terminate(); } MeshRenderer::InitializeMeshDataStorage(); // Only initialize after the OpenGL context has been created shader_manager_ = make_unique<ShaderManager>(); // OpenGL initialization gl::Enable(gl::kDepthTest); glClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE); // GLFW callbacks glfwSetWindowUserPointer(window_, this); glfwSetKeyCallback(window_, KeyCallback); glfwSetCharCallback(window_, CharCallback); glfwSetFramebufferSizeCallback(window_, ScreenResizeCallback); glfwSetScrollCallback(window_, MouseScrolledCallback); glfwSetMouseButtonCallback(window_, MouseButtonPressed); glfwSetCursorPosCallback(window_, MouseMoved); }
int main() { int fontNormal = FONS_INVALID; int fontItalic = FONS_INVALID; int fontBold = FONS_INVALID; int fontJapanese = FONS_INVALID; GLFWwindow* window; const GLFWvidmode* mode; if (!glfwInit()) return -1; mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); window = glfwCreateWindow(mode->width - 40, mode->height - 80, "Font Stash", NULL, NULL); if (!window) { glfwTerminate(); return -1; } glfwSetKeyCallback(window, key); glfwMakeContextCurrent(window); fs = glfonsCreate(256, 256, FONS_ZERO_TOPLEFT); if (fs == NULL) { printf("Could not create stash.\n"); return -1; } fonsSetErrorCallback(fs, stashError, fs); fontNormal = fonsAddFont(fs, "sans", "../example/DroidSerif-Regular.ttf"); if (fontNormal == FONS_INVALID) { printf("Could not add font normal.\n"); return -1; } fontItalic = fonsAddFont(fs, "sans-italic", "../example/DroidSerif-Italic.ttf"); if (fontItalic == FONS_INVALID) { printf("Could not add font italic.\n"); return -1; } fontBold = fonsAddFont(fs, "sans-bold", "../example/DroidSerif-Bold.ttf"); if (fontBold == FONS_INVALID) { printf("Could not add font bold.\n"); return -1; } fontJapanese = fonsAddFont(fs, "sans-jp", "../example/DroidSansJapanese.ttf"); if (fontJapanese == FONS_INVALID) { printf("Could not add font japanese.\n"); return -1; } while (!glfwWindowShouldClose(window)) { float sx, sy, dx, dy, lh = 0; int width, height; int atlasw, atlash; unsigned int white,black,brown,blue; char msg[64]; glfwGetFramebufferSize(window, &width, &height); // Update and render glViewport(0, 0, width, height); glClearColor(0.3f, 0.3f, 0.32f, 1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,width,height,0,-1,1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glDisable(GL_DEPTH_TEST); glColor4ub(255,255,255,255); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_CULL_FACE); white = glfonsRGBA(255,255,255,255); brown = glfonsRGBA(192,128,0,128); blue = glfonsRGBA(0,192,255,255); black = glfonsRGBA(0,0,0,255); sx = 50; sy = 50; dx = sx; dy = sy; dash(dx,dy); fonsClearState(fs); fonsSetSize(fs, size); fonsSetFont(fs, fontNormal); fonsVertMetrics(fs, NULL, NULL, &lh); dx = sx; dy += lh; dash(dx,dy); fonsSetSize(fs, size); fonsSetFont(fs, fontNormal); fonsSetColor(fs, white); dx = fonsDrawText(fs, dx,dy,"The quick ",NULL); fonsSetSize(fs, size/2); fonsSetFont(fs, fontItalic); fonsSetColor(fs, brown); dx = fonsDrawText(fs, dx,dy,"brown ",NULL); fonsSetSize(fs, size/3); fonsSetFont(fs, fontNormal); fonsSetColor(fs, white); dx = fonsDrawText(fs, dx,dy,"fox ",NULL); fonsSetSize(fs, 14); fonsSetFont(fs, fontNormal); fonsSetColor(fs, white); fonsDrawText(fs, 20, height-20,"Press UP / DOWN keys to change font size and to trigger atlas full callback, R to reset atlas, E to expand atlas.",NULL); fonsGetAtlasSize(fs, &atlasw, &atlash); snprintf(msg, sizeof(msg), "Atlas: %d × %d", atlasw, atlash); fonsDrawText(fs, 20, height-50, msg, NULL); fonsDrawDebug(fs, width - atlasw - 20, 20.0); glEnable(GL_DEPTH_TEST); glfwSwapBuffers(window); glfwPollEvents(); } glfonsDelete(fs); glfwTerminate(); return 0; }
int main(int argc, char **argv) { /* Options */ bool fullscreen = false; const char *title = "OpenGL 3.3 Demo"; int opt; while ((opt = getopt(argc, argv, "f")) != -1) { switch (opt) { case 'f': fullscreen = true; break; default: exit(EXIT_FAILURE); } } /* Create window and OpenGL context */ struct graphics_context context; if (!glfwInit()) { fprintf(stderr, "GLFW3: failed to initialize\n"); exit(EXIT_FAILURE); } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); if (fullscreen) { GLFWmonitor *monitor = glfwGetPrimaryMonitor(); const GLFWvidmode *m = glfwGetVideoMode(monitor); context.window = glfwCreateWindow(m->width, m->height, title, monitor, NULL); } else { context.window = glfwCreateWindow(640, 640, title, NULL, NULL); } glfwMakeContextCurrent(context.window); glfwSwapInterval(1); /* Initialize gl3w */ if (gl3wInit()) { fprintf(stderr, "gl3w: failed to initialize\n"); exit(EXIT_FAILURE); } /* Shader sources */ const GLchar *vert_shader = "#version 330\n" "layout(location = 0) in vec2 point;\n" "uniform float angle;\n" "void main() {\n" " mat2 rotate = mat2(cos(angle), -sin(angle),\n" " sin(angle), cos(angle));\n" " gl_Position = vec4(0.75 * rotate * point, 0.0, 1.0);\n" "}\n"; const GLchar *frag_shader = "#version 330\n" "out vec4 color;\n" "void main() {\n" " color = vec4(1, 0.15, 0.15, 0);\n" "}\n"; /* Compile and link OpenGL program */ GLuint vert = compile_shader(GL_VERTEX_SHADER, vert_shader); GLuint frag = compile_shader(GL_FRAGMENT_SHADER, frag_shader); context.program = link_program(vert, frag); context.uniform_angle = glGetUniformLocation(context.program, "angle"); glDeleteShader(frag); glDeleteShader(vert); /* Prepare vertex buffer object (VBO) */ glGenBuffers(1, &context.vbo_point); glBindBuffer(GL_ARRAY_BUFFER, context.vbo_point); glBufferData(GL_ARRAY_BUFFER, sizeof(SQUARE), SQUARE, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); /* Prepare vertrex array object (VAO) */ glGenVertexArrays(1, &context.vao_point); glBindVertexArray(context.vao_point); glBindBuffer(GL_ARRAY_BUFFER, context.vbo_point); glVertexAttribPointer(ATTRIB_POINT, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(ATTRIB_POINT); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); /* Start main loop */ glfwSetKeyCallback(context.window, key_callback); context.lastframe = glfwGetTime(); context.framecount = 0; while (!glfwWindowShouldClose(context.window)) { render(&context); glfwPollEvents(); } fprintf(stderr, "Exiting ...\n"); /* Cleanup and exit */ glDeleteVertexArrays(1, &context.vao_point); glDeleteBuffers(1, &context.vbo_point); glDeleteProgram(context.program); glfwTerminate(); return 0; }
int main( void ) { //init bullet initBullet(); // Initialise GLFW if( !glfwInit() ) { fprintf( stderr, "Failed to initialize GLFW\n" ); return -1; } glfwWindowHint(GLFW_SAMPLES, 4); // glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //screen resolution GLFW const GLFWvidmode * mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); int w = mode->width; int h = mode->height; if(MessageBox(NULL, L"Would you like to run in fullscreen?", L"Fullscreen", MB_ICONQUESTION | MB_YESNO) == IDYES) { window = glfwCreateWindow( w, h, "Ray Tracing - Alfonso Oricchio", glfwGetPrimaryMonitor(), NULL); printf("fullscreen\n"); } else { window = glfwCreateWindow( WINDOW_WIDTH, WINDOW_HEIGHT, "Ray Tracing - Alfonso Oricchio", NULL, NULL); printf("window\n"); } // Open a window and create its OpenGL context 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" ); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // Initialize GLEW glewExperimental = true; // Needed for core profile if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); return -1; } // Ensure we can capture the escape key being pressed below glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); glfwSetCursorPos(window, WINDOW_WIDTH/2, WINDOW_HEIGHT/2); // Dark blue background glClearColor(0.0f, 0.0f, 0.4f, 0.0f); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); // Cull triangles which normal is not towards the camera //glEnable(GL_CULL_FACE); GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); // Create and compile our GLSL program from the shaders GLuint depthProgramID = LoadShaders( "DepthRTT.vertexshader", "DepthRTT.fragmentshader" ); // Get a handle for our "MVP" uniform GLuint depthMatrixID = glGetUniformLocation(depthProgramID, "depthMVP"); // The framebuffer, which regroups 0, 1, or more textures, and 0 or 1 depth buffer. GLuint FramebufferName = 0; glGenFramebuffers(1, &FramebufferName); glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); // Depth texture. Slower than a depth buffer, but you can sample it later in your shader GLuint depthTexture; glGenTextures(1, &depthTexture); glBindTexture(GL_TEXTURE_2D, depthTexture); glTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT16, 1024, 1024, 0,GL_DEPTH_COMPONENT, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture, 0); // No color output in the bound framebuffer, only depth. glDrawBuffer(GL_NONE); // Always check that our framebuffer is ok if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) return false; /***********************************************************/ // The quad's FBO. Used only for visualizing the shadowmap. static const GLfloat g_quad_vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, }; GLuint quad_vertexbuffer; glGenBuffers(1, &quad_vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW); // Create and compile our GLSL program from the shaders GLuint quad_programID = LoadShaders( "Passthrough.vertexshader", "SimpleTexture.fragmentshader" ); GLuint texID = glGetUniformLocation(quad_programID, "texture"); /**********************************************************/ // Create and compile our GLSL program from the shaders GLuint programID = LoadShaders( "TransformVertexShader.vertexshader", "ColorFragmentShader.fragmentshader" ); // Get a handle for our "MVP" uniform GLuint MatrixID = glGetUniformLocation(programID, "MVP"); GLuint ViewMatrixID = glGetUniformLocation(programID, "V"); GLuint ModelMatrixID = glGetUniformLocation(programID, "M"); GLuint DepthBiasID = glGetUniformLocation(programID, "DepthBiasMVP"); GLuint ShadowMapID = glGetUniformLocation(programID, "shadowMap"); // Get a handle for our "LightPosition" uniform GLuint lightInvDirID = glGetUniformLocation(programID, "LightInvDirection_worldspace"); //CUBO1 addBox(2,2,2,0,0,0,1.0); //CUBO2 addBox2(2,2,2,0,6,0,1.0); //FLOOR initFloor(); //WALL initWall(); //BALL addScene(); do{ world->stepSimulation(1/60.f); if (glfwGetKey( window, GLFW_KEY_SPACE ) == GLFW_PRESS){ btRigidBody* ball = addBall(1.0,CamGetPosition().x,CamGetPosition().y,CamGetPosition().z,2.0); ball->setLinearVelocity(btVector3((CamGetDirection().x*50),(CamGetDirection().y*50),(CamGetDirection().z*50))); } // Render to our framebuffer glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); glViewport(0,0,1024,1024); // Render on the whole framebuffer, complete from the lower left corner to the upper right // Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ////////////////////////////// // Use our shader //SHADOW RENDER glUseProgram(depthProgramID); glm::vec3 lightInvDir = glm::vec3(0.5f,2,2); // Compute the MVP matrix from the light's point of view glm::mat4 depthProjectionMatrix = glm::ortho<float>(-10,10,-10,10,-10,20); glm::mat4 depthViewMatrix = glm::lookAt(lightInvDir, glm::vec3(0,0,0), glm::vec3(0,1,0)); // or, for spot light : //glm::vec3 lightPos(5, 20, 20); //glm::mat4 depthProjectionMatrix = glm::perspective<float>(45.0f, 1.0f, 2.0f, 50.0f); //glm::mat4 depthViewMatrix = glm::lookAt(lightPos, lightPos-lightInvDir, glm::vec3(0,1,0)); glm::mat4 depthModelMatrix = glm::mat4(1.0); glm::mat4 depthMVP = depthProjectionMatrix * depthViewMatrix * depthModelMatrix; // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(depthMatrixID, 1, GL_FALSE, &depthMVP[0][0]); // CUBE1 ------------------------------------------------------------------------- renderBox(bodies[0],true); //just a cube not really needed //CUBE2 -------------------------------------------------------------------------- renderBox2(bodies[1],true); //just a cube not really needed //FLOOR -------------------------------------------------------------------------- renderPlane(bodies[2],true); //floor //WALL --------------------------------------------------------------------------- renderWall(bodies[3],true); //back wall //CASTLE ------------------------------------------------------------------------- renderScene(true); //castle, main scene //BALL --------------------------------------------------------------------------- int iv; for(iv = 4; iv < bodies.size();iv++) { renderBall(bodies[iv],(iv - 4),true); //"cannon balls" shooted from the camera } ////////////////////////////// //STANDARD RENDER // Compute the MVP matrix from keyboard and mouse input // Clear the screen // Render to the screen glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0,0,1024,768); // Render on the whole framebuffer, complete from the lower left corner to the upper right glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Use our shader glUseProgram(programID); computeMatricesFromInputs(); glm::mat4 ProjectionMatrix = getProjectionMatrix(); glm::mat4 ViewMatrix = getViewMatrix(); glm::mat4 ModelMatrix = glm::mat4(1.0); glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix; glm::mat4 biasMatrix( 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0 ); glm::mat4 depthBiasMVP = biasMatrix*depthMVP; // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix[0][0]); glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]); glUniformMatrix4fv(DepthBiasID, 1, GL_FALSE, &depthBiasMVP[0][0]); glUniform3f(lightInvDirID, lightInvDir.x, lightInvDir.y, lightInvDir.z); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, depthTexture); glUniform1i(ShadowMapID, 0); // CUBE1 ------------------------------------------------------------------------- renderBox(bodies[0],false); //just a cube not really needed //CUBE2 -------------------------------------------------------------------------- renderBox2(bodies[1],false); //just a cube not really needed //FLOOR -------------------------------------------------------------------------- renderPlane(bodies[2],false); //floor //WALL --------------------------------------------------------------------------- renderWall(bodies[3],false); //back wall //CASTLE ------------------------------------------------------------------------- renderScene(false); //castle, main scene //BALL --------------------------------------------------------------------------- // int iv; for(iv = 4; iv < bodies.size();iv++) { renderBall(bodies[iv],(iv - 4),false); //"cannon balls" shooted from the camera } /*--------------------------------------------------*/ // Optionally render the shadowmap (for debug only) // Render only on a corner of the window (or we we won't see the real rendering...) glViewport(0,0,512,512); // Use our shader glUseProgram(quad_programID); // Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, depthTexture); // Set our "renderedTexture" sampler to user Texture Unit 0 glUniform1i(texID, 0); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer); glVertexAttribPointer( 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // Draw the triangle ! // You have to disable GL_COMPARE_R_TO_TEXTURE above in order to see anything ! //glDrawArrays(GL_TRIANGLES, 0, 6); // 2*3 indices starting at 0 -> 2 triangles glDisableVertexAttribArray(0); /*--------------------------------------------------*/ // Swap buffers glfwSwapBuffers(window); glfwPollEvents(); } // Check if the ESC key was pressed or the window was closed while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS && glfwWindowShouldClose(window) == 0 ); deleteALL(); glDeleteProgram(programID); glDeleteVertexArrays(1, &VertexArrayID); // Close OpenGL window and terminate GLFW glfwTerminate(); return 0; }
//Method initializes OpenGL for rendering to a window/viewport bool engine_3d::Init() { /// We need our GLFW function pointers to be assigned, if this process fails we cannot continue if ( !glfwInit() ) { return false; } /// Here we query how much sampling is possible and set that to be used if possible GLint samples = 8; glGetIntegerv( GL_SAMPLES, &samples ); if ( samples ) { glEnable( GL_MULTISAMPLE ); } glfwWindowHint( GLFW_SAMPLES, samples ); GLFWmonitor** monitors; int count; monitors = glfwGetMonitors( &count ); const GLFWvidmode* mode = glfwGetVideoMode( glfwGetPrimaryMonitor() ); ///Create a window of a particular type switch ( winMode ) { case engine_WindowModel::FULLSCREEN: window = glfwCreateWindow( mode->width, mode->height, "Fullscreen", glfwGetPrimaryMonitor(), NULL ); screenHeight = mode->height; screenWidth = mode->width; break; case engine_WindowModel::DECORATEDWINDOW: window = glfwCreateWindow( screenWidth, screenHeight, "Decorated Window", NULL, NULL ); break; case engine_WindowModel::BORDERLESSFULLSCREEN: glfwWindowHint( GLFW_DECORATED, false ); glfwWindowHint( GLFW_RED_BITS, mode->redBits ); glfwWindowHint( GLFW_GREEN_BITS, mode->greenBits ); glfwWindowHint( GLFW_BLUE_BITS, mode->blueBits ); glfwWindowHint( GLFW_REFRESH_RATE, mode->refreshRate ); window = glfwCreateWindow( mode->width, mode->height, "Borderless Fullscreen", NULL, NULL ); screenHeight = mode->height; screenWidth = mode->width; break; } /// If creating the window failed we need to terminate if ( !window ) { glfwTerminate(); return false; } /// Associates this window with OpenGL's rendering (I believe) glfwMakeContextCurrent( window ); /// Sets our input processing function, all input will be passed to this function //glfwSetScrollCallback( window, scroll_callback ); glfwSetKeyCallback( window, key_callback ); glfwSetCursorPosCallback( window, cursor_position_callback ); glfwSetMouseButtonCallback( window, mouse_button_callback ); /// start GLEW extension handler glewExperimental = GL_TRUE; ///Initialize OpenGL functions glewInit(); const GLubyte* renderer = glGetString( GL_RENDERER ); /// get renderer string const GLubyte* version = glGetString( GL_VERSION ); /// version as a string ///oLog( Level::Info ) << "Renderer: " << renderer; ///oLog( Level::Info ) << "OpenGL version supported: " << version; projectionMatrix = glm::mat4( 1.f ); viewMatrix = glm::mat4( 1.f ); glEnable( GL_CULL_FACE ); glCullFace( GL_BACK ); glFrontFace( GL_CCW ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); ///clear colour: r,g,b,a glfwSwapInterval( 1 ); ///cap FPS currentDC = wglGetCurrentDC(); currentContext = wglGetCurrentContext(); return true; }
int main(int argc, char* argv[]) { if (!setupGLFW()) return 1; glfwWindowHint(GLFW_SAMPLES, 4); setupCoreGL(); #ifndef __APPLE__ const char* exePath = dirname(argv[0]); const char* resPath = "/Resources/"; const int newPathLen = strlen(exePath) + strlen(resPath) + 1; char newPath[newPathLen]; strcpy(newPath, exePath); strcat(newPath, resPath); int cwdError; if ((cwdError = chdir(newPath)) != 0) { perror(newPath); return 1; } #endif set_log_file(fopen("../Logs/uf.log", "a")); setDebug(DEBUG); setBind(DEBUG); #ifdef FULLSCREEN GLFWmonitor* monitor = glfwGetPrimaryMonitor(); const GLFWvidmode* vidmode = glfwGetVideoMode(monitor); int width = vidmode->width; int height = vidmode->height; const char* title = "Ultra Fighters"; GLFWwindow* window = glfwCreateWindow(width, height, title, monitor, NULL); #else int width = 640; int height = 480; const char* title = "Ultra Fighters"; GLFWwindow* window = glfwCreateWindow(width, height, title, NULL, NULL); #endif if (!window) { log_msg(LOG_ERROR, "GLFW3 window creation failed.\n"); return 1; } glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); char cwd[PATH_MAX]; getcwd(cwd, sizeof(cwd)); log_msg(LOG_INFO, "#####################################\n"); log_msg(LOG_INFO, "Started Ultra Fighters!\n"); log_msg(LOG_INFO, "Current Working Directory: %s\n", cwd); log_msg(LOG_INFO, "Started loop!\n"); GameScene scene(window); std::ifstream levelFile("levelname.txt"); std::string levelName; std::getline(levelFile, levelName); WavefrontObject room(levelName.c_str()); scene.addChild(&room); HUD hud; scene.addChild(&hud); SphereNode snode(glm::vec3(-2, 2, 4), 0.75); // @temp scene.addChild(&snode); // @temp Loop loop = Loop(&scene); loop.start(); while (!glfwGetKey(window, GLFW_KEY_ESCAPE) && !glfwWindowShouldClose(window)) { glfwPollEvents(); } log_msg(LOG_INFO, "Stopping program...\n"); loop.stop(); glfwTerminate(); return 0; }
int main(int argc, char** argv) { Slot* slots; GLFWmonitor* monitor = NULL; int ch, i, width, height, count = 1; setlocale(LC_ALL, ""); glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); printf("Library initialized\n"); glfwSetMonitorCallback(monitor_callback); glfwSetJoystickCallback(joystick_callback); while ((ch = getopt(argc, argv, "hfn:")) != -1) { switch (ch) { case 'h': usage(); exit(EXIT_SUCCESS); case 'f': monitor = glfwGetPrimaryMonitor(); break; case 'n': count = (int) strtol(optarg, NULL, 10); break; default: usage(); exit(EXIT_FAILURE); } } if (monitor) { const GLFWvidmode* mode = glfwGetVideoMode(monitor); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); width = mode->width; height = mode->height; } else { width = 640; height = 480; } if (!count) { fprintf(stderr, "Invalid user\n"); exit(EXIT_FAILURE); } slots = calloc(count, sizeof(Slot)); for (i = 0; i < count; i++) { char title[128]; slots[i].closeable = GLFW_TRUE; slots[i].number = i + 1; sprintf(title, "Event Linter (Window %i)", slots[i].number); if (monitor) { printf("Creating full screen window %i (%ix%i on %s)\n", slots[i].number, width, height, glfwGetMonitorName(monitor)); } else { printf("Creating windowed mode window %i (%ix%i)\n", slots[i].number, width, height); } slots[i].window = glfwCreateWindow(width, height, title, monitor, NULL); if (!slots[i].window) { free(slots); glfwTerminate(); exit(EXIT_FAILURE); } glfwSetWindowUserPointer(slots[i].window, slots + i); glfwSetWindowPosCallback(slots[i].window, window_pos_callback); glfwSetWindowSizeCallback(slots[i].window, window_size_callback); glfwSetFramebufferSizeCallback(slots[i].window, framebuffer_size_callback); glfwSetWindowCloseCallback(slots[i].window, window_close_callback); glfwSetWindowRefreshCallback(slots[i].window, window_refresh_callback); glfwSetWindowFocusCallback(slots[i].window, window_focus_callback); glfwSetWindowIconifyCallback(slots[i].window, window_iconify_callback); glfwSetMouseButtonCallback(slots[i].window, mouse_button_callback); glfwSetCursorPosCallback(slots[i].window, cursor_position_callback); glfwSetCursorEnterCallback(slots[i].window, cursor_enter_callback); glfwSetScrollCallback(slots[i].window, scroll_callback); glfwSetKeyCallback(slots[i].window, key_callback); glfwSetCharCallback(slots[i].window, char_callback); glfwSetCharModsCallback(slots[i].window, char_mods_callback); glfwSetDropCallback(slots[i].window, drop_callback); glfwMakeContextCurrent(slots[i].window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); glfwSwapInterval(1); } printf("Main loop starting\n"); for (;;) { for (i = 0; i < count; i++) { if (glfwWindowShouldClose(slots[i].window)) break; } if (i < count) break; glfwWaitEvents(); // Workaround for an issue with msvcrt and mintty fflush(stdout); } free(slots); glfwTerminate(); exit(EXIT_SUCCESS); }
GLFWView::GLFWView(bool fullscreen_, bool benchmark_) : fullscreen(fullscreen_), benchmark(benchmark_) { glfwSetErrorCallback(glfwError); std::srand(std::time(0)); if (!glfwInit()) { mbgl::Log::Error(mbgl::Event::OpenGL, "failed to initialize glfw"); exit(1); } GLFWmonitor *monitor = nullptr; if (fullscreen) { monitor = glfwGetPrimaryMonitor(); auto videoMode = glfwGetVideoMode(monitor); width = videoMode->width; height = videoMode->height; } #ifdef DEBUG glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif #ifdef GL_ES_VERSION_2_0 glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); #endif glfwWindowHint(GLFW_RED_BITS, 8); glfwWindowHint(GLFW_GREEN_BITS, 8); glfwWindowHint(GLFW_BLUE_BITS, 8); glfwWindowHint(GLFW_ALPHA_BITS, 8); glfwWindowHint(GLFW_STENCIL_BITS, 8); glfwWindowHint(GLFW_DEPTH_BITS, 16); window = glfwCreateWindow(width, height, "Mapbox GL", monitor, NULL); if (!window) { glfwTerminate(); mbgl::Log::Error(mbgl::Event::OpenGL, "failed to initialize window"); exit(1); } glfwSetWindowUserPointer(window, this); glfwMakeContextCurrent(window); if (benchmark) { // Disables vsync on platforms that support it. glfwSwapInterval(0); } else { glfwSwapInterval(1); } glfwSetCursorPosCallback(window, onMouseMove); glfwSetMouseButtonCallback(window, onMouseClick); glfwSetWindowSizeCallback(window, onWindowResize); glfwSetFramebufferSizeCallback(window, onFramebufferResize); glfwSetScrollCallback(window, onScroll); glfwSetKeyCallback(window, onKey); mbgl::gl::InitializeExtensions(glfwGetProcAddress); glfwGetWindowSize(window, &width, &height); glfwGetFramebufferSize(window, &fbWidth, &fbHeight); pixelRatio = static_cast<float>(fbWidth) / width; glfwMakeContextCurrent(nullptr); printf("\n"); printf("================================================================================\n"); printf("\n"); printf("- Press `S` to cycle through bundled styles\n"); printf("- Press `X` to reset the transform\n"); printf("- Press `N` to reset north\n"); printf("- Press `R` to toggle any available `night` style class\n"); printf("- Press `Z` to cycle through north orientations\n"); printf("- Prezz `X` to cycle through the viewport modes\n"); printf("- Press `A` to cycle through Mapbox offices in the world + dateline monument\n"); printf("\n"); printf("- Press `1` through `6` to add increasing numbers of point annotations for testing\n"); printf("- Press `7` through `0` to add increasing numbers of shape annotations for testing\n"); printf("\n"); printf("- Press `Q` to remove annotations\n"); printf("- Press `P` to add a random custom runtime imagery annotation\n"); printf("- Press `W` to pop the last-added annotation off\n"); printf("\n"); printf("- `Control` + mouse drag to rotate\n"); printf("- `Shift` + mouse drag to tilt\n"); printf("\n"); printf("- Press `Tab` to cycle through the map debug options\n"); printf("- Press `Esc` to quit\n"); printf("\n"); printf("================================================================================\n"); printf("\n"); }
int main(int argc, char** argv) { int ch, width, height; thrd_t physics_thread = 0; GLFWwindow* window; GLFWmonitor* monitor = NULL; if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); exit(EXIT_FAILURE); } while ((ch = getopt(argc, argv, "fh")) != -1) { switch (ch) { case 'f': monitor = glfwGetPrimaryMonitor(); break; case 'h': usage(); exit(EXIT_SUCCESS); } } if (monitor) { const GLFWvidmode* mode = glfwGetVideoMode(monitor); glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); width = mode->width; height = mode->height; } else { width = 640; height = 480; } window = glfwCreateWindow(width, height, "Particle Engine", monitor, NULL); if (!window) { fprintf(stderr, "Failed to create GLFW window\n"); glfwTerminate(); exit(EXIT_FAILURE); } if (monitor) glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwMakeContextCurrent(window); glfwSwapInterval(1); glfwSetFramebufferSizeCallback(window, resize_callback); glfwSetKeyCallback(window, key_callback); // Set initial aspect ratio glfwGetFramebufferSize(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); }
void Application::Init() { //Set the error callback glfwSetErrorCallback(error_callback); //Initialize GLFW if (!glfwInit()) { exit(EXIT_FAILURE); } //Set the GLFW window creation hints - these are optional 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_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL const GLFWvidmode *win_data = glfwGetVideoMode(glfwGetPrimaryMonitor()); glfwWindowHint(GLFW_RED_BITS, win_data->redBits); glfwWindowHint(GLFW_GREEN_BITS, win_data->greenBits); glfwWindowHint(GLFW_BLUE_BITS, win_data->blueBits); glfwWindowHint(GLFW_REFRESH_RATE, win_data->refreshRate); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); FPS = win_data->refreshRate; // FPS of this game frameTime = 1000 / FPS; //Create a window and create its OpenGL context if (FULL_SCREEN) { i_WINDOW_WIDTH = win_data->width; i_WINDOW_HEIGHT = win_data->height; glfwWindowHint(GLFW_DECORATED, GL_FALSE); m_window = glfwCreateWindow(win_data->width, win_data->height, WIN_NAME, NULL, NULL); } else { glfwWindowHint(GLFW_DECORATED, GL_TRUE); m_window = glfwCreateWindow(i_WINDOW_WIDTH, i_WINDOW_HEIGHT, WIN_NAME, NULL, NULL); } glfwSetWindowSizeCallback(m_window, resize_callback); //If the window couldn't be created if (!m_window) { fprintf(stderr, "Failed to open GLFW window.\n"); glfwTerminate(); exit(EXIT_FAILURE); } //This function makes the context of the specified window current on the calling thread. glfwMakeContextCurrent(m_window); //Sets the key callback //glfwSetKeyCallback(m_window, key_callback); glewExperimental = true; // Needed for core profile //Initialize GLEW GLenum err = glewInit(); //If GLEW hasn't initialized if (err != GLEW_OK) { fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); //return -1; } togglefullscreen = false; m_dElapsedTime = 0.0; m_dAccumulatedTime_ThreadOne = 0.0; m_dAccumulatedTime_ThreadTwo = 0.0; S_MANAGER = SceneManager::Instance(); S_MANAGER->Init(SceneManager::S_MAIN_MENU_SPLASH); }
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; }