Example #1
0
Uint32 temp_shift_release_callback(Uint32 interval, void *param) {
	const Uint8* state = SDL_GetKeyboardState(NULL);
	if (state[SDL_SCANCODE_LSHIFT]) key_states[SDL_SCANCODE_LSHIFT] = 1;
	if (state[SDL_SCANCODE_RSHIFT]) key_states[SDL_SCANCODE_RSHIFT] = 1;
	return 0; // causes the timer to be removed
}
Example #2
0
void Player::render(SDL_Renderer* gRenderer, const SDL_Rect &mapVisibleLevel){

    if(dieTimer.isStarted()){ //play death animation
        if(dieTimer.getTicks() > PLAYER_DIE_TIME){
            died = true;
        }else if(dieTimer.getTicks() > frame * (PLAYER_DIE_TIME/4) + (PLAYER_DIE_TIME/4)){
            frame = (frame + 1) % 4; //change frame
        }
        SDL_Rect* currentClip = &gSpriteClips[ frame ];
        gAnimDeath->render( pos.x - mapVisibleLevel.x, pos.y, currentClip );
        return;
    }

    if(fireTimer.isStarted() && fireTimer.getTicks() < PLAYER_FIRE_ANIM_TIME){ //play fire animation
        LTexture* fireAnim;
        if(facingLeft()){
            fireAnim = gFireTextureLeft;
        }else{
            fireAnim = gFireTextureRight;
        }

        fireAnim->render(pos.x - mapVisibleLevel.x, pos.y);

        SDL_RenderPresent( gRenderer );
        return;
    }else if(jumpTimer.isStarted()){ //render with jump texture
        LTexture* jumpAnim;
        if(facingLeft()){
            jumpAnim = gJumpTextureLeft;
        }else{
            jumpAnim = gJumpTextureRight;
        }

        jumpAnim->render(pos.x - mapVisibleLevel.x, pos.y);

        SDL_RenderPresent( gRenderer );
        return;
    }

    const Uint8* currentKeyStates = SDL_GetKeyboardState( NULL ); //get pressed key

    if( currentKeyStates[ SDL_SCANCODE_RIGHT ] || currentKeyStates[ SDL_SCANCODE_LEFT ]){
        if(!walkTimer.isStarted()){
            walkTimer.start();
        }

        if(walkTimer.getTicks() > PLAYER_FIRE_ANIM_TIME){
            frame++;

            //Cycle animation
            if( frame >= WALKING_ANIMATION_FRAMES ){
                frame = 0;
            }
            walkTimer.reset();
        }
    }

    SDL_Rect* currentClip = &gSpriteClips[ frame ];

    LTexture* anim = gAnimRight;

    if(facingLeft()){
        anim = gAnimLeft;
    }

    anim->render( pos.x - mapVisibleLevel.x, pos.y, currentClip );
}
Example #3
0
void update(SDL_Event& event)
{
	const Uint8* state = SDL_GetKeyboardState(NULL);
	if (state[SDL_SCANCODE_LEFT]) {
		camX -= CAM_INC;
	}
	else if (state[SDL_SCANCODE_RIGHT]) {
		camX += CAM_INC;
	}
	if (state[SDL_SCANCODE_UP]) {
		camY -= CAM_INC;
	}
	else if (state[SDL_SCANCODE_DOWN]) {
		camY += CAM_INC;
	}

	if (state[SDL_SCANCODE_P]) {
		input_offset++;
	}
	else if(state[SDL_SCANCODE_O]) {
		input_offset--;
	}

	if (state[SDL_SCANCODE_L]) {
		input_scale += 0.2;
	}
	else if (state[SDL_SCANCODE_K]) {
		input_scale -= 0.2;
	}

	if (state[SDL_SCANCODE_M]) {
		reset_view();
	}
	if (state[SDL_SCANCODE_F]) {
		input_draw_space = !input_draw_space;
	}

	SDL_GetMouseState(&mouse_x, &mouse_y);

	if (event.type == SDL_MOUSEBUTTONDOWN) {
		if (event.button.button == SDL_BUTTON_LEFT) {
			if(!mouseLeftPressed) {
				mouseLeftPressed = true;
				mouseLeft = false;
			}
		}
		else if (event.button.button == SDL_BUTTON_RIGHT) {
			if (!mouseRightPressed) {
				mouseRightPressed = true;
				mouseRight = false;
			}
		}
	}
	else if (event.type == SDL_MOUSEBUTTONUP) {
		if (event.button.button == SDL_BUTTON_LEFT) {
			if (mouseLeftPressed) {
				mouseLeftPressed = false;
				mouseLeft = true;
			}
		}
		else if (event.button.button == SDL_BUTTON_RIGHT) {
			if (mouseRightPressed) {
				mouseRightPressed = false;
				mouseRight = true;
			}
		}
	}
	else if (event.type == SDL_KEYDOWN) {
		if (event.key.keysym.sym == SDLK_s) {
			if (!key1Pressed) {
				key1Pressed = true;
				key1 = false;
			}
		}
		else if (event.key.keysym.sym == SDLK_d) {
			if (!key2Pressed) {
				key2Pressed = true;
				key2 = false;
			}
		}
		else if (event.key.keysym.sym == SDLK_f) {
			if (!keyDebugPressed) {
				keyDebugPressed = true;
				keyDebug = false;
			}
		}
	}
	else if (event.type == SDL_KEYUP) {
		if (event.key.keysym.sym == SDLK_s) {
			if (key1Pressed) {
				key1Pressed = false;
				key1 = true;
			}
		}
		else if (event.key.keysym.sym == SDLK_d) {
			if (key2Pressed) {
				key2Pressed = false;
				key2 = true;
			}
		}
		else if (event.key.keysym.sym == SDLK_f) {
			if (keyDebugPressed) {
				keyDebugPressed = false;
				keyDebug = true;
			}
		}
	}

	if (mouseLeft) {
		mouseLeft = false;
		std::cout << "mouse click left\n";
		mouseClick(MOUSE_LEFT);
	}
	if (mouseRight) {
		mouseRight = false;
		std::cout << "mouse click right\n";
		mouseClick(MOUSE_RIGHT);
	}

	if (key1) {
		key1 = false;
		std::cout << "key1\n";
		keyClick(1);
	}
	else if (key2) {
		key2 = false;
		std::cout << "key2\n";
		keyClick(2);
	}

	if (keyDebug) {
		keyDebug = false;
		input_show_debug_rect = !input_show_debug_rect;
	}

	/*rect.x = i * tileSizeX;
	rect.y = WIN_HEIGHT - tileSizeY;*/
}
Example #4
0
int CInput::Update()
{
	// keep the counter between 1..0xFFFF, 0 means not pressed
	m_InputCounter = (m_InputCounter%0xFFFF)+1;

	{
		int i;
		const Uint8 *pState = SDL_GetKeyboardState(&i);
		if(i >= KEY_LAST)
			i = KEY_LAST-1;
		mem_copy(m_aInputState, pState, i);
	}

	// these states must always be updated manually because they are not in the GetKeyState from SDL
	int i = SDL_GetMouseState(NULL, NULL);
	if(i&SDL_BUTTON(1)) m_aInputState[KEY_MOUSE_1] = 1; // 1 is left
	if(i&SDL_BUTTON(3)) m_aInputState[KEY_MOUSE_2] = 1; // 3 is right
	if(i&SDL_BUTTON(2)) m_aInputState[KEY_MOUSE_3] = 1; // 2 is middle
	if(i&SDL_BUTTON(4)) m_aInputState[KEY_MOUSE_4] = 1;
	if(i&SDL_BUTTON(5)) m_aInputState[KEY_MOUSE_5] = 1;
	if(i&SDL_BUTTON(6)) m_aInputState[KEY_MOUSE_6] = 1;
	if(i&SDL_BUTTON(7)) m_aInputState[KEY_MOUSE_7] = 1;
	if(i&SDL_BUTTON(8)) m_aInputState[KEY_MOUSE_8] = 1;
	if(i&SDL_BUTTON(9)) m_aInputState[KEY_MOUSE_9] = 1;

	{
		SDL_Event Event;

		while(SDL_PollEvent(&Event))
		{
			int Key = -1;
			int Scancode = 0;
			int Action = IInput::FLAG_PRESS;
			switch (Event.type)
			{
				case SDL_TEXTINPUT:
					AddEvent(Event.text.text, 0, IInput::FLAG_TEXT);
					break;

				// handle keys
				case SDL_KEYDOWN:
					Key = KeycodeToKey(Event.key.keysym.sym);
					Scancode = Event.key.keysym.scancode;
					break;
				case SDL_KEYUP:
					Action = IInput::FLAG_RELEASE;
					Key = KeycodeToKey(Event.key.keysym.sym);
					Scancode = Event.key.keysym.scancode;
					break;

				// handle the joystick events
				case SDL_JOYBUTTONUP:
					Action = IInput::FLAG_RELEASE;

					// fall through
				case SDL_JOYBUTTONDOWN:
					Key = Event.jbutton.button + KEY_JOYSTICK_BUTTON_0;
					Scancode = Key;
					break;

				case SDL_JOYHATMOTION:
					switch (Event.jhat.value) {
					case SDL_HAT_LEFTUP:
						Key = KEY_JOY_HAT_LEFTUP;
						Scancode = Key;
						m_PreviousHat = Key;
						break;
					case SDL_HAT_UP:
						Key = KEY_JOY_HAT_UP;
						Scancode = Key;
						m_PreviousHat = Key;
						break;
					case SDL_HAT_RIGHTUP:
						Key = KEY_JOY_HAT_RIGHTUP;
						Scancode = Key;
						m_PreviousHat = Key;
						break;
					case SDL_HAT_LEFT:
						Key = KEY_JOY_HAT_LEFT;
						Scancode = Key;
						m_PreviousHat = Key;
						break;
					case SDL_HAT_CENTERED:
						Action = IInput::FLAG_RELEASE;
						Key = m_PreviousHat;
						Scancode = m_PreviousHat;
						m_PreviousHat = 0;
						break;
					case SDL_HAT_RIGHT:
						Key = KEY_JOY_HAT_RIGHT;
						Scancode = Key;
						m_PreviousHat = Key;
						break;
					case SDL_HAT_LEFTDOWN:
						Key = KEY_JOY_HAT_LEFTDOWN;
						Scancode = Key;
						m_PreviousHat = Key;
						break;
					case SDL_HAT_DOWN:
						Key = KEY_JOY_HAT_DOWN;
						Scancode = Key;
						m_PreviousHat = Key;
						break;
					case SDL_HAT_RIGHTDOWN:
						Key = KEY_JOY_HAT_RIGHTDOWN;
						Scancode = Key;
						m_PreviousHat = Key;
						break;
					}
					break;

				// handle mouse buttons
				case SDL_MOUSEBUTTONUP:
					Action = IInput::FLAG_RELEASE;

					// fall through
				case SDL_MOUSEBUTTONDOWN:
					if(Event.button.button == SDL_BUTTON_LEFT) Key = KEY_MOUSE_1; // ignore_convention
					if(Event.button.button == SDL_BUTTON_RIGHT) Key = KEY_MOUSE_2; // ignore_convention
					if(Event.button.button == SDL_BUTTON_MIDDLE) Key = KEY_MOUSE_3; // ignore_convention
					if(Event.button.button == 4) Key = KEY_MOUSE_4; // ignore_convention
					if(Event.button.button == 5) Key = KEY_MOUSE_5; // ignore_convention
					if(Event.button.button == 6) Key = KEY_MOUSE_6; // ignore_convention
					if(Event.button.button == 7) Key = KEY_MOUSE_7; // ignore_convention
					if(Event.button.button == 8) Key = KEY_MOUSE_8; // ignore_convention
					if(Event.button.button == 9) Key = KEY_MOUSE_9; // ignore_convention
					if(Event.button.button == SDL_BUTTON_LEFT)
					{
						if(Event.button.clicks%2 == 0)
							m_MouseDoubleClick = true;
						if(Event.button.clicks == 1)
							m_MouseDoubleClick = false;
					}
					Scancode = Key;
					break;

				case SDL_MOUSEWHEEL:
					if(Event.wheel.y > 0) Key = KEY_MOUSE_WHEEL_UP; // ignore_convention
					if(Event.wheel.y < 0) Key = KEY_MOUSE_WHEEL_DOWN; // ignore_convention
					Action |= IInput::FLAG_RELEASE;
					break;

#if defined(CONF_PLATFORM_MACOSX)	// Todo SDL: remove this when fixed (mouse state is faulty on start)
				case SDL_WINDOWEVENT:
					if(Event.window.event == SDL_WINDOWEVENT_MAXIMIZED)
					{
						MouseModeAbsolute();
						MouseModeRelative();
					}
					break;
#endif

				// other messages
				case SDL_QUIT:
					return 1;
			}

			//
			if(Key != -1)
			{
				if(Action&IInput::FLAG_PRESS)
				{
					m_aInputState[Scancode] = 1;
					m_aInputCount[Key] = m_InputCounter;
				}
				AddEvent(0, Key, Action);
			}

		}
	}

	return 0;
}
Example #5
0
//TODO clean this shitty code
void Player::move(Map* map){
    if(fireTimer.isStarted() && fireTimer.getTicks() > PLAYER_FIRE_INTERVAL){
        fireTimer.stop();
    }

    //save current player position before trying to change it
    int initPosX = pos.x;
    int initPosY = pos.y;
    int initPlayerSpeed = playerSpeed;

    const Uint8* currentKeyStates = SDL_GetKeyboardState( NULL ); //get pressed key

    //TODO clean following code

    /************ HANDLE X ***************/
    checkX:
    if(!isDying() && currentKeyStates[ SDL_SCANCODE_RIGHT ]) { //right key pressed
        pos.x += playerSpeed;
    }

    if(!isDying() && currentKeyStates[ SDL_SCANCODE_LEFT ]){ //left key pressed
        pos.x -= playerSpeed;
    }
    mCollider.x = pos.x;

    //if end level or collision
    if( ( pos.x < 0 ) || ( pos.x + PLAYER_WIDTH > map->getLevelWidth() ) || map->checkCollision(mCollider, false) ){

        SDL_Rect upCollider = mCollider;
        upCollider.y -= PLAYER_CLIMB_STEP; //retry in case of 1 pixel step

        if( !jumpTimer.isStarted() && pos.x >= 0 && pos.x + PLAYER_WIDTH < map->getLevelWidth() && !map->checkCollision(upCollider, false) ){
            pos.y = upCollider.y; //move player up (because of step)
        }else{
            pos.x = initPosX;    //revert position to initPos
            mCollider.x = pos.x;

            if(playerSpeed > 0 && !jumpTimer.isStarted()){
                playerSpeed-=2; //retry with smaller displacement
                goto checkX;
            }
        }
    }

    /************ HANDLE Y ***************/
    playerSpeed = initPlayerSpeed; //save initial displacement

    gravity(map); //(try to) move playing according to gravity

    checkY:

    pos.y += mVelY; //add vertical velocity to player position
    mCollider.y = pos.y;

    //if end level or collision
    if( ( pos.y < 0 ) || ( pos.y + PLAYER_HEIGHT > SCREEN_HEIGHT - MARGIN_BOTTOM ) || map->checkCollision(mCollider, false) ){
        pos.y = initPosY; //revert to initial position
        mCollider.y = pos.y;

        if(jumpTimer.isStarted()){ //if in jump

            if(mVelY < 0){ //if going up
                mVelY = -1 * mVelY; //invert vertical velocity
            }else{ //going down
                jumpTimer.stop(); //end of jump (hit ground)
                playerSpeed=PLAYER_INIT_SPEED;
                goto checkY;
            }
        }else if(mVelY>0){ //if falling
            //mVelY=1;
            if(mVelY >= 1){
                mVelY--;
                goto checkY;
            }else{
                mVelY-=0.2;
                goto checkY;
            }
        }
    }
}
Example #6
0
inline bool is_pressed(int32_t key_code) noexcept {
    const auto* data = SDL_GetKeyboardState(nullptr);
    return data[SDL_GetScancodeFromKey(key_code)];
}
Example #7
0
inline bool is_pressed(int32_t scan_code) noexcept {
    const auto* data = SDL_GetKeyboardState(nullptr);
    return data[scan_code];
}
Example #8
0
void AKeyboard::think()
{
	keystate = SDL_GetKeyboardState(NULL);
}
Example #9
0
void run(){
	
	SDL_Window* window;
	SDL_Renderer* renderer;
	SDL_Surface* mover;
	SDL_Texture *tmover, *tbullet;
	SDL_Rect rmover;
	SDL_Event e;
	int quit = 0, mx, my, cx, cy;
	double rotate = 0;
	Bullet **bulletarray;
	const Uint8* currentKeyStates;
	
	/* Creating Window */
	SDL_Init(SDL_INIT_EVERYTHING);
	window = SDL_CreateWindow("Player", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	renderer = SDL_CreateRenderer(window, -1, 0);
	SDL_SetRenderDrawColor(renderer, 90, 90, 90, 0);
	bulletarray = initialiseshoot(renderer, &tbullet);
	
	
	/* Load Player */
	mover = SDL_LoadBMP("mover2.bmp");
	tmover = SDL_CreateTextureFromSurface(renderer, mover);
	SDL_FreeSurface(mover);
	mover = NULL;
	
	rmover.x = 320;
	rmover.y = 240;
	rmover.h = PLAYER_HEIGHT;
	rmover.w = PLAYER_WIDTH;

	/*Event loop*/
	do{
		SDL_PollEvent(&e);
		if(e.type == SDL_QUIT){
			quit = 1;
		}
		
		/* Moving Direction */
		currentKeyStates = SDL_GetKeyboardState(NULL);
		if( currentKeyStates[ SDL_SCANCODE_W ] )
		{
			rmover.y -= 2;
		}
		if( currentKeyStates[ SDL_SCANCODE_S ] )
		{
			rmover.y += 2;
		}
		if( currentKeyStates[ SDL_SCANCODE_A ] )
		{
			rmover.x -= 2;
		}
		if( currentKeyStates[ SDL_SCANCODE_D ] )
		{
			rmover.x += 2;
		}
		
		/* Rotation Angle */
		SDL_GetMouseState(&mx, &my);
		cy = rmover.y + PLAYER_HEIGHT/2;
		cx = rmover.x + PLAYER_WIDTH/2;
		rotate = (atan2(my-cy, mx-cx))*57.295;
		
		/* fire bullet */
		if(e.type == SDL_MOUSEBUTTONDOWN){
			if(e.button.button == SDL_BUTTON_LEFT){
				firebullet(bulletarray, cx, cy);
			}
		}
		
		deletebulletatboundary(bulletarray);
		bulletmovement(bulletarray);
		
		/* Update Screen */
		SDL_RenderClear(renderer);
		renderbullets(renderer, tbullet, bulletarray);
		SDL_RenderCopyEx(renderer, tmover, NULL, &rmover, rotate, NULL, SDL_FLIP_NONE);
		SDL_RenderPresent(renderer);
		
		SDL_Delay(20);
		
	}while(quit == 0);
	
	/* Memory Cleanup */
	SDL_DestroyTexture(tmover);
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);
	quitshoot(tbullet, bulletarray);
	tmover = NULL;
	renderer = NULL;
	window = NULL;
	SDL_Quit();
}
Example #10
0
//Check for any window messages (keypress, paint, mousemove, etc)
void CheckMessages()
{
    SDL_Event ev;
    bool quit = false;
    if(HandleDPad()) {
        return;
    }

    lastchar_is_mouse = false;
    while(SDL_PollEvent(&ev)) {
        switch(ev.type) {
            case SDL_WINDOWEVENT:
                switch(ev.window.event) {
                case SDL_WINDOWEVENT_SHOWN:
                case SDL_WINDOWEVENT_EXPOSED:
                case SDL_WINDOWEVENT_RESTORED:
                    needupdate = true;
                    break;
                default:
                    break;
                }
            break;
            case SDL_KEYDOWN:
            {
                int lc = 0;
                //hide mouse cursor on keyboard input
                if(OPTIONS["HIDE_CURSOR"] != "show" && SDL_ShowCursor(-1)) { SDL_ShowCursor(SDL_DISABLE); }
                const Uint8 *keystate = SDL_GetKeyboardState(NULL);
                // manually handle Alt+F4 for older SDL lib, no big deal
                if( ev.key.keysym.sym == SDLK_F4
                && (keystate[SDL_SCANCODE_RALT] || keystate[SDL_SCANCODE_LALT]) ) {
                    quit = true;
                    break;
                }
                switch (ev.key.keysym.sym) {
                    case SDLK_KP_ENTER:
                    case SDLK_RETURN:
                    case SDLK_RETURN2:
                        lc = 10;
                        break;
                    case SDLK_BACKSPACE:
                    case SDLK_KP_BACKSPACE:
                        lc = 127;
                        break;
                    case SDLK_ESCAPE:
                        lc = 27;
                        break;
                    case SDLK_TAB:
                        lc = 9;
                        break;
                    case SDLK_RALT:
                    case SDLK_LALT:
                        begin_alt_code();
                        break;
                    case SDLK_LEFT:
                        lc = KEY_LEFT;
                        break;
                    case SDLK_RIGHT:
                        lc = KEY_RIGHT;
                        break;
                    case SDLK_UP:
                        lc = KEY_UP;
                        break;
                    case SDLK_DOWN:
                        lc = KEY_DOWN;
                        break;
                    case SDLK_PAGEUP:
                        lc = KEY_PPAGE;
                        break;
                    case SDLK_PAGEDOWN:
                        lc = KEY_NPAGE;
                        break;
                }
                if( !lc ) { break; }
                if( alt_down ) {
                    add_alt_code( lc );
                } else {
                    lastchar = lc;
                }
                lastchar_isbutton = false;
            }
            break;
            case SDL_KEYUP:
            {
                if( ev.key.keysym.sym == SDLK_LALT || ev.key.keysym.sym == SDLK_RALT ) {
                    int code = end_alt_code();
                    if( code ) { lastchar = code; }
                }
            }
            break;
            case SDL_TEXTINPUT:
                lastchar = *ev.text.text;
            break;
            case SDL_JOYBUTTONDOWN:
                lastchar = ev.jbutton.button;
                lastchar_isbutton = true;
            break;
            case SDL_JOYAXISMOTION: // on gamepads, the axes are the analog sticks
                // TODO: somehow get the "digipad" values from the axes
            break;
            case SDL_MOUSEMOTION:
                if (OPTIONS["HIDE_CURSOR"] == "show" || OPTIONS["HIDE_CURSOR"] == "hidekb") {
                    if (!SDL_ShowCursor(-1)) {
                        SDL_ShowCursor(SDL_ENABLE);
                    }

                    // Only monitor motion when cursor is visible
                    lastchar_is_mouse = true;
                    lastchar = MOUSE_MOVE;
                }
                break;

            case SDL_MOUSEBUTTONUP:
                lastchar_is_mouse = true;
                switch (ev.button.button) {
                    case SDL_BUTTON_LEFT:
                        lastchar = MOUSE_BUTTON_LEFT;
                        break;
                    case SDL_BUTTON_RIGHT:
                        lastchar = MOUSE_BUTTON_RIGHT;
                        break;
                    }
                break;

            case SDL_MOUSEWHEEL:
                lastchar_is_mouse = true;
                if(ev.wheel.y > 0) {
                    lastchar = SCROLLWHEEL_UP;
                } else if(ev.wheel.y < 0) {
                    lastchar = SCROLLWHEEL_DOWN;
                }
                break;
                
            case SDL_QUIT:
                quit = true;
                break;
        }
    }
#ifdef SDLTILES
    if (needupdate) {
        try_update();
    }
#endif
    if(quit) {
        endwin();
        exit(0);
    }
}
Example #11
0
int main(int argc, char *argv[]) {
//    Initialize SDL
    SDL_Init(SDL_INIT_VIDEO);
    displayWindow = SDL_CreateWindow("Homework 1", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
    SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
    SDL_GL_MakeCurrent(displayWindow, context);
#ifdef _WINDOWS
    glewInit();
#endif
    
//    Define shader program
    ShaderProgram program(RESOURCE_FOLDER "vertex_textured.glsl", RESOURCE_FOLDER "fragment_textured.glsl");
    glViewport(0, 0, 800, 600);
    
//    Load textures
    GLuint emoji = LoadTexture("emoji.png");
    GLuint alien = LoadTexture("p1_front.png");
    GLuint medal = LoadTexture("flat_medal6.png");
//    Enable blending
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glUseProgram(program.programID);
    
//    Initialize local variables
    float lastFrameTicks = 0.0f;
    float angle = 0.0f;
    float X,Y,moveX, moveY = 0.0;
    
    SDL_Event event;
    bool done = false;
    while (!done) {
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
                done = true;
            }
        }
//        Define matrixes
        program.setProjectionMatrix(projectionMatrix);
        program.setModelMatrix(modelMatrix);
        program.setViewMatrix(viewMatrix);
        
//        Calculate elapsed time
        float ticks = (float)SDL_GetTicks()/1000.0f;
        float elapsed = ticks - lastFrameTicks;
        lastFrameTicks = ticks;
        
//        Calculate angle based on elapsed time
        angle += elapsed;
        if (X < .35 && Y < .35) {
            X += elapsed/2;
            Y += elapsed/2;
        }
        else if (X < -.35 && Y < -.35) {
            X -= elapsed/2;
            Y -= elapsed/2;
        }
        
//        Initialize keyboard state
        const Uint8 *keys = SDL_GetKeyboardState(NULL);
        
//        Clear and set color
        glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        
//        Draw alien texture
//        glActiveTexture(GL_TEXTURE1);
        modelMatrix.identity();
        modelMatrix.Scale(.2, .2, 1.0);
        program.setModelMatrix(modelMatrix);
        glBindTexture(GL_TEXTURE_2D, alien);
        float vertices1[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5};
        float texCoords1[] = {0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0};
        glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices1);
        glEnableVertexAttribArray(program.positionAttribute);
        glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords1);
        glEnableVertexAttribArray(program.texCoordAttribute);
        glEnable(GL_TEXTURE_2D);
        glDrawArrays(GL_TRIANGLES, 0, 6);
        glDisableVertexAttribArray(program.positionAttribute);
        glDisableVertexAttribArray(program.texCoordAttribute);
        
