Example #1
0
void Window::close(bool allowExceptions)
{
	if (graphics.get())
	{
		if (allowExceptions && graphics->isCanvasActive())
			throw love::Exception("love.window.close cannot be called while a Canvas is active in love.graphics.");

		graphics->unSetMode();
	}

	if (context)
	{
		SDL_GL_DeleteContext(context);
		context = nullptr;
	}

	if (window)
	{
		SDL_DestroyWindow(window);
		window = nullptr;

		// The old window may have generated pending events which are no longer
		// relevant. Destroy them all!
		SDL_FlushEvent(SDL_WINDOWEVENT);
	}

	open = false;
}
Example #2
0
    void InputWrapper::updateMouseSettings()
    {
        mGrabPointer = mWantGrab && mMouseInWindow && mWindowHasFocus;
        SDL_SetWindowGrab(mSDLWindow, mGrabPointer && mAllowGrab ? SDL_TRUE : SDL_FALSE);

        SDL_ShowCursor(mWantMouseVisible || !mWindowHasFocus);

        bool relative = mWantRelative && mMouseInWindow && mWindowHasFocus;
        if(mMouseRelative == relative)
            return;

        mMouseRelative = relative;

        mWrapPointer = false;

        //eep, wrap the pointer manually if the input driver doesn't support
        //relative positioning natively
        int success = SDL_SetRelativeMouseMode(relative ? SDL_TRUE : SDL_FALSE);
        if(relative && success != 0)
            mWrapPointer = true;

        //now remove all mouse events using the old setting from the queue
        SDL_PumpEvents();
        SDL_FlushEvent(SDL_MOUSEMOTION);
    }
Example #3
0
    void InputWrapper::updateMouseSettings()
    {
        mGrabPointer = mWantGrab && mMouseInWindow && mWindowHasFocus;
        SDL_SetWindowGrab(mSDLWindow, mGrabPointer && mAllowGrab ? SDL_TRUE : SDL_FALSE);

        SDL_ShowCursor(mWantMouseVisible || !mWindowHasFocus);

        bool relative = mWantRelative && mMouseInWindow && mWindowHasFocus;
        if(mMouseRelative == relative)
            return;

        mMouseRelative = relative;

        mWrapPointer = false;

        // eep, wrap the pointer manually if the input driver doesn't support
        // relative positioning natively
        // also use wrapping if no-grab was specified in options (SDL_SetRelativeMouseMode
        // appears to eat the mouse cursor when pausing in a debugger)
        bool success = mAllowGrab && SDL_SetRelativeMouseMode(relative ? SDL_TRUE : SDL_FALSE) == 0;
        if(relative && !success)
            mWrapPointer = true;

        //now remove all mouse events using the old setting from the queue
        SDL_PumpEvents();
        SDL_FlushEvent(SDL_MOUSEMOTION);
    }
Example #4
0
/*
 * SDL.flushEvent(type)
 *
 * Arguments:
 *	type the event type
 */
