int main(int argc, char *argv[]) { Uint32 flags; SDL_Surface *screen, *image; int i, depth, done; SDL_Event event; SDL_RWops* rw_ops; /* Check command line usage */ if ( ! argv[1] ) { fprintf(stderr, "Usage: %s <image_file>\n", argv[0]); return(1); } /* Initialize the SDL library */ if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) { fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError()); return(255); } flags = SDL_SWSURFACE; for ( i=1; argv[i]; ++i ) { if ( strcmp(argv[i], "-fullscreen") == 0 ) { SDL_ShowCursor(0); flags |= SDL_FULLSCREEN; continue; } #if 0 rw_ops = SDL_RWFromFile(argv[1], "r"); fprintf(stderr, "BMP:\t%d\n", IMG_isBMP(rw_ops)); fprintf(stderr, "GIF:\t%d\n", IMG_isGIF(rw_ops)); fprintf(stderr, "JPG:\t%d\n", IMG_isJPG(rw_ops)); fprintf(stderr, "PNG:\t%d\n", IMG_isPNG(rw_ops)); fprintf(stderr, "TIF:\t%d\n", IMG_isTIF(rw_ops)); /* fprintf(stderr, "TGA:\t%d\n", IMG_isTGA(rw_ops)); */ fprintf(stderr, "PCX:\t%d\n", IMG_isPCX(rw_ops)); #endif /* Open the image file */ #ifdef XPM_INCLUDED image = IMG_ReadXPMFromArray(picture_xpm); #else image = IMG_Load(argv[i]); #endif if ( image == NULL ) { fprintf(stderr, "Couldn't load %s: %s\n", argv[i], SDL_GetError()); continue; } SDL_WM_SetCaption(argv[i], "showimage"); /* Create a display for the image */ depth = SDL_VideoModeOK(image->w, image->h, 32, flags); /* Use the deepest native mode, except that we emulate 32bpp for viewing non-indexed images on 8bpp screens */ if ( depth == 0 ) { if ( image->format->BytesPerPixel > 1 ) { depth = 32; } else { depth = 8; } } else if ( (image->format->BytesPerPixel > 1) && (depth == 8) ) { depth = 32; } if(depth == 8) flags |= SDL_HWPALETTE; screen = SDL_SetVideoMode(image->w, image->h, depth, flags); if ( screen == NULL ) { fprintf(stderr,"Couldn't set %dx%dx%d video mode: %s\n", image->w, image->h, depth, SDL_GetError()); continue; } /* Set the palette, if one exists */ if ( image->format->palette ) { SDL_SetColors(screen, image->format->palette->colors, 0, image->format->palette->ncolors); } /* Draw a background pattern if the surface has transparency */ if(image->flags & (SDL_SRCALPHA | SDL_SRCCOLORKEY)) draw_background(screen); /* Display the image */ SDL_BlitSurface(image, NULL, screen, NULL); SDL_UpdateRect(screen, 0, 0, 0, 0); done = 0; while ( ! done ) { if ( SDL_PollEvent(&event) ) { switch (event.type) { case SDL_KEYUP: switch (event.key.keysym.sym) { case SDLK_LEFT: if ( i > 1 ) { i -= 2; done = 1; } break; case SDLK_RIGHT: if ( argv[i+1] ) { done = 1; } break; case SDLK_ESCAPE: case SDLK_q: argv[i+1] = NULL; /* Drop through to done */ case SDLK_SPACE: case SDLK_TAB: done = 1; break; default: break; } break; case SDL_MOUSEBUTTONDOWN: done = 1; break; case SDL_QUIT: argv[i+1] = NULL; done = 1; break; default: break; } } else { SDL_Delay(10); } } SDL_FreeSurface(image); } /* We're done! */ SDL_Quit(); return(0); }
/* =============== GLimp_SetMode =============== */ static int GLimp_SetMode(int mode, qboolean fullscreen, qboolean noborder) { const char* glstring; int sdlcolorbits; int colorbits, depthbits, stencilbits; int tcolorbits, tdepthbits, tstencilbits; int samples; int i = 0; SDL_Surface *vidscreen = NULL; Uint32 flags = SDL_OPENGL; ri.Printf( PRINT_ALL, "Initializing OpenGL display\n"); if ( r_allowResize->integer ) flags |= SDL_RESIZABLE; if( videoInfo == NULL ) { static SDL_VideoInfo sVideoInfo; static SDL_PixelFormat sPixelFormat; videoInfo = SDL_GetVideoInfo( ); // Take a copy of the videoInfo Com_Memcpy( &sPixelFormat, videoInfo->vfmt, sizeof( SDL_PixelFormat ) ); sPixelFormat.palette = NULL; // Should already be the case Com_Memcpy( &sVideoInfo, videoInfo, sizeof( SDL_VideoInfo ) ); sVideoInfo.vfmt = &sPixelFormat; videoInfo = &sVideoInfo; if( videoInfo->current_h > 0 ) { // Guess the display aspect ratio through the desktop resolution // by assuming (relatively safely) that it is set at or close to // the display's native aspect ratio displayAspect = (float)videoInfo->current_w / (float)videoInfo->current_h; ri.Printf( PRINT_ALL, "Estimated display aspect: %.3f\n", displayAspect ); } else { ri.Printf( PRINT_ALL, "Cannot estimate display aspect, assuming 1.333\n" ); } } ri.Printf (PRINT_ALL, "...setting mode %d:", mode ); if ( !R_GetModeInfo( &glConfig.vidWidth, &glConfig.vidHeight, &glConfig.windowAspect, mode ) ) { ri.Printf( PRINT_ALL, " invalid mode\n" ); return RSERR_INVALID_MODE; } ri.Printf( PRINT_ALL, " %d %d\n", glConfig.vidWidth, glConfig.vidHeight); if (fullscreen) { flags |= SDL_FULLSCREEN; glConfig.isFullscreen = qtrue; } else { if (noborder) flags |= SDL_NOFRAME; glConfig.isFullscreen = qfalse; } colorbits = r_colorbits->value; if ((!colorbits) || (colorbits >= 32)) colorbits = 24; if (!r_depthbits->value) depthbits = 24; else depthbits = r_depthbits->value; stencilbits = r_stencilbits->value; samples = r_ext_multisample->value; for (i = 0; i < 16; i++) { // 0 - default // 1 - minus colorbits // 2 - minus depthbits // 3 - minus stencil if ((i % 4) == 0 && i) { // one pass, reduce switch (i / 4) { case 2 : if (colorbits == 24) colorbits = 16; break; case 1 : if (depthbits == 24) depthbits = 16; else if (depthbits == 16) depthbits = 8; case 3 : if (stencilbits == 24) stencilbits = 16; else if (stencilbits == 16) stencilbits = 8; } } tcolorbits = colorbits; tdepthbits = depthbits; tstencilbits = stencilbits; if ((i % 4) == 3) { // reduce colorbits if (tcolorbits == 24) tcolorbits = 16; } if ((i % 4) == 2) { // reduce depthbits if (tdepthbits == 24) tdepthbits = 16; else if (tdepthbits == 16) tdepthbits = 8; } if ((i % 4) == 1) { // reduce stencilbits if (tstencilbits == 24) tstencilbits = 16; else if (tstencilbits == 16) tstencilbits = 8; else tstencilbits = 0; } sdlcolorbits = 4; if (tcolorbits == 24) sdlcolorbits = 8; #ifdef __sgi /* Fix for SGIs grabbing too many bits of color */ if (sdlcolorbits == 4) sdlcolorbits = 0; /* Use minimum size for 16-bit color */ /* Need alpha or else SGIs choose 36+ bit RGB mode */ SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 1); #endif SDL_GL_SetAttribute( SDL_GL_RED_SIZE, sdlcolorbits ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, sdlcolorbits ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, sdlcolorbits ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, tdepthbits ); SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, tstencilbits ); if( haveMultiSample ) { SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, samples ? 1 : 0 ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, samples ); } if(r_stereoEnabled->integer) { glConfig.stereoEnabled = ( SDL_GL_SetAttribute(SDL_GL_STEREO, 1) == 0 ); } else { glConfig.stereoEnabled = qfalse; SDL_GL_SetAttribute(SDL_GL_STEREO, 0); } SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); #if 0 // See http://bugzilla.icculus.org/show_bug.cgi?id=3526 // If not allowing software GL, demand accelerated if( !r_allowSoftwareGL->integer ) { if( SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 ) < 0 ) { ri.Printf( PRINT_ALL, "Unable to guarantee accelerated " "visual with libSDL < 1.2.10\n" ); } } #endif if( SDL_GL_SetAttribute( SDL_GL_SWAP_CONTROL, r_swapInterval->integer ) < 0 ) ri.Printf( PRINT_ALL, "r_swapInterval requires libSDL >= 1.2.10\n" ); #ifdef USE_ICON { SDL_Surface *icon = SDL_CreateRGBSurfaceFrom( (void *)CLIENT_WINDOW_ICON.pixel_data, CLIENT_WINDOW_ICON.width, CLIENT_WINDOW_ICON.height, CLIENT_WINDOW_ICON.bytes_per_pixel * 8, CLIENT_WINDOW_ICON.bytes_per_pixel * CLIENT_WINDOW_ICON.width, #ifdef Q3_LITTLE_ENDIAN 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 #else 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF #endif ); SDL_WM_SetIcon( icon, NULL ); SDL_FreeSurface( icon ); } #endif SDL_WM_SetCaption(CLIENT_WINDOW_TITLE, CLIENT_WINDOW_MIN_TITLE); SDL_ShowCursor(0); if (!(vidscreen = SDL_SetVideoMode(glConfig.vidWidth, glConfig.vidHeight, colorbits, flags))) { ri.Printf( PRINT_DEVELOPER, "SDL_SetVideoMode failed: %s\n", SDL_GetError( ) ); continue; } opengl_context = GLimp_GetCurrentContext(); ri.Printf( PRINT_ALL, "Using %d/%d/%d Color bits, %d depth, %d stencil display.\n", sdlcolorbits, sdlcolorbits, sdlcolorbits, tdepthbits, tstencilbits); glConfig.colorBits = tcolorbits; glConfig.depthBits = tdepthbits; glConfig.stencilBits = tstencilbits; break; } GLimp_DetectAvailableModes(); if (!vidscreen) { ri.Printf( PRINT_ALL, "Couldn't get a visual\n" ); return RSERR_INVALID_MODE; } screen = vidscreen; glstring = (char *) qglGetString (GL_RENDERER); ri.Printf( PRINT_ALL, "GL_RENDERER: %s\n", glstring ); return RSERR_OK; }
/** * Attempts to initialize the graphical video display. Returns 0 on * success, -1 on failure. */ int InitVideo(FCEUGI *gi) { // XXX soules - const? is this necessary? const SDL_VideoInfo *vinf; int error, flags = 0; int doublebuf, xstretch, ystretch, xres, yres; FCEUI_printf("Initializing video..."); // load the relevant configuration variables g_config->getOption("SDL.Fullscreen", &s_fullscreen); g_config->getOption("SDL.DoubleBuffering", &doublebuf); #ifdef OPENGL g_config->getOption("SDL.OpenGL", &s_useOpenGL); #endif g_config->getOption("SDL.SpecialFilter", &s_sponge); g_config->getOption("SDL.XStretch", &xstretch); g_config->getOption("SDL.YStretch", &ystretch); g_config->getOption("SDL.XResolution", &xres); g_config->getOption("SDL.YResolution", &yres); g_config->getOption("SDL.ClipSides", &s_clipSides); g_config->getOption("SDL.NoFrame", &noframe); // check the starting, ending, and total scan lines FCEUI_GetCurrentVidSystem(&s_srendline, &s_erendline); s_tlines = s_erendline - s_srendline + 1; // check for OpenGL and set the global flags #if OPENGL if(s_useOpenGL && !s_sponge) { flags = SDL_OPENGL; } #endif // initialize the SDL video subsystem if it is not already active if(!SDL_WasInit(SDL_INIT_VIDEO)) { error = SDL_InitSubSystem(SDL_INIT_VIDEO); if(error) { FCEUD_PrintError(SDL_GetError()); return -1; } } s_inited = 1; // shows the cursor within the display window SDL_ShowCursor(1); // determine if we can allocate the display on the video card vinf = SDL_GetVideoInfo(); if(vinf->hw_available) { flags |= SDL_HWSURFACE; } // check if we are rendering fullscreen if(s_fullscreen) { flags |= SDL_FULLSCREEN; SDL_ShowCursor(0); } else { SDL_ShowCursor(1); } if(noframe) { flags |= SDL_NOFRAME; } // gives the SDL exclusive palette control... ensures the requested colors flags |= SDL_HWPALETTE; // enable double buffering if requested and we have hardware support #ifdef OPENGL if(s_useOpenGL) { FCEU_printf("Initializing with OpenGL (Disable with '-opengl 0').\n"); if(doublebuf) { SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); } } else #endif if(doublebuf && (flags & SDL_HWSURFACE)) { flags |= SDL_DOUBLEBUF; } if(s_fullscreen) { int desbpp, autoscale; g_config->getOption("SDL.BitsPerPixel", &desbpp); g_config->getOption("SDL.AutoScale", &autoscale); if (autoscale) { double auto_xscale = GetXScale(xres); double auto_yscale = GetYScale(yres); double native_ratio = ((double)NWIDTH) / s_tlines; double screen_ratio = ((double)xres) / yres; int keep_ratio; g_config->getOption("SDL.KeepRatio", &keep_ratio); // Try to choose resolution if (screen_ratio < native_ratio) { // The screen is narrower than the original. Maximizing width will not clip auto_xscale = auto_yscale = GetXScale(xres); if (keep_ratio) auto_yscale = GetYScale(yres); } else { auto_yscale = auto_xscale = GetYScale(yres); if (keep_ratio) auto_xscale = GetXScale(xres); } s_exs = auto_xscale; s_eys = auto_yscale; } else { g_config->getOption("SDL.XScale", &s_exs); g_config->getOption("SDL.YScale", &s_eys); } g_config->getOption("SDL.SpecialFX", &s_eefx); #ifdef OPENGL if(!s_useOpenGL) { s_exs = (int)s_exs; s_eys = (int)s_eys; } else { desbpp = 0; } // -Video Modes Tag- if(s_sponge) { if(s_sponge == 4 || s_sponge == 5) { s_exs = s_eys = 3; } else { s_exs = s_eys = 2; } s_eefx = 0; if(s_sponge == 1 || s_sponge == 4) { desbpp = 32; } } if((s_useOpenGL && !xstretch) || !s_useOpenGL) #endif if(xres < (NWIDTH * s_exs) || s_exs <= 0.01) { FCEUD_PrintError("xscale out of bounds."); KillVideo(); return -1; } #ifdef OPENGL if((s_useOpenGL && !ystretch) || !s_useOpenGL) #endif if(yres < s_tlines * s_eys || s_eys <= 0.01) { FCEUD_PrintError("yscale out of bounds."); KillVideo(); return -1; } s_screen = SDL_SetVideoMode(xres, yres, desbpp, flags); if(!s_screen) { FCEUD_PrintError(SDL_GetError()); return -1; } } else { int desbpp; g_config->getOption("SDL.BitsPerPixel", &desbpp); g_config->getOption("SDL.XScale", &s_exs); g_config->getOption("SDL.YScale", &s_eys); g_config->getOption("SDL.SpecialFX", &s_eefx); // -Video Modes Tag- if(s_sponge) { if(s_sponge >= 4) { s_exs = s_eys = 3; } else { s_exs = s_eys = 2; } s_eefx = 0; } #ifdef OPENGL if(!s_useOpenGL) { s_exs = (int)s_exs; s_eys = (int)s_eys; } if(s_exs <= 0.01) { FCEUD_PrintError("xscale out of bounds."); KillVideo(); return -1; } if(s_eys <= 0.01) { FCEUD_PrintError("yscale out of bounds."); KillVideo(); return -1; } if(s_sponge && s_useOpenGL) { FCEUD_PrintError("scalers not compatible with openGL mode."); KillVideo(); return -1; } #endif s_screen = SDL_SetVideoMode((int)(NWIDTH * s_exs), (int)(s_tlines * s_eys), desbpp, flags); if(!s_screen) { FCEUD_PrintError(SDL_GetError()); return -1; } } s_curbpp = s_screen->format->BitsPerPixel; if(!s_screen) { FCEUD_PrintError(SDL_GetError()); KillVideo(); return -1; } #if 0 // XXX soules - this would be creating a surface on the video // card, but was commented out for some reason... s_BlitBuf = SDL_CreateRGBSurface(SDL_HWSURFACE, 256, 240, s_screen->format->BitsPerPixel, s_screen->format->Rmask, s_screen->format->Gmask, s_screen->format->Bmask, 0); #endif FCEU_printf(" Video Mode: %d x %d x %d bpp %s\n", s_screen->w, s_screen->h, s_screen->format->BitsPerPixel, s_fullscreen ? "full screen" : ""); if(s_curbpp != 8 && s_curbpp != 16 && s_curbpp != 24 && s_curbpp != 32) { FCEU_printf(" Sorry, %dbpp modes are not supported by FCE Ultra. Supported bit depths are 8bpp, 16bpp, and 32bpp.\n", s_curbpp); KillVideo(); return -1; } // if the game being run has a name, set it as the window name if(gi->name) { SDL_WM_SetCaption((const char *)gi->name, (const char *)gi->name); } else { SDL_WM_SetCaption(FCEU_NAME_AND_VERSION,"FCE Ultra"); } // create the surface for displaying graphical messages #ifdef LSB_FIRST s_IconSurface = SDL_CreateRGBSurfaceFrom((void *)fceu_playicon.pixel_data, 32, 32, 24, 32 * 3, 0xFF, 0xFF00, 0xFF0000, 0x00); #else s_IconSurface = SDL_CreateRGBSurfaceFrom((void *)fceu_playicon.pixel_data, 32, 32, 24, 32 * 3, 0xFF0000, 0xFF00, 0xFF, 0x00); #endif SDL_WM_SetIcon(s_IconSurface,0); s_paletterefresh = 1; // XXX soules - can't SDL do this for us? // if using more than 8bpp, initialize the conversion routines if(s_curbpp > 8) { InitBlitToHigh(s_curbpp >> 3, s_screen->format->Rmask, s_screen->format->Gmask, s_screen->format->Bmask, s_eefx, s_sponge, 0); #ifdef OPENGL if(s_useOpenGL) { int openGLip; g_config->getOption("SDL.OpenGLip", &openGLip); if(!InitOpenGL(NOFFSET, 256 - (s_clipSides ? 8 : 0), s_srendline, s_erendline + 1, s_exs, s_eys, s_eefx, openGLip, xstretch, ystretch, s_screen)) { FCEUD_PrintError("Error initializing OpenGL."); KillVideo(); return -1; } } #endif }
Gource::Gource(FrameExporter* exporter) { this->logfile = gGourceSettings.path; commitlog = 0; fontlarge = fontmanager.grab("FreeSans.ttf", 42); fontlarge.dropShadow(true); fontlarge.roundCoordinates(true); fontmedium = fontmanager.grab("FreeSans.ttf", gGourceSettings.font_size); fontmedium.dropShadow(true); fontmedium.roundCoordinates(false); font = fontmanager.grab("FreeSans.ttf", 14); font.dropShadow(true); font.roundCoordinates(true); bloomtex = texturemanager.grab("bloom.tga"); beamtex = texturemanager.grab("beam.png"); logotex = 0; backgroundtex = 0; //load logo if(gGourceSettings.logo.size() > 0) { logotex = texturemanager.grabFile(gGourceSettings.logo); } //load background image if(gGourceSettings.background_image.size() > 0) { backgroundtex = texturemanager.grabFile(gGourceSettings.background_image); } stop_position_reached=false; paused = false; first_read = true; draw_loading = true; mousemoved = false; mousedragged = false; mouseclicked = false; if(gGourceSettings.hide_mouse) { SDL_ShowCursor(false); } splash = -1.0; debug = false; trace_debug = false; frameExporter = 0; dirNodeTree = 0; userTree = 0; selectedFile = 0; hoverFile = 0; selectedUser = 0; hoverUser = 0; date_x_offset = 0; camera = ZoomCamera(vec3f(0,0, -300), vec3f(0.0, 0.0, 0.0), 250.0, 5000.0); setCameraMode(gGourceSettings.camera_mode); root = 0; //min phsyics rate 60fps (ie maximum allowed delta 1.0/60) max_tick_rate = 1.0 / 60.0; runtime = 0.0f; frameskip = 0; framecount = 0; reset(); if(exporter!=0) setFrameExporter(exporter, gGourceSettings.output_framerate); //if recording a video or in demo mode, or multiple repos, the slider is initially hidden if(exporter==0 && gGourceSettings.repo_count==1) slider.show(); }
void Gource::keyPress(SDL_KeyboardEvent *e) { if (e->type == SDL_KEYUP) return; if (e->type == SDL_KEYDOWN) { if (e->keysym.unicode == SDLK_ESCAPE) { appFinished=true; } if(commitlog==0) return; if(e->keysym.sym == SDLK_F12) { screenshot(); } if (e->keysym.sym == SDLK_q) { debug = !debug; } if (e->keysym.sym == SDLK_w) { trace_debug = !trace_debug; } if (e->keysym.sym == SDLK_m) { Uint8 ms = SDL_GetMouseState(0,0); //toggle mouse visiblity unless mouse clicked/pressed/dragged if(!(mousedragged || mouseclicked || ms & SDL_BUTTON(SDL_BUTTON_LEFT))) { if(SDL_ShowCursor(SDL_QUERY) == SDL_ENABLE) { SDL_ShowCursor(false); gGourceSettings.hide_mouse = true; } else { SDL_ShowCursor(true); gGourceSettings.hide_mouse = false; } } } if (e->keysym.sym == SDLK_n) { idle_time = gGourceSettings.auto_skip_seconds; } if (e->keysym.sym == SDLK_t) { gGourceQuadTreeDebug = !gGourceQuadTreeDebug; } if (e->keysym.sym == SDLK_g) { gGourceSettings.hide_users = !gGourceSettings.hide_users; } if (e->keysym.sym == SDLK_u) { gGourceSettings.hide_usernames = !gGourceSettings.hide_usernames; } if (e->keysym.sym == SDLK_d) { gGourceSettings.hide_dirnames = ! gGourceSettings.hide_dirnames; } if (e->keysym.sym == SDLK_f) { gGourceSettings.hide_filenames = !gGourceSettings.hide_filenames; } if(e->keysym.sym == SDLK_c) { splash = 15.0f; } if (e->keysym.sym == SDLK_v) { toggleCameraMode(); } if (e->keysym.sym == SDLK_z) { gGourceGravity = !gGourceGravity; } if(e->keysym.unicode == SDLK_TAB) { selectNextUser(); } if (e->keysym.unicode == SDLK_SPACE) { paused = !paused; } if (e->keysym.unicode == SDLK_EQUALS || e->keysym.unicode == SDLK_PLUS) { if(gGourceSettings.days_per_second>=1.0) { gGourceSettings.days_per_second = std::min(30.0f, floorf(gGourceSettings.days_per_second) + 1.0f); } else { gGourceSettings.days_per_second = std::min(1.0f, gGourceSettings.days_per_second * 2.0f); } } if (e->keysym.unicode == SDLK_MINUS) { if(gGourceSettings.days_per_second>1.0) { gGourceSettings.days_per_second = std::max(0.0f, floorf(gGourceSettings.days_per_second) - 1.0f); } else { gGourceSettings.days_per_second = std::max(0.0f, gGourceSettings.days_per_second * 0.5f); } } if(e->keysym.sym == SDLK_UP) { zoom(true); } if(e->keysym.sym == SDLK_DOWN) { zoom(false); } if(e->keysym.unicode == SDLK_LEFTBRACKET) { gGourceForceGravity /= 1.1; } if(e->keysym.unicode == SDLK_RIGHTBRACKET) { gGourceForceGravity *= 1.1; } if(e->keysym.unicode == SDLK_PERIOD) { if(time_scale>=1.0) { time_scale = std::min(4.0f, floorf(time_scale) + 1.0f); } else { time_scale = std::min(1.0f, time_scale * 2.0f); } } if(e->keysym.unicode == SDLK_COMMA) { if(time_scale>1.0) { time_scale = std::max(0.0f, floorf(time_scale) - 1.0f); } else { time_scale = std::max(0.25f, time_scale * 0.5f); } } if(e->keysym.unicode == SDLK_SLASH) { time_scale = 1.0f; } } }
//Enable / Disable cursor image void M_Input::EnableCursorImage() { SDL_ShowCursor(SDL_ENABLE); }
int main(int argc, char *argv[]) { #if PPSSPP_PLATFORM(RPI) bcm_host_init(); #endif putenv((char*)"SDL_VIDEO_CENTERED=1"); SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0"); std::string app_name; std::string app_name_nice; std::string version; bool landscape; NativeGetAppInfo(&app_name, &app_name_nice, &landscape, &version); bool joystick_enabled = true; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_AUDIO) < 0) { joystick_enabled = false; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) { fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError()); return 1; } } #ifdef __APPLE__ // Make sure to request a somewhat modern GL context at least - the // latest supported by MacOSX (really, really sad...) // Requires SDL 2.0 // We really should upgrade to SDL 2.0 soon. //SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); #endif #ifdef USING_EGL if (EGL_Open()) return 1; #endif // Get the video info before doing anything else, so we don't get skewed resolution results. // TODO: support multiple displays correctly SDL_DisplayMode displayMode; int should_be_zero = SDL_GetCurrentDisplayMode(0, &displayMode); if (should_be_zero != 0) { fprintf(stderr, "Could not get display mode: %s\n", SDL_GetError()); return 1; } g_DesktopWidth = displayMode.w; g_DesktopHeight = displayMode.h; SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetSwapInterval(1); Uint32 mode; #ifdef USING_GLES2 mode = SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN; #else mode = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE; #endif int set_xres = -1; int set_yres = -1; bool portrait = false; bool set_ipad = false; float set_dpi = 1.0f; float set_scale = 1.0f; // Produce a new set of arguments with the ones we skip. int remain_argc = 1; const char *remain_argv[256] = { argv[0] }; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i],"--fullscreen")) mode |= SDL_WINDOW_FULLSCREEN_DESKTOP; else if (set_xres == -2) set_xres = parseInt(argv[i]); else if (set_yres == -2) set_yres = parseInt(argv[i]); else if (set_dpi == -2) set_dpi = parseFloat(argv[i]); else if (set_scale == -2) set_scale = parseFloat(argv[i]); else if (!strcmp(argv[i],"--xres")) set_xres = -2; else if (!strcmp(argv[i],"--yres")) set_yres = -2; else if (!strcmp(argv[i],"--dpi")) set_dpi = -2; else if (!strcmp(argv[i],"--scale")) set_scale = -2; else if (!strcmp(argv[i],"--ipad")) set_ipad = true; else if (!strcmp(argv[i],"--portrait")) portrait = true; else { remain_argv[remain_argc++] = argv[i]; } } // Is resolution is too low to run windowed if (g_DesktopWidth < 480 * 2 && g_DesktopHeight < 272 * 2) { mode |= SDL_WINDOW_FULLSCREEN_DESKTOP; } if (mode & SDL_WINDOW_FULLSCREEN_DESKTOP) { pixel_xres = g_DesktopWidth; pixel_yres = g_DesktopHeight; g_Config.bFullScreen = true; } else { // set a sensible default resolution (2x) pixel_xres = 480 * 2 * set_scale; pixel_yres = 272 * 2 * set_scale; if (portrait) { std::swap(pixel_xres, pixel_yres); } g_Config.bFullScreen = false; } set_dpi = 1.0f / set_dpi; if (set_ipad) { pixel_xres = 1024; pixel_yres = 768; } if (!landscape) { std::swap(pixel_xres, pixel_yres); } if (set_xres > 0) { pixel_xres = set_xres; } if (set_yres > 0) { pixel_yres = set_yres; } float dpi_scale = 1.0f; if (set_dpi > 0) { dpi_scale = set_dpi; } dp_xres = (float)pixel_xres * dpi_scale; dp_yres = (float)pixel_yres * dpi_scale; #ifdef _MSC_VER // VFSRegister("temp/", new DirectoryAssetReader("E:\\Temp\\")); TCHAR path[MAX_PATH]; SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, path); PathAppend(path, (app_name + "\\").c_str()); #else // Mac / Linux char path[2048]; const char *the_path = getenv("HOME"); if (!the_path) { struct passwd* pwd = getpwuid(getuid()); if (pwd) the_path = pwd->pw_dir; } strcpy(path, the_path); if (path[strlen(path)-1] != '/') strcat(path, "/"); #endif #ifdef _WIN32 NativeInit(remain_argc, (const char **)remain_argv, path, "D:\\", nullptr); #else NativeInit(remain_argc, (const char **)remain_argv, path, "/tmp", nullptr); #endif // Use the setting from the config when initing the window. if (g_Config.bFullScreen) mode |= SDL_WINDOW_FULLSCREEN_DESKTOP; g_Screen = SDL_CreateWindow(app_name_nice.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(getDisplayNumber()),\ SDL_WINDOWPOS_UNDEFINED, pixel_xres, pixel_yres, mode); if (g_Screen == NULL) { NativeShutdown(); fprintf(stderr, "SDL_CreateWindow failed: %s\n", SDL_GetError()); SDL_Quit(); return 2; } SDL_GLContext glContext = SDL_GL_CreateContext(g_Screen); if (glContext == NULL) { NativeShutdown(); fprintf(stderr, "SDL_GL_CreateContext failed: %s\n", SDL_GetError()); SDL_Quit(); return 2; } #ifdef USING_EGL EGL_Init(); #endif SDL_SetWindowTitle(g_Screen, (app_name_nice + " " + PPSSPP_GIT_VERSION).c_str()); #ifdef MOBILE_DEVICE SDL_ShowCursor(SDL_DISABLE); #endif #ifndef USING_GLES2 // Some core profile drivers elide certain extensions from GL_EXTENSIONS/etc. // glewExperimental allows us to force GLEW to search for the pointers anyway. if (gl_extensions.IsCoreContext) glewExperimental = true; if (GLEW_OK != glewInit()) { printf("Failed to initialize glew!\n"); return 1; } // Unfortunately, glew will generate an invalid enum error, ignore. if (gl_extensions.IsCoreContext) glGetError(); if (GLEW_VERSION_2_0) { printf("OpenGL 2.0 or higher.\n"); } else { printf("Sorry, this program requires OpenGL 2.0.\n"); return 1; } #endif pixel_in_dps_x = (float)pixel_xres / dp_xres; pixel_in_dps_y = (float)pixel_yres / dp_yres; g_dpi_scale_x = dp_xres / (float)pixel_xres; g_dpi_scale_y = dp_yres / (float)pixel_yres; g_dpi_scale_real_x = g_dpi_scale_x; g_dpi_scale_real_y = g_dpi_scale_y; printf("Pixels: %i x %i\n", pixel_xres, pixel_yres); printf("Virtual pixels: %i x %i\n", dp_xres, dp_yres); GraphicsContext *graphicsContext = new GLDummyGraphicsContext(); NativeInitGraphics(graphicsContext); NativeResized(); SDL_AudioSpec fmt, ret_fmt; memset(&fmt, 0, sizeof(fmt)); fmt.freq = 44100; fmt.format = AUDIO_S16; fmt.channels = 2; fmt.samples = 2048; fmt.callback = &mixaudio; fmt.userdata = (void *)0; if (SDL_OpenAudio(&fmt, &ret_fmt) < 0) { ELOG("Failed to open audio: %s", SDL_GetError()); } else { if (ret_fmt.samples != fmt.samples) // Notify, but still use it ELOG("Output audio samples: %d (requested: %d)", ret_fmt.samples, fmt.samples); if (ret_fmt.freq != fmt.freq || ret_fmt.format != fmt.format || ret_fmt.channels != fmt.channels) { ELOG("Sound buffer format does not match requested format."); ELOG("Output audio freq: %d (requested: %d)", ret_fmt.freq, fmt.freq); ELOG("Output audio format: %d (requested: %d)", ret_fmt.format, fmt.format); ELOG("Output audio channels: %d (requested: %d)", ret_fmt.channels, fmt.channels); ELOG("Provided output format does not match requirement, turning audio off"); SDL_CloseAudio(); } } // Audio must be unpaused _after_ NativeInit() SDL_PauseAudio(0); #ifndef _WIN32 if (joystick_enabled) { joystick = new SDLJoystick(); } else { joystick = nullptr; } #endif EnableFZ(); int framecount = 0; float t = 0; float lastT = 0; bool mouseDown = false; while (true) { SDL_Event event; while (SDL_PollEvent(&event)) { float mx = event.motion.x * g_dpi_scale_x; float my = event.motion.y * g_dpi_scale_y; switch (event.type) { case SDL_QUIT: g_QuitRequested = 1; break; #if !defined(MOBILE_DEVICE) case SDL_WINDOWEVENT: switch (event.window.event) { case SDL_WINDOWEVENT_RESIZED: { Uint32 window_flags = SDL_GetWindowFlags(g_Screen); bool fullscreen = (window_flags & SDL_WINDOW_FULLSCREEN); pixel_xres = event.window.data1; pixel_yres = event.window.data2; dp_xres = (float)pixel_xres * dpi_scale; dp_yres = (float)pixel_yres * dpi_scale; NativeResized(); // Set variable here in case fullscreen was toggled by hotkey g_Config.bFullScreen = fullscreen; // Hide/Show cursor correctly toggling fullscreen if (lastUIState == UISTATE_INGAME && fullscreen && !g_Config.bShowTouchControls) { SDL_ShowCursor(SDL_DISABLE); } else if (lastUIState != UISTATE_INGAME || !fullscreen) { SDL_ShowCursor(SDL_ENABLE); } break; } default: break; } break; #endif case SDL_KEYDOWN: { if (event.key.repeat > 0) { break;} int k = event.key.keysym.sym; KeyInput key; key.flags = KEY_DOWN; auto mapped = KeyMapRawSDLtoNative.find(k); if (mapped == KeyMapRawSDLtoNative.end() || mapped->second == NKCODE_UNKNOWN) { break; } key.keyCode = mapped->second; key.deviceId = DEVICE_ID_KEYBOARD; NativeKey(key); break; } case SDL_KEYUP: { if (event.key.repeat > 0) { break;} int k = event.key.keysym.sym; KeyInput key; key.flags = KEY_UP; auto mapped = KeyMapRawSDLtoNative.find(k); if (mapped == KeyMapRawSDLtoNative.end() || mapped->second == NKCODE_UNKNOWN) { break; } key.keyCode = mapped->second; key.deviceId = DEVICE_ID_KEYBOARD; NativeKey(key); break; } case SDL_TEXTINPUT: { int pos = 0; int c = u8_nextchar(event.text.text, &pos); KeyInput key; key.flags = KEY_CHAR; key.keyCode = c; key.deviceId = DEVICE_ID_KEYBOARD; NativeKey(key); break; } case SDL_MOUSEBUTTONDOWN: switch (event.button.button) { case SDL_BUTTON_LEFT: { mouseDown = true; TouchInput input; input.x = mx; input.y = my; input.flags = TOUCH_DOWN | TOUCH_MOUSE; input.id = 0; NativeTouch(input); KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_1, KEY_DOWN); NativeKey(key); } break; case SDL_BUTTON_RIGHT: { KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_2, KEY_DOWN); NativeKey(key); } break; } break; case SDL_MOUSEWHEEL: { KeyInput key; key.deviceId = DEVICE_ID_MOUSE; if (event.wheel.y > 0) { key.keyCode = NKCODE_EXT_MOUSEWHEEL_UP; } else { key.keyCode = NKCODE_EXT_MOUSEWHEEL_DOWN; } key.flags = KEY_DOWN; NativeKey(key); // SDL2 doesn't consider the mousewheel a button anymore // so let's send the KEY_UP right away. // Maybe KEY_UP alone will suffice? key.flags = KEY_UP; NativeKey(key); } case SDL_MOUSEMOTION: if (mouseDown) { TouchInput input; input.x = mx; input.y = my; input.flags = TOUCH_MOVE | TOUCH_MOUSE; input.id = 0; NativeTouch(input); } break; case SDL_MOUSEBUTTONUP: switch (event.button.button) { case SDL_BUTTON_LEFT: { mouseDown = false; TouchInput input; input.x = mx; input.y = my; input.flags = TOUCH_UP | TOUCH_MOUSE; input.id = 0; NativeTouch(input); KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_1, KEY_UP); NativeKey(key); } break; case SDL_BUTTON_RIGHT: { KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_2, KEY_UP); NativeKey(key); } break; } break; default: #ifndef _WIN32 if (joystick) { joystick->ProcessInput(event); } #endif break; } } if (g_QuitRequested) break; const uint8_t *keys = SDL_GetKeyboardState(NULL); UpdateRunLoop(); if (g_QuitRequested) break; #if !defined(MOBILE_DEVICE) if (lastUIState != GetUIState()) { lastUIState = GetUIState(); if (lastUIState == UISTATE_INGAME && g_Config.bFullScreen && !g_Config.bShowTouchControls) SDL_ShowCursor(SDL_DISABLE); if (lastUIState != UISTATE_INGAME && g_Config.bFullScreen) SDL_ShowCursor(SDL_ENABLE); } #endif if (framecount % 60 == 0) { // glsl_refresh(); // auto-reloads modified GLSL shaders once per second. } #ifdef USING_EGL eglSwapBuffers(g_eglDisplay, g_eglSurface); #else if (!keys[SDLK_TAB] || t - lastT >= 1.0/60.0) { SDL_GL_SwapWindow(g_Screen); lastT = t; } #endif ToggleFullScreenIfFlagSet(); time_update(); t = time_now(); framecount++; } #ifndef _WIN32 delete joystick; #endif NativeShutdownGraphics(); graphicsContext->Shutdown(); NativeShutdown(); delete graphicsContext; // Faster exit, thanks to the OS. Remove this if you want to debug shutdown // The speed difference is only really noticable on Linux. On Windows you do notice it though #ifndef MOBILE_DEVICE exit(0); #endif SDL_PauseAudio(1); SDL_CloseAudio(); #ifdef USING_EGL EGL_Close(); #endif SDL_GL_DeleteContext(glContext); SDL_Quit(); #if PPSSPP_PLATFORM(RPI) bcm_host_deinit(); #endif exit(0); return 0; }
void Graphics::close() { stat("Graphics::Close()"); SDL_ShowCursor(true); SDL_DestroyWindow(window); window = NULL; }
int main(int argc, char **argv) { // initialize everything if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS ) < 0 ) { return 1; } if (!g_oculusVR.InitVR()) { SDL_Quit(); return 1; } ovrSizei hmdResolution = g_oculusVR.GetResolution(); ovrSizei windowSize = { hmdResolution.w / 2, hmdResolution.h / 2 }; g_renderContext.Init("Oculus Rift OpenGL Debug Info Renderer", 100, 100, windowSize.w, windowSize.h); SDL_ShowCursor(SDL_DISABLE); if (glewInit() != GLEW_OK) { g_oculusVR.DestroyVR(); g_renderContext.Destroy(); SDL_Quit(); return 1; } if (!g_oculusVR.InitVRBuffers(windowSize.w, windowSize.h)) { g_oculusVR.DestroyVR(); g_renderContext.Destroy(); SDL_Quit(); return 1; } ShaderManager::GetInstance()->LoadShaders(); g_oculusVR.CreateDebug(); g_application.OnStart(); while (g_application.Running()) { // handle key presses processEvents(); glClearColor(0.2f, 0.2f, 0.6f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); g_oculusVR.OnRenderStart(); g_oculusVR.UpdateDebug(); for (int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++) { OVR::Matrix4f MVPMatrix = g_oculusVR.OnEyeRender(eyeIndex); // update MVP in quad shader const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader); glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]); g_application.OnRender(); g_oculusVR.RenderDebug(); g_oculusVR.OnEyeRenderFinish(eyeIndex); } g_oculusVR.SubmitFrame(); g_oculusVR.BlitMirror(); SDL_GL_SwapWindow(g_renderContext.window); } g_oculusVR.DestroyVR(); g_renderContext.Destroy(); SDL_Quit(); return 0; }
Mouse::~Mouse() { // Show cursor SDL_ShowCursor(1); }
bool Graphics::InitVideo() { if (drawtarget == screen) drawtarget = NULL; if (screen) delete screen; uint32_t window_flags = SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS; if (is_fullscreen) window_flags |= SDL_WINDOW_FULLSCREEN; if (window) { stat("second call to Graphics::InitVideo()"); abort(); } stat("SDL_CreateWindow: %dx%d @ %dbpp", Graphics::SCREEN_WIDTH*SCALE, Graphics::SCREEN_HEIGHT*SCALE, screen_bpp); window = SDL_CreateWindow("NXEngine", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, Graphics::SCREEN_WIDTH*SCALE, Graphics::SCREEN_HEIGHT*SCALE, window_flags); if (!window) { staterr("Graphics::InitVideo: error setting video mode (SDL_CreateWindow: %s)", SDL_GetError()); return 1; } int drv_index = -1; #if 0 { int drivers = SDL_GetNumRenderDrivers(); SDL_RendererInfo info; for (int i = 0; i < drivers; ++i) { if (SDL_GetRenderDriverInfo(i, &info)) { staterr("Graphics::InitVideo: SDL_GetRenderDriverInfo() failed: %s", SDL_GetError()); } if (strcmp("opengl", info.name) == 0) { drv_index = i; break; } } } #endif renderer = SDL_CreateRenderer(window, drv_index, /*SDL_RENDERER_SOFTWARE | */SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE); if (!renderer) { staterr("Graphics::InitVideo: error setting video mode (SDL_CreateRenderer: %s)", SDL_GetError()); return 1; } SDL_RendererInfo info; if (SDL_GetRendererInfo(renderer, &info)) { staterr("Graphics::InitVideo: SDL_GetRendererInfo failed: %s", SDL_GetError()); return 1; } if (!(info.flags & SDL_RENDERER_TARGETTEXTURE)) { staterr("Graphics::InitVideo: SDL_RENDERER_TARGETTEXTURE is not supported"); return 1; } SDL_ShowCursor(is_fullscreen == false); screen = NXSurface::createScreen(Graphics::SCREEN_WIDTH*SCALE, Graphics::SCREEN_HEIGHT*SCALE, info.texture_formats[0]); if (!screen) { staterr("Graphics::InitVideo: no screen has been created"); return 1; } if (!drawtarget) drawtarget = screen; return 0; }
Mouse::Mouse() { // Hide cursor SDL_ShowCursor(0); setType(BIG_ARROW); }
void ImGui_ImplSdlGL2_NewFrame(SDL_Window *window) { if (!g_FontTexture) ImGui_ImplSdlGL2_CreateDeviceObjects(); ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) int w, h; int display_w, display_h; SDL_GetWindowSize(window, &w, &h); SDL_GL_GetDrawableSize(window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0); // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) static Uint64 frequency = SDL_GetPerformanceFrequency(); Uint64 current_time = SDL_GetPerformanceCounter(); io.DeltaTime = g_Time > 0 ? (float)((double)(current_time - g_Time) / frequency) : (float)(1.0f / 60.0f); g_Time = current_time; // Setup mouse inputs (we already got mouse wheel, keyboard keys & characters from our event handler) int mx, my; Uint32 mouse_buttons = SDL_GetMouseState(&mx, &my); io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); io.MouseDown[0] = g_MousePressed[0] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. io.MouseDown[1] = g_MousePressed[1] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0; io.MouseDown[2] = g_MousePressed[2] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0; g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false; // We need to use SDL_CaptureMouse() to easily retrieve mouse coordinates outside of the client area. This is only supported from SDL 2.0.4 (released Jan 2016) #if (SDL_MAJOR_VERSION >= 2) && (SDL_MINOR_VERSION >= 0) && (SDL_PATCHLEVEL >= 4) if ((SDL_GetWindowFlags(window) & (SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_MOUSE_CAPTURE)) != 0) io.MousePos = ImVec2((float)mx, (float)my); bool any_mouse_button_down = false; for (int n = 0; n < IM_ARRAYSIZE(io.MouseDown); n++) any_mouse_button_down |= io.MouseDown[n]; if (any_mouse_button_down && (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_CAPTURE) == 0) SDL_CaptureMouse(SDL_TRUE); if (!any_mouse_button_down && (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_CAPTURE) != 0) SDL_CaptureMouse(SDL_FALSE); #else if ((SDL_GetWindowFlags(window) & SDL_WINDOW_INPUT_FOCUS) != 0) io.MousePos = ImVec2((float)mx, (float)my); #endif // Update OS/hardware mouse cursor if imgui isn't drawing a software cursor ImGuiMouseCursor cursor = ImGui::GetMouseCursor(); if (io.MouseDrawCursor || cursor == ImGuiMouseCursor_None) { SDL_ShowCursor(0); } else { SDL_SetCursor(g_MouseCursors[cursor] ? g_MouseCursors[cursor] : g_MouseCursors[ImGuiMouseCursor_Arrow]); SDL_ShowCursor(1); } // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application. ImGui::NewFrame(); }
/** * Control for vout display */ static int Control(vout_display_t *vd, int query, va_list args) { vout_display_sys_t *sys = vd->sys; switch (query) { case VOUT_DISPLAY_HIDE_MOUSE: SDL_ShowCursor(0); return VLC_SUCCESS; case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE: { const vout_display_cfg_t *cfg = va_arg(args, const vout_display_cfg_t *); /* */ sys->display = SDL_SetVideoMode(cfg->display.width, cfg->display.height, sys->display_bpp, sys->display_flags); if (!sys->display) { sys->display = SDL_SetVideoMode(vd->cfg->display.width, vd->cfg->display.height, sys->display_bpp, sys->display_flags); return VLC_EGENERIC; } if (sys->overlay) vout_display_PlacePicture(&sys->place, &vd->source, cfg, !sys->overlay); else vout_display_SendEventPicturesInvalid(vd); return VLC_SUCCESS; } case VOUT_DISPLAY_CHANGE_FULLSCREEN: { vout_display_cfg_t cfg = *va_arg(args, const vout_display_cfg_t *); /* Fix flags */ sys->display_flags &= ~(SDL_FULLSCREEN | SDL_RESIZABLE); sys->display_flags |= cfg.is_fullscreen ? SDL_FULLSCREEN : SDL_RESIZABLE; if (cfg.is_fullscreen) { cfg.display.width = sys->desktop_width; cfg.display.height = sys->desktop_height; } if (sys->overlay) { sys->display = SDL_SetVideoMode(cfg.display.width, cfg.display.height, sys->display_bpp, sys->display_flags); vout_display_PlacePicture(&sys->place, &vd->source, &cfg, !sys->overlay); } vout_display_SendEventDisplaySize(vd, cfg.display.width, cfg.display.height, cfg.is_fullscreen); return VLC_SUCCESS; } case VOUT_DISPLAY_CHANGE_ZOOM: case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED: case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT: { const vout_display_cfg_t *cfg; const video_format_t *source; if (query == VOUT_DISPLAY_CHANGE_SOURCE_ASPECT) { source = va_arg(args, const video_format_t *); cfg = vd->cfg; } else { source = &vd->source; cfg = va_arg(args, const vout_display_cfg_t *); } if (sys->overlay) { sys->display = SDL_SetVideoMode(cfg->display.width, cfg->display.height, sys->display_bpp, sys->display_flags); vout_display_PlacePicture(&sys->place, source, cfg, !sys->overlay); } else { vout_display_SendEventPicturesInvalid(vd); } return VLC_SUCCESS; }
void os_poll(void) { #ifdef USE_SDL SDL_Event event; /* The event queue works only with the video initialized */ if (!SDL_WasInit(SDL_INIT_VIDEO)) return; log_debug(("os: SDL_PollEvent()\n")); while (SDL_PollEvent(&event)) { log_debug(("os: SDL_PollEvent() -> event.type:%d\n", (int)event.type)); switch (event.type) { case SDL_KEYDOWN : #ifdef USE_KEYBOARD_SDL keyb_sdl_event_press(event.key.keysym.sym); #endif #ifdef USE_INPUT_SDL inputb_sdl_event_press(event.key.keysym.sym); #endif /* toggle fullscreen check */ if (event.key.keysym.sym == SDLK_RETURN && (event.key.keysym.mod & KMOD_ALT) != 0) { if (SDL_WasInit(SDL_INIT_VIDEO) && SDL_GetVideoSurface()) { SDL_WM_ToggleFullScreen(SDL_GetVideoSurface()); if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) != 0) { SDL_ShowCursor(SDL_DISABLE); } else { SDL_ShowCursor(SDL_ENABLE); } } } break; case SDL_KEYUP : #ifdef USE_KEYBOARD_SDL keyb_sdl_event_release(event.key.keysym.sym); #endif #ifdef USE_INPUT_SDL inputb_sdl_event_release(event.key.keysym.sym); #endif break; case SDL_MOUSEMOTION : #ifdef USE_MOUSE_SDL mouseb_sdl_event_move(event.motion.xrel, event.motion.yrel); #endif break; case SDL_MOUSEBUTTONDOWN : #ifdef USE_MOUSE_SDL if (event.button.button > 0) mouseb_sdl_event_press(event.button.button-1); #endif break; case SDL_MOUSEBUTTONUP : #ifdef USE_MOUSE_SDL if (event.button.button > 0) mouseb_sdl_event_release(event.button.button-1); #endif break; case SDL_QUIT : OS.is_quit = 1; break; } } #endif }
/** * @brief Handles global input. * * Basically separates the event types * * @param event Incoming SDL_Event. */ void input_handle( SDL_Event* event ) { /* Special case mouse stuff. */ if ((event->type == SDL_MOUSEMOTION) || (event->type == SDL_MOUSEBUTTONDOWN) || (event->type == SDL_MOUSEBUTTONUP)) { input_mouseTimer = MOUSE_HIDE; SDL_ShowCursor( SDL_ENABLE ); } if (toolkit_isOpen()) /* toolkit handled completely separately */ if (toolkit_input(event)) return; /* we don't process it if toolkit grabs it */ if (ovr_isOpen()) if (ovr_input(event)) return; /* Don't process if the map overlay wants it. */ /* GUI gets event. */ if (gui_handleEvent(event)) return; switch (event->type) { /* * game itself */ case SDL_JOYAXISMOTION: input_joyaxis(event->jaxis.axis, event->jaxis.value); break; case SDL_JOYBUTTONDOWN: input_joyevent(KEY_PRESS, event->jbutton.button); break; case SDL_JOYBUTTONUP: input_joyevent(KEY_RELEASE, event->jbutton.button); break; case SDL_KEYDOWN: input_keyevent(KEY_PRESS, event->key.keysym.sym, event->key.keysym.mod, 0); break; case SDL_KEYUP: input_keyevent(KEY_RELEASE, event->key.keysym.sym, event->key.keysym.mod, 0); break; /* Mouse stuff. */ case SDL_MOUSEBUTTONDOWN: input_clickevent( event ); break; case SDL_MOUSEMOTION: input_mouseMove( event ); break; default: break; } }
void Application::on_loop() { SDL_GetMouseState(&m_mouse_x,&m_mouse_y); for(unsigned int i = 0; i < m_input_keys.size(); ++i) { if(m_input_keys.at(i)) { m_renderer->get_rig()->update_position(i,1.0f); } } if(m_joystick != NULL) { int epsilon = 3000; //~ //Forward / Backward if(SDL_JoystickGetAxis(m_joystick, 1) > epsilon) m_renderer->get_rig()->update_position(0,abs(SDL_JoystickGetAxis(m_joystick, 1)/10000.0)); if(SDL_JoystickGetAxis(m_joystick, 1) < -epsilon) m_renderer->get_rig()->update_position(1,abs(SDL_JoystickGetAxis(m_joystick, 1)/10000.0)); //~ //Left / Right if(SDL_JoystickGetAxis(m_joystick, 0) < -epsilon) m_renderer->get_rig()->update_position(2,abs(SDL_JoystickGetAxis(m_joystick, 0)/10000.0)); if(SDL_JoystickGetAxis(m_joystick, 0) > epsilon) m_renderer->get_rig()->update_position(3,abs(SDL_JoystickGetAxis(m_joystick, 0)/10000.0)); #ifdef _WIN32 epsilon = 10000; //~ //Eyes to the ground / sky if(SDL_JoystickGetAxis(m_joystick, 4) < -epsilon) m_mouse_x -= (abs(SDL_JoystickGetAxis(m_joystick, 4)/2500.0)); if(SDL_JoystickGetAxis(m_joystick, 4) > epsilon) m_mouse_x += (abs(SDL_JoystickGetAxis(m_joystick, 4)/2500.0)); if(SDL_JoystickGetAxis(m_joystick, 3) < -epsilon) m_mouse_y -= (abs(SDL_JoystickGetAxis(m_joystick, 3)/2500.0)); if(SDL_JoystickGetAxis(m_joystick, 3) > epsilon) m_mouse_y += (abs(SDL_JoystickGetAxis(m_joystick, 3)/2500.0)); #elif __linux if(SDL_JoystickGetAxis(m_joystick, 2) < -epsilon) m_mouse_x -= (abs(SDL_JoystickGetAxis(m_joystick, 2)/1000.0)); if(SDL_JoystickGetAxis(m_joystick, 2) > epsilon) m_mouse_x += (abs(SDL_JoystickGetAxis(m_joystick, 2)/1000.0)); if(SDL_JoystickGetAxis(m_joystick, 3) < -epsilon) m_mouse_y -= (abs(SDL_JoystickGetAxis(m_joystick, 3)/1000.0)); if(SDL_JoystickGetAxis(m_joystick, 3) > epsilon) m_mouse_y += (abs(SDL_JoystickGetAxis(m_joystick, 3)/1000.0)); #endif } if(m_display_gui) { m_renderer->get_rig()->update_horizontal_angle(m_display->w/2); m_renderer->get_rig()->update_vertical_angle(m_display->h/2); m_renderer->set_display_gui(true); SDL_ShowCursor(SDL_ENABLE); } else { SDL_WarpMouse(m_display->w/2, m_display->h/2); if(m_has_focus_changed) { #ifdef _WIN32 m_mouse_x = m_display->w/2; m_mouse_y = m_display->h/2; #elif __linux m_mouse_x = 0.0f; m_mouse_y = 0.0f; #endif m_has_focus_changed = !m_has_focus_changed; } m_renderer->get_rig()->update_horizontal_angle(m_mouse_x); m_renderer->get_rig()->update_vertical_angle(m_mouse_y); m_renderer->set_display_gui(false); SDL_ShowCursor(SDL_DISABLE); } m_renderer->get_rig()->update_target(); m_renderer->get_rig()->update_up(); m_renderer->get_rig()->get_camera_one()->compute_view_matrix(); m_renderer->get_rig()->get_camera_two()->compute_view_matrix(); }
/** * @brief Shows the mouse. */ void input_mouseShow (void) { SDL_ShowCursor( SDL_ENABLE ); input_mouseCounter++; }
void M_Input::DisableCursorImage() { SDL_ShowCursor(SDL_DISABLE); }
/** *\fn int main(int argc, char *argv[]) * Main *\param[in,out] argc argc *\param[in,out] argv argv */ int main(int argc, char *argv[]) { SDL_Surface *screen = NULL; int go = 1; int ret,ret1, ret2 = 0, ret3, ret4; char level_name[MAX_SIZE_FILE_NAME]; char player_name[MAX_SIZE_FILE_NAME]; int nb_lvl; /*sound*/ Sound *sound_system; sound_system = createSound(); /*keyboard config*/ SDLKey kc[NB_KEY-1]; /*input*/ Input in; SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_JOYSTICK); Player *current_player; current_player = (Player *)malloc(sizeof(Player)); /*screen initialization*/ screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_HWSURFACE | SDL_DOUBLEBUF); initInput(&in); /*configurations loading */ loadSoundOptions("configuration/sound.conf",sound_system); SDL_WM_SetCaption("Super Martin", NULL); //window name SDL_ShowCursor(SDL_DISABLE); //delete the mouse while (go) //main loop { if(titleMenu(screen,&go,sound_system, &in)) { while( (ret3 = menuPlayers(screen, player_name, &go, sound_system, &in)) != -1 && go) { switch(ret3) { case -1: break; case 2 : ret2 = newPlayer(screen, player_name, sound_system, &go); if(ret2 == 1) { current_player->levelMax = 1; current_player->nbCoins = 0; current_player->nbLifes = 3; current_player->nbProjectile = 5; savePlayer("save/.save", player_name, current_player); loadInputOptions("default",kc,&in); saveInputOptions(player_name, kc, &in); } else break; case 1 : loadPlayer("save/.save", player_name, current_player); loadInputOptions(player_name,kc,&in); while(go && (ret1 = mainMenu(screen,&go,sound_system, player_name, &in)) != -1) { switch(ret1) { case -1: break; case 0: while( (ret4 = menuLevel(screen,level_name,sound_system, player_name, current_player, &go, &nb_lvl, &in)) != -1 && go) { while(play(screen,level_name,sound_system,&go,kc, &in, current_player, player_name, ret4+1, nb_lvl) && go); } break; case 1 : save(screen, "save/.save", player_name, current_player, &go); loadPlayer("save/.save", player_name, current_player); break; case 2 : while((ret = optionMenu(screen,&go,sound_system,kc, &in)) != -1 && go) { switch(ret) { case -1: break; case 0: soundOptions(screen,&go,sound_system, &in); break; case 1: keyBoardOptions(screen,&go,kc,&in,player_name); break; default:; } } break; case 3 : deletePlayer(screen, "save/players", player_name); go = 0; break; default: ; } } go = 1; break; default : ; } } } SDL_FillRect(screen,NULL,SDL_MapRGB(screen->format,255,255,255)); //clear screen SDL_Flip(screen); } freeSound(sound_system); free((void*)current_player); freeInput(&in); SDL_Quit(); return EXIT_SUCCESS; }
/* =============== IN_ActivateMouse =============== */ static void IN_ActivateMouse( void ) { if (!mouseAvailable || !SDL_WasInit( SDL_INIT_VIDEO ) ) return; #ifdef MACOS_X_ACCELERATION_HACK if (!mouseActive) // mac os x mouse accel hack { // Save the status of mouse acceleration originalMouseSpeed = -1.0; // in case of error if(in_disablemacosxmouseaccel->integer) { io_connect_t mouseDev = IN_GetIOHandle(); if(mouseDev != 0) { if(IOHIDGetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), &originalMouseSpeed) == kIOReturnSuccess) { Com_Printf("previous mouse acceleration: %f\n", originalMouseSpeed); if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), -1.0) != kIOReturnSuccess) { Com_Printf("Could not disable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n"); Cvar_Set ("in_disablemacosxmouseaccel", 0); } } else { Com_Printf("Could not disable mouse acceleration (failed at IOHIDGetAccelerationWithKey).\n"); Cvar_Set ("in_disablemacosxmouseaccel", 0); } IOServiceClose(mouseDev); } else { Com_Printf("Could not disable mouse acceleration (failed at IO_GetIOHandle).\n"); Cvar_Set ("in_disablemacosxmouseaccel", 0); } } } #endif if( !mouseActive ) { SDL_ShowCursor( 0 ); #ifdef MACOS_X_CURSOR_HACK // This is a bug in the current SDL/macosx...have to toggle it a few // times to get the cursor to hide. SDL_ShowCursor( 1 ); SDL_ShowCursor( 0 ); #endif SDL_WM_GrabInput( SDL_GRAB_ON ); IN_GobbleMotionEvents( ); } // in_nograb makes no sense in fullscreen mode if( !r_fullscreen->integer ) { if( in_nograb->modified || !mouseActive ) { if( in_nograb->integer ) SDL_WM_GrabInput( SDL_GRAB_OFF ); else SDL_WM_GrabInput( SDL_GRAB_ON ); in_nograb->modified = qfalse; } } mouseActive = qtrue; }
int main(int argc, char** argv) { if(argc != 2) usage(argv[0]); FILE* infile = fopen(argv[1], "r"); if(infile == NULL) { perror("Error opening input file"); return EXIT_FAILURE; } System* sys = load_system(infile); if(sys == NULL) { printf("Loading input file failed\n"); return EXIT_FAILURE; } init_simulation(sys); state.sys = sys; state.views = malloc(sys->nplanets * sizeof(PlanetView)); for(int i = 0; i < sys->nplanets; i++) state.views[i].radius = pow(sys->planets[i].mass / DENSITY_FACTOR, 1.0f/3.0f); state.scale = 1.0f; Vector* fst_pos = &sys->planets[0].position; vector_copy(state.pos, *fst_pos); state.pos[1] += 1.1f*get_planet_radius(0); state.pos[0] -= get_planet_radius(0); state.rot_x = 90.0f; state.locked_planet = -1; state.hours_per_sec = DEFAULT_SIMULATION_SPEED; state.time_step = sys->time_step; state.paused = true; state.trails_enabled = true; if(SDL_Init(SDL_INIT_VIDEO) < 0) die("SDL initialization failed"); atexit(SDL_Quit); const SDL_VideoInfo* videoInfo = SDL_GetVideoInfo(); if(!videoInfo) die("Could not get video information"); int videoFlags = SDL_OPENGL | SDL_HWPALETTE | SDL_RESIZABLE | SDL_HWSURFACE | SDL_HWACCEL; SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4); surface = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, videoFlags); if(!surface) { printf("Surface creation failed, trying to disable anti-aliasing...\n"); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); surface = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, videoFlags); } if(!surface) die("Changing video mode failed"); init_gl(); init_viewport(); SDL_ShowCursor(0); SDL_WM_GrabInput(SDL_GRAB_ON); SDL_Event event; while(SDL_PollEvent(&event)) ; /* ignore spurious mouse events at startup */ bool window_is_active = true; int step = 0; while (true) { Uint32 next_update = SDL_GetTicks() + FRAME_INTERVAL; while (SDL_PollEvent(&event)) { switch(event.type) { case SDL_ACTIVEEVENT: window_is_active = event.active.gain; break; case SDL_VIDEORESIZE: surface = SDL_SetVideoMode(event.resize.w, event.resize.h, SCREEN_BPP, videoFlags); if(!surface) die("Lost video surface during resize"); init_viewport(); break; case SDL_KEYDOWN: handle_keypress(&event.key.keysym); break; case SDL_MOUSEMOTION: handle_mouse(&event.motion); break; case SDL_QUIT: goto out; default: break; } } update(); if(window_is_active) { draw_scene(); glFlush(); SDL_GL_SwapBuffers(); } if(!state.paused) { for(int i = 0; i < (state.hours_per_sec * 3600.0f / FRAME_INTERVAL) / state.time_step; i++) { if((step % TRAILS_INTERVAL) == 0) update_trails(); simulate_one_step(sys, step++, state.time_step); } } Sint32 delta = next_update - SDL_GetTicks(); if(delta > 0) SDL_Delay(delta); } out: return 0; }
void Gource::mouseClick(SDL_MouseButtonEvent *e) { if(commitlog==0) return; if(gGourceSettings.hide_mouse) return; if(e->type == SDL_MOUSEBUTTONUP) { if(e->button == SDL_BUTTON_LEFT) { //stop dragging mouse, return the mouse to where //the user started dragging. mousedragged=false; } Uint8 ms = SDL_GetMouseState(0,0); if(e->button == SDL_BUTTON_LEFT || e->button == SDL_BUTTON_RIGHT) { if(!(ms & SDL_BUTTON(SDL_BUTTON_RIGHT) || ms & SDL_BUTTON(SDL_BUTTON_LEFT))) { SDL_WM_GrabInput(SDL_GRAB_OFF); SDL_ShowCursor(true); SDL_WarpMouse(mousepos.x, mousepos.y); } } } if(e->type != SDL_MOUSEBUTTONDOWN) return; //wheel up if(e->button == SDL_BUTTON_WHEELUP) { zoom(true); return; } //wheel down if(e->button == SDL_BUTTON_WHEELDOWN) { zoom(false); return; } if(e->button == SDL_BUTTON_MIDDLE) { toggleCameraMode(); return; } if(e->button == SDL_BUTTON_RIGHT) { SDL_WM_GrabInput(SDL_GRAB_ON); SDL_ShowCursor(false); return; } if(e->button == SDL_BUTTON_LEFT) { //mousepos = vec2f(e->x, e->y); mouseclicked=true; if(canSeek()) { float position; if(slider.click(mousepos, &position)) { seekTo(position); } } } }
Game::Game() { SDL_Init(SDL_INIT_EVERYTHING); SDL_ShowCursor(SDL_DISABLE); eventLoop(); }
void FHTML5Application::PollGameDeviceState( const float TimeDelta ) { SDL_Event Event; while (SDL_PollEvent(&Event)) { // Tick Input Interface. switch (Event.type) { case SDL_WINDOWEVENT: { SDL_WindowEvent windowEvent = Event.window; // ignore resized client Height/Width #if PLATFORM_HTML5_BROWSER int fs; emscripten_get_canvas_size(&WindowWidth, &WindowHeight, &fs); UE_LOG(LogHTML5Application, Verbose, TEXT("emscripten_get_canvas_size: Width:%d, Height:%d, Fullscreen:%d"), WindowWidth, WindowHeight, fs); #endif #if PLATFORM_HTML5_WIN32 WindowWidth = windowEvent.data1; WindowHeight = windowEvent.data2; #endif switch (windowEvent.event) { case SDL_WINDOWEVENT_SIZE_CHANGED: { UE_LOG(LogHTML5Application, Verbose, TEXT("WindowSizeChanged: Width:%d, Height:%d"), WindowWidth, WindowHeight); FDisplayMetrics DisplayMetrics; FDisplayMetrics::GetDisplayMetrics(DisplayMetrics); if ( DisplayMetrics.PrimaryDisplayWidth != WindowWidth || DisplayMetrics.PrimaryDisplayHeight != WindowHeight ) { int32 delta = FMath::Abs<int32>(DisplayMetrics.PrimaryDisplayHeight - WindowHeight); if (delta > 2) // UE-35363: retina bug fix - otherwise, event does infinite loops { MessageHandler->OnSizeChanged(ApplicationWindow,WindowWidth,WindowHeight, false); MessageHandler->OnResizingWindow(ApplicationWindow); BroadcastDisplayMetricsChanged(DisplayMetrics); } } } break; case SDL_WINDOWEVENT_RESIZED: { UE_LOG(LogHTML5Application, Verbose, TEXT("WindowResized: Width:%d, Height:%d"), WindowWidth, WindowHeight); FDisplayMetrics DisplayMetrics; FDisplayMetrics::GetDisplayMetrics(DisplayMetrics); if ( DisplayMetrics.PrimaryDisplayWidth != WindowWidth || DisplayMetrics.PrimaryDisplayHeight != WindowHeight ) { int32 delta = FMath::Abs<int32>(DisplayMetrics.PrimaryDisplayHeight - WindowHeight); if (delta > 2) // UE-35363: retina bug fix - otherwise, event does infinite loops { MessageHandler->OnResizingWindow(ApplicationWindow); BroadcastDisplayMetricsChanged(DisplayMetrics); } } } break; case SDL_WINDOWEVENT_ENTER: { UE_LOG(LogHTML5Application, Verbose, TEXT("WindowEnter")); // MessageHandler->OnWindowActivationChanged(ApplicationWindow, EWindowActivation::Activate); WarmUpTicks = 0; } break; case SDL_WINDOWEVENT_LEAVE: { UE_LOG(LogHTML5Application, Verbose, TEXT("WindowLeave")); // MessageHandler->OnWindowActivationChanged(ApplicationWindow, EWindowActivation::Deactivate); } break; case SDL_WINDOWEVENT_FOCUS_GAINED: { UE_LOG(LogHTML5Application, Verbose, TEXT("WindowFocusGained")); MessageHandler->OnCursorSet(); MessageHandler->OnWindowActivationChanged(ApplicationWindow, EWindowActivation::Activate); WarmUpTicks = 0; } break; case SDL_WINDOWEVENT_FOCUS_LOST: { UE_LOG(LogHTML5Application, Verbose, TEXT("WindowFocusLost")); MessageHandler->OnWindowActivationChanged(ApplicationWindow, EWindowActivation::Deactivate); } break; default: break; } } default: { InputInterface->Tick( TimeDelta,Event, ApplicationWindow); } } } InputInterface->SendControllerEvents(); if ( WarmUpTicks >= 0) WarmUpTicks ++; if ( WarmUpTicks == MaxWarmUpTicks ) { // browsers don't allow locking and hiding to work independently. use warmup ticks after the application has settled // on its mouse lock/visibility status. This is necessary even in cases where the game doesn't want to locking because // the lock status oscillates for few ticks before settling down. This causes a Browser UI pop even when we don't intend to lock. // see http://www.w3.org/TR/pointerlock more for information. #if PLATFORM_HTML5_WIN32 SDL_Window* WindowHandle= SDL_GL_GetCurrentWindow(); if (((FHTML5Cursor*)Cursor.Get())->LockStatus && !((FHTML5Cursor*)Cursor.Get())->CursorStatus) { SDL_SetWindowGrab(WindowHandle, SDL_TRUE); SDL_ShowCursor(SDL_DISABLE); SDL_SetRelativeMouseMode(SDL_TRUE); } else { SDL_SetRelativeMouseMode(SDL_FALSE); SDL_ShowCursor(SDL_ENABLE); SDL_SetWindowGrab(WindowHandle, SDL_FALSE); } #endif #if PLATFORM_HTML5_BROWSER if (((FHTML5Cursor*)Cursor.Get())->LockStatus && !((FHTML5Cursor*)Cursor.Get())->CursorStatus) { UE_LOG(LogHTML5Application, Verbose, TEXT("Request pointer lock")); emscripten_request_pointerlock ( "#canvas" , true); } else { UE_LOG(LogHTML5Application, Verbose, TEXT("Exit pointer lock")); //emscripten_exit_pointerlock(); } #endif WarmUpTicks = -1; } }
int die(SDL_Window* dieWindow) { //create hitboxes SDL_DisplayMode mode; SDL_GetCurrentDisplayMode(0, &mode); SDL_Rect exit = {EXIT_X, EXIT_Y, BUTTON_WIDTH, BUTTON_HEIGHT }; SDL_Rect restart = { RESTART_X, RESTART_Y, BUTTON_WIDTH, BUTTON_HEIGHT }; //create renderer for die SDL_Renderer *rendererDie; rendererDie = SDL_CreateRenderer(dieWindow, -1, SDL_RENDERER_ACCELERATED); if (NULL == rendererDie) { fprintf(stderr, "Renderer could not be created! SDL_Error: %s", SDL_GetError()); } //show cursor SDL_ShowCursor(SDL_ENABLE); SDL_Cursor *cursor; cursor = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND); SDL_SetCursor(cursor); ///////////////////////////////////////////////MUSIC////////////////////////////////////////////////// Mix_Music *backgroundMusic = NULL; //init sdl mixer if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) { printf("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError()); } //load music backgroundMusic = Mix_LoadMUS("sounds/youdied.mp3"); if (NULL == backgroundMusic) { printf("Failed to load low sound effect! SDL_mixer Error: %s\n", Mix_GetError()); } //play music Mix_PlayMusic(backgroundMusic, 1); //load graphics for background SDL_Texture* background; background = loadImage("images/youdied.bmp", rendererDie); if (!background) { fprintf(stderr, "Could not load image! SDL_Error: %s", SDL_GetError()); } SDL_Event mouse; int x_button = -960; int y_button = -540; //render graphic SDL_RenderClear(rendererDie); SDL_RenderCopy(rendererDie, background, NULL, NULL); SDL_RenderPresent(rendererDie); while (1) { while (SDL_PollEvent(&mouse)) { switch (mouse.type) { //if click appears in hitbox open one of the panels in new window case SDL_MOUSEBUTTONDOWN: x_button = mouse.button.x; y_button = mouse.button.y; if (XYInRect(exit, x_button, y_button)) { Mix_HaltMusic(); Mix_FreeMusic(backgroundMusic); backgroundMusic = NULL; SDL_DestroyRenderer(rendererDie); SDL_FreeCursor(cursor); SDL_ShowCursor(SDL_DISABLE); return 0; } else if (XYInRect(restart, x_button, y_button)) { Mix_HaltMusic(); Mix_FreeMusic(backgroundMusic); backgroundMusic = NULL; SDL_DestroyRenderer(rendererDie); SDL_FreeCursor(cursor); SDL_ShowCursor(SDL_DISABLE); return 1; } break; default: break; } //present in mainWindow SDL_RenderClear(rendererDie); SDL_RenderCopy(rendererDie, background, NULL, NULL); SDL_RenderPresent(rendererDie); } } }
void Logstalgia::logic(float t, float dt) { float sdt = dt*simu_speed;; if(mousehide_timeout>0.0f) { mousehide_timeout -= dt; if(mousehide_timeout<0.0f) { SDL_ShowCursor(false); } } infowindow.hide(); if(end_reached && balls.empty()) { appFinished = true; return; } //if paused, dont move anything, only check what is under mouse if(paused) { for(std::map<std::string, Paddle*>::iterator it= paddles.begin(); it!=paddles.end();it++) { std::string paddle_token = it->first; Paddle* paddle = it->second; if(paddle->mouseOver(infowindow, mousepos)) { break; } } for(std::list<RequestBall*>::iterator it = balls.begin(); it != balls.end(); it++) { RequestBall* ball = *it; if(ball->mouseOver(infowindow, mousepos)) { break; } } if(!ipSummarizer->mouseOver(infowindow,mousepos)) { int nogrps = summGroups.size(); for(int i=0;i<nogrps;i++) { if(summGroups[i]->mouseOver(infowindow, mousepos)) break; } } return; } //increment clock elapsed_time += sdt; currtime = starttime + (long)(elapsed_time); //next will fast forward clock to the time of the next entry, //if the next entry is in the future if(next || gAutoSkip && balls.empty()) { if(!queued_entries.empty()) { LogEntry* le = queued_entries.front(); long entrytime = le->timestamp; if(entrytime > currtime) { elapsed_time = entrytime - starttime; currtime = starttime + (long)(elapsed_time); } } next = false; } //recalc spawn speed each second by if(currtime != lasttime) { //dont bother reading the log if we dont need to if(queued_entries.empty() || queued_entries.back()->timestamp <= currtime) { readLog(); } profile_start("determine new entries"); int items_to_spawn=0; for(std::list<LogEntry*>::iterator it = queued_entries.begin(); it != queued_entries.end(); it++) { LogEntry* le = *it; if(le->timestamp > currtime) break; items_to_spawn++; addStrings(le); } profile_stop(); //debugLog("items to spawn %d\n", items_to_spawn); if(items_to_spawn > 0) { profile_start("add new strings"); //re-summarize ipSummarizer->summarize(); int nogrps = summGroups.size(); for(int i=0;i<nogrps;i++) { summGroups[i]->summarize(); } profile_stop(); profile_start("add new entries"); float item_offset = 1.0 / (float) (items_to_spawn); int item_no = 0; while(!queued_entries.empty()) { LogEntry* le = queued_entries.front(); if(le->timestamp > currtime) break; float pos_offset = 1.0 - item_offset * (float) item_no++; float start_offset = std::min(1.0f, pos_offset); addBall(le, start_offset); queued_entries.pop_front(); } } //update date if(total_entries>0) { char datestr[256]; char timestr[256]; struct tm* timeinfo = localtime ( &currtime ); strftime(datestr, 256, "%A, %B %d, %Y", timeinfo); strftime(timestr, 256, "%X", timeinfo); displaydate = datestr; displaytime = timestr; } else { displaydate = ""; displaytime = ""; } lasttime=currtime; profile_stop(); } else { //do small reads per frame if we havent buffered the next second if(queued_entries.empty() || queued_entries.back()->timestamp <= currtime+1) { readLog(50); } } std::list<Paddle*> inactivePaddles; //update paddles for(std::map<std::string, Paddle*>::iterator it= paddles.begin(); it!=paddles.end();it++) { std::string paddle_token = it->first; Paddle* paddle = it->second; if(gPaddleMode > PADDLE_SINGLE && !paddle->moving() && !paddle->visible()) { bool token_match = false; //are there any requests that will match this paddle? for(std::list<RequestBall*>::iterator bit = balls.begin(); bit != balls.end();bit++) { RequestBall* ball = *bit; if( gPaddleMode == PADDLE_VHOST && ball->le->vhost == paddle_token || gPaddleMode == PADDLE_PID && ball->le->pid == paddle_token) { token_match = true; break; } } //mark this paddle for deletion, continue if(!token_match) { inactivePaddles.push_back(paddle); continue; } } // find nearest ball to this paddle if((recentre || !paddle->moving()) && balls.size()>0) { recentre=false; RequestBall* ball = findNearest(paddle, paddle_token); if(ball!=0 && !(paddle->moving() && paddle->getTarget() == ball)) { paddle->setTarget(ball); } } //if still not moving, recentre if(!paddle->moving()) { recentre=true; paddle->setTarget(0); } it->second->logic(sdt); } recentre = false; profile_start("check ball status"); for(std::list<RequestBall*>::iterator it = balls.begin(); it != balls.end();) { RequestBall* ball = *it; highscore += ball->logic(dt); if(ball->isFinished()) { it = balls.erase(it); removeBall(ball); } else { it++; } } profile_stop(); profile_start("ipSummarizer logic"); ipSummarizer->logic(dt); profile_stop(); profile_start("updateGroups logic"); updateGroups(dt); profile_stop(); screen_blank_elapsed += dt; if(screen_blank_elapsed-screen_blank_interval > screen_blank_period) screen_blank_elapsed = 0.0f; //update font alpha font_alpha = 1.0f; if(screen_blank_elapsed>screen_blank_interval) { font_alpha = std::min(1.0f, (float) fabs(1.0f - (screen_blank_elapsed-screen_blank_interval)/(screen_blank_period*0.5))); font_alpha *= font_alpha; } }
//Check for any window messages (keypress, paint, mousemove, etc) void CheckMessages() { SDL_Event ev; bool quit = false; while(SDL_PollEvent(&ev)) { switch(ev.type) { case SDL_KEYDOWN: { int lc = 0; if(OPTIONS["HIDE_CURSOR"] != "show" && SDL_ShowCursor(-1)) SDL_ShowCursor(SDL_DISABLE); //hide mouse cursor on keyboard input Uint8 *keystate = SDL_GetKeyState(NULL); // manually handle Alt+F4 for older SDL lib, no big deal if(ev.key.keysym.sym==SDLK_F4 && (keystate[SDLK_RALT] || keystate[SDLK_LALT]) ) { quit = true; break; } else if(ev.key.keysym.sym==SDLK_RSHIFT || ev.key.keysym.sym==SDLK_LSHIFT || ev.key.keysym.sym==SDLK_RCTRL || ev.key.keysym.sym==SDLK_LCTRL || ev.key.keysym.sym==SDLK_RALT ) { break; // temporary fix for unwanted keys } else if(ev.key.keysym.sym==SDLK_LALT) { begin_alt_code(); break; } else if (ev.key.keysym.unicode != 0) { lc = ev.key.keysym.unicode; switch (lc){ case 13: //Reroute ENTER key for compatilbity purposes lc=10; break; case 8: //Reroute BACKSPACE key for compatilbity purposes lc=127; break; } } if(ev.key.keysym.sym==SDLK_LEFT) { lc = KEY_LEFT; } else if(ev.key.keysym.sym==SDLK_RIGHT) { lc = KEY_RIGHT; } else if(ev.key.keysym.sym==SDLK_UP) { lc = KEY_UP; } else if(ev.key.keysym.sym==SDLK_DOWN) { lc = KEY_DOWN; } else if(ev.key.keysym.sym==SDLK_PAGEUP) { lc = KEY_PPAGE; } else if(ev.key.keysym.sym==SDLK_PAGEDOWN) { lc = KEY_NPAGE; } if(!lc) break; if(alt_down) { add_alt_code(lc); }else { lastchar = lc; } } break; case SDL_KEYUP: { if(ev.key.keysym.sym==SDLK_LALT) { int code = end_alt_code(); if(code) lastchar = code; } } break; case SDL_MOUSEMOTION: if((OPTIONS["HIDE_CURSOR"] == "show" || OPTIONS["HIDE_CURSOR"] == "hidekb") && !SDL_ShowCursor(-1)) SDL_ShowCursor(SDL_ENABLE); break; case SDL_QUIT: quit = true; break; } } if (needupdate) try_update(); if(quit) { endwin(); exit(0); } }
/* =============== GLimp_SetMode =============== */ static int GLimp_SetMode( int mode, qboolean fullscreen, qboolean noborder ) { const char *glstring; int perChannelColorBits; int alphaBits, depthBits, stencilBits; int samples; int i = 0; SDL_Surface *icon = NULL; SDL_DisplayMode desktopMode; Uint32 flags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL; int x, y; GLenum glewResult; ri.Printf( PRINT_ALL, "Initializing OpenGL display\n" ); if ( r_allowResize->integer ) { flags |= SDL_WINDOW_RESIZABLE; } if ( r_centerWindow->integer ) { // center window on specified display x = SDL_WINDOWPOS_CENTERED_DISPLAY( r_displayIndex->integer ); y = SDL_WINDOWPOS_CENTERED_DISPLAY( r_displayIndex->integer ); } else { x = SDL_WINDOWPOS_UNDEFINED_DISPLAY( r_displayIndex->integer ); y = SDL_WINDOWPOS_UNDEFINED_DISPLAY( r_displayIndex->integer ); } icon = SDL_CreateRGBSurfaceFrom( ( void * ) CLIENT_WINDOW_ICON.pixel_data, CLIENT_WINDOW_ICON.width, CLIENT_WINDOW_ICON.height, CLIENT_WINDOW_ICON.bytes_per_pixel * 8, CLIENT_WINDOW_ICON.bytes_per_pixel * CLIENT_WINDOW_ICON.width, #ifdef Q3_LITTLE_ENDIAN 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 #else 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF #endif ); if ( SDL_GetDesktopDisplayMode( r_displayIndex->integer, &desktopMode ) == 0 ) { displayAspect = ( float ) desktopMode.w / ( float ) desktopMode.h; ri.Printf( PRINT_ALL, "Display aspect: %.3f\n", displayAspect ); } else { Com_Memset( &desktopMode, 0, sizeof( SDL_DisplayMode ) ); ri.Printf( PRINT_ALL, "Cannot determine display aspect (%s), assuming 1.333\n", SDL_GetError() ); } ri.Printf( PRINT_ALL, "...setting mode %d:", mode ); if ( mode == -2 ) { // use desktop video resolution if ( desktopMode.h > 0 ) { glConfig.vidWidth = desktopMode.w; glConfig.vidHeight = desktopMode.h; } else { glConfig.vidWidth = 640; glConfig.vidHeight = 480; ri.Printf( PRINT_ALL, "Cannot determine display resolution, assuming 640x480\n" ); } glConfig.windowAspect = ( float ) glConfig.vidWidth / ( float ) glConfig.vidHeight; } else if ( !R_GetModeInfo( &glConfig.vidWidth, &glConfig.vidHeight, &glConfig.windowAspect, mode ) ) { ri.Printf( PRINT_ALL, " invalid mode\n" ); return RSERR_INVALID_MODE; } ri.Printf( PRINT_ALL, " %d %d\n", glConfig.vidWidth, glConfig.vidHeight ); do { if ( glContext != NULL ) { SDL_GL_DeleteContext( glContext ); glContext = NULL; } if ( window != NULL ) { SDL_GetWindowPosition( window, &x, &y ); ri.Printf( PRINT_DEVELOPER, "Existing window at %dx%d before being destroyed\n", x, y ); SDL_DestroyWindow( window ); window = NULL; } // we come back here if we couldn't get a visual and there's // something we can switch off if ( fullscreen ) { flags |= SDL_WINDOW_FULLSCREEN; glConfig.isFullscreen = qtrue; } else { if ( noborder ) { flags |= SDL_WINDOW_BORDERLESS; } glConfig.isFullscreen = qfalse; } colorBits = r_colorbits->integer; if ( ( !colorBits ) || ( colorBits >= 32 ) ) { colorBits = 24; } alphaBits = r_alphabits->integer; if ( alphaBits < 0 ) { alphaBits = 0; } depthBits = r_depthbits->integer; if ( !depthBits ) { depthBits = 24; } stencilBits = r_stencilbits->integer; samples = r_ext_multisample->integer; for ( i = 0; i < 16; i++ ) { int testColorBits, testDepthBits, testStencilBits; // 0 - default // 1 - minus colorbits // 2 - minus depthbits // 3 - minus stencil if ( ( i % 4 ) == 0 && i ) { // one pass, reduce switch ( i / 4 ) { case 2: if ( colorBits == 24 ) { colorBits = 16; } break; case 1: if ( depthBits == 24 ) { depthBits = 16; } else if ( depthBits == 16 ) { depthBits = 8; } case 3: if ( stencilBits == 24 ) { stencilBits = 16; } else if ( stencilBits == 16 ) { stencilBits = 8; } } } testColorBits = colorBits; testDepthBits = depthBits; testStencilBits = stencilBits; if ( ( i % 4 ) == 3 ) { // reduce colorbits if ( testColorBits == 24 ) { testColorBits = 16; } } if ( ( i % 4 ) == 2 ) { // reduce depthbits if ( testDepthBits == 24 ) { testDepthBits = 16; } else if ( testDepthBits == 16 ) { testDepthBits = 8; } } if ( ( i % 4 ) == 1 ) { // reduce stencilbits if ( testStencilBits == 24 ) { testStencilBits = 16; } else if ( testStencilBits == 16 ) { testStencilBits = 8; } else { testStencilBits = 0; } } if ( testColorBits == 24 ) { perChannelColorBits = 8; } else { perChannelColorBits = 4; } SDL_GL_SetAttribute( SDL_GL_RED_SIZE, perChannelColorBits ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, perChannelColorBits ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, perChannelColorBits ); SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, alphaBits ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, testDepthBits ); SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, testStencilBits ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, samples ? 1 : 0 ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, samples ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); #if !SDL_VERSION_ATLEAST( 2, 0, 0 ) SDL_GL_SetAttribute( SDL_GL_SWAP_CONTROL, r_swapInterval->integer ); #endif #if SDL_VERSION_ATLEAST( 2, 0, 0 ) if ( !r_glAllowSoftware->integer ) { SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 ); } if ( r_glCoreProfile->integer || r_glDebugProfile->integer ) { int major = r_glMajorVersion->integer; int minor = r_glMinorVersion->integer; SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, major ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, minor ); if ( r_glCoreProfile->integer ) { SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE ); } else { SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY ); } if ( r_glDebugProfile->integer ) { SDL_GL_SetAttribute( SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG ); } } #endif window = SDL_CreateWindow( CLIENT_WINDOW_TITLE, x, y, glConfig.vidWidth, glConfig.vidHeight, flags ); if ( !window ) { ri.Printf( PRINT_DEVELOPER, "SDL_CreateWindow failed: %s\n", SDL_GetError() ); continue; } SDL_SetWindowIcon( window, icon ); glContext = SDL_GL_CreateContext( window ); if ( !glContext ) { ri.Printf( PRINT_DEVELOPER, "SDL_GL_CreateContext failed: %s\n", SDL_GetError() ); continue; } #if SDL_VERSION_ATLEAST( 2, 0, 0 ) SDL_GL_SetSwapInterval( r_swapInterval->integer ); #endif SDL_ShowCursor( 0 ); glConfig.colorBits = testColorBits; glConfig.depthBits = testDepthBits; glConfig.stencilBits = testStencilBits; ri.Printf( PRINT_ALL, "Using %d Color bits, %d depth, %d stencil display.\n", glConfig.colorBits, glConfig.depthBits, glConfig.stencilBits ); break; } if ( samples && ( !glContext || !window ) ) { r_ext_multisample->integer = 0; } } while ( ( !glContext || !window ) && samples ); SDL_FreeSurface( icon ); glewResult = glewInit(); if ( glewResult != GLEW_OK ) { // glewInit failed, something is seriously wrong ri.Error( ERR_FATAL, "GLW_StartOpenGL() - could not load OpenGL subsystem: %s", glewGetErrorString( glewResult ) ); } else { ri.Printf( PRINT_ALL, "Using GLEW %s\n", glewGetString( GLEW_VERSION ) ); } int GLmajor, GLminor; sscanf( ( const char * ) glGetString( GL_VERSION ), "%d.%d", &GLmajor, &GLminor ); if ( GLmajor < 2 || ( GLmajor == 2 && GLminor < 1 ) ) { // missing shader support, switch to 1.x renderer return RSERR_OLD_GL; } if ( GLmajor < 3 || ( GLmajor == 3 && GLminor < 2 ) ) { // shaders are supported, but not all GL3.x features ri.Printf( PRINT_ALL, "Using enhanced (GL3) Renderer in GL 2.x mode...\n" ); } else { ri.Printf( PRINT_ALL, "Using enhanced (GL3) Renderer in GL 3.x mode...\n" ); glConfig.driverType = GLDRV_OPENGL3; } #if defined( SMP ) && !SDL_VERSION_ATLEAST( 2, 0, 0 ) // setup context for SDL_GL_MakeCurrent SDL_GL_GetCurrentContext(); #endif GLimp_DetectAvailableModes(); glstring = ( char * ) glGetString( GL_RENDERER ); ri.Printf( PRINT_ALL, "GL_RENDERER: %s\n", glstring ); return RSERR_OK; }
bool Mouse::isVisible() const { return (SDL_ShowCursor(SDL_QUERY) == SDL_ENABLE) ? true : false; }