//        Draw medal texture
//        glActiveTexture(GL_TEXTURE2);
        modelMatrix.identity();
        modelMatrix.Scale(.05, .05, 1.0);
        modelMatrix.Translate(0, -.95, 0);
        program.setModelMatrix(modelMatrix);
        glBindTexture(GL_TEXTURE_2D, medal);
        float vertices2[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5};
        float texCoords2[] = {0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0};
        glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices2);
        glEnableVertexAttribArray(program.positionAttribute);
        glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords2);
        glEnableVertexAttribArray(program.texCoordAttribute);
        glEnable(GL_TEXTURE_2D);
        glDrawArrays(GL_TRIANGLES, 0, 6);
        glDisableVertexAttribArray(program.positionAttribute);
        glDisableVertexAttribArray(program.texCoordAttribute);
        
//        Draw emoji texture
//        glActiveTexture(GL_TEXTURE0);
        modelMatrix.identity();
        modelMatrix.Scale(X*2, Y*2, 1.0);
        modelMatrix.Rotate((angle*100.0f) * M_PI/180);
        if(keys[SDL_SCANCODE_SPACE]) {
            modelMatrix.identity();
            modelMatrix.Scale(X*2, Y*2, 1.0);
        }
        modelMatrix.Translate(X*1.5, Y*1.5, 0);
        program.setModelMatrix(modelMatrix);
        glBindTexture(GL_TEXTURE_2D, emoji);
        float vertices[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5};
        float texCoords[] = {0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0};
        glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices);
        glEnableVertexAttribArray(program.positionAttribute);
        glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords);
        glEnableVertexAttribArray(program.texCoordAttribute);
        glEnable(GL_TEXTURE_2D);
        glDrawArrays(GL_TRIANGLES, 0, 6);
        glDisableVertexAttribArray(program.positionAttribute);
        glDisableVertexAttribArray(program.texCoordAttribute);
        
        SDL_GL_SwapWindow(displayWindow);
    }
    
    SDL_Quit();
    return 0;
}
Example #12
0
void osinterface_process_messages()
{
	SDL_Event e;

	gLastKeyPressed = 0;
	// gCursorState.wheel = 0;
	gCursorState.left &= ~CURSOR_CHANGED;
	gCursorState.middle &= ~CURSOR_CHANGED;
	gCursorState.right &= ~CURSOR_CHANGED;
	gCursorState.old = 0;

	while (SDL_PollEvent(&e)) {
		switch (e.type) {
		case SDL_QUIT:
			rct2_finish();
			break;
		case SDL_WINDOWEVENT:
			if (e.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
				osinterface_resize(e.window.data1, e.window.data2);
			break;
		case SDL_MOUSEMOTION:
			RCT2_GLOBAL(0x0142406C, int) = e.motion.x;
			RCT2_GLOBAL(0x01424070, int) = e.motion.y;

			gCursorState.x = e.motion.x;
			gCursorState.y = e.motion.y;
			break;
		case SDL_MOUSEWHEEL:
			gCursorState.wheel += e.wheel.y * 128;
			break;
		case SDL_MOUSEBUTTONDOWN:
			RCT2_GLOBAL(0x01424318, int) = e.button.x;
			RCT2_GLOBAL(0x0142431C, int) = e.button.y;
			switch (e.button.button) {
			case SDL_BUTTON_LEFT:
				RCT2_CALLPROC_1(0x00406C96, int, 1);
				gCursorState.left = CURSOR_PRESSED;
				gCursorState.old = 1;
				break;
			case SDL_BUTTON_MIDDLE:
				gCursorState.middle = CURSOR_PRESSED;
				break;
			case SDL_BUTTON_RIGHT:
				RCT2_CALLPROC_1(0x00406C96, int, 3);
				gCursorState.right = CURSOR_PRESSED;
				gCursorState.old = 2;
				break;
			}
			break;
		case SDL_MOUSEBUTTONUP:
			*((int*)0x01424318) = e.button.x;
			*((int*)0x0142431C) = e.button.y;
			switch (e.button.button) {
			case SDL_BUTTON_LEFT:
				RCT2_CALLPROC_1(0x00406C96, int, 2);
				gCursorState.left = CURSOR_RELEASED;
				gCursorState.old = 3;
				break;
			case SDL_BUTTON_MIDDLE:
				gCursorState.middle = CURSOR_RELEASED;
				break;
			case SDL_BUTTON_RIGHT:
				RCT2_CALLPROC_1(0x00406C96, int, 4);
				gCursorState.right = CURSOR_RELEASED;
				gCursorState.old = 4;
				break;
			}
			break;
		case SDL_KEYDOWN:
			gLastKeyPressed = e.key.keysym.sym;
			gKeysPressed[e.key.keysym.scancode] = 1;
			break;
		default:
			break;
		}
	}

	gCursorState.any = gCursorState.left | gCursorState.middle | gCursorState.right;

	// Updates the state of the keys
	int numKeys = 256;
	gKeysState = SDL_GetKeyboardState(&numKeys);
}
Example #13
0
void controlplayer(GameState *gamestate)
{
    /*
    Funktionen tar hand om alla input kommand från användaren. Antingen handlar det om förflyttning på spelaren eller attack.
    Redan i denna funktion väljs det vilken sprite som ska användas beroende på vilket håll spelaren kollar mot.
    Med SDL_Getticks kan man göra en animation så det ser ut som att han går eller attackerar.
    */
    int ms = SDL_GetTicks();
    int sprite = ms /3 % 3;
    int tmpFaceing = gamestate->playerEntity[gamestate->mySlot].facing; ///Kommer ihåg vilket håll spelaren kollade mot från början
    const Uint8 *state = SDL_GetKeyboardState(NULL);
    if(state[SDL_SCANCODE_LEFT]) ///Vänster
    {
        gamestate->playerEntity[gamestate->mySlot].spriteFacing.x=sprite*32; ///Gör så att det blir animering
        gamestate->playerEntity[gamestate->mySlot].spriteFacing.y=64; ///Vart datorn kommer att kolla i sprite-sheeten
        gamestate->playerEntity[gamestate->mySlot].facing = 3; ///Vilket håll spelaren kollar mot

        gamestate->playerEntity[gamestate->mySlot].object.rect.x -= PLAYER_SPEED; ///Uppdaterar spelarens position
        if(TilemapCollisionDetection(gamestate->playerEntity[gamestate->mySlot].object.rect))///Kollar om spelaren hamnat in i en kollisionstile
        {
           gamestate->playerEntity[gamestate->mySlot].object.rect.x += PLAYER_SPEED; ///Om det ovanför blir sann så återställer den positionen
        }
    }
    if(state[SDL_SCANCODE_RIGHT]) ///Höger
    {

        gamestate->playerEntity[gamestate->mySlot].spriteFacing.x=sprite*32;
        gamestate->playerEntity[gamestate->mySlot].spriteFacing.y=96;
        gamestate->playerEntity[gamestate->mySlot].facing = 1;

        gamestate->playerEntity[gamestate->mySlot].object.rect.x += PLAYER_SPEED;
        if(TilemapCollisionDetection(gamestate->playerEntity[gamestate->mySlot].object.rect))
        {
           gamestate->playerEntity[gamestate->mySlot].object.rect.x -= PLAYER_SPEED;
        }
    }
    if(state[SDL_SCANCODE_UP])
    {
        gamestate->playerEntity[gamestate->mySlot].spriteFacing.x=sprite*32;
        gamestate->playerEntity[gamestate->mySlot].spriteFacing.y=0;
        gamestate->playerEntity[gamestate->mySlot].facing = 0;

        gamestate->playerEntity[gamestate->mySlot].object.rect.y -= PLAYER_SPEED;
        if(TilemapCollisionDetection(gamestate->playerEntity[gamestate->mySlot].object.rect))
        {
          gamestate->playerEntity[gamestate->mySlot].object.rect.y += PLAYER_SPEED;
        }
    }
    if(state[SDL_SCANCODE_DOWN])
    {
        gamestate->playerEntity[gamestate->mySlot].spriteFacing.x=sprite*32;
        gamestate->playerEntity[gamestate->mySlot].spriteFacing.y=32;
        gamestate->playerEntity[gamestate->mySlot].facing = 2;
        gamestate->playerEntity[gamestate->mySlot].object.rect.y += PLAYER_SPEED;
        if(TilemapCollisionDetection(gamestate->playerEntity[gamestate->mySlot].object.rect))
        {
           gamestate->playerEntity[gamestate->mySlot].object.rect.y -= PLAYER_SPEED;
        }
    }
    if(state[SDL_SCANCODE_SPACE]){///När användaren vill attackera
        if(gamestate->playerEntity[gamestate->mySlot].attackTimer == 0 || (SDL_GetTicks() - gamestate->playerEntity[gamestate->mySlot].attackTimer) >100){///Delay för att attackeera så det finns en mellanrum
            if(gamestate->playerEntity[gamestate->mySlot].attack.rect.x == 0) { ///Kontrollerar om en förgående attack existerar
                spawnAttack(&gamestate->playerEntity[gamestate->mySlot]);///Spawnar attacken
                sendAttack(gamestate);///Skickar iväg till alla klienter att det skapats en attack.
                gamestate->playerEntity[gamestate->mySlot].attackTimer = SDL_GetTicks();///Starta delayen
            }
        }
    }

    if(gamestate->playerEntity[gamestate->mySlot].facing == tmpFaceing && gamestate->playerEntity[gamestate->mySlot].facing!=4) {///Om inget har hänt står så tillsätter den facing = 4 vilket animerar så spelaren står stilla
        gamestate->playerEntity[gamestate->mySlot].facing = 4;
        updatePlayerMovement(gamestate);
    }
    playWallCollision(&gamestate->playerEntity[gamestate->mySlot].object);
        ///*********************player colliction detector with wall*************************////

}
Example #14
0
void KeyboardInterface::poll(Context& ctx)
{
    auto sdl_keystate = SDL_GetKeyboardState(NULL);

    auto& keymap = ctx.keyboardKeys();
    auto& axisMap = ctx.axisMapping();

    auto axisIt = axisMap.begin();
    auto axisEnd = axisMap.end();

    for(;axisIt!=axisEnd;++axisIt)
    {
        if(axisIt->idx.deviceType == SDL_Axis::Type::Keyboard)
        {
            auto data = axisIt->data;

            auto pollResult = 0.0f;

            auto neg = sdl_keystate[axisIt->idx.axis.rawNegative];
            auto pos = sdl_keystate[axisIt->idx.axis.rawPositive];

            if(neg == SDL_PRESSED)
            {
                pollResult -= 1.0f;
            }
            if(pos == SDL_PRESSED)
            {
                pollResult += 1.0f;
            }
            if(logicAnalogData.at(data->axis)==nullptr)
            {
                logicAnalogData.emplace(data->axis);
            }

            auto& currentStatus = logicAnalogData.get(data->axis).currentStatus;
            if(currentStatus!=0.0f)
            {
                currentStatus = sdli::clamp(currentStatus + pollResult, -1, 1) / data->normalize;
            }
            else
            {
                currentStatus = pollResult / data->normalize;
            }
        }
    }

    auto it = keymap.begin();



    std::vector<unsigned int> polled(captureBuffer.size());
    auto hasPolled = [](unsigned int id, std::vector<unsigned int>& v)
    {
        auto it = v.cbegin();
        auto end = v.cend();
        for(;it!=end;++it)
        {
            if(id == *it)
                return true;
        }
        return false;
    };

    for(;it!=keymap.end();++it)
    {
        auto state = sdl_keystate[it->idx];
        auto action = *(it->data);
        if(captureBuffer.at(action)==nullptr)
        {
            captureBuffer.emplace(action);
        }

        if(hasPolled(action, polled))
        {
            captureBuffer.get(action).currentStatus |= state;
        }
        else
        {
            captureBuffer.get(action).previousStatus = captureBuffer.get(action).currentStatus;
            captureBuffer.get(action).currentStatus = state;
            polled.push_back(action);
        }
    }
}
int main(int argc, char** argv){
	float lastFrameTicks = 0.0f;

	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 690, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);

	glClearColor(1.0, 0.0, 2.0, 0.0);

	int Mix_OpenAudio(int frequency, Uint16 format, int channels, int chunksize);
	Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096);
	
	Mix_Music *music;
	music = Mix_LoadMUS("hyruletemple.mp3");
	Mix_PlayMusic(music, -1);

	//Mix_FreeChunk(someSound);
	//Mix_FreeMusic(music);
	//SDL_Quit();