static int
l_event_flushEvent(lua_State *L)
{
	int type = luaL_checkinteger(L, 1);

	SDL_FlushEvent(type);

	return 0;
}
Example #5
0
bool tdialog::show(CVideo& video, const unsigned auto_close_time)
{
	if(video.faked() && !show_even_without_video_) {
		if(!allow_plugin_skip_) {
			return false;
		}

		plugins_manager* pm = plugins_manager::get();
		if (pm && pm->any_running())
		{
			plugins_context pc("Dialog");
			pc.set_callback("skip_dialog", [this](config) { retval_ = twindow::OK; }, false);
			pc.set_callback("quit", [](config) {}, false);
			pc.play_slice();
		}

		return false;
	}

	std::unique_ptr<twindow> window(build_window(video));
	assert(window.get());

	post_build(*window);

	window->set_owner(this);

	init_fields(*window);

	pre_show(*window);

	retval_ = window->show(restore_, auto_close_time);

	/*
	 * It can happen that when two clicks follow each other fast that the event
	 * handling code in events.cpp generates a DOUBLE_CLICK_EVENT. For some
	 * reason it can happen that this event gets pushed in the queue when the
	 * window is shown, but processed after the window is closed. This causes
	 * the next window to get this pending event.
	 *
	 * This caused a bug where double clicking in the campaign selection dialog
	 * directly selected a difficulty level and started the campaign. In order
	 * to avoid that problem, filter all pending DOUBLE_CLICK_EVENT events after
	 * the window is closed.
	 */
	SDL_FlushEvent(DOUBLE_CLICK_EVENT);

	finalize_fields(*window, (retval_ == twindow::OK || always_save_fields_));

	post_show(*window);

	// post_show may have updated the windoe retval. Update it here.
	retval_ = window->get_retval();

	return retval_ == twindow::OK;
}
Example #6
0
void Player::handleEvent(SDL_Event& e){

    if(init){ //flushes all key events after init so we avoid false moves
        SDL_FlushEvent(SDL_KEYDOWN);
        SDL_FlushEvent(SDL_KEYUP);
        init = false;
    }

	if( e.type == SDL_KEYDOWN && e.key.repeat == 0 ){
        switch( e.key.keysym.sym ){
            case SDLK_SPACE:
                if(!jumpTimer.isStarted() && mVelY <= 2){ //if not in jump and not in the air
                    SoundEngine::getInstance()->soundEvent(superJump ? SUPERJUMP : JUMP);
                    mVelY = -1 * ((superJump)?PLAYER_SUPER_JUMP_VEL:PLAYER_JUMP_VEL);
                    playerSpeed = playerSpeedInJump;
                    jumpTimer.start();
                }
            break;
            case SDLK_j:
                if(inventory->hasItem(2)){ //item 2 = super jump
                    superJump = !superJump;
                    inventory->getItems().at(2)->setDisabled(!superJump); //disable/enable in inventory
                    SoundEngine::getInstance()->soundEvent(superJump ? CLICK_UP : CLICK_DOWN);
                }
                break;
            case SDLK_LEFT: mVelX = -10; break; //just for animation
            case SDLK_RIGHT: mVelX = 10; break;
            case SDLK_f:
                if(inventory->hasItem(1) && !fireTimer.isStarted()){ //item 1 = basic gun
                    SoundEngine::getInstance()->soundEvent(FIRE);
                    Position bulletPosition = pos;
                    bulletPosition.y += BULLET_PLAYER_TOP_MARGIN;
                    ballisticEngine->fireBullet(bulletPosition, facingLeft() ? LEFT : RIGHT);
                    fireTimer.start();
                }
                break;
            case SDLK_ESCAPE:
                pause = true;
        }
    }
}
Example #7
0
int
SDL_SetRelativeMouseMode(SDL_bool enabled)
{
    SDL_Mouse *mouse = SDL_GetMouse();
    SDL_Window *focusWindow = SDL_GetKeyboardFocus();

    if (enabled == mouse->relative_mode) {
        return 0;
    }

    if (enabled && focusWindow) {
        /* Center it in the focused window to prevent clicks from going through
         * to background windows.
         */
        SDL_SetMouseFocus(focusWindow);
        SDL_WarpMouseInWindow(focusWindow, focusWindow->w/2, focusWindow->h/2);
    }

    /* Set the relative mode */
    if (!enabled && mouse->relative_mode_warp) {
        mouse->relative_mode_warp = SDL_FALSE;
    } else if (enabled && ShouldUseRelativeModeWarp(mouse)) {
        mouse->relative_mode_warp = SDL_TRUE;
    } else if (mouse->SetRelativeMouseMode(enabled) < 0) {
        if (enabled) {
            /* Fall back to warp mode if native relative mode failed */
            if (!mouse->WarpMouse) {
                return SDL_SetError("No relative mode implementation available");
            }
            mouse->relative_mode_warp = SDL_TRUE;
        }
    }
    mouse->relative_mode = enabled;
    mouse->scale_accum_x = 0.0f;
    mouse->scale_accum_y = 0.0f;

    if (mouse->focus) {
        SDL_UpdateWindowGrab(mouse->focus);

        /* Put the cursor back to where the application expects it */
        if (!enabled) {
            SDL_WarpMouseInWindow(mouse->focus, mouse->x, mouse->y);
        }
    }

    /* Flush pending mouse motion - ideally we would pump events, but that's not always safe */
    SDL_FlushEvent(SDL_MOUSEMOTION);

    /* Update cursor visibility */
    SDL_SetCursor(NULL);

    return 0;
}
Example #8
0
static mrb_value
mrb_sdl2_input_flush_event(mrb_state *mrb, mrb_value self)
{
  mrb_int min, max;
  int const argc = mrb_get_args(mrb, "i|i", &min, &max);
  if (1 == argc) {
    SDL_FlushEvent(min);
  } else {
    SDL_FlushEvents(min, max);
  }
  return self;
}
Example #9
0
void geGUIBase::doDragDropSynchronous(MDropData *dropData)
{
    SDL_Event event;
    event.type = SDL_DROPFILE;
    event.drop.file = (char*)dropData;
    
    SDL_PumpEvents();
    while (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT))
    {
        //stop the thread
        SDL_PumpEvents();
    }
    SDL_FlushEvent(SDL_MOUSEMOTION);
    SDL_PushEvent(&event);
}
Example #10
0
void mouselook_update(mouselook_state* state,
                      parchment* bg,
                      const SDL_MouseMotionEvent* evt,
                      angle fov_x, angle fov_y) {
  /* Ignore the first event that comes in during the process's lifetime, as it
   * will usually have large relative movements (since the initial position is
   * zero or so, regardless of the actual position).
   */
  static int ignore_next_event = 4;
  angle old_yrot = state->yrot, old_rxrot = state->rxrot;
  signed rxrot = state->rxrot;
  int w, h;
  SDL_GetWindowSize(window, &w, &h);

  /* Do nothing if this event is to be ignored because it was generated by a
   * call to SDL_WarpMouseInWindow().
   */
  if (ignore_next_event) {
    --ignore_next_event;
    SDL_FlushEvent(SDL_MOUSEMOTION);
    return;
  }

  /* Do nothing if not currently enabled */
  if (!is_enabled) return;

  /* TODO: Adjustable sensitivity */
  state->yrot += evt->xrel * DEG_180 / 1024;
  rxrot -= evt->yrel * DEG_180 / 1024;
  if (rxrot < -DEG_90) rxrot = -DEG_90;
  if (rxrot > +DEG_90) rxrot = +DEG_90;
  state->rxrot = rxrot;

  if (bg)
    parchment_xform(bg, old_yrot, old_rxrot,
                    state->yrot, state->rxrot,
                    fov_x, fov_y,
                    w, h);

  /* If necessary, warp cursor.
   * This generates another motion event, which we'll need to ignore on the
   * next call.
   */
  if (emulate_srmm) {
    SDL_WarpMouseInWindow(window, w/2, h/2);
    ignore_next_event = 1;
  }
}
Example #11
0
int
SDL_SetRelativeMouseMode(SDL_bool enabled)
{
    SDL_Mouse *mouse = SDL_GetMouse();
    SDL_Window *focusWindow = SDL_GetKeyboardFocus();
    int original_x = mouse->x, original_y = mouse->y;

    if (enabled == mouse->relative_mode) {
        return 0;
    }

    if (!mouse->SetRelativeMouseMode) {
        return SDL_Unsupported();
    }

    if (enabled && focusWindow) {
        /* Center it in the focused window to prevent clicks from going through
         * to background windows.
         */
        SDL_SetMouseFocus(focusWindow);
        SDL_WarpMouseInWindow(focusWindow, focusWindow->w/2, focusWindow->h/2);
    }

    if (mouse->SetRelativeMouseMode(enabled) < 0) {
        return -1;
    }

    /* Set the relative mode */
    mouse->relative_mode = enabled;

    if (enabled) {
        /* Save the expected mouse position */
        mouse->original_x = original_x;
        mouse->original_y = original_y;
    } else if (mouse->focus) {
        /* Restore the expected mouse position */
        SDL_WarpMouseInWindow(mouse->focus, mouse->original_x, mouse->original_y);
    }

    /* Flush pending mouse motion */
    SDL_FlushEvent(SDL_MOUSEMOTION);

    /* Update cursor visibility */
    SDL_SetCursor(NULL);

    return 0;
}
Example #12
0
    /// \brief Set the mouse to relative positioning. Doesn't move the cursor
    ///        and disables mouse acceleration.
    void InputWrapper::setMouseRelative(bool relative)
    {
        if(mMouseRelative == relative && mMouseInWindow)
            return;

        mMouseRelative = relative && mMouseInWindow;

        mWrapPointer = false;

        //eep, wrap the pointer manually if the input driver doesn't support
        //relative positioning natively
        int success = SDL_SetRelativeMouseMode(relative && mMouseInWindow ? SDL_TRUE : SDL_FALSE);
        if(relative && mMouseInWindow && success != 0)
            mWrapPointer = true;

        //now remove all mouse events using the old setting from the queue
        SDL_PumpEvents();
        SDL_FlushEvent(SDL_MOUSEMOTION);
    }
