int main(int argc, char** argv) { std::cout << "Ami ViewPort3" << std::endl; // Init GLFW glfwInit(); // Create a GLFWwindow object that we can use for GLFW's functions GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); glEnable(GL_DEPTH_TEST); // Depth Testing glDepthFunc(GL_LEQUAL); glDisable(GL_CULL_FACE); glCullFace(GL_BACK); // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions glewExperimental = GL_TRUE; // Initialize GLEW to setup the OpenGL Function pointers glewInit(); glfwGetFramebufferSize(window, &width, &height); //Shader ourShader("C:\\C++\\ViewPort3\\ViewPort3\\Debug\\default.vs", "C:\\C++\\ViewPort3\\ViewPort3\\Debug\\default.frag"); while (!glfwWindowShouldClose(window)) { // Scale to window size GLint windowWidth, windowHeight; glfwGetWindowSize(window, &windowWidth, &windowHeight); // Draw stuff glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); { glViewport(0, windowHeight / 2, windowWidth / 2, windowHeight / 2); // top left glMatrixMode(GL_PROJECTION_MATRIX); glLoadIdentity(); gluPerspective(80, (double)windowWidth / (double)windowHeight, 0.1, 100); glMatrixMode(GL_MODELVIEW_MATRIX); glTranslatef(0, 0, -5); //ourShader.Use(); // as soon as i use shader, image wont rotate drawTriangle(); } { glViewport(windowWidth / 2, 0, windowWidth / 2, windowHeight / 2); // bottom right glMatrixMode(GL_PROJECTION_MATRIX); glLoadIdentity(); gluPerspective(-45, (double)windowWidth / (double)windowHeight, 0.1, 100); glMatrixMode(GL_MODELVIEW_MATRIX); glTranslatef(0, 0, -5); drawCube(); } glfwSwapBuffers(window); glfwPollEvents(); } // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; return 0; }
int Window::GetHeight() const { int* w = 0; int* h = 0; glfwGetWindowSize(window, w, h); return (*h); }
void RenderText::draw(){ //glClearColor(1, 1, 1, 0); glEnable(GL_BLEND); //glEnable(GL_TEXTURE_2D); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //glDisable(GL_DEPTH_TEST); //glDisable(GL_CULL_FACE); //glDisable(GL_TEXTURE_2D); //glDisable(GL_LIGHTING); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); int stageWidth, stageHeight; glfwGetWindowSize(&stageWidth, &stageHeight); glOrtho(0.0f, stageWidth, 0.0f, stageHeight, 0.0f, 1.0f); glMatrixMode(GL_MODELVIEW); int i; if(selectedInputs.size()>0&&selectedInputs[0]!=this&&inputAllowed&&text==""){ dispText = "Click to type here"; }else { dispText=text; } if(selectedInputs.size()>0&&selectedInputs[0]==this&&inputAllowed){ static int curserOn = 0; static float prevSwitchTime=glfwGetTime(); if(glfwGetTime()-prevSwitchTime>0.3){ curserOn = !curserOn; prevSwitchTime=glfwGetTime(); } if(curserOn){ dispText.append("_"); } } const size_t length = dispText.length(); textures = (GLuint*)calloc(length, sizeof(GLuint)); glGenTextures(length, textures); glPushMatrix(); glTranslatef(x, y, 0); glPushMatrix(); for (i = 0; i < length; ++i) { FT_Load_Glyph(face, FT_Get_Char_Index(face, dispText.at(i)), FT_LOAD_DEFAULT); FT_Get_Glyph(face->glyph, &glyph); FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1); bitmap_glyph = (FT_BitmapGlyph)glyph; bitmap = bitmap_glyph->bitmap; int width = RenderText::npo2(bitmap.width); int height = RenderText::npo2(bitmap.rows); float x = (float)bitmap.width / (float)width; float y = (float)bitmap.rows / (float)height; glBindTexture(GL_TEXTURE_2D, textures[i]); 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_RGBA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, 0); glPixelStorei(GL_UNPACK_ALIGNMENT,1); // no alignment glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bitmap.width, bitmap.rows, GL_ALPHA, GL_UNSIGNED_BYTE, bitmap.buffer); glPushMatrix(); glTranslatef(0, bitmap_glyph->top - bitmap.rows, 0); glBindTexture(GL_TEXTURE_2D, textures[i]); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(0, bitmap.rows); glTexCoord2f(0, y); glVertex2f(0, 0); glTexCoord2f(x, y); glVertex2f(bitmap.width, 0); glTexCoord2f(x, 0); glVertex2f(bitmap.width, bitmap.rows); glEnd(); glPopMatrix(); glTranslatef(glyph->advance.x / 65536, 0, 0); FT_Done_Glyph(glyph); } glPopMatrix(); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glDeleteTextures(length, textures); free(textures); }
void Camera::getWindowDimensions() { glfwGetWindowSize(m_window, &m_windowWidth, &m_windowHeight); // get current window size }
void on_draw() override { glfwMakeContextCurrent(window); if (igm) igm->begin_frame(); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); int width, height; glfwGetWindowSize(window, &width, &height); glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(1.0f, 0.1f, 0.0f, 1.0f); const auto proj = camera.get_projection_matrix((float) width / (float) height); const float4x4 view = camera.get_view_matrix(); const float4x4 viewProj = mul(proj, view); if (ImGui::SliderInt("Sun Theta", &sunPos.x, 0, 90)) skydome.set_sun_position(sunPos.x, sunPos.y); if (ImGui::SliderInt("Sun Phi", &sunPos.y, 0, 360)) skydome.set_sun_position(sunPos.x, sunPos.y); auto draw_cubes = [&](float3 eye, float4x4 vp) { simpleShader->bind(); simpleShader->uniform("u_eye", eye); simpleShader->uniform("u_viewProj", vp); simpleShader->uniform("u_emissive", float3(0, 0, 0)); simpleShader->uniform("u_diffuse", float3(0.33f, 0.33f, 0.33f)); for (int i = 0; i < 2; i++) { simpleShader->uniform("u_lights[" + std::to_string(i) + "].position", lights[i].position); simpleShader->uniform("u_lights[" + std::to_string(i) + "].color", lights[i].color); } for (const auto & model : regularModels) { simpleShader->uniform("u_modelMatrix", model.get_model()); simpleShader->uniform("u_modelMatrixIT", inv(transpose(model.get_model()))); model.draw(); } simpleShader->unbind(); }; // Render/Update cube camera cubeCamera->render = [&](float3 eyePosition, float4x4 viewMatrix, float4x4 projMatrix) { skydome.render(mul(projMatrix, viewMatrix), eyePosition, camera.farClip); draw_cubes(eyePosition, mul(projMatrix, viewMatrix)); }; cubeCamera->update(camera.get_eye_point()); // render from a camera positioned @ {0, 0, 0} glViewport(0, 0, width, height); skydome.render(viewProj, camera.get_eye_point(), camera.farClip); grid.render(proj, view); draw_cubes(camera.get_eye_point(), viewProj); // Glass material { glassMaterialShader->bind(); glassMaterialShader->uniform("u_eye", camera.get_eye_point()); glassMaterialShader->uniform("u_viewProj", viewProj); // Can set from either a pre-loaded cubemap, or one capured from the cubeCamera glassMaterialShader->texture("u_cubemapTex", 0, cubeCamera->get_cubemap_handle(), GL_TEXTURE_CUBE_MAP); // cubeTex.get_gl_handle() for (const auto & model : glassModels) { glassMaterialShader->uniform("u_modelMatrix", model.get_model()); glassMaterialShader->uniform("u_modelMatrixIT", inv(transpose(model.get_model()))); model.draw(); } glassMaterialShader->unbind(); glDisable(GL_BLEND); } gl_check_error(__FILE__, __LINE__); if (igm) igm->end_frame(); glfwSwapBuffers(window); frameCount++; }
void renderInit(GLFWwindow* window) { // Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle. // A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices static const GLfloat g_vertex_buffer_data[] = { -1.0f,-1.0f,-1.0f, -1.0f,-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f, -1.0f,-1.0f,-1.0f, -1.0f, 1.0f,-1.0f, 1.0f,-1.0f, 1.0f, -1.0f,-1.0f,-1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f,-1.0f,-1.0f, -1.0f,-1.0f,-1.0f, -1.0f,-1.0f,-1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f,-1.0f, 1.0f,-1.0f, 1.0f, -1.0f,-1.0f, 1.0f, -1.0f,-1.0f,-1.0f, -1.0f, 1.0f, 1.0f, -1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f, -1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f,-1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f,-1.0f, 1.0f }; // One color for each vertex. They were generated randomly. static const GLfloat g_color_buffer_data[] = { 0.583f, 0.771f, 0.014f, 0.609f, 0.115f, 0.436f, 0.327f, 0.483f, 0.844f, 0.822f, 0.569f, 0.201f, 0.435f, 0.602f, 0.223f, 0.310f, 0.747f, 0.185f, 0.597f, 0.770f, 0.761f, 0.559f, 0.436f, 0.730f, 0.359f, 0.583f, 0.152f, 0.483f, 0.596f, 0.789f, 0.559f, 0.861f, 0.639f, 0.195f, 0.548f, 0.859f, 0.014f, 0.184f, 0.576f, 0.771f, 0.328f, 0.970f, 0.406f, 0.615f, 0.116f, 0.676f, 0.977f, 0.133f, 0.971f, 0.572f, 0.833f, 0.140f, 0.616f, 0.489f, 0.997f, 0.513f, 0.064f, 0.945f, 0.719f, 0.592f, 0.543f, 0.021f, 0.978f, 0.279f, 0.317f, 0.505f, 0.167f, 0.620f, 0.077f, 0.347f, 0.857f, 0.137f, 0.055f, 0.953f, 0.042f, 0.714f, 0.505f, 0.345f, 0.783f, 0.290f, 0.734f, 0.722f, 0.645f, 0.174f, 0.302f, 0.455f, 0.848f, 0.225f, 0.587f, 0.040f, 0.517f, 0.713f, 0.338f, 0.053f, 0.959f, 0.120f, 0.393f, 0.621f, 0.362f, 0.673f, 0.211f, 0.457f, 0.820f, 0.883f, 0.371f, 0.982f, 0.099f, 0.879f }; glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); programID = loadShaders("multibuffer.vertexshader", "multibuffer.fragmentshader"); int width, height; glfwGetWindowSize(window, &width, &height); // Create framebuffer glGenFramebuffers(1, &framebuffer); // Create depth renderbuffer glGenRenderbuffers(1, &depthbuffer); glBindRenderbuffer(GL_RENDERBUFFER, depthbuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height); // Create 3 color rednerbuffers glGenRenderbuffers(3, renderbuffers); glBindRenderbuffer(GL_RENDERBUFFER, renderbuffers[0]); glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, width, height); glBindRenderbuffer(GL_RENDERBUFFER, renderbuffers[1]); glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, width, height); glBindRenderbuffer(GL_RENDERBUFFER, renderbuffers[2]); glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, width, height); // Attach all renderbuffers to FBO glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthbuffer); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffers[0]); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_RENDERBUFFER, renderbuffers[1]); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_RENDERBUFFER, renderbuffers[2]); //GLenum fboStatus = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW); glGenBuffers(1, &colorbuffer); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_color_buffer_data), g_color_buffer_data, GL_STATIC_DRAW); //glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); if (checkErrors(0)) exit(10); }
int main(int argc, char *argv[]) { CmdLine cmd; std::string sSfM_Dir; cmd.add( make_option('i', sSfM_Dir, "sfmdir") ); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch(const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--sfmdir SfM_Output path]\n" << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } if (m_doc.load(sSfM_Dir)) { current_cam = 0; std::cout << "Press left or right key to navigate between cameras ;-)" << std::endl << "Move viewpoint with Q,W,E,A,S,D" << std::endl << "Change Normalized focal with Z and X" << std::endl << "Reset viewpoint position with R" << std::endl << "Esc to quit" << std::endl; } else { exit( EXIT_FAILURE); } //-- Create the GL window context GLFWwindow* window; int width, height; if( !glfwInit() ) { fprintf( stderr, "Failed to initialize GLFW\n" ); exit( EXIT_FAILURE ); } glfwWindowHint(GLFW_DEPTH_BITS, 16); window = glfwCreateWindow( 1000, 600, "SfmViewer", NULL, NULL ); if (!window) { fprintf( stderr, "Failed to open GLFW window\n" ); glfwTerminate(); exit( EXIT_FAILURE ); } // Set callback functions glfwSetWindowCloseCallback(window, window_close_callback); glfwSetWindowSizeCallback(window, reshape); glfwSetKeyCallback(window, key); glfwMakeContextCurrent(window); glfwSwapInterval( 1 ); glfwGetWindowSize(window, &width, &height); reshape(window, width, height); load_textures(); // Main loop while( running ) { // Draw SfM Scene draw(); // Swap buffers glfwSwapBuffers(window); glfwPollEvents(); } // Terminate GLFW glfwTerminate(); // Exit program exit( EXIT_SUCCESS ); }
int main() { GLFWwindow* window; struct DemoData data; struct NVGcontext* vg = NULL; struct PerfGraph fps; double prevt = 0; if (!glfwInit()) { printf("Failed to init GLFW."); return -1; } initGraph(&fps, GRAPH_RENDER_FPS, "Frame Time"); glfwSetErrorCallback(errorcb); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); #ifdef DEMO_MSAA glfwWindowHint(GLFW_SAMPLES, 4); #endif window = glfwCreateWindow(1000, 600, "NanoVG", NULL, NULL); // window = glfwCreateWindow(1000, 600, "NanoVG", glfwGetPrimaryMonitor(), NULL); if (!window) { glfwTerminate(); return -1; } glfwSetKeyCallback(window, key); glfwMakeContextCurrent(window); #ifdef NANOVG_GLEW if(glewInit() != GLEW_OK) { printf("Could not init glew.\n"); return -1; } #endif #ifdef DEMO_MSAA vg = nvgCreateGL2(512, 512, 0); #else vg = nvgCreateGL2(512, 512, NVG_ANTIALIAS); #endif if (vg == NULL) { printf("Could not init nanovg.\n"); return -1; } if (loadDemoData(vg, &data) == -1) return -1; glfwSwapInterval(0); glfwSetTime(0); prevt = glfwGetTime(); while (!glfwWindowShouldClose(window)) { double mx, my, t, dt; int winWidth, winHeight; int fbWidth, fbHeight; float pxRatio; t = glfwGetTime(); dt = t - prevt; prevt = t; updateGraph(&fps, dt); glfwGetCursorPos(window, &mx, &my); glfwGetWindowSize(window, &winWidth, &winHeight); glfwGetFramebufferSize(window, &fbWidth, &fbHeight); // Calculate pixel ration for hi-dpi devices. pxRatio = (float)fbWidth / (float)winWidth; // Update and render glViewport(0, 0, fbWidth, fbHeight); if (premult) glClearColor(0,0,0,0); else glClearColor(0.3f, 0.3f, 0.32f, 1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT); nvgBeginFrame(vg, winWidth, winHeight, pxRatio, premult ? NVG_PREMULTIPLIED_ALPHA : NVG_STRAIGHT_ALPHA); renderDemo(vg, mx,my, winWidth,winHeight, t, blowup, &data); renderGraph(vg, 5,5, &fps); nvgEndFrame(vg); if (screenshot) { screenshot = 0; saveScreenShot(fbWidth, fbHeight, premult, "dump.png"); } glfwSwapBuffers(window); glfwPollEvents(); } freeDemoData(vg, &data); nvgDeleteGL2(vg); glfwTerminate(); return 0; }
int main(void) { int width, height, x; GLFWwindow window; // Initialise GLFW if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); exit(EXIT_FAILURE); } // Open a window and create its OpenGL context window = glfwOpenWindow(640, 480, GLFW_WINDOWED, "Spinning Triangle", NULL); if (!window) { fprintf(stderr, "Failed to open GLFW window\n"); exit(EXIT_FAILURE); } // Ensure we can capture the escape key being pressed below glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); // Enable vertical sync (on cards that support it) glfwSwapInterval(1); do { double t = glfwGetTime(); glfwGetMousePos(window, &x, NULL); // Get window size (may be different than the requested size) glfwGetWindowSize(window, &width, &height); // Special case: avoid division by zero below height = height > 0 ? height : 1; glViewport(0, 0, width, height); // Clear color buffer to black glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT); // Select and setup the projection matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(65.f, (GLfloat) width / (GLfloat) height, 1.f, 100.f); // Select and setup the modelview matrix glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); gluLookAt(0.f, 1.f, 0.f, // Eye-position 0.f, 20.f, 0.f, // View-point 0.f, 0.f, 1.f); // Up-vector // Draw a rotating colorful triangle glTranslatef(0.f, 14.f, 0.f); glRotatef(0.3f * (GLfloat) x + (GLfloat) t * 100.f, 0.f, 0.f, 1.f); glBegin(GL_TRIANGLES); glColor3f(1.f, 0.f, 0.f); glVertex3f(-5.f, 0.f, -4.f); glColor3f(0.f, 1.f, 0.f); glVertex3f(5.f, 0.f, -4.f); glColor3f(0.f, 0.f, 1.f); glVertex3f(0.f, 0.f, 6.f); glEnd(); // Swap buffers glfwSwapBuffers(); glfwPollEvents(); } // Check if the ESC key was pressed or the window was closed while (glfwIsWindow(window) && glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS); // Close OpenGL window and terminate GLFW glfwTerminate(); exit(EXIT_SUCCESS); }
int main() { GLFWwindow* window; UIcontext *uictx; uictx = uiCreateContext(4096, 1<<20); uiMakeCurrent(uictx); uiSetHandler(ui_handler); if (!glfwInit()) { printf("Failed to init GLFW."); return -1; } glfwSetErrorCallback(errorcb); #ifndef _WIN32 // don't require this on win32, and works with more cards glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #endif glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, 1); window = glfwCreateWindow(650, 650, "OUI Blendish Demo", NULL, NULL); if (!window) { glfwTerminate(); return -1; } glfwSetKeyCallback(window, key); glfwSetCharCallback(window, charevent); glfwSetCursorPosCallback(window, cursorpos); glfwSetMouseButtonCallback(window, mousebutton); glfwSetScrollCallback(window, scrollevent); glfwMakeContextCurrent(window); #ifdef NANOVG_GLEW glewExperimental = GL_TRUE; if(glewInit() != GLEW_OK) { printf("Could not init glew.\n"); return -1; } // GLEW generates GL error because it calls glGetString(GL_EXTENSIONS), we'll consume it here. glGetError(); #endif //_vg = nvgCreateGL3(NVG_ANTIALIAS | NVG_STENCIL_STROKES); _vg = nvgCreateGL3(NVG_ANTIALIAS); if (_vg == NULL) { printf("Could not init nanovg.\n"); return -1; } init(_vg); printf("sizeof(UIitem)=%lu\n", sizeof(UIitem)); glfwSwapInterval(0); glfwSetTime(0); double c = 0.0; int total = 0; int peak_items = 0; unsigned int peak_alloc = 0; while (!glfwWindowShouldClose(window)) { double mx, my; int winWidth, winHeight; int fbWidth, fbHeight; float pxRatio; glfwGetCursorPos(window, &mx, &my); glfwGetWindowSize(window, &winWidth, &winHeight); glfwGetFramebufferSize(window, &fbWidth, &fbHeight); // Calculate pixel ration for hi-dpi devices. pxRatio = (float)fbWidth / (float)winWidth; // Update and render glViewport(0, 0, fbWidth, fbHeight); glClearColor(0,0,0,1); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT); double t = glfwGetTime(); nvgBeginFrame(_vg, winWidth, winHeight, pxRatio); draw(_vg, winWidth, winHeight); peak_items = (peak_items > uiGetItemCount())?peak_items:uiGetItemCount(); peak_alloc = (peak_alloc > uiGetAllocSize())?peak_alloc:uiGetAllocSize(); nvgEndFrame(_vg); double t2 = glfwGetTime(); c += (t2 - t); total++; if (total > (1*60)) { printf("%fms\n", (c / (double)total)*1000.0); total = 0; c = 0.0; } glfwSwapBuffers(window); glfwPollEvents(); } printf("Peak item count: %i (%lu bytes)\nPeak allocated handles: %u bytes\n", peak_items, peak_items * sizeof(UIitem), peak_alloc); uiDestroyContext(uictx); nvgDeleteGL3(_vg); glfwTerminate(); return 0; }
void kl::GuiManager::Init() { int w, h; int fb_w, fb_h; glfwGetWindowSize( g_Window, &w, &h ); glfwGetFramebufferSize( g_Window, &fb_w, &fb_h ); mousePosScale.x = ( float ) fb_w / w; // Some screens e.g. Retina display have framebuffer size != from window size, and mouse inputs are given in window/screen coordinates. mousePosScale.y = ( float ) fb_h / h; ImGuiIO &io = ImGui::GetIO(); io.DisplaySize = ImVec2( ( float ) fb_w, ( float ) fb_h ); // Display size, in pixels. For clamping windows positions. io.DeltaTime = 1.0f / 60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our timestep is variable) io.PixelCenterOffset = 0.0f; // Align OpenGL texels io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT; io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP; io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN; io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME; io.KeyMap[ImGuiKey_End] = GLFW_KEY_END; io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE; io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE; io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER; io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE; io.KeyMap[ImGuiKey_A] = GLFW_KEY_A; io.KeyMap[ImGuiKey_C] = GLFW_KEY_C; io.KeyMap[ImGuiKey_V] = GLFW_KEY_V; io.KeyMap[ImGuiKey_X] = GLFW_KEY_X; io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y; io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z; io.RenderDrawListsFn = ImImpl_RenderDrawLists; io.SetClipboardTextFn = ImImpl_SetClipboardTextFn; io.GetClipboardTextFn = ImImpl_GetClipboardTextFn; #if 0 #ifdef _MSC_VER io.ImeSetInputScreenPosFn = ImImpl_ImeSetInputScreenPosFn; #endif #endif // Load font texture glGenTextures( 1, &fontTex ); glBindTexture( GL_TEXTURE_2D, fontTex ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); #if 1 // Default font (embedded in code) const void *png_data; unsigned int png_size; ImGui::GetDefaultFontData( NULL, NULL, &png_data, &png_size ); int tex_x, tex_y, tex_comp; void *tex_data = stbi_load_from_memory( ( const unsigned char * ) png_data, ( int ) png_size, &tex_x, &tex_y, &tex_comp, 0 ); IM_ASSERT( tex_data != NULL ); #else // Custom font from filesystem io.Font = new ImBitmapFont(); io.Font->LoadFromFile( "../../extra_fonts/mplus-2m-medium_18.fnt" ); IM_ASSERT( io.Font->IsLoaded() ); int tex_x, tex_y, tex_comp; void *tex_data = stbi_load( "../../extra_fonts/mplus-2m-medium_18.png", &tex_x, &tex_y, &tex_comp, 0 ); IM_ASSERT( tex_data != NULL ); // Automatically find white pixel from the texture we just loaded // (io.FontTexUvForWhite needs to contains UV coordinates pointing to a white pixel in order to render solid objects) for ( int tex_data_off = 0; tex_data_off < tex_x * tex_y; tex_data_off++ ) if ( ( ( unsigned int * ) tex_data )[tex_data_off] == 0xffffffff ) { io.FontTexUvForWhite = ImVec2( ( float )( tex_data_off % tex_x ) / ( tex_x ), ( float )( tex_data_off / tex_x ) / ( tex_y ) ); break; } #endif glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data ); stbi_image_free( tex_data ); /************************************************************************/ /* NEW: Material */ /************************************************************************/ kl::ShaderLoader loader; handle = loader.Compile( Resource("shaders/GUI.vert"), Resource("shaders/GUI.frag") ); // Uniforms uniforms.mvp_matrix = glGetUniformLocation( handle, "mvp_matrix" ); // Samplers glUseProgram( handle ); glUniform1i( glGetUniformLocation( handle, "diffuseSampler" ), 0 ); /************************************************************************/ /* NEW: Vertex buffer */ /************************************************************************/ glGenVertexArrays( 1, &vao ); glBindVertexArray( vao ); glGenBuffers( 1, &vertexBuffer ); glBindBuffer( GL_ARRAY_BUFFER, vertexBuffer ); // Allocate 4 MB vertex attribute buffer without setting data glBufferData( GL_ARRAY_BUFFER, 4 * 1024 * 1024, nullptr, GL_STATIC_DRAW ); // Tell OpenGL where we can find vertex attributes // Position glVertexAttribPointer( 0, 2, GL_FLOAT, GL_FALSE, sizeof( ImDrawVert ), nullptr ); glEnableVertexAttribArray( 0 ); // Normal glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, sizeof( ImDrawVert ), ( void * ) 8 ); glEnableVertexAttribArray( 1 ); // Texcoord (normalize [0-255] -> [0,1]) glVertexAttribPointer( 2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( ImDrawVert ), ( void * ) 16 ); glEnableVertexAttribArray( 2 ); // Unbind glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); }
int main( int argc, char **argv ) { int width = 1024, height=768; // Initialise GLFW if( !glfwInit() ) { fprintf( stderr, "Failed to initialize GLFW\n" ); exit( EXIT_FAILURE ); } // Open a window and create its OpenGL context if( !glfwOpenWindow( width, height, 0,0,0,0, 24,0, GLFW_WINDOW ) ) { fprintf( stderr, "Failed to open GLFW window\n" ); glfwTerminate(); exit( EXIT_FAILURE ); } glfwSetWindowTitle( "imgui sample imguiRenderGL2" ); GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); exit( EXIT_FAILURE ); } // Ensure we can capture the escape key being pressed below glfwEnable( GLFW_STICKY_KEYS ); // Enable vertical sync (on cards that support it) glfwSwapInterval( 1 ); // Init UI if (!imguiRenderGLInit("DroidSans.ttf")) { fprintf(stderr, "Could not init GUI renderer.\n"); exit(EXIT_FAILURE); } glClearColor(0.8f, 0.8f, 0.8f, 1.f); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_DEPTH_TEST); // imgui states bool checked1 = false; bool checked2 = false; bool checked3 = true; bool checked4 = false; float value1 = 50.f; float value2 = 30.f; int scrollarea1 = 0; int scrollarea2 = 0; // glfw scrolling int glfwscroll = 0; do { glfwGetWindowSize(&width, &height); glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Mouse states unsigned char mousebutton = 0; int currentglfwscroll = glfwGetMouseWheel(); int mscroll = 0; if (currentglfwscroll < glfwscroll) mscroll = 2; if (currentglfwscroll > glfwscroll) mscroll = -2; glfwscroll = currentglfwscroll; int mousex; int mousey; glfwGetMousePos(&mousex, &mousey); mousey = height - mousey; int leftButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_LEFT ); int rightButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_RIGHT ); int middleButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_MIDDLE ); int toggle = 0; if( leftButton == GLFW_PRESS ) mousebutton |= IMGUI_MBUT_LEFT; // Draw UI glMatrixMode(GL_PROJECTION); glLoadIdentity(); float projection[16] = { 2.f/width, 0.f, 0.f, 0.f, 0.f, 2.f/height, 0.f, 0.f, 0.f, 0.f, -2.f, 0.f, -1.f, -1.f, -1.f, 1.f }; glLoadMatrixf(projection); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glUseProgram(0); imguiBeginFrame(mousex, mousey, mousebutton, mscroll); imguiBeginScrollArea("Scroll area", 10, 10, width / 5, height - 20, &scrollarea1); imguiSeparatorLine(); imguiSeparator(); imguiButton("Button"); imguiButton("Disabled button", false); imguiItem("Item"); imguiItem("Disabled item", false); toggle = imguiCheck("Checkbox", checked1); if (toggle) checked1 = !checked1; toggle = imguiCheck("Disabled checkbox", checked2, false); if (toggle) checked2 = !checked2; toggle = imguiCollapse("Collapse", "subtext", checked3); if (checked3) { imguiIndent(); imguiLabel("Collapsible element"); imguiUnindent(); } if (toggle) checked3 = !checked3; toggle = imguiCollapse("Disabled collapse", "subtext", checked4, false); if (toggle) checked4 = !checked4; imguiLabel("Label"); imguiValue("Value"); imguiSlider("Slider", &value1, 0.f, 100.f, 1.f); imguiSlider("Disabled slider", &value2, 0.f, 100.f, 1.f, false); imguiIndent(); imguiLabel("Indented"); imguiUnindent(); imguiLabel("Unindented"); imguiEndScrollArea(); imguiBeginScrollArea("Scroll area", 20 + width / 5, 500, width / 5, height - 510, &scrollarea2); imguiSeparatorLine(); imguiSeparator(); for (int i = 0; i < 100; ++i) imguiLabel("A wall of text"); imguiEndScrollArea(); imguiEndFrame(); imguiDrawText(30 + width / 5 * 2, height - 20, IMGUI_ALIGN_LEFT, "Free text", imguiRGBA(32,192, 32,192)); imguiDrawText(30 + width / 5 * 2 + 100, height - 40, IMGUI_ALIGN_RIGHT, "Free text", imguiRGBA(32, 32, 192, 192)); imguiDrawText(30 + width / 5 * 2 + 50, height - 60, IMGUI_ALIGN_CENTER, "Free text", imguiRGBA(192, 32, 32,192)); imguiDrawLine(30 + width / 5 * 2, height - 80, 30 + width / 5 * 2 + 100, height - 60, 1.f, imguiRGBA(32,192, 32,192)); imguiDrawLine(30 + width / 5 * 2, height - 100, 30 + width / 5 * 2 + 100, height - 80, 2.f, imguiRGBA(32, 32, 192, 192)); imguiDrawLine(30 + width / 5 * 2, height - 120, 30 + width / 5 * 2 + 100, height - 100, 3.f, imguiRGBA(192, 32, 32,192)); imguiDrawRoundedRect(30 + width / 5 * 2, height - 240, 100, 100, 5.f, imguiRGBA(32,192, 32,192)); imguiDrawRoundedRect(30 + width / 5 * 2, height - 350, 100, 100, 10.f, imguiRGBA(32, 32, 192, 192)); imguiDrawRoundedRect(30 + width / 5 * 2, height - 470, 100, 100, 20.f, imguiRGBA(192, 32, 32,192)); imguiDrawRect(30 + width / 5 * 2, height - 590, 100, 100, imguiRGBA(32, 192, 32, 192)); imguiDrawRect(30 + width / 5 * 2, height - 710, 100, 100, imguiRGBA(32, 32, 192, 192)); imguiDrawRect(30 + width / 5 * 2, height - 830, 100, 100, imguiRGBA(192, 32, 32,192)); imguiRenderGLDraw(width, height); // Check for errors GLenum err = glGetError(); if(err != GL_NO_ERROR) { fprintf(stderr, "OpenGL Error : %s\n", gluErrorString(err)); } // Swap buffers glfwSwapBuffers(); } // Check if the ESC key was pressed or the window was closed while( glfwGetKey( GLFW_KEY_ESC ) != GLFW_PRESS && glfwGetWindowParam( GLFW_OPENED ) ); // Clean UI imguiRenderGLDestroy(); // Close OpenGL window and terminate GLFW glfwTerminate(); exit( EXIT_SUCCESS ); }
bool Tutorial4::onCreate(int a_argc, char* a_argv[]) { // create a world-space matrix for a camera m_cameraMatrix = glm::inverse( glm::lookAt(glm::vec3(10,10,10),glm::vec3(0,0,0), glm::vec3(0,1,0)) ); // get window dimensions to calculate aspect ratio int width = 0, height = 0; glfwGetWindowSize(m_window, &width, &height); // create a perspective projection matrix with a 90 degree field-of-view and widescreen aspect ratio m_projectionMatrix = glm::perspective(glm::pi<float>() * 0.25f, width / (float)height, 0.1f, 1000.0f); // set the clear colour and enable depth testing and backface culling glClearColor(0.25f,0.25f,0.25f,1); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); m_renderProgram = LoadShaders("VertexShader.glsl", "FragmentShader.glsl"); // load an image using STB // temp vars for storing the dimensions/format of our image retrieved by STB int imgWidth = 0; int imgHeight = 0; int imgFormat = 0; unsigned char * pixelData = stbi_load( "./textures/numbered_grid.tga", &imgWidth, &imgHeight, &imgFormat, STBI_default); printf("\nWidth: %i, Height: %i, Format: %i", imgWidth, imgHeight, imgFormat); // texture generation, binding, and buffering // OGL DOCUMENTATION // http://docs.gl/gl4/glGenTextures // http://docs.gl/gl4/glBindTexture // http://docs.gl/gl4/glTexImage2D glGenTextures(1, &m_texture); glBindTexture(GL_TEXTURE_2D, m_texture); glTexImage2D( GL_TEXTURE_2D, //target - only certain GLenum values are accepted. 0, //level imgFormat, //internal format - STB does NOT retrieve this properly ._. imgWidth, //width imgHeight, //height 0, //border - must be 0 (even the documentation says so) GL_RGBA, //format - GL_UNSIGNED_BYTE, //type pixelData); //data - the data retrieved by STB // filtering //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // clear bound texture state so we don't accidentally change it glBindTexture(GL_TEXTURE_2D, 0); // creating a simple plane to render Utility::build3DPlane(10, m_VAO, m_VBO, m_IBO); delete[] pixelData; return true; }
int main() { GLFWwindow* window; struct DemoData data; struct NVGcontext* vg = NULL; struct GPUtimer gpuTimer; struct PerfGraph fps, cpuGraph, gpuGraph; double prevt = 0, cpuTime = 0; if (!glfwInit()) { printf("Failed to init GLFW."); return -1; } initGraph(&fps, GRAPH_RENDER_FPS, "Frame Time"); initGraph(&cpuGraph, GRAPH_RENDER_MS, "CPU Time"); initGraph(&gpuGraph, GRAPH_RENDER_MS, "GPU Time"); glfwSetErrorCallback(errorcb); #ifndef _WIN32 // don't require this on win32, and works with more cards glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #endif #ifdef DEMO_MSAA glfwWindowHint(GLFW_SAMPLES, 4); #endif window = glfwCreateWindow(1000, 600, "NanoVG", NULL, NULL); // window = glfwCreateWindow(1000, 600, "NanoVG", glfwGetPrimaryMonitor(), NULL); if (!window) { glfwTerminate(); return -1; } glfwSetKeyCallback(window, key); glfwMakeContextCurrent(window); #ifdef NANOVG_GLEW glewExperimental = GL_TRUE; if(glewInit() != GLEW_OK) { printf("Could not init glew.\n"); return -1; } #endif #ifdef DEMO_MSAA vg = nvgCreateGL3(512, 512, 0); #else vg = nvgCreateGL3(512, 512, NVG_ANTIALIAS); #endif if (vg == NULL) { printf("Could not init nanovg.\n"); return -1; } if (loadDemoData(vg, &data) == -1) return -1; glfwSwapInterval(0); initGPUTimer(&gpuTimer); glfwSetTime(0); prevt = glfwGetTime(); while (!glfwWindowShouldClose(window)) { double mx, my, t, dt; int winWidth, winHeight; int fbWidth, fbHeight; float pxRatio; float gpuTimes[3]; int i, n; t = glfwGetTime(); dt = t - prevt; prevt = t; startGPUTimer(&gpuTimer); glfwGetCursorPos(window, &mx, &my); glfwGetWindowSize(window, &winWidth, &winHeight); glfwGetFramebufferSize(window, &fbWidth, &fbHeight); // Calculate pixel ration for hi-dpi devices. pxRatio = (float)fbWidth / (float)winWidth; // Update and render glViewport(0, 0, fbWidth, fbHeight); if (premult) glClearColor(0,0,0,0); else glClearColor(0.3f, 0.3f, 0.32f, 1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); nvgBeginFrame(vg, winWidth, winHeight, pxRatio, premult ? NVG_PREMULTIPLIED_ALPHA : NVG_STRAIGHT_ALPHA); renderDemo(vg, mx,my, winWidth,winHeight, t, blowup, &data); renderGraph(vg, 5,5, &fps); renderGraph(vg, 5+200+5,5, &cpuGraph); if (gpuTimer.supported) renderGraph(vg, 5+200+5+200+5,5, &gpuGraph); nvgEndFrame(vg); glEnable(GL_DEPTH_TEST); // Measure the CPU time taken excluding swap buffers (as the swap may wait for GPU) cpuTime = glfwGetTime() - t; updateGraph(&fps, dt); updateGraph(&cpuGraph, cpuTime); // We may get multiple results. n = stopGPUTimer(&gpuTimer, gpuTimes, 3); for (i = 0; i < n; i++) updateGraph(&gpuGraph, gpuTimes[i]); if (screenshot) { screenshot = 0; saveScreenShot(fbWidth, fbHeight, premult, "dump.png"); } glfwSwapBuffers(window); glfwPollEvents(); } freeDemoData(vg, &data); nvgDeleteGL3(vg); printf("Average Frame Time: %.2f ms\n", getGraphAverage(&fps) * 1000.0f); printf(" CPU Time: %.2f ms\n", getGraphAverage(&cpuGraph) * 1000.0f); printf(" GPU Time: %.2f ms\n", getGraphAverage(&gpuGraph) * 1000.0f); glfwTerminate(); return 0; }
void VCWindow::Initalize() { std::cout << "Creating a VCWindow..." << std::endl; // ===== GLFW ====================================================== glfwSetErrorCallback(glewErrorCallback); if (!glfwInit()) { std::cout << "Failed to initialize GLFW." << std::endl; std::cin.ignore(); } //glfwWindowHint(GLFW_DECORATED, false); //glfwWindowHint(GLFW_SAMPLES, 4); //glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #if DEBUG glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, true); #endif GLFWWindowHandle = glfwCreateWindow(1280, 600, "Thilenius - A 0.0.1", NULL, NULL); if (!GLFWWindowHandle) { glfwTerminate(); std::cout << "Failed to create a window." << std::endl; std::cin.ignore(); } glfwMakeContextCurrent(GLFWWindowHandle); // ===== GLEW ====================================================== glewExperimental = true; GLenum glewError = glewInit(); if( glewError != GLEW_OK ) { printf( "Error initializing GLEW! %s\n", glewGetErrorString( glewError ) ); std::cin.ignore(); } // ===== Debug ====================================================== #if DEBUG glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE); glDebugMessageCallbackARB(&glDebugCallback, NULL); #endif GLint major, minor; glGetIntegerv(GL_MAJOR_VERSION, &major); glGetIntegerv(GL_MINOR_VERSION, &minor); std::cout << "OpenGL version: " << major << "." << minor << std::endl; std::cout << "Hardware: " << glGetString(GL_RENDERER) << std::endl << std::endl; glfwGetWindowSize(GLFWWindowHandle, &Width, &Height); FullViewport = VCRectangle(0, 0, Width, Height); SetVSync(false); std::cout << "VCWindow Initialized." << std::endl; glErrorCheck(); VCInteropWindowSetPos(200, 200); }
//Get height of display. int GraphicsSystem::getHeight() { int width, height; glfwGetWindowSize(mpDisplay, &width, &height); return height; }
void VCInteropWindowGetSize(int* width, int* height) { glfwGetWindowSize(VCWindow::Instance->GLFWWindowHandle, width, height); }
int main( void ) { int width, height, x; double time; GLboolean running; GLuint textureID; char* texturePath = "mipmaps.tga"; // Initialise GLFW if( !glfwInit() ) { fprintf( stderr, "Failed to initialize GLFW\n" ); exit( EXIT_FAILURE ); } // Open OpenGL window if( !glfwOpenWindow( 640, 480, 0,0,0,0, 0,0, GLFW_WINDOW ) ) { fprintf( stderr, "Failed to open GLFW window\n" ); glfwTerminate(); exit( EXIT_FAILURE ); } glfwSetWindowTitle( "Trilinear interpolation" ); // Enable sticky keys glfwEnable( GLFW_STICKY_KEYS ); // Enable vertical sync (on cards that support it) glfwSwapInterval( 1 ); // Generate and bind our texture ID glGenTextures( 1, &textureID ); glBindTexture( GL_TEXTURE_2D, textureID ); // Load texture from file into video memory, including mipmap levels if( !glfwLoadTexture2D( texturePath, GLFW_BUILD_MIPMAPS_BIT ) ) { fprintf( stderr, "Failed to load texture %s\n", texturePath ); glfwTerminate(); exit( EXIT_FAILURE ); } // Use trilinear interpolation (GL_LINEAR_MIPMAP_LINEAR) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); // Enable plain 2D texturing glEnable( GL_TEXTURE_2D ); running = GL_TRUE; while( running ) { // Get time and mouse position time = glfwGetTime(); glfwGetMousePos( &x, NULL ); // Get window size (may be different than the requested size) glfwGetWindowSize( &width, &height ); height = height > 0 ? height : 1; // Set viewport glViewport( 0, 0, width, height ); // Clear color buffer glClearColor( 0.0f, 0.0f, 0.0f, 0.0f); glClear( GL_COLOR_BUFFER_BIT ); // Select and setup the projection matrix glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( 65.0f, (GLfloat)width / (GLfloat)height, 1.0f, 50.0f ); // Select and setup the modelview matrix glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); gluLookAt( 0.0f, 3.0f, -20.0f, // Eye-position 0.0f, -4.0f, -11.0f, // View-point 0.0f, 1.0f, 0.0f ); // Up-vector // Draw a textured quad glRotatef( 0.05f * (GLfloat)x + (GLfloat)time * 5.0f, 0.0f, 1.0f, 0.0f ); glBegin( GL_QUADS ); glTexCoord2f( -20.0f, 20.0f ); glVertex3f( -50.0f, 0.0f, -50.0f ); glTexCoord2f( 20.0f, 20.0f ); glVertex3f( 50.0f, 0.0f, -50.0f ); glTexCoord2f( 20.0f, -20.0f ); glVertex3f( 50.0f, 0.0f, 50.0f ); glTexCoord2f( -20.0f, -20.0f ); glVertex3f( -50.0f, 0.0f, 50.0f ); glEnd(); // Swap buffers glfwSwapBuffers(); // Check if the ESC key was pressed or the window was closed running = !glfwGetKey( GLFW_KEY_ESC ) && glfwGetWindowParam( GLFW_OPENED ); } // Close OpenGL window and terminate GLFW glfwTerminate(); exit( EXIT_SUCCESS ); }
void render(GLFWwindow* window) { int width, height; glfwGetWindowSize(window, &width, &height); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer); glViewport(0, 0, width, height); glDrawBuffers(3, fboBuffs); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 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 ); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glVertexAttribPointer( 1, // attribute 1. No particular reason for 1, 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 ! glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(programID); // Projection matrix : 45бу Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f); // Camera matrix glm::mat4 View = glm::lookAt( glm::vec3(4, 3, 3), // Camera is at (4,3,3), in World Space glm::vec3(0, 0, 0), // and looks at the origin glm::vec3(0, 1, 0) // Head is up (set to 0,-1,0 to look upside-down) ); // Model matrix : an identity matrix (model will be at the origin) glm::mat4 Model = glm::mat4(1.0f); // Changes for each model ! // Our ModelViewProjection : multiplication of our 3 matrices glm::mat4 MVP = Projection * View * Model; // Remember, matrix multiplication is the other way around // Get a handle for our "MVP" uniform. // Only at initialisation time. GLuint MatrixID = glGetUniformLocation(programID, "MVP"); // Send our transformation to the currently bound shader, // in the "MVP" uniform // For each model you render, since the MVP will be different (at least the M part) glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glDrawArrays(GL_TRIANGLES, 0, 12*3); // Starting from vertex 0; 3 vertices total -> 1 triangle glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisable(GL_DEPTH_TEST); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer); // Copy greyscale output to the left half of the screen glReadBuffer(GL_COLOR_ATTACHMENT2); glBlitFramebuffer(0, 0, width/2, height, 0, 0, width/2, height, GL_COLOR_BUFFER_BIT, GL_NEAREST); // Copy the luminance adjusted color to the right half of the screen glReadBuffer(GL_COLOR_ATTACHMENT1); glBlitFramebuffer(width / 2, 0, width, height, width / 2, 0, width, height, GL_COLOR_BUFFER_BIT, GL_LINEAR); // Scale the unaltered image to the upper right of the screen glReadBuffer(GL_COLOR_ATTACHMENT0); glBlitFramebuffer(0, 0, width, width, width - (int)(height*(0.2)), (int)(height*(0.8)), width, height, GL_COLOR_BUFFER_BIT, GL_LINEAR); }
glm::ivec2 kit::Window::getSize() { glm::ivec2 returner; glfwGetWindowSize(this->m_glfwHandle, &returner.x, &returner.y); return returner; }
bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor) { setViewName(viewName); _frameZoomFactor = frameZoomFactor; if (s_intriGdipCanvasEnabled) IrregularGL::thisObject()->setupGL(); glfwWindowHint(GLFW_RESIZABLE,GL_FALSE); glfwWindowHint(GLFW_RED_BITS,_glContextAttrs.redBits); glfwWindowHint(GLFW_GREEN_BITS,_glContextAttrs.greenBits); glfwWindowHint(GLFW_BLUE_BITS,_glContextAttrs.blueBits); glfwWindowHint(GLFW_ALPHA_BITS,_glContextAttrs.alphaBits); glfwWindowHint(GLFW_DEPTH_BITS,_glContextAttrs.depthBits); glfwWindowHint(GLFW_STENCIL_BITS,_glContextAttrs.stencilBits); // x-studio365 spec hints glfwWindowHint(GLFW_DECORATED, !s_intriWindowNoB); glfwWindowHint(GLFW_VISIBLE, s_intriWindowVisible); glfwWindowHint(GLFW_ALPHA_MASK, s_intriWindowAlphaEnabled); glfwxSetParent(s_intriWindowParent); int needWidth = rect.size.width * _frameZoomFactor; int neeHeight = rect.size.height * _frameZoomFactor; _mainWindow = glfwCreateWindow(needWidth, neeHeight, _viewName.c_str(), _monitor, nullptr); if (_mainWindow == nullptr) { std::string message = "Can't create window"; if (!_glfwError.empty()) { message.append("\nMore info: \n"); message.append(_glfwError); } ccMessageBox(message.c_str(), "Error launch application"); return false; } /* * Note that the created window and context may differ from what you requested, * as not all parameters and hints are * [hard constraints](@ref window_hints_hard). This includes the size of the * window, especially for full screen windows. To retrieve the actual * attributes of the created window and context, use queries like @ref * glfwGetWindowAttrib and @ref glfwGetWindowSize. * * see declaration glfwCreateWindow */ int realW = 0, realH = 0; glfwGetWindowSize(_mainWindow, &realW, &realH); if (realW != needWidth) { rect.size.width = realW / _frameZoomFactor; } if (realH != neeHeight) { rect.size.height = realH / _frameZoomFactor; } glfwMakeContextCurrent(_mainWindow); // x-studio365 spec: use glfwx setMouseButtonCallback ensure update mouse coord immediately. glfwxSetMouseButtonCallback(_mainWindow, GLFWEventHandler::onGLFWMouseCallBackEx); glfwSetCursorPosCallback(_mainWindow, GLFWEventHandler::onGLFWMouseMoveCallBack); glfwSetScrollCallback(_mainWindow, GLFWEventHandler::onGLFWMouseScrollCallback); glfwSetCharCallback(_mainWindow, GLFWEventHandler::onGLFWCharCallback); glfwSetKeyCallback(_mainWindow, GLFWEventHandler::onGLFWKeyCallback); glfwSetWindowPosCallback(_mainWindow, GLFWEventHandler::onGLFWWindowPosCallback); glfwSetFramebufferSizeCallback(_mainWindow, GLFWEventHandler::onGLFWframebuffersize); glfwSetWindowSizeCallback(_mainWindow, GLFWEventHandler::onGLFWWindowSizeFunCallback); glfwSetWindowIconifyCallback(_mainWindow, GLFWEventHandler::onGLFWWindowIconifyCallback); setFrameSize(rect.size.width, rect.size.height); // check OpenGL version at first const GLubyte* glVersion = glGetString(GL_VERSION); if ( utils::atof((const char*)glVersion) < 1.5 ) { char strComplain[256] = {0}; sprintf(strComplain, "OpenGL 1.5 or higher is required (your version is %s). Please upgrade the driver of your video card.", glVersion); ccMessageBox(strComplain, "OpenGL version too old"); return false; } initGlew(); // Enable point size by default. glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); return true; }
void Game::update(float delta) { for (size_t i = 0; i < delays.size(); i++) { delays[i].time -= delta; if (!delays[i].fired && delays[i].time <= 0.0f) { delays[i].fired = true; delays[i].func(); delays[i] = delays[delays.size() - 1]; delays.pop_back(); i--; } } highestBlock = 0.0f; shakeIntensity = glm::max(0.0f, shakeIntensity - delta * 1.5f); for (int i = 0; i < 2; i++) bound[i] = glm::clamp(bound[i] - delta * 2.0f, 0.0f, 1.0f); for (auto it = powerups.begin(); it != powerups.end(); ++it) { if (it->update(delta)) { *it = powerups.back(); it--; powerups.pop_back(); continue; } } for (auto it = blocks.begin(); it != blocks.end(); ++it) { if (!it->alive) { *it = blocks.back(); it--; blocks.pop_back(); continue; } it->update(delta); } if (glfwGetTime() >= nextBlockSpawn) { scheduleNextBlockSpawn(); std::uniform_int_distribution<> dist(4, 8); std::uniform_real_distribution<> dist2(0.0f, 3150.0f); int count = dist(random); for (int i = 0; i < count; i++) { float x = 50 * glm::round((float)dist2(random) / 50); blocks.push_back(Block(this, glm::vec2(x, highestBlock -1050.0f))); } } if (glfwGetTime() >= nextPowerupSpawn) { scheduleNextPowerupSpawn(); powerups.push_back(Powerup(this)); } glm::vec2 pos_min, pos_max; bool pos_one = false; //for (auto it = players.begin(); it != players.end(); ++it) for (size_t i = 0; i < players.size(); i++) { Player *it = &*players[i]; if (!it->dead) { glm::vec2 pos = it->getPosition(); if (!pos_one) { pos_min = pos; pos_max = pos; pos_one = true; } else { pos_min = glm::min(pos_min, pos); pos_max = glm::max(pos_max, pos); } it->update(delta); } else if (glfwGetTime() - it->deathTime >= 3.0f) it->resetFinish(); } for (auto it = particles.begin(); it != particles.end(); ++it) { if (it->duration <= 0.0f) { *it = particles.back(); it--; particles.pop_back(); continue; } it->update(delta); } if (pos_one) { int width, height; glfwGetWindowSize(window, &width, &height); //camera.pos_dest.x = (pos_min.x + pos_max.x) / 2.0f - width / 2.0f + 25.0f; //camera.pos_dest.y = (pos_min.y + pos_max.y) / 2.0f - height / 2.0f + 25.0f; camera.pos_dest.x = (pos_min.x + pos_max.x) / 2.0f + 25.0f; camera.pos_dest.y = (pos_min.y + pos_max.y) / 2.0f + 25.0f; //camera.pos_dest.y = 1000.0f - height; camera.scale_dest = glm::min(1.0f, (width - 200) / glm::abs(pos_min.x - pos_max.x)); camera.pos -= (camera.pos - camera.pos_dest) * delta * camera.speed; camera.scale -= (camera.scale - camera.scale_dest) * delta * camera.speed; } fmod->update(); }
void ShadowMapping::renderScene(bool fromLight, float time){ gllog::update_fps_counter (window_); const GLfloat color[] = {0.0f, 0.0f, 0.0f, 1.0f}; const GLfloat depth[] = {1.0f}; static const GLfloat ones[] = { 1.0f }; static const GLfloat zero[] = { 0.0f }; static const GLfloat gray[] = { 0.1f, 0.1f, 0.1f, 0.0f }; camera_->update(); glm::mat4 projectionMatrix = camera_->getProjectionMatrix(); glm::mat4 viewMatrix = camera_->getViewMatrix(); const float *viewSource = (const float*)glm::value_ptr(viewMatrix); const float *projectionSource = (const float*)glm::value_ptr(projectionMatrix); float angle; if(params_["manualLight"]){ angle = params_["angle"]; } else { angle = (time - previousTime) * 0.5f; } //Move the light std::shared_ptr<gland::Body> lightSource = lightSources_.at(0); glm::vec3 vLightPos = glm::vec3(0.0f); glm::mat4 rot = lightSource->getRotationMatrix(); glm::mat4 trm = glm::translate(glm::vec3(params_["lightRadius"], 0.0f, 0.0f)); rot = glm::rotate(rot, -sinf(angle*2e1f) * (params_["lightSpeed"]) , glm::vec3(0.0f, 1.0f, 0.0f)); //We want a circular motion, so we first translate then rotate glm::mat4 transform = rot * trm; vLightPos = glm::vec3(transform * glm::vec4(vLightPos, 1.0f)); trm = rot * trm; //And save the newly computed matrices in the light object lightSource->setTranslationMatrix(trm); lightSource->setRotationMatrix(rot); //Restore manuel rotation params_["angle"] = 0.0f; //Matrices from light's position for depth computation glm::mat4 lightViewMatrix = glm::lookAt(vLightPos, glm::vec3(-5.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 lightProjMatrix = glm::frustum(-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 200.0f); glm::mat4 lightVp = lightProjMatrix * lightViewMatrix; glm::mat4 scaleBiasMatrix = glm::mat4(glm::vec4(0.5f, 0.0f, 0.0f, 0.0f), glm::vec4(0.0f, 0.5f, 0.0f, 0.0f), glm::vec4(0.0f, 0.0f, 0.5f, 0.0f), glm::vec4(0.5f, 0.5f, 0.5f, 1.0f)); //Light in view space, for rendering the source vLightPos = glm::vec3(viewMatrix*glm::vec4(vLightPos, 1.0f)); const float *light = (const float*)glm::value_ptr(vLightPos); if(fromLight){ //Render from light glBindFramebuffer(GL_FRAMEBUFFER, nDepthFbo_); glViewport(0, 0, DEPTH_TEXTURE_SIZE, DEPTH_TEXTURE_SIZE); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(params_["offsetFactor"], params_["offsetUnits"]); glUseProgram(nLightProgram_); static const GLenum buffs[] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, buffs); glClearBufferfv(GL_COLOR, 0, zero); } else { int width, height; glfwGetWindowSize(window_, &width, &height); glViewport(0, 0, width, height); glClearBufferfv(GL_COLOR, 0, gray); glUseProgram(nViewProgram_); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, nDepthTex_); GLuint projLocation = glGetUniformLocation (shaderPrograms_.at(0), "proj"); glUniformMatrix4fv (projLocation, 1, GL_FALSE, projectionSource); glDrawBuffer(GL_BACK); } glClearBufferfv(GL_DEPTH, 0, ones); //============================== //Draw standard objects //============================== for(std::shared_ptr<gland::Body> b : standardObjects_){ glm::mat4 modelMatrix = b->getModelMatrix(); glm::mat4 modelViewMatrix = viewMatrix * modelMatrix; glm::mat4 normalMatrix = glm::transpose(glm::inverse(modelViewMatrix)); //TODO Is it safe to use this array, or should I create a //fixed-size one? const float *mSource = (const float*)glm::value_ptr(modelMatrix); const float *mvSource = (const float*)glm::value_ptr(modelViewMatrix); const float *normalMatrixSource = (const float*)glm::value_ptr(normalMatrix); glm::mat4 shadowSbpvMatrix = scaleBiasMatrix * lightProjMatrix * lightViewMatrix * modelMatrix; const float *shadowSource = (const float*)glm::value_ptr(shadowSbpvMatrix); if(fromLight){ glUseProgram (nLightProgram_); const float *lightVpSource = (const float*)glm::value_ptr(lightVp); GLuint lightVpLocation = glGetUniformLocation (nLightProgram_, "vp"); if(lightVpLocation >= 0){ glUniformMatrix4fv(lightVpLocation, 1, GL_FALSE, lightVpSource); } else { std::cerr << "Non-existent uniform: vp" << std::endl; } GLuint modelLocation = glGetUniformLocation (nLightProgram_, "model"); if(modelLocation >= 0){ glUniformMatrix4fv(modelLocation, 1, GL_FALSE, mSource); } else { std::cerr << "Non-existent uniform: model" << std::endl; } } else { GLuint shaderProgram = b->getShader(); glUseProgram (shaderProgram); GLuint projLocation = glGetUniformLocation (shaderProgram, "proj"); if(projLocation >= 0){ glUniformMatrix4fv (projLocation, 1, GL_FALSE, projectionSource); } else { std::cerr << "Non-existent uniform" << std::endl; } GLuint viewLocation = glGetUniformLocation (shaderProgram, "view"); if(viewLocation >= 0){ glUniformMatrix4fv (viewLocation, 1, GL_FALSE, viewSource); } else { std::cerr << "Non-existent uniform" << std::endl; } GLuint mvLocation = glGetUniformLocation (shaderProgram, "mvMatrix"); if(mvLocation >= 0){ glUniformMatrix4fv (mvLocation, 1, GL_FALSE, mvSource); } else { std::cerr << "Non-existent uniform" << std::endl; } GLuint normalMatrixLocation = glGetUniformLocation (shaderProgram, "normalMatrix"); if(normalMatrixLocation >= 0){ glUniformMatrix4fv (normalMatrixLocation, 1, GL_FALSE, normalMatrixSource); } else { std::cerr << "Non-existent uniform" << std::endl; } GLuint shadowMatrixLocation = glGetUniformLocation (shaderProgram, "shadowMatrix"); if(shadowMatrixLocation >= 0){ glUniformMatrix4fv (shadowMatrixLocation, 1, GL_FALSE, shadowSource); } else { std::cerr << "Non-existent uniform" << std::endl; } GLuint lightLocation = glGetUniformLocation (shaderProgram, "viewLightPos"); if(lightLocation >= 0){ glUniform3fv (lightLocation, 1, light); } else { std::cerr << "Non-existent uniform" << std::endl; } GLuint stepLocation = glGetUniformLocation (shaderProgram, "step"); if(stepLocation >= 0){ glUniform1f(stepLocation, time - previousTime); } else { std::cerr << "Non-existent uniform" << std::endl; } } glBindVertexArray(b->getVaoName()); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, b->getIndexBufferName()); glDrawElements( GL_TRIANGLES, // mode b->getIndices().size(), // count GL_UNSIGNED_INT, // type (void*)0 // element array buffer offset ); glBindVertexArray(0); } if(!fromLight){ for(std::shared_ptr<gland::Body> b : lightSources_){ glm::mat4 modelMatrix = b->getModelMatrix(); glm::mat4 modelViewMatrix = viewMatrix * modelMatrix; //TODO Is it safe to use this array, or should I create a //fixed-size one? const float *mSource = (const float*)glm::value_ptr(modelMatrix); const float *mvSource = (const float*)glm::value_ptr(modelViewMatrix); GLuint shaderProgram = b->getShader(); glUseProgram (shaderProgram); GLuint projLocation = glGetUniformLocation (shaderProgram, "proj"); if(projLocation >= 0){ glUniformMatrix4fv (projLocation, 1, GL_FALSE, projectionSource); } else { std::cerr << "Non-existent uniform" << std::endl; } GLuint viewLocation = glGetUniformLocation (shaderProgram, "view"); if(viewLocation >= 0){ glUniformMatrix4fv (viewLocation, 1, GL_FALSE, viewSource); } else { std::cerr << "Non-existent uniform" << std::endl; } GLuint mvLocation = glGetUniformLocation (shaderProgram, "mvMatrix"); if(mvLocation >= 0){ glUniformMatrix4fv (mvLocation, 1, GL_FALSE, mvSource); } else { std::cerr << "Non-existent uniform" << std::endl; } GLuint stepLocation = glGetUniformLocation (shaderProgram, "step"); if(stepLocation >= 0){ glUniform1f(stepLocation, time-previousTime); } else { std::cerr << "Non-existent uniform" << std::endl; } glBindVertexArray(b->getVaoName()); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, b->getIndexBufferName()); //glDrawArrays (GL_TRIANGLES, 0, b->getVertexCount()); glDrawElements( GL_TRIANGLES, // mode b->getIndices().size(), // count GL_UNSIGNED_INT, // type (void*)0 // element array buffer offset ); glBindVertexArray(0); } } if(fromLight){ glDisable(GL_POLYGON_OFFSET_FILL); glBindFramebuffer(GL_FRAMEBUFFER, 0); } else { glBindTexture(GL_TEXTURE_2D, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } //======================================== }
int main(int argc, char* argv[]) { app_argc = argc; app_argv = argv; int width, height, running, frames, x, y; double t, t1; char titlestr[ 200 ]; // Initialise GLFW glfwInit(); bool start_fullscreen = false; int x_res = 1280; int y_res = 720; bool manual_resolution_set = false; for (int i = 1; i < argc; i++) { vsx_string arg1 = argv[i]; if (arg1 == "--help" || arg1 == "/?" || arg1 == "-help" || arg1 == "-?") { printf( "Usage:\n" " vsxu_player [path_to_vsx_file]\n" "\n" "Flags: \n" " -pl Preload all visuals on start \n" " -dr Disable randomizer \n" " -p [x,y] Set window position x,y \n" " -s [x,y] Set window size x,y \n\n\n" ); exit(0); } else if (arg1 == "-f") { start_fullscreen = true; } else if (arg1 == "-pl") { option_preload_all = true; } else if (arg1 == "-dr") { disable_randomizer = true; } else if (arg1 == "-no") { no_overlay = true; } else if (arg1 == "-s") { if (i+1 < argc) { i++; vsx_string arg2 = argv[i]; vsx_avector<vsx_string> parts; vsx_string deli = ","; explode(arg2, deli, parts); if (parts.size() == 2) { x_res = s2i(parts[0]); y_res = s2i(parts[1]); manual_resolution_set = true; } else { deli = "x"; explode(arg2, deli, parts); if ( parts.size() == 2 ) { x_res = s2i(parts[0]); y_res = s2i(parts[1]); manual_resolution_set = true; } } } } } if (start_fullscreen && !manual_resolution_set) { // try to get the resolution from the desktop for fullscreen GLFWvidmode video_mode; glfwGetDesktopMode(&video_mode); x_res = video_mode.Height; y_res = video_mode.Width; } // Open OpenGL window glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); if( !glfwOpenWindow( x_res, y_res, 0,0,0,0,16,0, start_fullscreen?GLFW_FULLSCREEN:GLFW_WINDOW ) ) // GLFW_FULLSCREEN { printf("Error! Could not create an OpenGL context. Please check your GPU drivers...\n"); glfwTerminate(); return 0; } if (start_fullscreen) glfwEnable( GLFW_MOUSE_CURSOR ); app_init(0); glfwEnable(GLFW_AUTO_POLL_EVENTS); for (int i = 1; i < argc; i++) { vsx_string arg1 = argv[i]; if (arg1 == "-p") { if (i+1 < argc) { i++; vsx_string arg2 = argv[i]; vsx_avector<vsx_string> parts; vsx_string deli = ","; explode(arg2, deli, parts); glfwSetWindowPos(s2i(parts[0]), s2i(parts[1])); } } } glfwSetKeyCallback(&key_event); glfwSetMouseButtonCallback(&mouse_button_event); glfwSetMousePosCallback(&mouse_pos_event); glfwSetCharCallback(&key_char_event); glfwSetMouseWheelCallback(&mouse_wheel); // set window size callback function glfwSetWindowSizeCallback(window_size); // Enable sticky keys glfwEnable( GLFW_STICKY_KEYS ); glfwSwapInterval(1); // Main loop running = GL_TRUE; frames = 0; #if PLATFORM_FAMILY == PLATFORM_FAMILY_UNIX sprintf( titlestr, "Vovoid VSXu Player %s [GNU/Linux %d-bit]", vsxu_ver, PLATFORM_BITS); #endif #if PLATFORM_FAMILY == PLATFORM_FAMILY_WINDOWS sprintf( titlestr, "Vovoid VSXu Player %s [Windows %d-bit]", vsxu_ver, PLATFORM_BITS); #endif glfwSetWindowTitle( titlestr ); while( running ) { if (mouse_pos_type) { if (mouse_pos_type == 1) app_mouse_move(last_x,last_y); else app_mouse_move_passive(last_x,last_y); mouse_pos_type = 0; } app_pre_draw(); // Get time and mouse position t = glfwGetTime(); glfwGetMousePos( &x, &y ); float delta = t-t1; t1 = t; if (key_pressed != -1) { //printf("%f\n", delta); key_time += delta; if (key_time > 0.3f) { key_repeat_time += delta; if (key_repeat_time > initial_key_delay) { key_repeat_time = 0.0f; if (key_character != -1) app_char(key_character); app_key_down((long)key_pressed); initial_key_delay *= 0.99f; //printf("repeating key: %d\n", key_character); } } } frames ++; // Get window size (may be different than the requested size) glfwGetWindowSize( &width, &height ); height = height > 0 ? height : 1; // Set viewport gl_state.viewport_set( 0, 0, width, height ); // Clear color buffer glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); glClear( GL_COLOR_BUFFER_BIT ); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); app_draw(0); glfwSwapBuffers(); // Check if the ESC key was pressed or the window was closed running = /*!glfwGetKey( GLFW_KEY_ESC ) &&*/ glfwGetWindowParam( GLFW_OPENED ); } // Close OpenGL window and terminate GLFW glfwTerminate(); return 0; }
int Window::GetWidth() const { int *w = 0; int *h = 0; glfwGetWindowSize(window, w, h); return (*w); }
int main(void) { GLFWwindow* window; int width = 1024; int height = 768; glfwSetErrorCallback (glfw_error_callback); if(!glfwInit ()) { fprintf (stderr, "ERROR: could not start GLFW3\n"); return 1; } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // to use this: http://stackoverflow.com/questions/17923782/simple-opengl-image-library-soil-uses-deprecated-functionality // glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE); /*glfwWindowHint(GLFW_SAMPLES, 1); // 2x antialiasing int stencil_bits = 8; glfwWindowHint(GLFW_STENCIL_BITS, 8); // request a stencil buffer for object selection*/ glfwWindowHint(GLFW_ALPHA_BITS, 8); /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(width, height, "Game", NULL, NULL); glfwRestoreWindow(window); if (!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); // start GLEW extension handler glewExperimental = GL_TRUE; GLenum err = glewInit(); if(err != GLEW_OK) { cout << "GLEW error: " << glewGetErrorString(err); exit(1); // or handle the error in a nicer way } GLenum glErr = glGetError(); if (glErr != GL_NO_ERROR) { cout << "Caught GLEW init error in GL" << endl; } printOpenGLError(); // get version info const GLubyte* gl_renderer = glGetString (GL_RENDERER); // get renderer string const GLubyte* gl_version = glGetString (GL_VERSION); // version as a string int gl_alpha; glGetIntegerv(GL_ALPHA_BITS, &gl_alpha); printf ("Renderer: %s\n", gl_renderer); printf ("OpenGL version supported %s\n", gl_version); printf ("Alphabits: %d", gl_alpha); glfwSwapInterval(1); printOpenGLError(); cout << "Setting GL" << endl; //glClearColor(0.2f, 0.2f, 0.2f, 1.0f); glClearColor(0.9f, 0.9f, 0.99f, 1.0f); glEnable(GL_DEPTH_TEST); glClearDepth(1.0f); glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_CULL_FACE); glfwSetCharCallback(window, &Input::glfw_character_callback); glfwSetKeyCallback(window, &Input::glfw_key_callback); // create new Lua state lua_State *lua_state; lua_state = luaL_newstate(); luaL_openlibs(lua_state); // load Lua libraries /*static const luaL_Reg lualibs[] = { { "base", luaopen_base }, { "io", luaopen_io }, { "string", luaopen_string }, { NULL, NULL} }; const luaL_Reg *lib = lualibs; for(; lib->func != NULL; lib++) { lib->func(lua_state); lua_settop(lua_state, 0); }*/ lua_pushcfunction(lua_state, lua_set_camera); lua_setglobal(lua_state, "camera"); lua_pushcfunction(lua_state, lua_drawcube); lua_setglobal(lua_state, "drawblock"); lua_pushcfunction(lua_state, lua_load_renderer); lua_setglobal(lua_state, "load_renderer"); lua_pushcfunction(lua_state, lua_drawbatch); lua_setglobal(lua_state, "drawbatch"); lua_pushcfunction(lua_state, lua_time); lua_setglobal(lua_state, "time"); run(lua_state, "class.lua"); run(lua_state, "entity.lua"); run(lua_state, "world.lua"); run(lua_state, "component.lua"); run(lua_state, "block.lua"); run(lua_state, "physics.lua"); run(lua_state, "load.lua"); //camera = new CameraArcBall(glm::vec3(5,5,5), glm::vec3(0,0,0)); //renderer.push_back(new RenderCube("assets/textures/grass.jpg", "assets/textures/dirt.jpg")); // default renderer? cout << "Starting main loop:" << endl; glm::vec3 size = glm::vec3(2); RenderQuad quad("assets/textures/jap.png", "inversion"); RenderRect rect("assets/textures/tex16.png", "inversion2"); BatchedRenderCube batch("assets/textures/dirt.jpg"); cout << "[initmain]" << endl; printOpenGLError(); /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window) && !glfwGetKey(window, GLFW_KEY_ESCAPE)) { glfwGetWindowSize(window, &width, &height); glViewport(0, 0, width, height); //glClearStencil(0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT /*| GL_STENCIL_BUFFER_BIT*/); // update input and actions Input::instance().update(window); // update view and projection camera->update(window); if(glfwGetKey(window, 'U')) run(lua_state, "action.lua"); run(lua_state, "update.lua"); run(lua_state, "render.lua"); if(glfwGetKey(window, 'F')) std::cout << "FPS: " << calcFPS(glfwGetTime()) << std::endl; if(glfwGetKey(window, 'Q')) screenshot(); quad.draw(camera, glm::vec3(0, 0, 0)); if(glfwGetKey(window, GLFW_KEY_ENTER)) rect.draw(camera, glm::vec2(width, height)); printOpenGLError(); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); } // Cleanup VBO and shader //glDeleteBuffers(1, &vertexbuffer); //glDeleteProgram(shader.id()); // close the Lua state lua_close(lua_state); glfwTerminate(); return 0; }
void RenderText::setPos(int xPos, int yPos){ int width, height; glfwGetWindowSize(&width, &height); this->x=(width*xPos)/100; this->y=(height*yPos)/100; }
/** main */ int main() { // GLFW and GLEW initialization glfwInit(); // Core profile glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Window creation pWindow = glfwCreateWindow(1280, 720, "PerVoxelRaycaster", NULL, NULL); if (!pWindow) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(pWindow); ogl_LoadFunctions(); glfwSetCursorPosCallback(pWindow, cursorCallback); glfwSetMouseButtonCallback(pWindow, buttonsCallback); glfwSetScrollCallback(pWindow, scrollCallback); // OpenGL initialization glEnable(GL_DEPTH_TEST); glClearColor(0.0f, 0.0f, 0.0f, 1); // Setup shader // ### CHOOSE FROM ONE OF THESE THREE SHADERS ### //shader.loadShaders("Raycaster.vert", "SimpleRaycaster.frag"); //shader.loadShaders("Raycaster.vert", "SimplePerVoxelRaycaster.frag"); shader.loadShaders("Raycaster.vert", "PerVoxelRaycaster.frag"); shader.setVertexBuffer(cube::vertices, sizeof(cube::vertices), "positionAttribute"); uniformModelHandle= shader.getUniformHandle("uniformModel"); uniformViewHandle= shader.getUniformHandle("uniformView"); uniformProjectionHandle = shader.getUniformHandle("uniformProjection"); uniformCameraPositionHandle= shader.getUniformHandle("uniformCameraPosition"); uniformVolumeHandle= shader.getUniformHandle("uniformVolume"); uniformTransferfunctionHandle= shader.getUniformHandle("uniformTransferfunction"); shader.use(); // Initialize camera camera.init(glm::vec3(0.5f), glm::radians(-135.0f), glm::radians(80.0f), 2, 0.5f, 5); // Other initializations prevCursorX = cursorX; prevCursorY = cursorY; // Read volume const GLuint volumeX = 256; const GLuint volumeY = 256; const GLuint volumeZ = 256; GLuint voxelCount = volumeX * volumeY * volumeZ; GLubyte* volumeData = new GLubyte[voxelCount]; std::ifstream rawDataFile(std::string(RESOURCES_PATH) + "/bonsai.raw", std::ios::in|std::ios::binary); rawDataFile.read((GLchar*)volumeData, static_cast<GLuint>(voxelCount) * sizeof(GLubyte)); // Create volume 3D texture glGenTextures(1, &uniformVolume); glBindTexture(GL_TEXTURE_3D, uniformVolume); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage3D(GL_TEXTURE_3D, 0, GL_R8, volumeX, volumeY, volumeZ, 0, GL_RED, GL_UNSIGNED_BYTE, volumeData); glBindTexture(GL_TEXTURE_3D, 0); delete[] volumeData; // Set volume in shader shader.setUniformTexture(uniformVolumeHandle, uniformVolume, GL_TEXTURE_3D); // Read transfer function std::vector<GLubyte> transferfunction; unsigned long transferfunctionX; unsigned long transferfunctionY; std::ifstream in(std::string(std::string(RESOURCES_PATH) + "/Transferfunction.png").c_str(), std::ios::in|std::ios::binary); in.seekg(0, std::ios::end); std::streamsize size = in.tellg(); in.seekg(0, std::ios::beg); std::vector<GLchar> buffer(static_cast<GLuint>(size)); in.read(&(buffer[0]), static_cast<size_t>(size)); in.close(); decodePNG(transferfunction, transferfunctionX, transferfunctionY, reinterpret_cast<GLubyte*>(&(buffer[0])), static_cast<size_t>(size), GL_FALSE); // Create transfer function 1D texture glGenTextures(1, &uniformTransferfunction); glBindTexture(GL_TEXTURE_1D, uniformTransferfunction); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA8, transferfunctionX, 0, GL_RGBA, GL_UNSIGNED_BYTE, &transferfunction[0]); glBindTexture(GL_TEXTURE_1D, 0); // Set transfer function in shader shader.setUniformTexture(uniformTransferfunctionHandle, uniformTransferfunction, GL_TEXTURE_1D); // Loop while(!glfwWindowShouldClose(pWindow)) { // Clear buffers glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // Get window resolution GLint width, height; glfwGetWindowSize(pWindow, &width, &height); // Give OpenGL the window resolution if(width != prevWidth || height != prevHeight) { glViewport(0, 0, width, height); prevWidth = width; prevHeight = height; } // Calc time per frame GLfloat currentTime = (GLfloat)glfwGetTime(); deltaTime = currentTime - prevTime; prevTime = currentTime; std::cout << 1.0f / deltaTime << std::endl; // Calculate cursor movement cursorDeltaX = cursorX - prevCursorX; cursorDeltaY = cursorY - prevCursorY; prevCursorX = cursorX; prevCursorY = cursorY; // Model matrix uniformModel = glm::mat4(1.0f); // View matrix if(buttonPressed) { camera.setAlpha(camera.getAlpha() + 0.005f * cursorDeltaX); camera.setBeta(camera.getBeta() - 0.005f * cursorDeltaY); } uniformView = camera.getViewMatrix(); // Projection matrix uniformProjection = glm::perspective(glm::radians(30.f), ((GLfloat)width/(GLfloat)height), 0.1f, 100.f); // Set updated uniforms in shader shader.setUniformValue(uniformModelHandle, uniformModel); shader.setUniformValue(uniformViewHandle, uniformView); shader.setUniformValue(uniformProjectionHandle, uniformProjection); shader.setUniformValue(uniformCameraPositionHandle, camera.getPosition()); // Draw cube shader.draw(GL_TRIANGLES); // GLFW updates glfwSwapBuffers(pWindow); glfwPollEvents(); } // Clean up glfwDestroyWindow(pWindow); glfwTerminate(); return 0; }
int main(void) { int i; GLFWwindow* window; GLFWcursor* star_cursors[CURSOR_FRAME_COUNT]; glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); for (i = 0; i < CURSOR_FRAME_COUNT; i++) { star_cursors[i] = create_cursor_frame(i / (float) CURSOR_FRAME_COUNT); if (!star_cursors[i]) { glfwTerminate(); exit(EXIT_FAILURE); } } for (i = 0; i < sizeof(standard_cursors) / sizeof(standard_cursors[0]); i++) { const int shapes[] = { GLFW_ARROW_CURSOR, GLFW_IBEAM_CURSOR, GLFW_CROSSHAIR_CURSOR, GLFW_HAND_CURSOR, GLFW_HRESIZE_CURSOR, GLFW_VRESIZE_CURSOR }; standard_cursors[i] = glfwCreateStandardCursor(shapes[i]); if (!standard_cursors[i]) { glfwTerminate(); exit(EXIT_FAILURE); } } window = glfwCreateWindow(640, 480, "Cursor Test", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glfwGetCursorPos(window, &cursor_x, &cursor_y); printf("Cursor position: %f %f\n", cursor_x, cursor_y); glfwSetCursorPosCallback(window, cursor_position_callback); glfwSetKeyCallback(window, key_callback); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT); if (track_cursor) { int wnd_width, wnd_height, fb_width, fb_height; float scale; glfwGetWindowSize(window, &wnd_width, &wnd_height); glfwGetFramebufferSize(window, &fb_width, &fb_height); scale = (float) fb_width / (float) wnd_width; glViewport(0, 0, fb_width, fb_height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.f, fb_width, 0.f, fb_height, 0.f, 1.f); glBegin(GL_LINES); glVertex2f(0.f, (GLfloat) (fb_height - cursor_y * scale)); glVertex2f((GLfloat) fb_width, (GLfloat) (fb_height - cursor_y * scale)); glVertex2f((GLfloat) cursor_x * scale, 0.f); glVertex2f((GLfloat) cursor_x * scale, (GLfloat) fb_height); glEnd(); } glfwSwapBuffers(window); if (animate_cursor) { const int i = (int) (glfwGetTime() * 30.0) % CURSOR_FRAME_COUNT; glfwSetCursor(window, star_cursors[i]); } if (wait_events) glfwWaitEvents(); else glfwPollEvents(); // Workaround for an issue with msvcrt and mintty fflush(stdout); } glfwDestroyWindow(window); for (i = 0; i < CURSOR_FRAME_COUNT; i++) glfwDestroyCursor(star_cursors[i]); for (i = 0; i < sizeof(standard_cursors) / sizeof(standard_cursors[0]); i++) glfwDestroyCursor(standard_cursors[i]); glfwTerminate(); exit(EXIT_SUCCESS); }
void PullInfo(){ printf("================================================================================\n"); int major, minor, rev; glfwGetVersion(&major, &minor, &rev); printf("GLFW version is %i.%i.%i\n", major, minor, rev); int width, height; glfwGetWindowSize(&width, &height); printf("Window size is %i %i\n", width, height); int status = glfwGetKey(GLFW_KEY_LCTRL); if(status == GLFW_PRESS) printf("Left control is pressed\n"); else printf("Left control is released\n"); status = glfwGetMouseButton(GLFW_MOUSE_BUTTON_1); if(status == GLFW_PRESS) printf("Mouse button 1 is pressed\n"); else printf("Mouse button 1 is released\n"); int x, y; glfwGetMousePos(&x, &y); printf("Mouse position is %i %i\n", x, y); int wheel = glfwGetMouseWheel(); printf("Mouse wheel pos is %i\n", wheel); double time = glfwGetTime(); printf("Time is %f\n", time); glfwGetGLVersion(&major, &minor, &rev); printf("GL version is %i.%i.%i\n", major, minor, rev); int proc = glfwGetNumberOfProcessors(); printf("%i processors are available\n", proc); unsigned int i; for(i = 0; i<nb_params; i++) printf(" - %-27s : %i\n", GetParamName(params[i]), glfwGetWindowParam(params[i])); const char* extension = "MOZ_WEBGL_compressed_texture_s3tc"; printf("'%s' extension is %s.\n", extension, glfwExtensionSupported(extension) ? "supported" : "not supported"); extension = "GL_EXT_framebuffer_object"; printf("'%s' extension is %s.\n", extension, glfwExtensionSupported(extension) ? "supported" : "not supported"); extension = "glBindBuffer"; void* proc_addr = glfwGetProcAddress(extension); printf("'%s' extension proc address is %p.\n", extension, proc_addr); printf("Sleeping 1 sec...\n"); glfwSleep(1); printf("...Done.\n"); printf("================================================================================\n"); #ifdef REPORT_RESULT int result = 1; REPORT_RESULT(); #endif }