#ifdef _WINDOWS
	glewInit();
#endif
	glViewport(0, 0, 1280, 690);
	ShaderProgram program(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");

	Object leftPaddle(0.1f, 0.7f, 1.0f, 1.0f, -5.1f, 0.0f, 3.0f, 0.0f);
	leftPaddle.setOrthoProj();
	leftPaddle.setObjMatrices(program);
	leftPaddle.translateObj(-3.2, -1.5, 0.0);
	leftPaddle.scaleObj(leftPaddle.width, leftPaddle.height, 1.0);
	
	
	Object rightPaddle(0.1f, 0.7f, 1.0f, 1.0f, 5.1f, 0.0f, 3.0f, 0.0);
	rightPaddle.setOrthoProj();
	rightPaddle.setObjMatrices(program);
	rightPaddle.translateObj(3.2, 1.5, 0.0);
	rightPaddle.scaleObj(rightPaddle.width, rightPaddle.height, 1.0);
	

	Object ball(0.1f, 0.1f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f);
	ball.setOrthoProj();
	ball.setObjMatrices(program);
	ball.translateObj(0.0, 0.0, 0.0);
	ball.scaleObj(ball.width, ball.height, 1.0);
	
	Object topWall(7.65f, 0.25f, 1.0f, 1.0f, 0.0f, 1.95f, 0.0f, 0.0f);
	topWall.setOrthoProj();
	topWall.setObjMatrices(program);
	topWall.translateObj(topWall.posX, topWall.posY, 0.0);
	topWall.scaleObj(topWall.width, topWall.height, 1.0);


	Object bottomWall(7.65f, 0.25f, 1.0f, 1.0f, 0.0f, -1.95f, 0.0f, 0.0f);
	bottomWall.setOrthoProj();
	bottomWall.setObjMatrices(program);
	bottomWall.translateObj(bottomWall.posX, bottomWall.posY, 0.0);
	bottomWall.scaleObj(bottomWall.width, bottomWall.height, 1.0);

	

	float paddleSpeed = 0.0;


	SDL_Event event;
	bool done = false;
	while (!done) {
		while (SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
				done = true;
			}
		}

			float ticks = (float)SDL_GetTicks() / 1000.0f;
			float elapsed = ticks - lastFrameTicks;
			lastFrameTicks = ticks;

			glClear(GL_COLOR_BUFFER_BIT);

			leftPaddle.setObjMatrices(program);
			leftPaddle.drawObject(program);

			rightPaddle.setObjMatrices(program);
			rightPaddle.drawObject(program);

			ball.setObjMatrices(program);
			ball.drawObject(program);

			topWall.setObjMatrices(program);
			topWall.drawObject(program);

			bottomWall.setObjMatrices(program);
			bottomWall.drawObject(program);

			ball.posX += 0.0025 *elapsed * ball.xDir;
			ball.posY += 0.0001 * elapsed * ball.yDir;

			ball.translateObj(ball.posX, ball.posY, 0.0);

			paddleSpeed += 0.0015 * elapsed;

			
			// Ball dimensions
			float ballTop, ballBottom, ballLeft, ballRight;
			ballTop = ball.posY + (ball.height / 2.0f);
			ballBottom = ball.posY - (ball.height / 2.0f);
			ballLeft = ball.posX - (ball.width / 2.0f);
			ballRight = ball.posX + (ball.width / 2.0f);

			// Wall Dimension
			float topWallBottom = topWall.posY - (topWall.height / 2.0);
			float topWallTop = topWall.posY + (topWall.height / 2.0);
			float bottomWallBottom = bottomWall.posY - (bottomWall.height / 2.0);
			float bottomWallTop = bottomWall.posY + (bottomWall.height / 2.0);

			// Left Paddle Dimensions
			float leftPaddleTop = leftPaddle.posY + (leftPaddle.height / 2.0f);
			float leftPaddleBottom = leftPaddle.posY - (leftPaddle.height / 2.0f);
			float leftPaddleRight = leftPaddle.posX + (leftPaddle.width / 2.0f);
			float leftPaddleLeft = leftPaddle.posX - (leftPaddle.width / 2.0f);
			// Right Paddle Dimensions
			float rightPaddleTop = rightPaddle.posY + (rightPaddle.height / 2.0f);
			float rightPaddleBottom = rightPaddle.posY - (rightPaddle.height / 2.0f);
			float rightPaddleRight = rightPaddle.posX + (rightPaddle.width / 2.0f);
			float rightPaddleLeft = rightPaddle.posX - (rightPaddle.width / 2.0f);

			// Collision with the top
			if ((ballTop >= topWallBottom) || (ballBottom <= bottomWallTop)) {
				ball.yDir = -ball.yDir;
			}

			// Collisions Left Paddle - Ball
			if ((
				(leftPaddleBottom > ballTop) ||
				(leftPaddleTop < ballBottom) ||
				(leftPaddleLeft > ballRight) ||
				(leftPaddleRight < ballLeft))) {
				
			}
			else{
				ball.xDir = -ball.xDir;
				ball.yDir = -ball.yDir;
			}
			if ((
				(rightPaddleBottom < ballTop) ||
				(rightPaddleTop > ballBottom) ||
				(rightPaddleLeft > ballRight) ||
				(rightPaddleRight < ballLeft))) {
				
			}
			else{
				ball.xDir = -ball.xDir;
				ball.yDir = -ball.yDir;
			}


			/*if ((ball.getObjPos())[0] == (rightPaddle.getObjPos())[0] && (ball.getObjPos())[1] == (rightPaddle.getObjPos())[1]){
				float newX = (ball.getObjPos())[0] * -1;
				ball.setObjYpos(newX);
			}

			if ((ball.getObjPos())[0] == (leftPaddle.getObjPos())[0] && (ball.getObjPos())[1] == (leftPaddle.getObjPos())[1]){
				float newX = (ball.getObjPos())[0] * -1;
				ball.setObjYpos(newX);
			}

			if ((ball.getObjPos())[1] == 1.6 || (ball.getObjPos())[1] == -1.6){
				float newX = (ball.getObjPos())[1] * -1;
				ball.setObjYpos(newX);
			}*/




			const Uint8 *keys = SDL_GetKeyboardState(NULL);

			if (keys[SDL_SCANCODE_UP]) {
				rightPaddle.setObjMatrices(program);
				rightPaddle.translateObj(0.0, paddleSpeed, 0.0);
			}
			else if (keys[SDL_SCANCODE_DOWN]) {
				rightPaddle.setObjMatrices(program);
				rightPaddle.translateObj(0.0, -paddleSpeed, 0.0);
			}

			if (keys[SDL_SCANCODE_W]) {
				leftPaddle.setObjMatrices(program);
				leftPaddle.translateObj(0.0, paddleSpeed, 0.0);
			}
			else if (keys[SDL_SCANCODE_S]) {
				leftPaddle.setObjMatrices(program);
				leftPaddle.translateObj(0.0, -paddleSpeed, 0.0);
			}


			////If left paddle wins
			//if ((ball.getObjPos())[0] > 3.5){
			//	glClearColor(1.0, 0.0, 0.0, 0.0);
			//}

			////If right paddle wins
			//if ((ball.getObjPos())[0]  < -3.5){
			//	glClearColor(0.0, 0.0, 1.0, 0.0);
			//}


		

		SDL_GL_SwapWindow(displayWindow);

	}


	SDL_Quit();
	return 0;

}
Example #16
0
void input_match_keyboard(Input::Controllers *controllers, SDL_Event event) {
    // Match NES buttons to keyboard buttons

    nesinput_t input;

    input.nescode = 0x00;
    input.player = 0;
    input.pressed = 0;
    input.turboa = 0;
    input.turbob = 0;

    if (event.type == SDL_KEYDOWN) {
        input.pressed = 1;
    }

    for (int i = 0; i < NUMGAMEPADS; i++) {
        if (player[i].u == event.key.keysym.scancode) {
            input.nescode = Input::Controllers::Pad::UP;
            input.player = i;
        }
        else if (player[i].d == event.key.keysym.scancode) {
            input.nescode = Input::Controllers::Pad::DOWN;
            input.player = i;
        }
        else if (player[i].l == event.key.keysym.scancode) {
            input.nescode = Input::Controllers::Pad::LEFT;
            input.player = i;
        }
        else if (player[i].r == event.key.keysym.scancode) {
            input.nescode = Input::Controllers::Pad::RIGHT;
            input.player = i;
        }
        else if (player[i].select == event.key.keysym.scancode) {
            input.nescode = Input::Controllers::Pad::SELECT;
            input.player = i;
        }
        else if (player[i].start == event.key.keysym.scancode) {
            input.nescode = Input::Controllers::Pad::START;
            input.player = i;
        }
        else if (player[i].a == event.key.keysym.scancode) {
            input.nescode = Input::Controllers::Pad::A;
            input.player = i;
        }
        else if (player[i].b == event.key.keysym.scancode) {
            input.nescode = Input::Controllers::Pad::B;
            input.player = i;
        }
        else if (player[i].ta == event.key.keysym.scancode) {
            input.nescode = Input::Controllers::Pad::A;
            input.player = i;
            input.turboa = 1;
        }
        else if (player[i].tb == event.key.keysym.scancode) {
            input.nescode = Input::Controllers::Pad::B;
            input.player = i;
            input.turbob = 1;
        }
    }

    input_inject(controllers, input);

    if (event.key.keysym.scancode == ui.altspeed && event.type == SDL_KEYDOWN) {
        timing_set_altspeed();
    }
    if (event.key.keysym.scancode == ui.altspeed && event.type == SDL_KEYUP) {
        timing_set_default();
    }

    const Uint8 *keys = SDL_GetKeyboardState(NULL);

    // Insert Coins
    controllers->vsSystem.insertCoin = 0;
    if (keys[ui.insertcoin1]) {
        controllers->vsSystem.insertCoin |= Input::Controllers::VsSystem::COIN_1;
    }
    if (keys[ui.insertcoin2]) {
        controllers->vsSystem.insertCoin |= Input::Controllers::VsSystem::COIN_2;
    }

    // Process non-game events
    if (keys[ui.fdsflip]) {
        nst_flip_disk();
    }
    if (keys[ui.fdsswitch]) {
        nst_switch_disk();
    }
    if (keys[ui.qsave1]) {
        nst_state_quicksave(0);
    }
    if (keys[ui.qsave2]) {
        nst_state_quicksave(1);
    }
    if (keys[ui.qload1]) {
        nst_state_quickload(0);
    }
    if (keys[ui.qload2]) {
        nst_state_quickload(1);
    }

    // Screenshot
    if (keys[ui.screenshot]) {
        video_screenshot(NULL);
    }

    // Reset
    if (keys[ui.reset]) {
        nst_reset(0);
    }

    // Rewinder
    if (keys[ui.rwstart]) {
        nst_set_rewind(0);
    }
    if (keys[ui.rwstop]) {
        nst_set_rewind(1);
    }

    // Video
    if (keys[ui.fullscreen]) {
        video_toggle_fullscreen();
    }
    if (keys[ui.filter]) {
        video_toggle_filter();
    }
    if (keys[ui.scalefactor]) {
        video_toggle_scalefactor();
    }

    // NSF
    if (nst_nsf) {
        Nsf nsf(emulator);

        if (keys[SDL_SCANCODE_UP]) {
            nsf.PlaySong();
            video_clear_buffer();
            video_disp_nsf();
        }
        if (keys[SDL_SCANCODE_DOWN]) {
            //nsf.StopSong();
        }
        if (keys[SDL_SCANCODE_LEFT]) {
            nsf.SelectPrevSong();
            video_clear_buffer();
            video_disp_nsf();
        }
        if (keys[SDL_SCANCODE_RIGHT]) {
            nsf.SelectNextSong();
            video_clear_buffer();
            video_disp_nsf();
        }
    }

    // Escape exits when not in GUI mode
    if (keys[SDL_SCANCODE_ESCAPE]) {
        if (conf.misc_disable_gui) {
            nst_schedule_quit();
        }
    }
}
Example #17
0
bool CGame::Start()
{
	// Esta variable nos ayudara a controlar la salida del juego...
	int salirJuego = false;

	while (salirJuego == false){
		openGlImplement.DrawStart();
		keys = (Uint8*)SDL_GetKeyboardState(NULL);
		//Maquina de estados
		switch (estadoJuego){
		case ESTADO_INICIANDO:
			IniciandoVideo();
			openGlImplement.InitGL();
			openGlImplement.InitShaders();
			CargandoObjetos();
			InicializandoStage();
			estadoJuego = ESTADO_MENU;
			break;
		case ESTADO_MENU:
			MenuActualizar();
			MenuPintar();
			break;
		case ESTADO_PRE_JUGANDO:
			nivelActual = CERO;
			vida = UNO;
			enemigosEliminados = CERO;
			estadoJuego = ESTADO_JUGANDO;
			juegoGanado = false;
			IniciarEnemigo();
			IniciarNave();
			break;
		case ESTADO_JUGANDO:
			JugandoActualizar();
			JugandoPintar();
			break;
		case ESTADO_FINALIZANDO:
			salirJuego = true;
			break;
		case ESTADO_TERMINANDO:
			TerminadoPintar();
			TerminadoActualizar();
			break;
		};

		openGlImplement.DrawEnd();

		while (SDL_PollEvent(&event))//Aqui sdl creara una lista de eventos ocurridos
		{
			if (event.type == SDL_QUIT) { salirJuego = true; } //si se detecta una salida del sdl o.....
			if (event.type == SDL_KEYDOWN) {}
		}

		//Calculando fps
		tiempoFrameFinal = SDL_GetTicks();
		while (tiempoFrameFinal < (tiempoFrameInicial + FPS_DELAY))
		{
			tiempoFrameFinal = SDL_GetTicks();
			SDL_Delay(1);
		}

		tiempoFrameInicial = tiempoFrameFinal;
		tick++;


	}
	return true;
}
Example #18
0
Enemy::Enemy(ShaderProgram* program, SheetSprite sprite, SheetSprite bulletSprite, float xposi, float yposi)
: program(program), keys(SDL_GetKeyboardState(NULL)), sprite(sprite), bulletSprite(bulletSprite), xposi(xposi), yposi(yposi), speed(0.5),
bullet(Bullet(program, bulletSprite)), alive(true) {};
Example #19
0
/*
================================================================================

Game::Initialize

    Performs the bulk of game initialization.  Creates a window, renderer, and
    resource managers.  Loads resources, spawns entities, and creates the
    initial scene layout.

================================================================================
*/
bool Game::Initialize()
{
	// Instructions:
    std::cout << "***" << std::endl;
    std::cout << "*** Press A and D to move left and right" << std::endl;
	std::cout << "*** Press SPACE to jump" << std::endl;
	std::cout << "*** Press K to remove all the crawlers from a scene!" << std::endl;
	std::cout << "*** Press P to pause/unpause the game" << std::endl;
	std::cout << "*** Press V to show/hide the collision rectangles" << std::endl;
	std::cout << "*** Press 9 to stop/play background music" << std::endl;
	std::cout << "*** Press X to add a strong crawler on the ground tiles" << std::endl;
	std::cout << "*** Press C to add a weak crawler on the ground tiles" << std::endl;
	std::cout << "*** Press R to resurrect from death" << std::endl;
	std::cout << "*** Each coin is worth 5 points" << std::endl;
	std::cout << "*** Each weak crawler is worth 25 points" << std::endl;
	std::cout << "*** Each strong crawler is worth 50 points (2 x 25)" << std::endl;
	std::cout << "*** You have a total of 5 lives to begin with" << std::endl;
    std::cout << "***" << std::endl;

    // initialize SDL
    if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
        std::cerr << "*** Failed to initialize SDL: " << SDL_GetError() << std::endl;
        return false;
    }

    // initialize SDL_image add-on
    if (!IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG))
	{
        std::cerr << "*** Failed to initialize SDL_image: " << IMG_GetError() << std::endl;
        return false;
    }

    mScrWidth = 640;
    mScrHeight = 480;

    // create a window
    mWindow = SDL_CreateWindow("C++ Final Project",
                               SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                               mScrWidth, mScrHeight,
                               SDL_WINDOW_SHOWN /*| SDL_WINDOW_RESIZABLE*/);
    if (!mWindow)
	{
        std::cerr << "*** Failed to create window: " << SDL_GetError() << std::endl;
        return false;
    }

    // create a renderer that takes care of drawing stuff to the window
    mRenderer = SDL_CreateRenderer(mWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (!mRenderer)
	{
        std::cerr << "*** Failed to create renderer: " << SDL_GetError() << std::endl;
        return false;
    }

    // get a pointer to keyboard state managed by SDL
    mKeyState = SDL_GetKeyboardState(NULL);

	// Initialize SDL_ttf library
	if (TTF_Init() != 0)
	{
		std::cerr << "TTF_Init() Failed: " << TTF_GetError() << std::endl;
		SDL_Quit();
		exit(1);
	}

    // create a texture manager
    mTexMgr = new GG::TextureManager;
    if (!mTexMgr->Initialize(mRenderer, "media/"))
	{
        std::cerr << "*** Failed to initialize texture manager" << std::endl;
        return false;
    }

	//Initialize SDL Audio
	if (SDL_INIT_AUDIO < 0)
	{
		std::cerr << "SDL audio not initialize! SDL Error: " << SDL_GetError() << std::endl;
		return false;
	}

	//Initialize SDL_mixer
	if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
	{
		std::cerr << "SDL_mixer could not initialize! SDL_mixer Error: " << Mix_GetError() << std::endl;
		return false;
	}

	//Load musicIn
	mMusic = Mix_LoadMUS("media/music.mp3");
	mGoodGameOverMusic = Mix_LoadMUS("media/gameover_music.wav");
	mBadGameOverMusic = Mix_LoadMUS("media/gameover_music.mp3");
	if (mMusic == NULL || mGoodGameOverMusic == NULL || mBadGameOverMusic == NULL)
	{
		std::cerr << " Failed to load beat music! SDL_mixer Error:" << Mix_GetError() << std::endl;
		return false;
	}
	//loading the Coin Sound
	LoadSounds();
	if (mCoinSound == NULL || mJumpSound == NULL || mStompSound == NULL || 
		mDieSound == NULL || mStompSoundNoKill == NULL || mBlockSound == NULL)
	{
		std::cerr << "*** Failed to initialize mCoinSound" << Mix_GetError()<<std::endl;
		return false;
	}

    // load textures
	LoadTextures();
	LoadGrayscaleTextures();

    // initialize grid from a text file (including crawlers and coins!)
    LoadScene(mScene, true);

	// initialize the robot
	mRobot = new Robot(35.0f, mScrHeight-160.0f);

	// initialize the foreground
	mForeground = new Layer(0.0f, 0.0f, 800.0f, 480.0f, "Foreground", "Foreground2");

    return true;
}
Example #20
0
File: sdl.c Project: gbraad/fs-uae
int fs_ml_event_loop(void)
{
    // printf("fs_ml_event_loop\n");
    int result = 0;
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
        switch(event.type) {
        case SDL_QUIT:
            fs_log("intercepted SDL_QUIT\n");
            fs_ml_quit();
#ifdef FS_EMU_DRIVERS
            printf("returning 1 from fs_ml_event_loop\n");
            result = 1;
#endif
            continue;
#ifdef USE_SDL2
        case SDL_WINDOWEVENT:
            // printf("SDL_WINDOWEVENT...\n");
            if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
                on_resize(event.window.data1, event.window.data2);
            }
            else if (event.window.event == SDL_WINDOWEVENT_CLOSE) {
                event.type = SDL_QUIT;
                SDL_PushEvent(&event);
            }
            continue;
#else
        case SDL_VIDEORESIZE:
            on_resize(event.resize.w, event.resize.h);
            continue;
        case SDL_ACTIVEEVENT:
            //fs_log("got active event %d %d %d %d\n", event.active.state,
            //      SDL_APPMOUSEFOCUS, SDL_APPINPUTFOCUS, SDL_APPACTIVE);
            if ((event.active.state & SDL_APPINPUTFOCUS)) {
                if (event.active.gain) {
                    fs_log("got keyboard focus\n");
                    // just got keyboard focus -- clearing modifier states
                    fs_ml_clear_keyboard_modifier_state();
                    if (g_fs_ml_had_input_grab) {
                        fs_log("- had input grab, re-acquiring\n");
                        fs_ml_grab_input(1, 1);
                        g_fs_ml_had_input_grab = 0;
                    }
                    if (g_fs_ml_was_fullscreen) {
                        if (!g_fs_emu_video_fullscreen) {
                            fs_log("- was in fullsreen mode before (switching)\n");
                            fs_ml_toggle_fullscreen();
                        }
                        g_fs_ml_was_fullscreen = 0;
                    }
                }
                else {
                    fs_log("lost keyboard focus\n");
                    if (fs_ml_has_input_grab()) {
                        fs_log("- releasing input grab\n");
                        fs_ml_grab_input(0, 1);
                        g_fs_ml_had_input_grab = 1;
                    }
                    else {
                        fs_log("- did not have input grab\n");
                        //g_fs_ml_had_input_grab = 0;
                    }
                }
            }
            continue;
#endif
        case SDL_KEYDOWN:
        case SDL_KEYUP:
            if (g_debug_input) {
                fs_log("SDL key sym %d mod %d scancode %d state %d\n",
                        event.key.keysym.sym, event.key.keysym.mod,
                        event.key.keysym.scancode, event.key.state);
            }
            if (event.key.keysym.sym == 0 && event.key.keysym.scancode == 0) {
                // ignore "ghost key" seen on OS X which without this
                // specific check will cause the A key to be mysteriously
                // pressed.
                if (g_debug_input) {
                    fs_log("- ignored key with keysym 0 and scancode 0\n");
                }
                continue;
            }
            /*
            if (event.key.keysym.sym == SDLK_F12) {
                g_f12_state = event.key.state ? FS_ML_KEY_MOD_F12 : 0;
                printf("-- g_f12_state is %d\n", g_f12_state);
            }
            else if (event.key.keysym.sym == SDLK_F11) {
                g_f11_state = event.key.state ? FS_ML_KEY_MOD_F11 : 0;
            }
            */

            const Uint8* key_state;
            int num_keys;
#ifdef USE_SDL2
            key_state = SDL_GetKeyboardState(&num_keys);
            g_f11_state = key_state[SDL_SCANCODE_F11] ? FS_ML_KEY_MOD_F11 : 0;
            g_f12_state = key_state[SDL_SCANCODE_F12] ? FS_ML_KEY_MOD_F12 : 0;
            // printf("%d %d\n", g_f11_state, g_f12_state);
#else
            key_state = SDL_GetKeyState(&num_keys);
            g_f11_state = key_state[SDLK_F11] ? FS_ML_KEY_MOD_F11 : 0;
            g_f12_state = key_state[SDLK_F12] ? FS_ML_KEY_MOD_F12 : 0;
#endif

            int key = -1;
#ifdef USE_SDL2
            if (event.key.keysym.scancode <= LAST_SDL2_SCANCODE) {
                key = g_sdl2_keys[event.key.keysym.scancode];
            }
#else
            if (0) {
            }
#endif
#if defined(MACOSX)
#ifdef USE_SDL2

#else
            else if (event.key.keysym.sym == SDLK_LSHIFT) {
                key = SDLK_LSHIFT;
            }
            else if (event.key.keysym.sym == SDLK_LCTRL) {
                key = SDLK_LCTRL;
            }
            else if (event.key.keysym.sym == SDLK_LALT) {
                key = SDLK_LALT;
            }
            else if (event.key.keysym.sym == SDLK_LMETA) {
                key = SDLK_LSUPER;
            }
            else if (event.key.keysym.sym == SDLK_RMETA) {
                key = SDLK_RSUPER;
            }
            else if (event.key.keysym.sym == SDLK_RALT) {
                key = SDLK_RALT;
            }
            else if (event.key.keysym.sym == SDLK_RCTRL) {
                key = SDLK_RCTRL;
            }
            else if (event.key.keysym.sym == SDLK_RSHIFT) {
                key = SDLK_RSHIFT;
            }
            else if (event.key.keysym.sym == SDLK_CAPSLOCK) {
                key = SDLK_CAPSLOCK;
            }
#endif
#elif defined(WINDOWS)

#else
            else if (event.key.keysym.sym == SDLK_MODE) {
                key = SDLK_RALT;
            }
#endif
            else {
                key = fs_ml_scancode_to_key(event.key.keysym.scancode);
            }

#ifdef USE_SDL2
            if (0) {
                // the below trick does not currently work for SDL2, as
                // there is no mapping yet for translated keys
            }
#else
            if (g_f12_state || g_f11_state) {
                // leave translated key code in keysym
            }
#endif
            else if (key >= 0) {
                if (g_debug_input) {
                    fs_log("- key code set to %d (was %d) based on "
                           "scancode %d\n", key, event.key.keysym.sym,
                           event.key.keysym.scancode);
                }
                event.key.keysym.sym = key;
            }

            int mod = event.key.keysym.mod;
            if (mod & KMOD_LSHIFT || mod & KMOD_RSHIFT) {
                event.key.keysym.mod |= KMOD_SHIFT;
            }
            if (mod & KMOD_LALT || mod & KMOD_RALT) {
                //mod & ~(KMOD_LALT | KMOD_RALT);
                event.key.keysym.mod |= KMOD_ALT;
            }
            if (mod & KMOD_LCTRL || mod & KMOD_RCTRL) {
                event.key.keysym.mod |= KMOD_CTRL;
            }
            if (mod & KMOD_LMETA || mod & KMOD_RMETA) {
                event.key.keysym.mod |= KMOD_META;
            }
            // filter out other modidifers
            event.key.keysym.mod &= (KMOD_SHIFT | KMOD_ALT | KMOD_CTRL |
                    KMOD_META);
            // add F11/F12 state
            event.key.keysym.mod |= g_f11_state | g_f12_state;

            //printf("%d %d %d %d\n", event.key.keysym.mod,
            //        KMOD_ALT, KMOD_LALT, KMOD_RALT);
            break;
        //case SDL_MOUSEBUTTONDOWN:
        //    printf("--- mousebutton down ---\n");
        }
        fs_ml_event *new_event = NULL;