int
SDL_SetRelativeMouseMode(SDL_bool enabled)
{
    SDL_Mouse *mouse = &SDL_mouse;

    /* Flush pending mouse motion */
    SDL_FlushEvent(SDL_MOUSEMOTION);

    /* Set the relative mode */
    mouse->relative_mode = enabled;

    if (!enabled) {
        /* Restore the expected mouse position */
        SDL_WarpMouseInWindow(mouse->focus, mouse->x, mouse->y);
    }

    /* Update cursor visibility */
    SDL_SetCursor(NULL);

    return 0;
}
Example #14
0
int
SDL_SetRelativeMouseMode(SDL_bool enabled)
{
    SDL_Mouse *mouse = SDL_GetMouse();

    if (enabled == mouse->relative_mode) {
        return 0;
    }

    if (!mouse->SetRelativeMouseMode) {
        SDL_Unsupported();
        return -1;
    }

    if (mouse->SetRelativeMouseMode(enabled) < 0) {
        return -1;
    }

    /* Set the relative mode */
    mouse->relative_mode = enabled;

    if (enabled) {
        /* Save the expected mouse position */
        mouse->original_x = mouse->x;
        mouse->original_y = mouse->y;
    } else if (mouse->focus) {
        /* Restore the expected mouse position */
        SDL_WarpMouseInWindow(mouse->focus, mouse->original_x, mouse->original_y);
    }

    /* Flush pending mouse motion */
    SDL_FlushEvent(SDL_MOUSEMOTION);

    /* Update cursor visibility */
    SDL_SetCursor(NULL);

    return 0;
}
Example #15
0
    //-----------------------------------------------------------------------------------
    void SdlInputHandler::updateMouseSettings(void)
    {
        mGrabPointer = mWantMouseGrab && mMouseInWindow && mWindowHasFocus;
        SDL_SetWindowGrab( mSdlWindow, mGrabPointer ? SDL_TRUE : SDL_FALSE );

        SDL_ShowCursor( mWantMouseVisible || !mWindowHasFocus );

        bool relative = mWantRelative && mMouseInWindow && mWindowHasFocus;
        if( mIsMouseRelative == relative )
            return;

        mIsMouseRelative = relative;

        mWrapPointerManually = false;

        //Input driver doesn't support relative positioning. Do it manually.
        int success = SDL_SetRelativeMouseMode( relative ? SDL_TRUE : SDL_FALSE );
        if( !relative || (relative && success != 0) )
            mWrapPointerManually = true;

        //Remove all pending mouse events that were queued with the old settings.
        SDL_PumpEvents();
        SDL_FlushEvent( SDL_MOUSEMOTION );
    }