#if !defined(USE_SDL2)
        fs_ml_event *new_event_2 = NULL;
#endif
        if (event.type == SDL_KEYDOWN) {
            new_event = fs_ml_alloc_event();
            new_event->type = FS_ML_KEYDOWN;
            new_event->key.keysym.sym = event.key.keysym.sym;
            new_event->key.keysym.mod = event.key.keysym.mod;
#ifdef USE_SDL2
            // SDL2 sends its own text input events
#else
            if (event.key.keysym.unicode && event.key.keysym.unicode < 128) {
                // FIXME: only supporting ASCII for now..
                new_event_2 = fs_ml_alloc_event();
                new_event_2->type = FS_ML_TEXTINPUT;
                new_event_2->text.text[0] = event.key.keysym.unicode;
                new_event_2->text.text[1] = '\0';
            }
#endif
            new_event->key.state = event.key.state;
        }
        else if (event.type == SDL_KEYUP) {
            new_event = fs_ml_alloc_event();
            new_event->type = FS_ML_KEYUP;
            new_event->key.keysym.sym = event.key.keysym.sym;
            new_event->key.keysym.mod = event.key.keysym.mod;
            new_event->key.state = event.key.state;
        }
        else if (event.type == SDL_JOYBUTTONDOWN) {
            new_event = fs_ml_alloc_event();
            new_event->type = FS_ML_JOYBUTTONDOWN;
            new_event->jbutton.which = g_fs_ml_first_joystick_index + \
                    event.jbutton.which;
            new_event->jbutton.button = event.jbutton.button;
            new_event->jbutton.state = event.jbutton.state;
        }
        else if (event.type == SDL_JOYBUTTONUP) {
            new_event = fs_ml_alloc_event();
            new_event->type = FS_ML_JOYBUTTONUP;
            new_event->jbutton.which = g_fs_ml_first_joystick_index + \
                    event.jbutton.which;
            new_event->jbutton.button = event.jbutton.button;
            new_event->jbutton.state = event.jbutton.state;
        }
        else if (event.type == SDL_JOYAXISMOTION) {
            new_event = fs_ml_alloc_event();
            new_event->type = FS_ML_JOYAXISMOTION;
            new_event->jaxis.which = g_fs_ml_first_joystick_index + \
                    event.jaxis.which;
            new_event->jaxis.axis = event.jaxis.axis;
            new_event->jaxis.value = event.jaxis.value;
        }
        else if (event.type == SDL_JOYHATMOTION) {
            new_event = fs_ml_alloc_event();
            new_event->type = FS_ML_JOYHATMOTION;
            new_event->jhat.which = g_fs_ml_first_joystick_index + \
                    event.jhat.which;
            new_event->jhat.hat = event.jhat.hat;
            new_event->jhat.value = event.jhat.value;
        }
        else if (event.type == SDL_MOUSEMOTION) {
            new_event = fs_ml_alloc_event();
            new_event->type = FS_ML_MOUSEMOTION;
            new_event->motion.device = g_fs_ml_first_mouse_index;
            new_event->motion.xrel = event.motion.xrel;
            new_event->motion.yrel = event.motion.yrel;
            /* Absolute window coordinates */
            new_event->motion.x = event.motion.x;
            new_event->motion.y = event.motion.y;
            //printf("ISREL %d\n", SDL_GetRelativeMouseMode());

            if (g_debug_input) {
                fs_log("SDL mouse event x: %4d y: %4d xrel: %4d yrel: %4d\n", 
                    event.motion.x, event.motion.y,
                    event.motion.xrel, event.motion.yrel);
            }
        }
        else if (event.type == SDL_MOUSEBUTTONDOWN) {
            new_event = fs_ml_alloc_event();
            new_event->type = FS_ML_MOUSEBUTTONDOWN;
            new_event->button.device = g_fs_ml_first_mouse_index;
            new_event->button.button = event.button.button;
#ifdef MACOSX
            if (new_event->button.button == 1) {
                int mod = SDL_GetModState();
                if (mod & KMOD_ALT) {
                    new_event->button.button = 2;
                }
                else if (mod & KMOD_CTRL) {
                    new_event->button.button = 3;
                }
            }
#endif
            new_event->button.state = event.button.state;
        }
        else if (event.type == SDL_MOUSEBUTTONUP) {
            new_event = fs_ml_alloc_event();
            new_event->type = FS_ML_MOUSEBUTTONUP;
            new_event->button.device = g_fs_ml_first_mouse_index;
            new_event->button.button = event.button.button;
#ifdef MACOSX
            if (new_event->button.button == 1) {
                int mod = SDL_GetModState();
                if (mod & KMOD_ALT) {
                    new_event->button.button = 2;
                }
                else if (mod & KMOD_CTRL) {
                    new_event->button.button = 3;
                }
            }
#endif
            new_event->button.state = event.button.state;
        }
#ifdef USE_SDL2
        else if (event.type == SDL_MOUSEWHEEL) {
            /*
            if (event.wheel.which == SDL_TOUCH_MOUSEID) {

            }
            */
            if (event.wheel.y) {
                if (g_debug_input) {
                    fs_log("SDL mouse event y-scroll: %4d\n",
                        event.wheel.y);
                }
                new_event = fs_ml_alloc_event();
                new_event->type = FS_ML_MOUSEBUTTONDOWN;
                if (event.wheel.y > 0) {
                    new_event->button.button = FS_ML_BUTTON_WHEELUP;
                }
                else {
                    new_event->button.button = FS_ML_BUTTON_WHEELDOWN;
                }
                new_event->button.device = g_fs_ml_first_mouse_index;
                new_event->button.state = 1;
            }
        }
        else if (event.type == SDL_TEXTINPUT) {
            new_event = fs_ml_alloc_event();
            new_event->type = FS_ML_TEXTINPUT;
            memcpy(&(new_event->text.text), &(event.text.text),
                   MIN(TEXTINPUTEVENT_TEXT_SIZE, SDL_TEXTINPUTEVENT_TEXT_SIZE));
            new_event->text.text[TEXTINPUTEVENT_TEXT_SIZE - 1] = 0;
        }