Example #16
0
// Actually put us in windowed or full screen mode.  Pass true the first time this is used, false subsequently.
// This has the unfortunate side-effect of triggering a mouse move event.
void VideoSystem::actualizeScreenMode(GameSettings *settings, bool changingInterfaces, bool currentUIUsesEditorScreenMode)
{
   DisplayMode displayMode = settings->getSetting<DisplayMode>(IniKey::WindowMode);

   DisplayManager::getScreenInfo()->resetGameCanvasSize();     // Set GameCanvasSize vars back to their default values
   DisplayManager::getScreenInfo()->setActualized();


   // If old display mode is windowed or current is windowed but we change interfaces,
   // save the window position
   if(settings->getIniSettings()->oldDisplayMode == DISPLAY_MODE_WINDOWED ||
         (changingInterfaces && displayMode == DISPLAY_MODE_WINDOWED))
   {
      settings->setWindowPosition(VideoSystem::getWindowPositionX(), VideoSystem::getWindowPositionY());
   }

   // When we're in the editor, let's take advantage of the entire screen unstretched
   // We might want to disallow this when we're in split screen mode?
   if(currentUIUsesEditorScreenMode &&
         (displayMode == DISPLAY_MODE_FULL_SCREEN_STRETCHED || displayMode == DISPLAY_MODE_FULL_SCREEN_UNSTRETCHED))
   {
      // Smaller values give bigger magnification; makes small things easier to see on full screen
      F32 magFactor = 0.85f;

      // For screens smaller than normal, we need to readjust magFactor to make sure we get the full canvas height crammed onto
      // the screen; otherwise our dock will break.  Since this mode is only used in the editor, we don't really care about
      // screen width; tall skinny screens will work just fine.
      magFactor = max(magFactor, (F32)DisplayManager::getScreenInfo()->getGameCanvasHeight() / (F32)DisplayManager::getScreenInfo()->getPhysicalScreenHeight());

      DisplayManager::getScreenInfo()->setGameCanvasSize(S32(DisplayManager::getScreenInfo()->getPhysicalScreenWidth() * magFactor), S32(DisplayManager::getScreenInfo()->getPhysicalScreenHeight() * magFactor));

      displayMode = DISPLAY_MODE_FULL_SCREEN_STRETCHED;
   }


   // Set up video/window flags amd parameters and get ready to change the window
   S32 sdlWindowWidth, sdlWindowHeight;
   F64 orthoLeft, orthoRight, orthoTop, orthoBottom;

   getWindowParameters(settings, displayMode, sdlWindowWidth, sdlWindowHeight, orthoLeft, orthoRight, orthoTop, orthoBottom);

   // Change video modes based on selected display mode
   // Note:  going into fullscreen you have to do in order:
   //  - SDL_SetWindowSize()
   //  - SDL_SetWindowFullscreen()
   //
   // However, coming out of fullscreen mode you must do the reverse
   switch (displayMode)
   {
   case DISPLAY_MODE_FULL_SCREEN_STRETCHED:
      SDL_SetWindowSize(DisplayManager::getScreenInfo()->sdlWindow, sdlWindowWidth, sdlWindowHeight);
      SDL_SetWindowFullscreen(DisplayManager::getScreenInfo()->sdlWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);

      break;

   case DISPLAY_MODE_FULL_SCREEN_UNSTRETCHED:
      SDL_SetWindowSize(DisplayManager::getScreenInfo()->sdlWindow, sdlWindowWidth, sdlWindowHeight);
      SDL_SetWindowFullscreen(DisplayManager::getScreenInfo()->sdlWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);

      break;

   case DISPLAY_MODE_WINDOWED:
   default:
      // Reverse order, leave fullscreen before setting size
      SDL_SetWindowFullscreen(DisplayManager::getScreenInfo()->sdlWindow, 0);
      SDL_SetWindowSize(DisplayManager::getScreenInfo()->sdlWindow, sdlWindowWidth, sdlWindowHeight);
      break;
   }

   if(settings->getSetting<YesNo>(IniKey::DisableScreenSaver))
      SDL_DisableScreenSaver();
   else
      SDL_EnableScreenSaver();

   // Flush window events because SDL_SetWindowSize triggers a SDL_WINDOWEVENT_RESIZED 
   // event (which in turn triggers another SDL_SetWindowSize)
   SDL_FlushEvent(SDL_WINDOWEVENT);

   SDL_GL_SetSwapInterval(settings->getSetting<YesNo>(IniKey::Vsync) ? 1 : 0);

   // Now save the new window dimensions in ScreenInfo
   DisplayManager::getScreenInfo()->setWindowSize(sdlWindowWidth, sdlWindowHeight);

   mGL->glClearColor(0, 0, 0, 0);

   mGL->glViewport(0, 0, sdlWindowWidth, sdlWindowHeight);

   mGL->glMatrixMode(GLOPT::Projection);
   mGL->glLoadIdentity();

   // The best understanding I can get for glOrtho is that these are the coordinates you want to appear at the four corners of the
   // physical screen. If you want a "black border" down one side of the screen, you need to make left negative, so that 0 would
   // appear some distance in from the left edge of the physical screen.  The same applies to the other coordinates as well.
   mGL->glOrtho(orthoLeft, orthoRight, orthoBottom, orthoTop, 0, 1);

   mGL->glMatrixMode(GLOPT::Modelview);
   mGL->glLoadIdentity();

   // Do the scissoring
   if(displayMode == DISPLAY_MODE_FULL_SCREEN_UNSTRETCHED)
   {
      mGL->glScissor(DisplayManager::getScreenInfo()->getHorizPhysicalMargin(),    // x
                DisplayManager::getScreenInfo()->getVertPhysicalMargin(),     // y
                DisplayManager::getScreenInfo()->getDrawAreaWidth(),          // width
                DisplayManager::getScreenInfo()->getDrawAreaHeight());        // height
   }
   else
   {
      // Enabling scissor appears to fix crashing problem switching screen mode
      // in linux and "Mobile 945GME Express Integrated Graphics Controller",
      // probably due to lines and points was not being clipped,
      // causing some lines to wrap around the screen, or by writing other
      // parts of RAM that can crash Bitfighter, graphics driver, or the entire computer.
      // This is probably a bug in the Linux Intel graphics driver.
      mGL->glScissor(0, 0, DisplayManager::getScreenInfo()->getWindowWidth(), DisplayManager::getScreenInfo()->getWindowHeight());
   }

   mGL->glEnable(GLOPT::ScissorTest);    // Turn on clipping

   mGL->setDefaultBlendFunction();
   mGL->glLineWidth(RenderUtils::DEFAULT_LINE_WIDTH);

   // Enable Line smoothing everywhere!  Make sure to disable temporarily for filled polygons and such
   if(settings->getSetting<YesNo>(IniKey::LineSmoothing))
   {
      mGL->glEnable(GLOPT::LineSmooth);
      //glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
   }

   mGL->glEnable(GLOPT::Blend);

   // Now set the window position
   if(displayMode == DISPLAY_MODE_WINDOWED)
   {
      // Sometimes it happens to be (0,0) hiding the top title bar preventing ability to
      // move the window, in this case we are not moving it unless it is not (0,0).
      // Note that ini config file will default to (0,0).
      if(settings->getWindowPositionX() != 0 || settings->getWindowPositionY() != 0)
         setWindowPosition(settings->getWindowPositionX(), settings->getWindowPositionY());
   }
   else
      setWindowPosition(0, 0);

   // Notify all active UIs that the screen has changed mode.  This will likely need some work to not do something
   // horrible in split-screen mode.
   const Vector<ClientGame *> *clientGames = GameManager::getClientGames();
   for(S32 i = 0; i < clientGames->size(); i++)
      if(clientGames->get(i)->getUIManager()->getCurrentUI())
         clientGames->get(i)->getUIManager()->getCurrentUI()->onDisplayModeChange();

   // Re-initialize our fonts because OpenGL textures can be lost upon screen change
   FontManager::reinitialize(settings);

   // This needs to happen after font re-initialization because I think fontstash interferes
   // with the oglconsole font somehow...
   GameManager::gameConsole->onScreenModeChanged();
}
Example #17
0
static int
SDL_CompatEventFilter(void *userdata, SDL_Event * event)
{
    SDL_Event fake;

    switch (event->type) {
    case SDL_WINDOWEVENT:
        switch (event->window.event) {
        case SDL_WINDOWEVENT_EXPOSED:
            if (!SDL_HasEvent(SDL_VIDEOEXPOSE)) {
                fake.type = SDL_VIDEOEXPOSE;
                SDL_PushEvent(&fake);
            }
            break;
        case SDL_WINDOWEVENT_RESIZED:
            SDL_FlushEvent(SDL_VIDEORESIZE);
            /* We don't want to expose that the window width and height will
               be different if we don't get the desired fullscreen mode.
            */
            if (SDL_VideoWindow && !(SDL_GetWindowFlags(SDL_VideoWindow) & SDL_WINDOW_FULLSCREEN)) {
                fake.type = SDL_VIDEORESIZE;
                fake.resize.w = event->window.data1;
                fake.resize.h = event->window.data2;
                SDL_PushEvent(&fake);
            }
            break;
        case SDL_WINDOWEVENT_MINIMIZED:
            fake.type = SDL_ACTIVEEVENT;
            fake.active.gain = 0;
            fake.active.state = SDL_APPACTIVE;
            SDL_PushEvent(&fake);
            break;
        case SDL_WINDOWEVENT_RESTORED:
            fake.type = SDL_ACTIVEEVENT;
            fake.active.gain = 1;
            fake.active.state = SDL_APPACTIVE;
            SDL_PushEvent(&fake);
            break;
        case SDL_WINDOWEVENT_ENTER:
            fake.type = SDL_ACTIVEEVENT;
            fake.active.gain = 1;
            fake.active.state = SDL_APPMOUSEFOCUS;
            SDL_PushEvent(&fake);
            break;
        case SDL_WINDOWEVENT_LEAVE:
            fake.type = SDL_ACTIVEEVENT;
            fake.active.gain = 0;
            fake.active.state = SDL_APPMOUSEFOCUS;
            SDL_PushEvent(&fake);
            break;
        case SDL_WINDOWEVENT_FOCUS_GAINED:
            fake.type = SDL_ACTIVEEVENT;
            fake.active.gain = 1;
            fake.active.state = SDL_APPINPUTFOCUS;
            SDL_PushEvent(&fake);
            break;
        case SDL_WINDOWEVENT_FOCUS_LOST:
            fake.type = SDL_ACTIVEEVENT;
            fake.active.gain = 0;
            fake.active.state = SDL_APPINPUTFOCUS;
            SDL_PushEvent(&fake);
            break;
        case SDL_WINDOWEVENT_CLOSE:
            fake.type = SDL_QUIT;
            SDL_PushEvent(&fake);
            break;
        }
    case SDL_KEYDOWN:
    case SDL_KEYUP:
        {
            Uint32 unicode = 0;
            if (event->key.type == SDL_KEYDOWN && event->key.keysym.sym < 256) {
                unicode = event->key.keysym.sym;
                if (unicode >= 'a' && unicode <= 'z') {
                    int shifted = !!(event->key.keysym.mod & KMOD_SHIFT);
                    int capslock = !!(event->key.keysym.mod & KMOD_CAPS);
                    if ((shifted ^ capslock) != 0) {
                        unicode = SDL_toupper(unicode);
                    }
                }
            }
            if (unicode) {
                event->key.keysym.unicode = unicode;
            }
            break;
        }
    case SDL_TEXTINPUT:
        {
            /* FIXME: Generate an old style key repeat event if needed */
            //printf("TEXTINPUT: '%s'\n", event->text.text);
            break;
        }
    case SDL_MOUSEMOTION:
        {
            event->motion.x -= SDL_VideoViewport.x;
            event->motion.y -= SDL_VideoViewport.y;
            break;
        }
    case SDL_MOUSEBUTTONDOWN:
    case SDL_MOUSEBUTTONUP:
        {
            event->button.x -= SDL_VideoViewport.x;
            event->button.y -= SDL_VideoViewport.y;
            break;
        }
    case SDL_MOUSEWHEEL:
        {
            Uint8 button;
            int x, y;

            if (event->wheel.y == 0) {
                break;
            }

            SDL_GetMouseState(&x, &y);

            if (event->wheel.y > 0) {
                button = SDL_BUTTON_WHEELUP;
            } else {
                button = SDL_BUTTON_WHEELDOWN;
            }

            fake.button.button = button;
            fake.button.x = x;
            fake.button.y = y;
            fake.button.windowID = event->wheel.windowID;

            fake.type = SDL_MOUSEBUTTONDOWN;
            fake.button.state = SDL_PRESSED;
            SDL_PushEvent(&fake);

            fake.type = SDL_MOUSEBUTTONUP;
            fake.button.state = SDL_RELEASED;
            SDL_PushEvent(&fake);
            break;
        }

    }
    return 1;
}
Example #18
0
File: main.c Project: odrevet/GE2
/**
   Display a menu to resize the map
   enter the new map size for width, height and depth. 

TODO
   if the value entered is lower than the current map size 
   ask if the tiles to delete are at front or at rear
TODO
   if the value entered is higher than the current map size
   ask if the tile to create are at front or a rear and select
   in the chipset which tile to fill
 */