#endif
        if (new_event) {
            fs_ml_post_event(new_event);
        }
#if !defined(USE_SDL2)
        if (new_event_2) {
            fs_ml_post_event(new_event_2);
        }
#endif
    }
    return result;
}
Example #21
0
// Called each loop iteration
bool M_Input::PreUpdate()
{
	static SDL_Event event;
	
	const Uint8* keys = SDL_GetKeyboardState(NULL);

	for(int i = 0; i < MAX_KEYS; ++i)
	{
		if(keys[i] == 1)
		{
			if(keyboard[i] == KEY_IDLE)
				keyboard[i] = KEY_DOWN;
			else
				keyboard[i] = KEY_REPEAT;
		}
		else
		{
			if(keyboard[i] == KEY_REPEAT || keyboard[i] == KEY_DOWN)
				keyboard[i] = KEY_UP;
			else
				keyboard[i] = KEY_IDLE;
		}
	}

	mouse_motion_x = mouse_motion_y = 0;

	for(int i = 0; i < NUM_MOUSE_BUTTONS; ++i)
	{
		if(mouse_buttons[i] == KEY_DOWN)
			mouse_buttons[i] = KEY_REPEAT;

		if(mouse_buttons[i] == KEY_UP)
			mouse_buttons[i] = KEY_IDLE;
	}

	while(SDL_PollEvent(&event) != 0)
	{
		switch(event.type)
		{
			case SDL_QUIT:
				windowEvents[WE_QUIT] = true;
			break;

			case SDL_WINDOWEVENT:
				switch(event.window.event)
				{
					//case SDL_WINDOWEVENT_LEAVE:
					case SDL_WINDOWEVENT_HIDDEN:
					case SDL_WINDOWEVENT_MINIMIZED:
					case SDL_WINDOWEVENT_FOCUS_LOST:
					windowEvents[WE_HIDE] = true;
					break;

					//case SDL_WINDOWEVENT_ENTER:
					case SDL_WINDOWEVENT_SHOWN:
					case SDL_WINDOWEVENT_FOCUS_GAINED:
					case SDL_WINDOWEVENT_MAXIMIZED:
					case SDL_WINDOWEVENT_RESTORED:
					windowEvents[WE_SHOW] = true;
					break;
				}
			break;

			case SDL_MOUSEBUTTONDOWN:
				mouse_buttons[event.button.button - 1] = KEY_DOWN;
				//LOG("Mouse button %d down", event.button.button-1);
			break;

			case SDL_MOUSEBUTTONUP:
				mouse_buttons[event.button.button - 1] = KEY_UP;
				//LOG("Mouse button %d up", event.button.button-1);
			break;

			case SDL_MOUSEMOTION:
			{
				int scale = App->win->GetScale();
				mouse_motion_x = event.motion.xrel / scale;
				mouse_motion_y = event.motion.yrel / scale;
				mouse_x = event.motion.x / scale;
				mouse_y = event.motion.y / scale;
				//LOG("Mouse motion x %d y %d", mouse_motion_x, mouse_motion_y);
			}
			
			break;
			
			case SDL_TEXTINPUT:
				App->gui->SendNewInput(event.text.text);
			break;

		}
	}

	return true;
}
Example #22
0
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;
}
Example #23
0
void Character::logic()
{
    const Uint8* currentKeyStates = SDL_GetKeyboardState( NULL );

    if( currentKeyStates[ SDL_SCANCODE_Q ] )
    {
        this->current_move = "bola";
        this->current_sprite = 0;
    }
    else if( currentKeyStates[ SDL_SCANCODE_W ] )
    {
        if(moves["bola"]->canCancel(this->current_move))
        {
            this->current_move = "bola";
            this->current_sprite = 0;
        }
    }
    else if( currentKeyStates[ SDL_SCANCODE_E ] )
    {
        if(moves["vuelta"]->canCancel(this->current_move))
        {
            this->current_move = "vuelta";
            this->current_sprite = 0;
        }
    }
    else if( currentKeyStates[ SDL_SCANCODE_R ] )
    {
        if(moves["bola"]->canCancel(this->current_move))
        {
            if(this->current_move!="bola")
            {
                this->current_sprite = 0;
            }
            this->current_move = "bola";
            this->x-=1;
        }
    }
    else if( currentKeyStates[ SDL_SCANCODE_T ] )
    {
        if(this->current_move=="bola"
           || this->current_move=="bola")
       {
            if(this->current_move!="bola")
            {
                this->current_sprite = 0;
            }
            this->current_move = "bola";
            this->x+=1;
       }

    }
    else if( currentKeyStates[ SDL_SCANCODE_M ] )
    {
        if(this->current_move=="bola"
           || this->current_move=="bola")
       {
            if(this->current_move!="bola")
            {
                this->current_sprite = 0;
            }
            this->current_move = "bola";
            this->x-=1;
       }

    }
    else
    {
        if(this->current_move=="bola")
        {
            this->current_move = "bola";
            this->current_sprite = 0;
        }
    }

    current_sprite_frame+=1;
    if(current_sprite_frame>=moves[current_move]->sprites[current_sprite]->frames)
    {
        current_sprite++;
        if(current_sprite>=moves[current_move]->sprites.size())
        {
            current_move= "bola";
            current_sprite=0;
        }
        current_sprite_frame=0;
    }
}
Example #24
0
int main (int argc, char* args[]) {

	//SDL Window setup
	if (init(SCREEN_WIDTH, SCREEN_HEIGHT) == 1) {
		
		return 0;
	}

	char msg[] = "this is a test string";

	SDL_Rect src, dest;

	int sleep = 0;
	int quit = 0;
	Uint32 next_game_tick = SDL_GetTicks();
	
	int i = 0;
	float sin_t[360];
	
	for (i = 0; i < 360; i++) {
		
		sin_t[i] =  sin(i * M_PI / 180);
	}
	
	int c_offset = 0;
	int d = 1;

	//render loop
	while(quit == 0) {
	
		//check for new events every frame
		SDL_PumpEvents();

		const Uint8 *state = SDL_GetKeyboardState(NULL);
		
		if (state[SDL_SCANCODE_ESCAPE]) {
		
			quit = 1;
		}
		
		SDL_RenderClear(renderer);
		
		for (i = 0; i < strlen(msg); i++) {
			
			struct vector3d v = get_char(msg[i]);
			
			if (msg[i] == ' ') {
				
				c_offset += CHAR_WIDTH;
				continue;
			}

			src.x = v.x;
			src.y = v.y;
			src.w = CHAR_WIDTH;
			src.h = CHAR_WIDTH;
	
			dest.x = c_offset;
			dest.y = SCREEN_HEIGHT / 2 + sin_t[(int) fabs(c_offset) % 360] * 25;
			dest.w = CHAR_WIDTH;
			dest.h = CHAR_HEIGHT;
			
			SDL_RenderCopy(renderer, c_map, &src, &dest);
			
			c_offset += CHAR_WIDTH;
		}

		if (d > strlen(msg) * CHAR_WIDTH + SCREEN_WIDTH) {
			
			d = 0;
		}

		c_offset = SCREEN_WIDTH - d;
		d += 5;

		//draw to the screen
		SDL_RenderPresent(renderer);
				
		//time it takes to render 1 frame in milliseconds
		next_game_tick += 1000 / 60;
		sleep = next_game_tick - SDL_GetTicks();
	
		if( sleep >= 0 ) {
            				
			SDL_Delay(sleep);
		}
	}

	//free the source image
	SDL_FreeSurface(char_map);
	
	//Destroy window 
	SDL_DestroyWindow(window);

	//Quit SDL subsystems 
	SDL_Quit(); 
	 
	return 0;
}
Example #25
0
 bool InputWrapper::isKeyDown(SDL_Scancode key)
 {
     return (SDL_GetKeyboardState(NULL)[key]) != 0;
 }