game_status state_resize_menu(SDL_Renderer *renderer, game* p_game){
  bool done=false;

  char text[BUFSIZ] = {'\0'}; 
  map *p_map = p_game->p_map;
  int new_width,  new_height, new_depth;

  //flush the keys input which triggered this game state
  SDL_FlushEvent(SDL_TEXTINPUT);
  
  SDL_StartTextInput();
  while (!done){
    //draw
    SDL_RenderClear(renderer);
    SDL_SetRenderDrawColor(renderer, 0x22, 0x22, 0x42, 0x4F);
    SDL_Rect r = {.x=0, .y=0, .w=SCREEN_WIDTH, .h=SCREEN_HEIGHT};
    SDL_RenderFillRect(renderer, &r);
    fontmap_printf(p_game->p_fontmap, 0, p_game->p_fontmap->size, renderer,
		   "CURRENT MAP SIZE WIDTH %d HEIGHT %d DEPTH %d\n\
ENTER NEW SIZE WITH FORMAT %d-%d-%d ",
		   p_map->width, p_map->height, p_map->depth,
		   p_map->width, p_map->height, p_map->depth);


    //print back to the user the entered text
    fontmap_printf(p_game->p_fontmap, 0, p_game->p_fontmap->size*3, renderer, text);

    //render
    SDL_RenderPresent(renderer);

    //input
    SDL_Event event;
    while (SDL_PollEvent(&event)){

      if(event.type ==  SDL_QUIT){
	exit(EXIT_SUCCESS);
      }
      
      switch ( event.type )
	{
	case SDL_KEYDOWN:
	  switch (event.key.keysym.sym)
	    {
	    case SDLK_q:
	      done=true;
	      break;
	      case SDLK_RETURN:
		//assign integers from the formated input
		sscanf(text, "%d-%d-%d", &new_width, &new_height, &new_depth);
		  
		//allocate memory
	        tile *tiles = calloc(new_width*new_height*new_depth, sizeof(tile));

		//copy the current map tile into the new tiles
		memmove(tiles, p_map->tiles, p_map->height*p_map->width*p_map->depth);

		//free map tiles
		free(p_map->tiles);

		//allocate new tiles
		p_map->tiles = tiles;
		p_map->width = new_width;
		p_map->height = new_height;
		p_map->depth = new_depth;
		
		break;
	    case SDLK_BACKSPACE:
	      //remove the last character by replacing it by the EOS char
	      text[strlen(text)-1] = '\0';
	      break;
	    }
	  break;
	case SDL_TEXTINPUT:
	  strcat(text, event.text.text);
	  break;
	}
    }
  }

  SDL_StopTextInput();
  return STAY;
}