Example #26
0
void PlatformerGame::Init() {
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);

	glViewport(0, 0, 800, 600);
	glMatrixMode(GL_PROJECTION);

	glOrtho(-1.33, 1.33, -1.0, 1.0, -1.0, 1.0);
	glMatrixMode(GL_MODELVIEW);
	glClearColor(1.0, 1.0, 1.0, 1.0);
	glClear(GL_COLOR_BUFFER_BIT);

	keys = SDL_GetKeyboardState(NULL);

	GLuint sprites = loadTexture("sprites.png");

	Entity player = Entity(sprites, 0.0f, 0.0f, 64.0 / 256.0f, 64.0 / 256.0f, true, false);
	player.setX(0.0f);
	player.setY(-0.5f);
	player.setScale(0.3);
	//player.insertUVPoints(0.0f, (66.0 / 256.0f));					//Facing left - 0,1
	//player.insertUVPoints((66.0 / 256.0f), (66.0 / 256.0f));		//Facing left idle - 2,3
	//player.insertUVPoints(0.0f, (66.0 / 256.0f));					//Facing left - 4,5
	//player.insertUVPoints(0.0f, (132.0 / 25.0f));					//Facing right - 6,7
	//player.insertUVPoints((66.0 / 256.0f), 0.0f);					//Facing right idle - 8,9
	//player.insertUVPoints((66.0 / 256.0f), (132.0 / 256.0f));		//Facing right - 10,11
	dynamicEntities.push_back(player);

	Entity floor = Entity(sprites, 0.0f, 198.0 / 256.0f, 48.0 / 256.0f, 48.0 / 256.0f, true, true);
	floor.setY(-0.9f);
	floor.setX(-0.9f);
	floor.setScale(0.3);
	for (int floorCount = 0; floorCount < 18; floorCount++) {		
		floor.setX(floor.getX() + (48.0 / 256.0)*0.5);
		staticEntities.push_back(floor);
	}

	Entity floor1 = Entity(sprites, 0.0f, 198.0 / 256.0f, 48.0 / 256.0f, 48.0 / 256.0f, true, true);
	floor1.setY(-0.3f);
	floor1.setX(-0.9);
	floor1.setScale(0.3);
	for (int floorCounter = 0; floorCounter < 9; floorCounter++) {	
		floor1.setX(floor1.getX() + (48.0 / 256.0)*0.5);
		staticEntities.push_back(floor1);
	}

	Entity wallL = Entity(sprites, 50.0 / 256.0f, 198.0 / 256.0f, 48.0 / 256.0f, 48.0 / 256.0f, true, true);
	wallL.setX(-0.9);
	wallL.setY(-0.9);
	wallL.setScale(0.3);
	for (int wallCount = 0; wallCount < 20; wallCount++) {		
		wallL.setY(wallL.getY() + (48.0 / 256.0)*0.5);
		staticEntities.push_back(wallL);
	}

	Entity wallR = Entity(sprites, 50.0 / 256.0f, 198.0 / 256.0f, 48.0 / 256.0f, 48.0 / 256.0f, true, true);
	wallR.setX(0.9);
	wallR.setY(-0.9);
	wallR.setScale(0.3);
	for (int wallCounter = 0; wallCounter < 20; wallCounter++) {	
		wallR.setY(wallR.getY() + (48.0 / 256.0)*0.5);
		staticEntities.push_back(wallR);
	}

	Entity floor2 = Entity(sprites, 0.0f, 198.0 / 256.0f, 48.0 / 256.0f, 48.0 / 256.0f, true, true);
	floor2.setX(0.0f);
	floor2.setY(0.3f);
	floor2.setScale(0.3);
	for (int floorCounter1 = 0; floorCounter1 < 9; floorCounter1++) {	
		floor2.setX(floor2.getX() + (48.0 / 256.0)*0.5);
		staticEntities.push_back(floor2);
	}

	Entity floor3 = Entity(sprites, 0.0f, 198.0 / 256.0f, 48.0 / 256.0f, 48.0 / 256.0f, true, true);
	floor3.setY(0.9f);
	floor3.setX(-0.9f);
	floor3.setScale(0.3);
	for (int floorCount3 = 0; floorCount3 < 18; floorCount3++) {
		floor3.setX(floor3.getX() + (48.0 / 256.0)*0.5);
		staticEntities.push_back(floor3);
	}

	// Creating target entities
	Entity target = Entity(sprites, 100.0 / 256.0f, 198.0 / 256.0f, 48.0 / 256.0f, 48.0 / 256.0f, true, true);
	target.setScale(0.5);
	target.setX(staticEntities[staticEntities.size() - 20].getX()); 
	target.setY(staticEntities[staticEntities.size() - 20].getY() + staticEntities[staticEntities.size() - 20].getHeight() * 0.5);
	target.setVisible(true);
	dynamicEntities.push_back(target);


}
Example #27
0
void ClassDemoApp::UpdateGameLevel(float elapsed) {

    const Uint8 *keys = SDL_GetKeyboardState(NULL);

    player->velocity_x = 5.0f;

    if (keys[SDL_SCANCODE_LEFT]) {
        player->acceleration_x = -10.0f;
    }
    else if (keys[SDL_SCANCODE_RIGHT]) {
        player->acceleration_x = 10.0f;
    }
    else {
        player->acceleration_x = 0.0f;
    }
    if (keys[SDL_SCANCODE_UP] && player->velocity_y < 10.0f) {
        Mix_PlayChannel(-1, someSound, 0);
        player->velocity_y += 1.5f;
        player->collidedBottom = false;
    }

    for (size_t i = 0; i < enemies.size(); i++) {
        enemies[i].Update(elapsed);

        int gridX = 0, gridY = 0;

        worldToTileCoordinates(enemies[i].position_x - enemies[i].width / 2, enemies[i].position_y, &gridX, &gridY);
        if (checkIfSolid(gridX, gridY, levelData)) {
            enemies[i].velocity_y *= -1;
        }

        worldToTileCoordinates(enemies[i].position_x + enemies[i].width / 2, enemies[i].position_y, &gridX, &gridY);
        if (checkIfSolid(gridX, gridY, levelData)) {
            enemies[i].velocity_y *= -1;
        }

        worldToTileCoordinates(enemies[i].position_x, enemies[i].position_y + enemies[i].height / 2, &gridX, &gridY);
        if (checkIfSolid(gridX, gridY, levelData)) {
            enemies[i].velocity_y *= -1;
        }

        worldToTileCoordinates(enemies[i].position_x, enemies[i].position_y - enemies[i].height / 2, &gridX, &gridY);
        if (checkIfSolid(gridX, gridY, levelData)) {
            enemies[i].velocity_y *= -1;
        }

        float ydiff = enemies[i].position_y - player->position_y;
        float xdiff = enemies[i].position_x - player->position_x;
        if (xdiff < 5.0f) {
            enemies[i].position_y -= ydiff / 100.0f;
            enemies[i].position_x -= xdiff / 100.0f;
        }

    }

    for (size_t i = 0; i < entities.size(); i++) {
        if (!entities[i]->isStatic) {

            entities[i]->Update(elapsed);

            int gridX = 0, gridY = 0;

            worldToTileCoordinates(entities[i]->position_x - entities[i]->width / 2, entities[i]->position_y, &gridX, &gridY);
            if (checkIfSolid(gridX, gridY, levelData)) {
                entities[i]->position_x = (gridX + 1) * TILE_SIZE + entities[i]->width / 2 + 0.005f;
                entities[i]->velocity_x = 0;
                entities[i]->collidedLeft = true;
            }

            worldToTileCoordinates(entities[i]->position_x + entities[i]->width / 2, entities[i]->position_y, &gridX, &gridY);
            if (checkIfSolid(gridX, gridY, levelData)) {
                entities[i]->position_x = gridX * TILE_SIZE - entities[i]->width / 2 - 0.005f;
                entities[i]->velocity_x = 0;
                entities[i]->collidedRight = true;
            }

            worldToTileCoordinates(entities[i]->position_x, entities[i]->position_y + entities[i]->height / 2, &gridX, &gridY);
            if (checkIfSolid(gridX, gridY, levelData)) {
                entities[i]->position_y = (-gridY - 1) * TILE_SIZE - entities[i]->height / 2 - 0.005f;
                entities[i]->velocity_y = 0;
                entities[i]->collidedTop = true;
            }

            worldToTileCoordinates(entities[i]->position_x, entities[i]->position_y - entities[i]->height / 2, &gridX, &gridY);
            if (checkIfSolid(gridX, gridY, levelData)) {
                entities[i]->position_y = -gridY * TILE_SIZE + entities[i]->height / 2 + 0.005f;
                entities[i]->velocity_y = 0;
                entities[i]->collidedBottom = true;
            }
        }

        for (Entity& enemy : enemies) {
            if (enemy.active) {
                if (player->collidesWith(enemy)) {
                    RenderGameOver();
                }
            }
        }

        for (Entity& key : keyv) {
            if (key.active) {
                if (player->collidesWith(key)) {
                    score++;
                    key.active = false;
                }
            }
        }
    }

}
Example #28
0
#define RESOURCE_FOLDER "NYUCodebase.app/Contents/Resources/"
#endif