void game_tile_click(game* p_game,
		    int x,
		    int y,
		    Uint8 button){
  map *p_map = p_game->p_map;
  int x_offset = p_map->p_chipset->width;
  int y_offset = p_map->p_chipset->height;
  
  if(x < x_offset && y < y_offset){
    //the click was on the chipset part
    //set the chipset tile
    p_map->chipset_tile_x_index = x / p_map->tile_width;
    p_map->chipset_tile_y_index = y / p_map->tile_height;
  }
  else{
    //the clic was on the map part
    //change the clicked map tile with the selected chipset tile   
    //check if the index is in the map boundaries
    if(p_map->map_tile_x_index >= 0 &&
       p_map->map_tile_x_index < p_map->width &&
       p_map->map_tile_y_index >= 0 &&
       p_map->map_tile_y_index < p_map->height){

      tile* p_tile = map_get_tile(p_map,
				  p_map->map_tile_x_index,
				  p_map->map_tile_y_index,
				  p_map->map_tile_z_index);
	
      switch(p_game->tile_mode){
      default:
      case TILE:
	tile_set_coord(p_tile,
		       p_map->chipset_tile_x_index,
		       p_map->chipset_tile_y_index);
	break;
      case LINE:
	if(p_game->tile_from_x < 0 ||
	   p_game->tile_from_y < 0 ||
	   p_game->tile_from_z < 0){
	  //set the tile to draw from
	  p_game->tile_from_x = p_map->map_tile_x_index;
	  p_game->tile_from_y = p_map->map_tile_y_index;
	  p_game->tile_from_z = p_map->map_tile_z_index;	  
	}
	else{
	  //set the tile to draw to
	  //the tile to draw to is always superior to the tile to draw from
	  if(p_map->map_tile_x_index < p_game->tile_from_x){
	    p_game->tile_to_x = p_game->tile_from_x;
	    p_game->tile_from_x = p_map->map_tile_x_index;
	  }
	  else{
	     p_game->tile_to_x = p_map->map_tile_x_index;
	  }
	  
	  if(p_map->map_tile_y_index < p_game->tile_from_y){
	    p_game->tile_to_y = p_game->tile_from_y;
	    p_game->tile_from_y = p_map->map_tile_y_index;
	  }
	  else{
	     p_game->tile_to_y = p_map->map_tile_y_index;
	  }

	  if(p_map->map_tile_z_index < p_game->tile_from_z){
	    p_game->tile_to_z = p_game->tile_from_z;
	    p_game->tile_from_z = p_map->map_tile_z_index;
	  }
	  else{
	     p_game->tile_to_z = p_map->map_tile_z_index;
	  }
	  
	  for(int x=p_game->tile_from_x;x<=p_game->tile_to_x;x++){
	    for(int y=p_game->tile_from_y;y<=p_game->tile_to_y;y++){
	      for(int z=p_game->tile_from_z;z<=p_game->tile_to_z;z++){
		p_tile = map_get_tile(p_map, x, y, z);
		tile_set_coord(p_tile,
			       p_map->chipset_tile_x_index,
			       p_map->chipset_tile_y_index);
	      }
	    }
	  }
	  p_game->tile_from_x = -1;
	  p_game->tile_from_y = -1;
	  p_game->tile_from_z = -1;
	  p_game->tile_to_x = -1;
	  p_game->tile_to_y = -1;
	  p_game->tile_to_z = -1;	  
	}
	break;
      }
    }
  }

#ifdef DEBUG
    printf("map clicked at index %d %d %d\n",
	   p_map->map_tile_x_index,
	   p_map->map_tile_y_index,
	   p_map->map_tile_z_index);
#endif  
}
Example #19
0
bool Window::createWindowAndContext(int x, int y, int w, int h, Uint32 windowflags, int msaa, bool stencil, int depth)
{
	std::vector<ContextAttribs> attribslist = getContextAttribsList();

	std::string windowerror;
	std::string contexterror;
	std::string glversion;

	// Unfortunately some OpenGL context settings are part of the internal
	// window state in the Windows and Linux SDL backends, so we have to
	// recreate the window when we want to change those settings...
	// Also, apparently some Intel drivers on Windows give back a Microsoft
	// OpenGL 1.1 software renderer context when high MSAA values are requested!

	const auto create = [&](ContextAttribs attribs) -> bool
	{
		if (context)
		{
			SDL_GL_DeleteContext(context);
			context = nullptr;
		}

		if (window)
		{
			SDL_DestroyWindow(window);
			SDL_FlushEvent(SDL_WINDOWEVENT);
			window = nullptr;
		}

		window = SDL_CreateWindow(title.c_str(), x, y, w, h, windowflags);

		if (!window)
		{
			windowerror = std::string(SDL_GetError());
			return false;
		}

		context = SDL_GL_CreateContext(window);

		if (!context)
			contexterror = std::string(SDL_GetError());

		// Make sure the context's version is at least what we requested.
		if (context && !checkGLVersion(attribs, glversion))
		{
			SDL_GL_DeleteContext(context);
			context = nullptr;
		}

		if (!context)
		{
			SDL_DestroyWindow(window);
			window = nullptr;
			return false;
		}

		return true;
	};

	// Try each context profile in order.
	for (ContextAttribs attribs : attribslist)
	{
		int curMSAA  = msaa;
		bool curSRGB = love::graphics::isGammaCorrect();

		setGLFramebufferAttributes(curMSAA, curSRGB, stencil, depth);
		setGLContextAttributes(attribs);

		windowerror.clear();
		contexterror.clear();

		create(attribs);

		if (!window && curMSAA > 0)
		{
			// The MSAA setting could have caused the failure.
			setGLFramebufferAttributes(0, curSRGB, stencil, depth);
			if (create(attribs))
				curMSAA = 0;
		}

		if (!window && curSRGB)
		{
			// same with sRGB.
			setGLFramebufferAttributes(curMSAA, false, stencil, depth);
			if (create(attribs))
				curSRGB = false;
		}

		if (!window && curMSAA > 0 && curSRGB)
		{
			// Or both!
			setGLFramebufferAttributes(0, false, stencil, depth);
			if (create(attribs))
			{
				curMSAA = 0;
				curSRGB = false;
			}
		}

		if (window && context)
		{
			// Store the successful context attributes so we can re-use them in
			// subsequent calls to createWindowAndContext.
			contextAttribs = attribs;
			love::graphics::setGammaCorrect(curSRGB);
			break;
		}
	}

	if (!context || !window)
	{
		std::string title = "Unable to create OpenGL window";
		std::string message = "This program requires a graphics card and video drivers which support OpenGL 2.1 or OpenGL ES 2.";

		if (!glversion.empty())
			message += "\n\nDetected OpenGL version:\n" + glversion;
		else if (!contexterror.empty())
			message += "\n\nOpenGL context creation error: " + contexterror;
		else if (!windowerror.empty())
			message += "\n\nSDL window creation error: " + windowerror;

		std::cerr << title << std::endl << message << std::endl;

		// Display a message box with the error, but only once.
		if (!displayedWindowError)
		{
			showMessageBox(title, message, MESSAGEBOX_ERROR, false);
			displayedWindowError = true;
		}

		close();
		return false;
	}

	open = true;
	return true;
}
Example #20
0
void SDLInput::Init()
{
	SDL_FlushEvent(SDL_KEYDOWN);  
}