int p1ScoreCount = 0;
int p2ScoreCount = 0;
float MaxYPos = 2.0f;
float MaxXPos = 3.55f;
bool done = false;


float ticks;
float lastFrameTicks = 0.0f;
float elapsed;


const Uint8 *keys = SDL_GetKeyboardState(NULL);

SDL_Window* displayWindow;

GLuint LoadTexture(const char *image_path);
void setBackgroundColorAndClear();
void drawTexture(GLuint theTexture, ShaderProgram program, float height = 0.5f, float width = 0.5f);
void Setup(ShaderProgram program, Matrix &projectionMatrix);

void ProcessEvents();

void Update(float lastFrameTicks, Matrix &modelMatrix, ShaderProgram program);
void Render(ShaderProgram program, Matrix modelMatrix);
void DrawSpriteSheetSprite(ShaderProgram &program, GLuint theTexture, int index, int SpriteXCount, int SpriteYCount);

void initializeEntities();
Example #29
-1
int main(int argc, char** argv) {
	// Seed and refresh RNG
	std::srand((unsigned)std::time(NULL) ^ (unsigned)std::rand());
	short n = 10 + rand() % 10;
	for (short i = 0; i < n; i++) {
		std::rand();
	}

	// Initialize SDL
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
		std::cerr << "*** Failed to initialize SDL: " << SDL_GetError() << std::endl;
		return EXIT_FAILURE;
	}

	// Initialize SDL_image library
	if (!IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG)) {
		std::cerr << "*** Failed to initialize SDL_image: " << IMG_GetError() << std::endl;
		return EXIT_FAILURE;
	}

	// Initialize SDL_mixer library
	if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024) < 0) {
		std::cerr << "*** Failed to initialize SDL_mixer: " << Mix_GetError() << std::endl;
		return EXIT_FAILURE;
	}

	Mix_AllocateChannels(64);

	// Initialize TTF library
	if (TTF_Init() == -1) {
		std::cerr << "*** Failed to initialize SDL_ttf: " << TTF_GetError() << std::endl;
		return EXIT_FAILURE;
	}

	// Create a window
	g_WindowWidth = 800;
	g_WindowHeight = 600;
	g_Window = SDL_CreateWindow("Loading...",
		SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
		g_WindowWidth, g_WindowHeight,
		SDL_WINDOW_SHOWN);
	if (!g_Window) {
		std::cerr << "*** Failed to create window: " << SDL_GetError() << std::endl;
		return EXIT_FAILURE;
	}

	// Get a pointer to keyboard state managed by SDL
	g_KeyStates = SDL_GetKeyboardState(NULL);

	// Create a renderer that takes care of drawing stuff to the window
	g_Renderer = SDL_CreateRenderer(g_Window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (!g_Renderer) {
		std::cerr << "*** Failed to create renderer: " << SDL_GetError() << std::endl;
		return EXIT_FAILURE;
	}

	SDL_SetRenderDrawBlendMode(g_Renderer, SDL_BLENDMODE_BLEND);

	// Create game
	Game game;

	if (!game.Initialize()) {
		std::cerr << "*** Game initialization failed" << std::endl;
		return EXIT_FAILURE;
	}

	// Main loop

	// Start tracking total game time and frame time
	g_Timer.Start();
	Timer frameTimer;
	frameTimer.Start();

	while (!g_ShouldQuit) {
		++g_FrameNo;

		// Draw current frame
		game.Draw(g_Renderer);
		SDL_RenderPresent(g_Renderer);

		// Forward events to game handlers
		SDL_Event e;
		while (SDL_PollEvent(&e)) {
			switch (e.type) {
			case SDL_QUIT:
				g_ShouldQuit = true;
				break;
			case SDL_KEYDOWN:
				game.OnKeyDown(e.key);
				break;
			case SDL_KEYUP:
				game.OnKeyUp(e.key);
				break;
			case SDL_MOUSEBUTTONDOWN:
				game.OnMouseDown(e.button);
				break;
			case SDL_MOUSEBUTTONUP:
				game.OnMouseUp(e.button);
				break;
			case SDL_MOUSEMOTION:
				game.OnMouseMotion(e.motion);
				break;
			default:
				break;
			}
		}

		// Update total game time
		g_Time = g_Timer.GetTime();

		// Get time elapsed since last frame and restart frame timer
		g_TimeSinceLastFrame = frameTimer.GetTime();
		frameTimer.Start();

		// Update game if it's not paused
		if (!g_IsPaused) {
			game.Update(g_TimeSinceLastFrame);
		}
	}

	// Cleanup
	game.Shutdown();
	TTF_Quit();
	IMG_Quit();
	Mix_Quit();
	SDL_Quit();

	std::cout << "## Goodbye!" << std::endl;
	return 0;
}
Example #30
-1
void Level::handleEvents(GameEngine* ge)
{
  SDL_Event e;
  while (SDL_PollEvent(&e))
  {
    if (e.type == SDL_QUIT)
    {
      ge->stop();
    }
    if (e.type == SDL_KEYDOWN)
    {
      if (e.key.keysym.sym == SDLK_ESCAPE)
      {
        ge->changeState(Title::Instance());
      }
    }
  }

  const Uint8* state = SDL_GetKeyboardState(NULL);

  if (gAI_Enable && !is_player1 && ball.isDead() && !is_a_player_dead)
  {
    double ai_angle = (-(double)nrand(60)) - 15.0;
    double ai_shot_dt = ((double) nrand(100))/50.0 + 1.0; 
    double ai_increment = ((double)missed_distance)/500.0;
    if (missed_right)
    {
      // if ai keeps guessing close, randomize angle again, otherwise use last angle
      if (ai_increment >= .04)
      {
        ai_angle = last_ai_angle;
      }
      ai_shot_dt = last_ai_shot_dt + ai_increment;
      missed_right = false;
    }
    if (missed_left)
    {
      if (ai_increment >= .04)
      {
        ai_angle = last_ai_angle;
      }
      ai_shot_dt = last_ai_shot_dt - ai_increment;
      missed_left = false;
    }
    //std::cout << ai_angle << " " << ai_shot_dt << " " << ai_increment << std::endl;

    cannonR.setAngle(ai_angle);
    ball.shoot(cannonR.getCX(), cannonR.getCY(), ai_shot_dt, cannonR.getAngle());
    last_ai_angle = ai_angle;
    last_ai_shot_dt = ai_shot_dt;
  }

  if (state[SDL_SCANCODE_D] || state[SDL_SCANCODE_RIGHT])
  {
    if (ball.isDead())
    {
      if (is_player1)
        cannonL.incrementAngle(180.0*dt);
      else
        cannonR.incrementAngle(180.0*dt);
    }
  }
  if (state[SDL_SCANCODE_A] || state[SDL_SCANCODE_LEFT])
  {
    if (ball.isDead())
    {
      if (is_player1)
        cannonL.incrementAngle(-180.0*dt);
      else
        cannonR.incrementAngle(-180.0*dt);
    }
  }
  if (state[SDL_SCANCODE_SPACE])
  {
    if (ball.isDead())
    {
      if (!shooting)
      {
        shooting = true;
        shot_dt = 0.0;
        shot_timer.start();
      }
      else
      {
        shot_dt = shot_timer.getTime();
        keyup_frames = 0;
      }
    }
  }
  else
  {
    if (shooting)
    {
      keyup_frames++; // synergy hack, synergy creates false positive keyups
      if (keyup_frames >= 5)
      {
        shooting = false;
        shot_dt = shot_timer.getTime();
        //std::cout << "shot_dt: " << shot_dt << "\n";
        keyup_frames = 0;

        if (is_player1)
          ball.shoot(cannonL.getCX(), cannonL.getCY(), shot_dt, cannonL.getAngle());
        else
          ball.shoot(cannonR.getCX(), cannonR.getCY(), shot_dt, cannonR.getAngle());
        shot_dt = 0.0;
      }
    }
  }
}