Exemple #1
0
static void sdl_joypad_poll(void)
{
#ifdef HAVE_SDL2
   SDL_Event event;

   SDL_PumpEvents();

   while (SDL_PeepEvents(&event, 1,
            SDL_GETEVENT, SDL_JOYDEVICEADDED, SDL_JOYDEVICEREMOVED) > 0)
   {
      switch (event.type)
      {
         case SDL_JOYDEVICEADDED:
            sdl_pad_connect(event.jdevice.which);
            break;
         case SDL_JOYDEVICEREMOVED:
            sdl_pad_disconnect(event.jdevice.which);
            break;
      }
   }
#else
   SDL_JoystickUpdate();
#endif
}
Exemple #2
0
int levelTwo()
{
	

	moving = 0;
	SDL_RenderClear(gt_graphics_get_active_renderer());
	ResetBuffer();

	backOffset = ((int)camera.x+3200)%3200;
	offset = ((int)camera.x+1600)%1600;

	drawSprite(moonBack,0,vec2d(0,0),vec2d(1,1),0,gt_graphics_get_active_renderer());
	
	drawSprite(levelTwoBackTrees,0,vec2d(-backOffset,0),vec2d(1,1),0,gt_graphics_get_active_renderer());
    drawSprite(levelTwoFrontTrees,0,vec2d(-offset,0),vec2d(1,1),0,gt_graphics_get_active_renderer());
	drawSprite(levelTwoFloor,0,vec2d(-offset,0),vec2d(1,1),0,gt_graphics_get_active_renderer());
	
	drawSprite(levelTwoFrontTrees,0,vec2d(-offset+1600,0),vec2d(1,1),0,gt_graphics_get_active_renderer());
	drawSprite(levelTwoBackTrees,0,vec2d(-backOffset+1600,0),vec2d(1,1),0,gt_graphics_get_active_renderer());
	drawSprite(levelTwoFloor,0,vec2d(-offset+1600,0),vec2d(1,1),0,gt_graphics_get_active_renderer());

	



	entity_think_all();
	entity_touch_all();
	entity_update_all();
	entity_draw_all();
	if(player->position.x >= 300)
		{
			camera.x = player->position.x - 300;
			
		}
	if(player->position.x < 300)
		{
			camera.x = 0;
			
		}
	if(xDistance == 12000.00)
	{
		done = 1;
	}

	healthBar();
    NextFrame();
    SDL_PumpEvents();
	diff = (gt_graphics_now - gt_graphics_then);
	
	if(playerData.shotTimer>0)
	{
		playerData.shotTimer -= diff;
	}
    keys = SDL_GetKeyboardState(NULL);
    if(keys[SDL_SCANCODE_ESCAPE])
    {
        done = 1;
    }
	else if(keys[SDL_SCANCODE_W])
	{
		moving = 1;
		moveCharacter(DIR_UP,player);
		yDistance = player->position.y;
	}
	else if(keys[SDL_SCANCODE_A])
	{
		moving = 1;
		moveCharacter(DIR_LEFT,player);
		xDistance = player->position.x;
	}
	else if(keys[SDL_SCANCODE_D])
	{
		moving = 1;
		moveCharacter(DIR_RIGHT,player);
		xDistance = player->position.x;
		
	}
	else if(keys[SDL_SCANCODE_S])
	{
		moving = 1;
		moveCharacter(DIR_DOWN,player);
		yDistance = player->position.y;
	}
	else if(keys[SDL_SCANCODE_1])
	{
		fire_Pistol();
	}
	else if(keys[SDL_SCANCODE_2])
	{
		fire_Shotgun();
	}
	else if(keys[SDL_SCANCODE_3])
	{
		fire_Machinegun();
	}
	else if(keys[SDL_SCANCODE_4])
	{
		fire_Heavy_Machinegun();
	}
	else if(keys[SDL_SCANCODE_P])
	{
		saveState();
	}
	else if(keys[SDL_SCANCODE_O])
	{
		loadState();
	}
	if(moving == 0)
	{
		resetAnimation(player, 0);
	}


	
  
  return 0;
}
Exemple #3
0
    void InputWrapper::capture(bool windowEventsOnly)
    {
        mViewer->getEventQueue()->frame(0.f);

        SDL_PumpEvents();

        SDL_Event evt;

        if (windowEventsOnly)
        {
            // During loading, just handle window events, and keep others for later
            while (SDL_PeepEvents(&evt, 1, SDL_GETEVENT, SDL_WINDOWEVENT, SDL_WINDOWEVENT))
                handleWindowEvent(evt);
            return;
        }

        while(SDL_PollEvent(&evt))
        {
            switch(evt.type)
            {
                case SDL_MOUSEMOTION:
                    // Ignore this if it happened due to a warp
                    if(!_handleWarpMotion(evt.motion))
                    {
                        // If in relative mode, don't trigger events unless window has focus
                        if (!mWantRelative || mWindowHasFocus)
                            mMouseListener->mouseMoved(_packageMouseMotion(evt));

                        // Try to keep the mouse inside the window
                        if (mWindowHasFocus)
                            _wrapMousePointer(evt.motion);
                    }
                    break;
                case SDL_MOUSEWHEEL:
                    mMouseListener->mouseMoved(_packageMouseMotion(evt));
                    break;
                case SDL_MOUSEBUTTONDOWN:
                    mMouseListener->mousePressed(evt.button, evt.button.button);
                    break;
                case SDL_MOUSEBUTTONUP:
                    mMouseListener->mouseReleased(evt.button, evt.button.button);
                    break;
                case SDL_KEYDOWN:
                    mKeyboardListener->keyPressed(evt.key);

                    if (!isModifierHeld(KMOD_ALT) && evt.key.keysym.sym >= SDLK_F1 && evt.key.keysym.sym <= SDLK_F12)
                    {
                        mViewer->getEventQueue()->keyPress(osgGA::GUIEventAdapter::KEY_F1 + (evt.key.keysym.sym - SDLK_F1));
                    }

                    break;
                case SDL_KEYUP:
                    if (!evt.key.repeat)
                    {
                        mKeyboardListener->keyReleased(evt.key);

                        if (!isModifierHeld(KMOD_ALT) && evt.key.keysym.sym >= SDLK_F1 && evt.key.keysym.sym <= SDLK_F12)
                            mViewer->getEventQueue()->keyRelease(osgGA::GUIEventAdapter::KEY_F1 + (evt.key.keysym.sym - SDLK_F1));
                    }

                    break;
                case SDL_TEXTEDITING:
                    break;
                case SDL_TEXTINPUT:
                    mKeyboardListener->textInput(evt.text);
                    break;

#if SDL_VERSION_ATLEAST(2, 0, 4)
                case SDL_KEYMAPCHANGED:
                    break;
#endif
                case SDL_JOYHATMOTION: //As we manage everything with GameController, don't even bother with these.
                case SDL_JOYAXISMOTION:
                case SDL_JOYBUTTONDOWN:
                case SDL_JOYBUTTONUP:
                case SDL_JOYDEVICEADDED:
                case SDL_JOYDEVICEREMOVED:
                    break;
                case SDL_CONTROLLERDEVICEADDED:
                    if(mConListener)
                        mConListener->controllerAdded(1, evt.cdevice); //We only support one joystick, so give everything a generic deviceID
                    break;
                case SDL_CONTROLLERDEVICEREMOVED:
                    if(mConListener)
                        mConListener->controllerRemoved(evt.cdevice);
                    break;
                case SDL_CONTROLLERBUTTONDOWN:
                    if(mConListener)
                        mConListener->buttonPressed(1, evt.cbutton);
                    break;
                case SDL_CONTROLLERBUTTONUP:
                    if(mConListener)
                        mConListener->buttonReleased(1, evt.cbutton);
                    break;
                case SDL_CONTROLLERAXISMOTION:
                    if(mConListener)
                        mConListener->axisMoved(1, evt.caxis);
                    break;
                case SDL_WINDOWEVENT:
                    handleWindowEvent(evt);
                    break;
                case SDL_QUIT:
                    if (mWindowListener)
                        mWindowListener->windowClosed();
                    break;
                case SDL_CLIPBOARDUPDATE:
                    break; // We don't need this event, clipboard is retrieved on demand

                case SDL_FINGERDOWN:
                case SDL_FINGERUP:
                case SDL_FINGERMOTION:
                case SDL_DOLLARGESTURE:
                case SDL_DOLLARRECORD:
                case SDL_MULTIGESTURE:
                    // No use for touch & gesture events
                    break;

                default:
                    Log(Debug::Info) << "Unhandled SDL event of type 0x" << std::hex << evt.type;
                    break;
            }
        }
    }
Exemple #4
0
int main(int argc,char **argv)
{
	setlocale(LC_ALL,"RUSSIAN");

	SDL_DisplayMode displayMode;

	if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
	{
    cout << "SDL_Init Error: " << SDL_GetError() << endl;
    return 1;
	}

	int request = SDL_GetDesktopDisplayMode(0,&displayMode); 

	SDL_Window *win = SDL_CreateWindow("Trubi", 300, 300,800, 800, SDL_WINDOW_SHOWN);
	if (win == nullptr)
	{
		cout << "SDL_CreateWindow Error: " << SDL_GetError() << endl;
	    return 1;
	}

	SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (ren == nullptr)
	{
		cout << "SDL_CreateRenderer Error: " << SDL_GetError() << endl;
	    return 1;
	}

	vector<DPipe> DPIPES(13);
	vector<DoublePipe> DOUBPIPES(6);

	DPipe background(400,400,800,800);
	DPipe a0(70,300,100,40);
	DPipe a1(170,300,100,40);
	DPipe a2(270,300,100,40);
	DPipe a3(370,400,100,40);
	DPipe a4(370,500,100,40);
	DPipe a5(470,600,100,40);
	DPipe a6(570,600,100,40);
	DPipe a7(670,500,100,40);
	DPipe a8(670,400,100,40);
	
	DPipe a9(370,200,100,40);
	DPipe a10(470,100,100,40);
	DPipe a11(570,100,100,40);
	DPipe a12(670,200,100,40);
	DPipe kletka(370,300,100,100);

	DoublePipe b0(370,300,70,40);
	DoublePipe b1(370,600,70,40);
	DoublePipe b2(670,600,70,40);
	DoublePipe b3(670,300,70,40);
	DoublePipe b4(370,100,70,40);
	DoublePipe b5(670,100,70,40);

	DPIPES[0]=a0;
	DPIPES[1]=a1;
	DPIPES[2]=a2;
	DPIPES[3]=a3;
	DPIPES[4]=a4;
	DPIPES[5]=a5;
	DPIPES[6]=a6;
	DPIPES[7]=a7;
	DPIPES[8]=a8;
	DPIPES[9]=a9;
	DPIPES[10]=a10;
	DPIPES[11]=a11;
	DPIPES[12]=a12;
	
	DOUBPIPES[0]=b0;
	DOUBPIPES[1]=b1;
	DOUBPIPES[2]=b2;
	DOUBPIPES[3]=b3;
	DOUBPIPES[4]=b4;
	DOUBPIPES[5]=b5;

	SDL_RenderClear(ren);
	background.default_create(ren,"newbackground.bmp");
	for(int i=0;i<DPIPES.size();++i)
	{
		DPIPES[i].default_create(ren,"text1.bmp");
	}
	for(int i=0;i<DOUBPIPES.size();++i)
	{
		DOUBPIPES[i].default_create1(ren,"double1.bmp","double2.bmp");
	}
	SDL_RenderPresent(ren); 

	bool quit=false;
	while(!quit)
	{
		 while(SDL_PollEvent(&event))
		 {
			SDL_PumpEvents(); 

			if(event.type == SDL_QUIT)
				quit=true;
			else if(event.type==SDL_MOUSEBUTTONDOWN &&  event.button.button==SDL_BUTTON_LEFT)
			{
				for(int i=0;i<DPIPES.size();++i)
				{
					if(DPIPES[i].ismouse())
					{
						SDL_RenderClear(ren);
						background.default_create(ren,"newbackground.bmp");
						nochangesDoub(ren,DOUBPIPES);
						somechanges(ren,DPIPES,i);
					}
				}
				for(int i=0;i<DOUBPIPES.size();++i)
				{
					if(DOUBPIPES[i].ismouse())
					{
						SDL_RenderClear(ren);
						background.default_create(ren,"newbackground.bmp");
						nochanges(ren,DPIPES);
						somechangesDoub(ren,DOUBPIPES,i);
					}
				}
			}
		 }
	}
	return 1;
}
Exemple #5
0
int main(int argc, char *argv[])
{
	GList* list = NULL;
	json_t *root;

	SDL_Surface *optimized_surface = NULL;
	SDL_Surface *temp = NULL;
	Sound *bg_music = NULL;
	Sound *level_music = NULL;
	int done;
	const Uint8 *keys;
	char imagepath[512];

	game_initialize_system();
	SDL_ShowCursor(SDL_DISABLE);

	bg_music = sound_load_music("sounds/vanguard_bouncy.mp3");
	if(!bg_music)
	{
		slog("Could not load music\n");
	}
	
	level_music = sound_load_music("sounds/chippy_cloud_kid.mp3");
	if(!level_music)
	{
		slog("Could not load music\n");
	}
	Mix_VolumeMusic(5);

	if(temp)
	{
		optimized_surface = SDL_ConvertSurface( temp, graphics_surface->format, NULL );
		SDL_FreeSurface(temp);
		
	}

	SDL_Event e;
	done = 0;

	int lock = true;
	do
	{
		if(menu_flag)
		{
			menu_draw();
			if(lock == false)
			{
				Mix_HaltMusic();
				lock = true;
			}

			if(Mix_PlayingMusic() == 0)
			{
				Mix_PlayMusic(bg_music->music, -1);
			}
		}
		else
		{
			tilemap_render_tile();
			entity_draw_all();
			if(lock == true)
			{
				Mix_HaltMusic();
				lock = false;
			}

			if(Mix_PlayingMusic() == 0)
			{
				Mix_PlayMusic(level_music->music, -1);
			}
		}

		mouse_draw_self();

		graphics_next_frame();
		SDL_PumpEvents();

		entity_think_all();

		while(SDL_PollEvent(&e) != 0)
		{
			if(e.type == SDL_QUIT)
			{
				done = 1;
			}
			
			bool leftclick = false ;
			bool rightclick = false;
			if(e.type == SDL_MOUSEBUTTONDOWN)
			{
				if(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT))
				{
					leftclick = true;
				}
				else if(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_RIGHT))
				{
					rightclick = true;
				}
			}

			if(leftclick == true)
			{
				if(menu_flag)
					menu_click();
				else
					tilemap_click();
			}
			else if(rightclick == true)
			{
				if(menu_flag)
					menu_click();
				else
					tilemap_remove_tile();
			}

			bool pressed = false;
			if(e.type == SDL_KEYDOWN)
			{
				if(!pressed)
				{
					if(make_flag)
					{
						keys = SDL_GetKeyboardState(NULL);
						if(keys[SDL_SCANCODE_W])
						{
							State state = UP;
							tilemap_m_click(state);
						}
						else if(keys[SDL_SCANCODE_A])
						{
							State state = LEFT;
							tilemap_m_click(state);
						}
						else if(keys[SDL_SCANCODE_S])
						{
							State state = DOWN;
							tilemap_m_click(state);
						}
						else if(keys[SDL_SCANCODE_D])
						{
							State state = RIGHT;
							tilemap_m_click(state);
						}

						if(keys[SDL_SCANCODE_T])
						{
							State state = UP;
							tilemap_c_click(state);
						}
						else if(keys[SDL_SCANCODE_F])
						{
							State state = LEFT;
							tilemap_c_click(state);
						}
						else if(keys[SDL_SCANCODE_G])
						{
							State state = DOWN;
							tilemap_c_click(state);
						}
						else if(keys[SDL_SCANCODE_H])
						{
							State state = RIGHT;
							tilemap_c_click(state);
						}
					}
				}
				pressed = true;
			}
			else if(e.type == SDL_KEYUP)
			{
				pressed = false;
			}
		}

		keys = SDL_GetKeyboardState(NULL);
		if(keys[SDL_SCANCODE_ESCAPE])
		{
			done = 1;
		}

		SDL_RenderPresent(graphics_renderer); // update the screen with any rendering performed since previous call

	} while(!done);

	exit(0);
	return 0;
}
/* Process pending events. Call with ->lock held */
static void
gst_sdlv_process_events (GstSDLVideoSink * sdlvideosink)
{
  SDL_Event event;
  int numevents;
  char *keysym = NULL;

  do {
    SDL_PumpEvents ();
    numevents = SDL_PeepEvents (&event, 1, SDL_GETEVENT,
        SDL_KEYDOWNMASK | SDL_KEYUPMASK |
        SDL_MOUSEMOTIONMASK | SDL_MOUSEBUTTONDOWNMASK |
        SDL_MOUSEBUTTONUPMASK | SDL_QUITMASK | SDL_VIDEORESIZEMASK);

    if (numevents > 0 && (event.type == SDL_KEYUP || event.type == SDL_KEYDOWN)) {
      keysym = SDL_GetKeyName (event.key.keysym.sym);
    }

    if (numevents > 0) {
      g_mutex_unlock (sdlvideosink->lock);
      switch (event.type) {
        case SDL_MOUSEMOTION:
          gst_navigation_send_mouse_event (GST_NAVIGATION (sdlvideosink),
              "mouse-move", 0, event.motion.x, event.motion.y);
          break;
        case SDL_MOUSEBUTTONDOWN:
          gst_navigation_send_mouse_event (GST_NAVIGATION (sdlvideosink),
              "mouse-button-press",
              event.button.button, event.button.x, event.button.y);
          break;
        case SDL_MOUSEBUTTONUP:
          gst_navigation_send_mouse_event (GST_NAVIGATION (sdlvideosink),
              "mouse-button-release",
              event.button.button, event.button.x, event.button.y);
          break;
        case SDL_KEYUP:
          GST_DEBUG ("key press event %s !",
              SDL_GetKeyName (event.key.keysym.sym));
          gst_navigation_send_key_event (GST_NAVIGATION (sdlvideosink),
              "key-release", keysym);
          break;
        case SDL_KEYDOWN:
          if (SDLK_ESCAPE != event.key.keysym.sym) {
            GST_DEBUG ("key press event %s !",
                SDL_GetKeyName (event.key.keysym.sym));
            gst_navigation_send_key_event (GST_NAVIGATION (sdlvideosink),
                "key-press", keysym);
            break;
          } else {
            /* fall through */
          }
        case SDL_QUIT:
          sdlvideosink->running = FALSE;
          GST_ELEMENT_ERROR (sdlvideosink, RESOURCE, OPEN_WRITE,
              ("Video output device is gone."),
              ("We were running fullscreen and user "
                  "pressed the ESC key, stopping playback."));
          break;
        case SDL_VIDEORESIZE:
          /* create a SDL window of the size requested by the user */
          g_mutex_lock (sdlvideosink->lock);
          GST_VIDEO_SINK_WIDTH (sdlvideosink) = event.resize.w;
          GST_VIDEO_SINK_HEIGHT (sdlvideosink) = event.resize.h;
          gst_sdlvideosink_create (sdlvideosink);
          g_mutex_unlock (sdlvideosink->lock);
          break;
      }
      g_mutex_lock (sdlvideosink->lock);
    }
  } while (numevents > 0);
}
Exemple #7
0
void pump()
{
	SDL_PumpEvents();

	pump_info info;

	//used to keep track of double click events
	static int last_mouse_down = -1;
	static int last_click_x = -1, last_click_y = -1;

	SDL_Event temp_event;
	int poll_count = 0;
	int begin_ignoring = 0;
	std::vector< SDL_Event > events;
	while(SDL_PollEvent(&temp_event)) {
		++poll_count;
		if(!begin_ignoring && temp_event.type == SDL_ACTIVEEVENT) {
			begin_ignoring = poll_count;
		} else if(begin_ignoring > 0 && SDL_EVENTMASK(temp_event.type)&INPUT_MASK) {
			//ignore user input events that occurred after the window was activated
			continue;
		}
		events.push_back(temp_event);
	}
	std::vector<SDL_Event>::iterator ev_it = events.begin();
	for(int i=1; i < begin_ignoring; ++i){
		if(SDL_EVENTMASK(ev_it->type)&INPUT_MASK) {
			//ignore user input events that occurred before the window was activated
			ev_it = events.erase(ev_it);
		} else {
			++ev_it;
		}
	}
	std::vector<SDL_Event>::iterator ev_end = events.end();
	for(ev_it = events.begin(); ev_it != ev_end; ++ev_it){
		SDL_Event &event = *ev_it;
		switch(event.type) {

			case SDL_ACTIVEEVENT: {
				SDL_ActiveEvent& ae = reinterpret_cast<SDL_ActiveEvent&>(event);
				if((ae.state & SDL_APPMOUSEFOCUS) != 0 || (ae.state & SDL_APPINPUTFOCUS) != 0) {
					cursor::set_focus(ae.gain != 0);
				}
				break;
			}

			//if the window must be redrawn, update the entire screen
			case SDL_VIDEOEXPOSE: {
				update_whole_screen();
				break;
			}

			case SDL_VIDEORESIZE: {
				const SDL_ResizeEvent* const resize = reinterpret_cast<SDL_ResizeEvent*>(&event);
				info.resize_dimensions.first = resize->w;
				info.resize_dimensions.second = resize->h;
				break;
			}

			case SDL_MOUSEMOTION: {
				//always make sure a cursor is displayed if the
				//mouse moves or if the user clicks
				cursor::set_focus(true);
				raise_help_string_event(event.motion.x,event.motion.y);
				break;
			}

			case SDL_MOUSEBUTTONDOWN: {
				//always make sure a cursor is displayed if the
				//mouse moves or if the user clicks
				cursor::set_focus(true);
				if(event.button.button == SDL_BUTTON_LEFT) {
					static const int DoubleClickTime = 500;
					static const int DoubleClickMaxMove = 3;
					if(last_mouse_down >= 0 && info.ticks() - last_mouse_down < DoubleClickTime &&
					   abs(event.button.x - last_click_x) < DoubleClickMaxMove &&
					   abs(event.button.y - last_click_y) < DoubleClickMaxMove) {
						SDL_UserEvent user_event;
						user_event.type = DOUBLE_CLICK_EVENT;
						user_event.code = 0;
						user_event.data1 = reinterpret_cast<void*>(event.button.x);
						user_event.data2 = reinterpret_cast<void*>(event.button.y);
						::SDL_PushEvent(reinterpret_cast<SDL_Event*>(&user_event));
					}
					last_mouse_down = info.ticks();
					last_click_x = event.button.x;
					last_click_y = event.button.y;
				}
				break;
			}

#if defined(_X11) && !defined(__APPLE__)
			case SDL_SYSWMEVENT: {
				//clipboard support for X11
				handle_system_event(event);
				break;
			}
#endif

			case SDL_QUIT: {
				throw CVideo::quit();
			}
		}

		if(event_contexts.empty() == false) {

			const std::vector<handler*>& event_handlers = event_contexts.back().handlers;

			//events may cause more event handlers to be added and/or removed,
			//so we must use indexes instead of iterators here.
			for(size_t i1 = 0, i2 = event_handlers.size(); i1 != i2 && i1 < event_handlers.size(); ++i1) {
				event_handlers[i1]->handle_event(event);
			}
		}
	}

	//inform the pump monitors that an events::pump() has occurred
	for(size_t i1 = 0, i2 = pump_monitors.size(); i1 != i2 && i1 < pump_monitors.size(); ++i1) {
		pump_monitors[i1]->process(info);
	}
}
Exemple #8
0
void pump()
{
	if(boost::this_thread::get_id() != main_thread) {
		// Can only call this on the main thread!
		return;
	}
	SDL_PumpEvents();
	peek_for_resize();
	pump_info info;

	//used to keep track of double click events
	static int last_mouse_down = -1;
	static int last_click_x = -1, last_click_y = -1;

	SDL_Event temp_event;
	int poll_count = 0;
	int begin_ignoring = 0;
	std::vector< SDL_Event > events;
	while(SDL_PollEvent(&temp_event)) {
		++poll_count;
		peek_for_resize();

		if(!begin_ignoring && temp_event.type == SDL_WINDOWEVENT
				&& (temp_event.window.event == SDL_WINDOWEVENT_ENTER
						|| temp_event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED))
		{
			begin_ignoring = poll_count;
		} else if(begin_ignoring > 0 && is_input(temp_event)) {
			//ignore user input events that occurred after the window was activated
			continue;
		}
		events.push_back(temp_event);
	}

	std::vector<SDL_Event>::iterator ev_it = events.begin();
	for(int i=1; i < begin_ignoring; ++i){
		if(is_input(*ev_it)) {
			//ignore user input events that occurred before the window was activated
			ev_it = events.erase(ev_it);
		} else {
			++ev_it;
		}
	}

	std::vector<SDL_Event>::iterator ev_end = events.end();
	bool resize_found = false;
	for(ev_it = events.begin(); ev_it != ev_end; ++ev_it){
		SDL_Event &event = *ev_it;
		if (event.type == SDL_WINDOWEVENT &&
				event.window.event == SDL_WINDOWEVENT_RESIZED) {
			resize_found = true;
			last_resize_event = event;
			last_resize_event_used = false;

		}
	}
	// remove all inputs, draw events and only keep the last of the resize events
	// This will turn horrible after ~38 days when the Uint32 wraps.
	if (resize_found || SDL_GetTicks() <= last_resize_event.window.timestamp + resize_timeout) {
		events.erase(std::remove_if(events.begin(), events.end(), remove_on_resize), events.end());
	} else if(SDL_GetTicks() > last_resize_event.window.timestamp + resize_timeout && !last_resize_event_used) {
		events.insert(events.begin(), last_resize_event);
		last_resize_event_used = true;
	}

	ev_end = events.end();

	for(ev_it = events.begin(); ev_it != ev_end; ++ev_it){
		for (context& c : event_contexts)
		{
			c.add_staging_handlers();
		}

		SDL_Event &event = *ev_it;
		switch(event.type) {

			case SDL_WINDOWEVENT:
				switch(event.window.event) {
					case SDL_WINDOWEVENT_ENTER:
					case SDL_WINDOWEVENT_FOCUS_GAINED:
						cursor::set_focus(1);
						break;

					case SDL_WINDOWEVENT_LEAVE:
					case SDL_WINDOWEVENT_FOCUS_LOST:
						cursor::set_focus(1);
						break;

					case SDL_WINDOWEVENT_RESIZED:
						info.resize_dimensions.first = event.window.data1;
						info.resize_dimensions.second = event.window.data2;
						break;
				}
				//make sure this runs in it's own scope.
				{
					flip_locker flip_lock(CVideo::get_singleton());
					for( std::deque<context>::iterator i = event_contexts.begin() ; i != event_contexts.end(); ++i) {
						const handler_list& event_handlers = (*i).handlers;
						for(auto handler : event_handlers) {
							handler->handle_window_event(event);
						}
					}
					const handler_list& event_handlers = event_contexts.front().handlers;
					for(auto handler : event_handlers) {
						handler->handle_window_event(event);
					}
				}

				//This event was just distributed, don't re-distribute.
				continue;

			case SDL_MOUSEMOTION: {
				//always make sure a cursor is displayed if the
				//mouse moves or if the user clicks
				cursor::set_focus(true);
				raise_help_string_event(event.motion.x,event.motion.y);
				break;
			}

			case SDL_MOUSEBUTTONDOWN: {
				//always make sure a cursor is displayed if the
				//mouse moves or if the user clicks
				cursor::set_focus(true);
				if(event.button.button == SDL_BUTTON_LEFT) {
					static const int DoubleClickTime = 500;
					static const int DoubleClickMaxMove = 3;
					if(last_mouse_down >= 0 && info.ticks() - last_mouse_down < DoubleClickTime &&
					   abs(event.button.x - last_click_x) < DoubleClickMaxMove &&
					   abs(event.button.y - last_click_y) < DoubleClickMaxMove) {
						SDL_UserEvent user_event;
						user_event.type = DOUBLE_CLICK_EVENT;
						user_event.code = 0;
						user_event.data1 = reinterpret_cast<void*>(event.button.x);
						user_event.data2 = reinterpret_cast<void*>(event.button.y);
						::SDL_PushEvent(reinterpret_cast<SDL_Event*>(&user_event));
					}
					last_mouse_down = info.ticks();
					last_click_x = event.button.x;
					last_click_y = event.button.y;
				}
				break;
			}
			case DRAW_ALL_EVENT:
			{
				flip_locker flip_lock(CVideo::get_singleton());
				/* iterate backwards as the most recent things will be at the top */
				for( std::deque<context>::iterator i = event_contexts.begin() ; i != event_contexts.end(); ++i) {
					handler_list& event_handlers = (*i).handlers;
					for( handler_list::iterator i1 = event_handlers.begin(); i1 != event_handlers.end(); ++i1) {
						(*i1)->handle_event(event);
					}
				}
				continue; //do not do further handling here
			}

#ifndef __APPLE__
			case SDL_KEYDOWN: {
				if(event.key.keysym.sym == SDLK_F4 && (event.key.keysym.mod == KMOD_RALT || event.key.keysym.mod == KMOD_LALT)) {
					quit_confirmation::quit_to_desktop();
					continue; // this event is already handled
				}
				break;
			}
#endif

#if defined(_X11) && !defined(__APPLE__)
			case SDL_SYSWMEVENT: {
				//clipboard support for X11
				desktop::clipboard::handle_system_event(event);
				break;
			}
#endif

#if defined _WIN32
			case SDL_SYSWMEVENT: {
				windows_tray_notification::handle_system_event(event);
				break;
			}
#endif

			case SDL_QUIT: {
				quit_confirmation::quit_to_desktop();
				continue; //this event is already handled.
			}
		}

		const handler_list& global_handlers = event_contexts.front().handlers;
		for(auto handler : global_handlers) {
			handler->handle_event(event);
		}

		if(event_contexts.empty() == false) {

			const handler_list& event_handlers = event_contexts.back().handlers;

			for(auto handler : event_handlers) {
				handler->handle_event(event);
			}
		}

	}

	//inform the pump monitors that an events::pump() has occurred
	for(size_t i1 = 0, i2 = pump_monitors.size(); i1 != i2 && i1 < pump_monitors.size(); ++i1) {
		pump_monitors[i1]->process(info);
	}
}
Exemple #9
0
int main(int argc,char** argv)
{
	DPipe tryba1_rect(200,200,100,40);
	DPipe tryba2_rect(400,400,100,40);
	DPipe background_rect(350,350,700,700);
	DPipe kletka_rect(200,200,100,100);
	DPipe kletka2_rect(400,400,100,100);


	setlocale(LC_ALL,"RUSSIAN");
	//------создаем окно с фоном и парой труб--------//
	SDL_DisplayMode displayMode;

	if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
	{
    cout << "SDL_Init Error: " << SDL_GetError() << endl;
    return 1;
	}

	int request = SDL_GetDesktopDisplayMode(0,&displayMode);

	//создаем монитор
	SDL_Window *win = SDL_CreateWindow("Trubi", 300, 300,SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	if (win == nullptr)
	{
		cout << "SDL_CreateWindow Error: " << SDL_GetError() << endl;
	    return 1;
	}

	//создаем рендерер
	SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (ren == nullptr)
	{
		cout << "SDL_CreateRenderer Error: " << SDL_GetError() << endl;
	    return 1;
	}

	SDL_Surface *BMP_TRYBA=SDL_LoadBMP("kletka.bmp");
	if (BMP_TRYBA == nullptr)
	{
	    cout << "SDL_LoadBMP Error: " << SDL_GetError() << endl;
		return 1;
	}
	SDL_Texture *TRYBA = SDL_CreateTextureFromSurface(ren, BMP_TRYBA);

	SDL_RenderClear(ren);
	background_rect.default_create(ren,"project.bmp");
	kletka_rect.default_create(ren,"kletka.bmp");
	kletka2_rect.default_create(ren,"kletka.bmp");
	tryba1_rect.default_create(ren,"text1.bmp");
	tryba2_rect.default_create(ren,"text1.bmp");
	SDL_RenderPresent(ren); 

	SDL_Event event;
	bool quit=false;
	int trybi=2;
	while(!quit)
	{
		 while(SDL_PollEvent(&event))
		 {
			SDL_PumpEvents(); // обработчик событий.
			
			//крестик
			if(event.type == SDL_QUIT)
				quit=true;
			else if(event.type==SDL_MOUSEBUTTONDOWN &&  event.button.button==SDL_BUTTON_LEFT)
			{
				if((event.button.x>=kletka_rect.center().x-kletka_rect.width()/2 && event.button.x<=kletka_rect.center().x+kletka_rect.width()/2) && 
					(event.button.y>=kletka_rect.center().y-kletka_rect.height()/2 && event.button.y<=kletka_rect.center().y+kletka_rect.height()/2))
				{
						SDL_RenderClear(ren);
						background_rect.default_create(ren,"project.bmp");
						kletka_rect.default_create(ren,"kletka.bmp");
						kletka2_rect.default_create(ren,"kletka.bmp");
						tryba2_rect.upgrade(ren); 
						tryba1_rect.spin(ren);
						SDL_RenderPresent(ren); 
				}
				else if((event.button.x>=kletka2_rect.center().x-kletka2_rect.width()/2 && event.button.x<=kletka2_rect.center().x+kletka2_rect.width()/2) && 
					(event.button.y>=kletka2_rect.center().y-kletka2_rect.height()/2 && event.button.y<=kletka2_rect.center().y+kletka2_rect.height()/2))
				{
						SDL_RenderClear(ren);
						background_rect.default_create(ren,"project.bmp");
						kletka_rect.default_create(ren,"kletka.bmp");
						kletka2_rect.default_create(ren,"kletka.bmp");
						tryba1_rect.upgrade(ren);
						tryba2_rect.spin(ren);
						SDL_RenderPresent(ren); 
				}
						
			}
		 }
	}
	return 1;
}
Exemple #10
0
void run(struct Computer *computer) {
	struct CPU *cpu = &computer->cpu;
	struct RAM *ram = &computer->ram;
	struct GPU *gpu = &computer->gpu;
	struct DMA *dma = &computer->dma;
	
	struct Screen *screen = computer->screen;
	
	// TODO boot computer
	initTime();
	
	// init CPU
	cpu->IP = CODE_ADDR;
	cpu->SP = ram->size - 1;
	
	CPU_run(cpu);
	
	// how many emulated cycles can we do until the next refresh
	uint32 cpuCycles = cpu->clockRate / gpu->refreshRate;
	uint32 tickCounter = 0;
		
	double refreshTimeMs = 1000.0 / (double) gpu->refreshRate;
	double sleepTimeMs = 0.0;
	
	double tickStartMs = 0.0;
	double tickEndMs = 0.0;
	double tickDiffMs = 0.0;
	
	printf("CPU clock rate: %ld Hz\n", cpu->clockRate);
	printf("Video refresh rate: %ld Hz\n", gpu->refreshRate);
	printf("CPU cycles per frame: %ld\n", cpuCycles);
	printf("Refresh time: %f ms\n", refreshTimeMs);
	
	while (CPU_isRunning(cpu)) {
		tickCounter = cpuCycles;
	
		tickStartMs = getMilliTime();
	
		while (CPU_isRunning(cpu) && tickCounter > 0) {
			CPU_tick(cpu);
			DMA_tick(dma);
			
			tickCounter--;
		}

		// update the screen
		if (screen != NULL) {
			draw(gpu, screen);
			CPU_interrupt(cpu, VBLANK_INTERRUPT);
		}
		
		// we need to pump events or the window freezes
		SDL_PumpEvents();
		
		SDL_RenderClear(screen->renderer);
		SDL_RenderCopy(screen->renderer, screen->texture, NULL, NULL);
		SDL_RenderPresent(screen->renderer);

		tickEndMs = getMilliTime();
		tickDiffMs = tickEndMs - tickStartMs;
		
		sleepTimeMs = refreshTimeMs - tickDiffMs;

		// printf("> %f %f\n", tickDiffMs, sleepTimeMs);
		
		if (sleepTimeMs >= 1.0) {
			SDL_Delay((Uint32) sleepTimeMs);
		}
	}
}
/*notice the default arguments for main.  SDL expects main to look like that, so don't change it*/
int main(int argc, char *argv[])
{
  SDL_Surface *temp = NULL;
  int done;
  int tx = 0,ty = 0;
  int i;
  const Uint8 *keys;
  char imagepath[512];
  SDL_Rect srcRect={0,0,SCREEN_WIDTH,SCREEN_HEIGHT};
  SDL_Event e;
  last_time = current_time = SDL_GetTicks();
  
  Init_All();
  slog("Finished Init All()");
  done = 0;
  do
  {
	   //render or draw functions go here
	//draw functions should go in order from background first to player draw calls last
    ResetBuffer();
    SDL_RenderClear(__gt_graphics_renderer);//clear screen
	tile_render();	
	player_draw();
	DrawMouse2();
	
	/*monster_spawn(Monster::grue);
	monster_spawn(Monster::spider01);
	monster_spawn(Monster::mino);		
	monster_spawn(Monster::orc);	
	support_spawn(Support::sara);	
	support_spawn(Support::healer);	
	support_spawn(Support::archer);
	
	*/
	entity_update_all();
	entity_think_all();
	entity_check_collision_all();
	particle_em_draw_all();
//	struct_update_all();
	

	G_MONSTER_SPAWN_TIMER -= 1;

	while(SDL_PollEvent(&e) != 0)
		player_move (&e);
    NextFrame();
	//end
    SDL_PumpEvents();
    keys = SDL_GetKeyboardState(NULL);
	//taken from lazyfoo
	//handles generally keyboard inputs	
	
	while( SDL_PollEvent( &e) != 0){
		if(e.type == SDL_QUIT)
			done = 1;
    	else
			player_move(&e);	
	}

		if(keys[SDL_SCANCODE_ESCAPE])
		{
			done = 1;
		}
		
	SDL_RenderPresent(__gt_graphics_renderer);
	last_time = current_time;
	current_time = SDL_GetTicks();
	delta = current_time - last_time;
  }while(!done);
  exit(0);		/*technically this will end the program, but the compiler likes all functions that can return a value TO return a value*/
  return 0;
}
Exemple #12
0
int main( int argc, char **argv )
{
#ifdef __APPLE__
    string macDir = get_mac_dir();
    string configFile = macDir + "/../configuration.ini";
#else
    string configFile = "configuration.ini";
#endif
    load_configuration(configFile);

    SDL_Surface *surface;
    SDL_Event event;

    int videoFlags;
    videoFlags  = SDL_OPENGL;          // Enable OpenGL in SDL
    videoFlags |= SDL_GL_DOUBLEBUFFER; // Enable double buffering
    //videoFlags |= SDL_HWPALETTE;       // Store the palette in hardware

    if ( displayFullscreen )
        videoFlags |= SDL_FULLSCREEN;

    if ( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        fprintf( stderr, "Video initialization failed: %s\n",
                 SDL_GetError( ) );
        //Quit( 1 );
    }

    if (hardwareCursor)
        SDL_ShowCursor(SDL_DISABLE);

    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
    surface = SDL_SetVideoMode( displayWidth, displayHeight, displayBpp, videoFlags );

    SDL_WM_SetCaption("Torque Tracer","icon");

    bindKeys();

    OpenGL_init();
#ifdef __APPLE__
    string fontPath = macDir + "/Contents/Resources/Vera.ttf";
    const char *fontFile = strdup(fontPath.c_str());
#else
    const char *fontFile = "Vera.ttf";
#endif
    load_font(fontFile, &font[0], 18);

    //////////////////////////////////////
    // torque curve initial points - for debugging
    /*torqueCurve.push_back( vector2fSet(-0.7, -0.7) );
     torqueCurve.push_back( vector2fSet(-0.7 + incrementX * 1, -0.7 + incrementY*2) );
     torqueCurve.push_back( vector2fSet(-0.7 + incrementX * 2, -0.7 + incrementY*3) );*/

    bool exitApplication = false;

    while ( true )
    {
        if (exitApplication == true) break;

        SDL_PollEvent( &event );

        SDL_PumpEvents();
        sdl_mouseUpdate();

        if (event.type == SDL_QUIT)
            exitApplication = true;

        ////////////////////////////////////////////
        // check keyboard keys
        unsigned char *keyState = (unsigned char *) SDL_GetKeyState(NULL);
        for ( unsigned int klv=0 ; klv<BUTTONS_KEYBOARD ; klv++)
        {
            if ( keyState[klv] && keyboardButtons[klv].pressedLf == false )
            {
                keyboardButtons[klv].pressedLf = true;

                if (keyboardButtons[klv].action == ACTION_QUIT) exitApplication = true;

                if (keyboardButtons[klv].action == ACTION_TOGGLE_MODE)
                {
                    if (inputMode == INPUT_MODE_RESIZE)
                        inputMode = INPUT_MODE_DRAW;
                    else if (inputMode == INPUT_MODE_DRAW)
                        inputMode = INPUT_MODE_ENTER_TEXT;
                    else if (inputMode == INPUT_MODE_ENTER_TEXT)
                        inputMode = INPUT_MODE_RESIZE;
                    //printf("toggle mode\n");
                }

                if (keyboardButtons[klv].action == ACTION_TORQUE_ZOOM_IN)
                {
                    if (incrementY < 6)
                        incrementY *= 1.25;
                }
                if (keyboardButtons[klv].action == ACTION_TORQUE_ZOOM_OUT)
                {
                    if (incrementY > 0.05)
                        incrementY /= 1.25;
                }
                if (keyboardButtons[klv].action == ACTION_WRITE_FILE)
                {
                    writeTorqueCurve();
                }
                if (keyboardButtons[klv].action == ACTION_TOGGLE_TORQUE_UNITS)
                {
                    if (torqueMode == TORQUEMODE_METRIC)
                        torqueMode = TORQUEMODE_IMPERIAL;
                    else
                        torqueMode = TORQUEMODE_METRIC;
                }

                if (inputMode == INPUT_MODE_ENTER_TEXT)
                {
                    // this covers numbers
                    if (  SDLK_0 <= klv && klv <= SDLK_9 )
                        enteredText += klv ;
                    if ( klv == SDLK_PERIOD)
                        enteredText += ".";

                    if ( klv == SDLK_n )
                        enteredText += "Nm @";
                    if ( klv == SDLK_f )
                        enteredText += "ft-lbs @";
                    if ( klv == SDLK_k )
                        enteredText += "kW @";
                    if ( klv == SDLK_h || klv == SDLK_b )
                        enteredText += "bhp @";

                    if ( klv == SDLK_BACKSPACE )
                    {
                        // if you're backspacing over an @ sign, just clear the whole string to start over
                        if (enteredText[enteredText.size()-1] == '@')
                            enteredText.resize(0);

                        if ( enteredText.size() > 0)
                            enteredText.resize(enteredText.size()-1);

                    }

                    if ( klv == SDLK_RETURN )
                    {
                        processEnteredText();
                    }
                }
            }
            else if (!keyState[klv] && keyboardButtons[klv].pressedLf == true)
            {
                keyboardButtons[klv].pressedLf = false;
            }
        }

        ///////////////////////////////////////
        // check mouse stuff
        for (unsigned int mlv=0 ; mlv<BUTTONS_MOUSE ; mlv++)
        {
            if ( inputMode == INPUT_MODE_DRAW)
            {
                if (mouseButtons[mlv].pressed && mouseButtons[mlv].pressedLf == false)
                {
                    if ( mlv == 1)			// left click
                    {
                        // no negative values please
                        if (mousePos.a[0] > gridStartX && mousePos.a[1] > gridStartY)
                        {
                            insertPointInCurve(mousePos);
                        }
                    }
                    else if ( mlv == 3)			// right click
                    {
                        // erase on right-click

                        //////////////////////////////////////////////
                        // this works
                        //if (torqueCurve.size() > 0)
                        //	torqueCurve.pop_back();

                        //////////////////////////////////////////////
                        // but we should probably erase whatever were closest to
                        if ( torqueCurve.size() == 0)
                        {
                            break;
                        }
                        if ( torqueCurve.size() == 1)
                        {
                            torqueCurve.pop_back();
                        }
                        if (closestPointToMouse == torqueCurve.size()-1)
                        {
                            torqueCurve.pop_back();
                            break;
                        }

                        vector<c_vector2f>::iterator it;
                        unsigned int index = 0;
                        for ( it=torqueCurve.begin() ; it<torqueCurve.end()-1 ; it++ )
                        {
                            if (index == closestPointToMouse)
                            {
                                torqueCurve.erase(it,it+1);
                                break;
                            }
                            index++;
                        }
                    }
                }
            }
            else if (inputMode == INPUT_MODE_RESIZE)
            {
                if ( mouseButtons[mlv].pressed)			// left click or right click
                {
                    if ( (mousePos.a[0] > pictureL-0.1) && (mousePos.a[0] < pictureL+0.1) )
                    {
                        pictureL = mousePos.a[0];
                        //printf("l-border\n");
                    }

                    if ( (mousePos.a[0] > pictureR-0.1) && (mousePos.a[0] < pictureR+0.1) )
                    {
                        pictureR = mousePos.a[0];
                        //printf("r-border\n");
                    }

                    if ( (mousePos.a[1] > pictureT-0.1) && (mousePos.a[1] < pictureT+0.1) )
                    {
                        pictureT = mousePos.a[1];
                        //printf("t-border\n");
                    }

                    if ( (mousePos.a[1] > pictureB-0.1) && (mousePos.a[1] < pictureB+0.1) )
                    {
                        pictureB = mousePos.a[1];
                        //printf("b-border\n");
                    }
                }
            }
        }

        // debug text
        for (unsigned int l=0 ; l<torqueCurve.size() ; l++ )
        {
            //printf("(%f,%f)\n", torqueCurve[l].a[0], torqueCurve[l].a[1]);
        }
        //printf("\n");

        OpenGL_render();
        SDL_GL_SwapBuffers();
    }

    printf("done.\n");

    // reset resolution
    SDL_Quit();

    /////////////////////////////////////
    // every generation of windows gets
    // progressively lamer.  xp requires
    // this to exit cleanly.
    // C'est la micro$oft
#ifdef WIN32
    FatalExit(666);
#endif

    return 0;
}
bool InputHandler::MousePressed(MouseButton button)
{
	SDL_PumpEvents();
	return(SDL_GetMouseState(&m_MouseX, &m_MouseY) & SDL_BUTTON(button));
}
void InputHandler::Update()
{
	SDL_PumpEvents();
	SDL_GetMouseState(&m_MouseX, &m_MouseY);
}
Exemple #15
0
int main_menu()
{
  static int i = 0;
  static int upHeld = 0;
  static int downHeld = 0;
  SDL_Renderer *render;
  render = gt_graphics_get_active_renderer();
  SDL_RenderClear(gt_graphics_get_active_renderer());
  ResetBuffer();
  mainScreen = loadSprite("images/opening_screen.png",800,600,1);
  selection = loadSprite("images/selection.png",149,53,1);
  printf("%i", i);
  if(i == 0)
	{
		drawSprite(mainScreen,0,vec2d(0,0),vec2d(1,1),0,gt_graphics_get_active_renderer());
		drawSprite(selection,0,vec2d(311,292),vec2d(1,1),0,gt_graphics_get_active_renderer());
  }else if(i == 1)
  {
	  drawSprite(mainScreen,0,vec2d(0,0),vec2d(1,1),0,gt_graphics_get_active_renderer());
	  drawSprite(selection,0,vec2d(275,376),vec2d(1.5,1),0,gt_graphics_get_active_renderer());
	  
  }else if(i == 2)
  {
	  drawSprite(mainScreen,0,vec2d(0,0),vec2d(1,1),0,gt_graphics_get_active_renderer());
	  drawSprite(selection,0,vec2d(311,460),vec2d(1,1),0,gt_graphics_get_active_renderer());
	  
  }
  NextFrame();
  SDL_PumpEvents();
  keys = SDL_GetKeyboardState(NULL);
  if(keys[SDL_SCANCODE_ESCAPE])
    {
        done = 1;
    }
  if(keys[SDL_SCANCODE_DOWN]&&downHeld == 0)
    {
	  i=(i+1)%3;
	  downHeld = 1;
	}else if(!keys[SDL_SCANCODE_DOWN])
  {
		downHeld = 0;
  }
  if(keys[SDL_SCANCODE_UP]&&upHeld == 0)
  {
	  if((i = i-1)<0)
		  i = 2;

	  upHeld = 1;
	}else if(!keys[SDL_SCANCODE_UP])
  {
		upHeld = 0;
  }
  if(keys[SDL_SCANCODE_RETURN])
  {
	  if(i == 0)
	  {
		  gameState = 1;
		  init_lvl1();
	  }
	  else if(i == 2)
	  {
		  done = 1;
	  }
	  else if(i == 1)
	  {
		  init_player();

		  loadState();
		  if(gameState == 1)
		  {
			  init_lvl1();
		  }else if(gameState == 2)
		  {
			  init_lvl2();
		  }
	  }
  }	  
   return 1;
}
void inputLib::readInput()
{
    _used_keyboard = false;
    while (SDL_PollEvent(&event)) {

        if (_show_btn_debug == false) {
            _show_btn_debug = true;
        }

        if (game_config.input_type == INPUT_TYPE_DOUBLE || game_config.input_type == INPUT_TYPE_KEYBOARD) {
            if (event.type == SDL_KEYDOWN) {
                for (int i=0; i<BTN_COUNT; i++) {
                    if (game_config.keys_codes[i] != -1 && game_config.keys_codes[i] == event.key.keysym.sym) {
                        p1_input[i] = 1;
                        _used_keyboard = true;
                        if (i == BTN_JUMP) {
                            p1_input[BTN_JUMP_TIMER] = timer.getTimer();
                        }
                    }
                }
            } else if (event.type == SDL_KEYUP) {
                for (int i=0; i<BTN_COUNT; i++) {
                    if (game_config.keys_codes[i] != -1 && game_config.keys_codes[i] == event.key.keysym.sym) {
                        p1_input[i] = 0;
                        _used_keyboard = true;
                        if (i == BTN_JUMP) {
                            p1_input[BTN_JUMP_TIMER] = 0;
                        }
                    }
                }
            }
            SDL_PumpEvents(); // check keyboard events
#if !defined(PLAYSTATION2) && !defined(PSP) && !defined(WII) && !defined(DREAMCAST)
            if (event.type == SDL_QUIT) {
                std::cout << "LEAVE #1" << std::endl;
                std::fflush(stdout);
                gameControl.leave_game();
            }
#endif
        }
        if (_used_keyboard == true) { // next commands are all joystick only
            return;
        }
        if (game_config.input_type == INPUT_TYPE_DOUBLE || game_config.input_type == INPUT_TYPE_JOYSTICK) {
            if (event.type == SDL_JOYBUTTONDOWN) {
                //std::cout << "#1 INPUT::readInput - joystick button[" << (int)event.jbutton.button << "] pressed." << std::endl;
                for (int i=0; i<BTN_COUNT; i++) {
                    //std::cout << "#1 INPUT::readInput - button_codes[" << i << "]: " << game_config.button_codes[i] << std::endl;
                    if (game_config.button_codes[i] != -1 && game_config.button_codes[i] == event.jbutton.button) {
                        //std::cout << "#1 INPUT::readInput - FOUND ACTION for i: " << i << std::endl;
                        p1_input[i] = 1;
                        if (i == BTN_JUMP) {
                            p1_input[BTN_JUMP_TIMER] = timer.getTimer();
                        }
                        //break;
                    }
                }
            } else if (event.type == SDL_JOYBUTTONUP) {
                //std::cout << "#2 INPUT::readInput - joystick button[" << event.jbutton.button << "] released" << std::endl;
                for (int i=0; i<BTN_COUNT; i++) {
                    if (game_config.button_codes[i] != -1 && game_config.button_codes[i] == event.jbutton.button) {
                        p1_input[i] = 0;
                        if (i == BTN_JUMP) {
                            p1_input[BTN_JUMP_TIMER] = 0;
                        }
                        break;
                    }
                }
            }
        }
        if ((game_config.input_mode == INPUT_MODE_ANALOG || game_config.input_mode == INPUT_MODE_DOUBLE) && event.type == SDL_JOYAXISMOTION) {
            if (event.jaxis.axis == 0) {
                if (event.jaxis.value < -JOYVAL) {
                    p1_input[BTN_RIGHT] = 0;
                    p1_input[BTN_LEFT] = 1;
                    _used_keyboard = false;
                } else if (event.jaxis.value > JOYVAL) {
                    p1_input[BTN_RIGHT] = 1;
                    p1_input[BTN_LEFT] = 0;
                    _used_keyboard = false;
                } else if ((event.jaxis.value < JOYVAL || event.jaxis.value > -JOYVAL) && _used_keyboard == false) {
                    p1_input[BTN_RIGHT] = 0;
                    p1_input[BTN_LEFT] = 0;
                }
            }
            if (event.jaxis.axis == 1) {
                if (event.jaxis.value < -JOYVAL) {
                    p1_input[BTN_DOWN] = 0;
                    p1_input[BTN_UP] = 1;
                    _used_keyboard = false;
                } else if (event.jaxis.value > JOYVAL) {
                    p1_input[BTN_DOWN] = 1;
                    p1_input[BTN_UP] = 0;
                    _used_keyboard = false;
                } else if ((event.jaxis.value < JOYVAL || event.jaxis.value > -JOYVAL) && _used_keyboard == false) {
                    p1_input[BTN_DOWN] = 0;
                    p1_input[BTN_UP] = 0;
                }
            }
        }
        if ((game_config.input_mode == INPUT_MODE_DIGITAL || game_config.input_mode == INPUT_MODE_DOUBLE) && event.type == SDL_JOYHATMOTION) {
            // CODES: up - 1, right: 2, down: 4, left: 8
            if (event.jhat.value == 1 || event.jhat.value == 3 || event.jhat.value == 9) { // up
                p1_input[BTN_DOWN] = 0;
                p1_input[BTN_UP] = 1;
                _used_keyboard = false;
            }
            if (event.jhat.value == 2 || event.jhat.value == 3 || event.jhat.value == 6) { // right
                p1_input[BTN_RIGHT] = 1;
                p1_input[BTN_LEFT] = 0;
                _used_keyboard = false;
            }
            if (event.jhat.value == 4 || event.jhat.value == 6 || event.jhat.value == 12) { // down
                p1_input[BTN_DOWN] = 1;
                p1_input[BTN_UP] = 0;
                _used_keyboard = false;
            }
            if (event.jhat.value == 8 || event.jhat.value == 9 || event.jhat.value == 12) { // left
                p1_input[BTN_LEFT] = 1;
                p1_input[BTN_RIGHT] = 0;
                _used_keyboard = false;
            }
            if (event.jhat.value == 0 && _used_keyboard == false) {
                p1_input[BTN_LEFT] = 0;
                p1_input[BTN_RIGHT] = 0;
                p1_input[BTN_DOWN] = 0;
                p1_input[BTN_UP] = 0;
            }
        }
    }
}
Exemple #17
0
void gen_interupt(void)
{
    if (stop == 1)
    {
        vi_counter = 0; // debug
        dyna_stop();
    }

    if (!interupt_unsafe_state)
    {
        if (savestates_get_job() == savestates_job_load)
        {
            savestates_load();
            return;
        }

        if (reset_hard_job)
        {
            reset_hard();
            reset_hard_job = 0;
            return;
        }
    }
   
    if (skip_jump)
    {
        unsigned int dest = skip_jump;
        skip_jump = 0;

        if (q->count > Count || (Count - q->count) < 0x80000000)
            next_interupt = q->count;
        else
            next_interupt = 0;
        
        last_addr = dest;
        generic_jump_to(dest);
        return;
    } 

    switch(q->type)
    {
        case SPECIAL_INT:
            if (Count > 0x10000000) return;
            remove_interupt_event();
            add_interupt_event_count(SPECIAL_INT, 0);
            return;
            break;
        case VI_INT:
            if(vi_counter < 60)
            {
                if (vi_counter == 0)
                    cheat_apply_cheats(ENTRY_BOOT);
                vi_counter++;
            }
            else
            {
                cheat_apply_cheats(ENTRY_VI);
            }
            gfx.updateScreen();
#ifdef WITH_LIRC
            lircCheckInput();
#endif
            SDL_PumpEvents();

            refresh_stat();

            // if paused, poll for input events
            if(rompause)
            {
                osd_render();  // draw Paused message in case gfx.updateScreen didn't do it
                VidExt_GL_SwapBuffers();
                while(rompause)
                {
                    SDL_Delay(10);
                    SDL_PumpEvents();
#ifdef WITH_LIRC
                    lircCheckInput();
#endif //WITH_LIRC
                }
            }

            new_vi();
            if (vi_register.vi_v_sync == 0) vi_register.vi_delay = 500000;
            else vi_register.vi_delay = ((vi_register.vi_v_sync + 1)*1500);
            next_vi += vi_register.vi_delay;
            if (vi_register.vi_status&0x40) vi_field=1-vi_field;
            else vi_field=0;

            remove_interupt_event();
            add_interupt_event_count(VI_INT, next_vi);
    
            MI_register.mi_intr_reg |= 0x08;
            if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                Cause = (Cause | 0x400) & 0xFFFFFF83;
            else
                return;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;
    
        case COMPARE_INT:
            remove_interupt_event();
            Count+=count_per_op;
            add_interupt_event_count(COMPARE_INT, Compare);
            Count-=count_per_op;
    
            Cause = (Cause | 0x8000) & 0xFFFFFF83;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;
    
        case CHECK_INT:
            remove_interupt_event();
            break;
    
        case SI_INT:
#ifdef WITH_LIRC
            lircCheckInput();
#endif //WITH_LIRC
            SDL_PumpEvents();
            PIF_RAMb[0x3F] = 0x0;
            remove_interupt_event();
            MI_register.mi_intr_reg |= 0x02;
            si_register.si_stat |= 0x1000;
            if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                Cause = (Cause | 0x400) & 0xFFFFFF83;
            else
                return;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;
    
        case PI_INT:
            remove_interupt_event();
            MI_register.mi_intr_reg |= 0x10;
            pi_register.read_pi_status_reg &= ~3;
            if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                Cause = (Cause | 0x400) & 0xFFFFFF83;
            else
                return;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;
    
        case AI_INT:
            if (ai_register.ai_status & 0x80000000) // full
            {
                unsigned int ai_event = get_event(AI_INT);
                remove_interupt_event();
                ai_register.ai_status &= ~0x80000000;
                ai_register.current_delay = ai_register.next_delay;
                ai_register.current_len = ai_register.next_len;
                add_interupt_event_count(AI_INT, ai_event+ai_register.next_delay);
         
                MI_register.mi_intr_reg |= 0x04;
                if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                    Cause = (Cause | 0x400) & 0xFFFFFF83;
                else
                    return;
                if ((Status & 7) != 1) return;
                if (!(Status & Cause & 0xFF00)) return;
            }
            else
            {
                remove_interupt_event();
                ai_register.ai_status &= ~0x40000000;

                //-------
                MI_register.mi_intr_reg |= 0x04;
                if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                    Cause = (Cause | 0x400) & 0xFFFFFF83;
                else
                    return;
                if ((Status & 7) != 1) return;
                if (!(Status & Cause & 0xFF00)) return;
            }
            break;

        case SP_INT:
            remove_interupt_event();
            sp_register.sp_status_reg |= 0x203;
            // sp_register.sp_status_reg |= 0x303;
    
            if (!(sp_register.sp_status_reg & 0x40)) return; // !intr_on_break
            MI_register.mi_intr_reg |= 0x01;
            if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                Cause = (Cause | 0x400) & 0xFFFFFF83;
            else
                return;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;
    
        case DP_INT:
            remove_interupt_event();
            dpc_register.dpc_status &= ~2;
            dpc_register.dpc_status |= 0x81;
            MI_register.mi_intr_reg |= 0x20;
            if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                Cause = (Cause | 0x400) & 0xFFFFFF83;
            else
                return;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;

        case HW2_INT:
            // Hardware Interrupt 2 -- remove interrupt event from queue
            remove_interupt_event();
            // setup r4300 Status flags: reset TS, and SR, set IM2
            Status = (Status & ~0x00380000) | 0x1000;
            Cause = (Cause | 0x1000) & 0xFFFFFF83;
            /* the exception_general() call below will jump to the interrupt vector (0x80000180) and setup the
             * interpreter or dynarec
             */
            break;

        case NMI_INT:
            // Non Maskable Interrupt -- remove interrupt event from queue
            remove_interupt_event();
            // setup r4300 Status flags: reset TS and SR, set BEV, ERL, and SR
            Status = (Status & ~0x00380000) | 0x00500004;
            Cause  = 0x00000000;
            // simulate the soft reset code which would run from the PIF ROM
            r4300_reset_soft();
            // clear all interrupts, reset interrupt counters back to 0
            Count = 0;
            vi_counter = 0;
            init_interupt();
            // clear the audio status register so that subsequent write_ai() calls will work properly
            ai_register.ai_status = 0;
            // set ErrorEPC with the last instruction address
            ErrorEPC = PC->addr;
            // reset the r4300 internal state
            if (r4300emu != CORE_PURE_INTERPRETER)
            {
                // clear all the compiled instruction blocks and re-initialize
                free_blocks();
                init_blocks();
            }
            // adjust ErrorEPC if we were in a delay slot, and clear the delay_slot and dyna_interp flags
            if(delay_slot==1 || delay_slot==3)
            {
                ErrorEPC-=4;
            }
            delay_slot = 0;
            dyna_interp = 0;
            // set next instruction address to reset vector
            last_addr = 0xa4000040;
            generic_jump_to(0xa4000040);
            return;

        default:
            DebugMessage(M64MSG_ERROR, "Unknown interrupt queue event type %.8X.", q->type);
            remove_interupt_event();
            break;
    }

#ifdef NEW_DYNAREC
    if (r4300emu == CORE_DYNAREC) {
        EPC = pcaddr;
        pcaddr = 0x80000180;
        Status |= 2;
        Cause &= 0x7FFFFFFF;
        pending_exception=1;
    } else {
        exception_general();
    }
#else
    exception_general();
#endif

    if (!interupt_unsafe_state)
    {
        if (savestates_get_job() == savestates_job_save)
        {
            savestates_save();
            return;
        }
    }
}
Exemple #18
0
int main(int argc, char *argv[])
{
    fs_uae_argc = argc;
    fs_uae_argv = argv;
    fs_set_argv(argc, argv);

#ifdef WITH_CEF
    cef_init(argc, argv);
#endif

    char **arg;
    arg = argv + 1;
    while (arg && *arg) {
        if (strcmp(*arg, "--list-joysticks") == 0) {
            list_joysticks();
            exit(0);
        } else if (strcmp(*arg, "--list-devices") == 0) {
            list_joysticks();
            exit(0);
        } else if (strcmp(*arg, "--version") == 0) {
            printf("%s\n", PACKAGE_VERSION);
            exit(0);
        } else if (strcmp(*arg, "--help") == 0) {
            printf(COPYRIGHT_NOTICE, PACKAGE_VERSION, OS_NAME_2, ARCH_NAME_2);
            printf(EXTRA_HELP_TEXT);
            exit(0);
        }
        arg++;
    }

    fs_init();
    int error = fs_data_init("fs-uae", "fs-uae.dat");
    if (error) {
        printf("WARNING: error (%d) loading fs-uae.dat\n", error);
    }

    fs_set_prgname("fs-uae");
    fs_set_application_name("Amiga Emulator");

    amiga_set_log_function(log_to_libfsemu);

    //result = parse_options(argc, argv);

    printf(COPYRIGHT_NOTICE, PACKAGE_VERSION, OS_NAME_2, ARCH_NAME_2);
    fs_log(COPYRIGHT_NOTICE, PACKAGE_VERSION, OS_NAME_2, ARCH_NAME_2);

    char *current_dir = g_get_current_dir();
    fs_log("current directory is %s\n", current_dir);
    g_free(current_dir);

    amiga_init();

#if 0
    // FIXME: disabling fullscreen spaces must be done before
    // SDL_INIT_VIDEO, but we need to check config to see if this should
    // be done, and we initialize SDL early to check for config file
    // (catch 22)...
    // FIXME: check fullscreen_spaces option
    SDL_SetHint(SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES, "0");
#endif

#ifdef MACOSX
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_PumpEvents();
    SDL_Event event;
    fs_log("OS X: Check for pending SDL_DROPFILE event\n");
    while (SDL_PollEvent(&event)) {
        fs_log("Got SDL event 0x%x\n", event.type);
        if (event.type == SDL_DROPFILE) {
            if (event.drop.file != NULL) {
                g_fs_uae_config_file_path = strdup(event.drop.file);
            }
            SDL_free(event.drop.file);
        }
    }
#endif

    // skip first entry
    arg = argv + 1;
    if (g_fs_uae_config_file_path == NULL) {
        while (arg && *arg) {
            const gchar *test_path = *arg;
            if (test_path && fs_path_exists(test_path)) {
                if (check_extension(test_path, ".fs-uae")) {
                    g_fs_uae_config_file_path = g_strdup(test_path);
                } else if (check_extension(test_path, ".conf")) {
                    g_fs_uae_config_file_path = g_strdup(test_path);
                } else if (check_extension(test_path, ".adf")) {
                    g_fs_uae_disk_file_path = g_strdup(test_path);
                } else if (check_extension(test_path, ".ipf")) {
                    g_fs_uae_disk_file_path = g_strdup(test_path);
                } else if (check_extension(test_path, ".dms")) {
                    g_fs_uae_disk_file_path = g_strdup(test_path);
                }
            }
            arg++;
        }
    }

    /* Parse options first, in case base_dir, logging  options etc is
     * specified on the command line. */
    fs_config_parse_options(argc - 1, argv + 1);

    fs_log("\n");
    fs_log(LOG_LINE);
    fs_log("libfsemu init\n");
    fs_log(LOG_LINE);
    fs_log("\n");

    fs_emu_path_set_expand_function(fs_uae_expand_path);

    fs_emu_init_overlays(overlay_names);
    fs_emu_init();

    // then load the config file
    load_config_file();

    init_i18n();

    if (g_fs_uae_disk_file_path) {
        fs_config_set_string(OPTION_FLOPPY_DRIVE_0, g_fs_uae_disk_file_path);
        g_warn_about_missing_config_file = 0;
    }

    if (g_warn_about_missing_config_file) {
        fs_emu_warning(_("No configuration file was found"));
    }

    fs_log("\n");
    fs_log(LOG_LINE);
    fs_log("fs-uae init\n");
    fs_log(LOG_LINE);
    fs_log("\n");

    configure_logging(fs_config_get_const_string("log"));
    fs_emu_set_state_check_function(amiga_get_state_checksum);
    fs_emu_set_rand_check_function(amiga_get_rand_checksum);

    // force creation of some recommended default directories
    fs_uae_kickstarts_dir();
    fs_uae_configurations_dir();
    fs_uae_init_path_resolver();

    fs_uae_plugins_init();

    // must be called early, before fs_emu_init -affects video output
    fs_uae_configure_amiga_model();

    // force creation of state directories
    //fs_uae_flash_memory_dir();
    //fs_uae_save_states_dir();
    //fs_uae_floppy_overlays_dir();
    fs_uae_state_dir();

    const char *controllers_dir = fs_uae_controllers_dir();
    if (controllers_dir) {
        fs_emu_set_controllers_dir(controllers_dir);
    }
    const char *logs_dir = fs_uae_logs_dir();
    if (logs_dir) {
        char *log_file;

        log_file = g_build_filename(logs_dir, "FS-UAE.log", NULL);
        if (fs_path_exists(log_file)) {
            g_unlink(log_file);
        }
        g_free(log_file);

        log_file = g_build_filename(logs_dir, "FS-UAE.log.txt", NULL);
        if (fs_path_exists(log_file)) {
            g_unlink(log_file);
        }
        g_free(log_file);

        log_file = g_build_filename(logs_dir, "Emulator.log.txt", NULL);
        if (fs_path_exists(log_file)) {
            g_unlink(log_file);
        }
        g_free(log_file);

        log_file = g_build_filename(logs_dir, "fs-uae.log.txt", NULL);
        fs_config_set_log_file(log_file);
        g_free(log_file);
    }

    fs_config_set_string_if_unset("themes_dir", fs_uae_themes_dir());

    fs_emu_set_pause_function(pause_function);

    //fs_uae_init_input();
    fs_emu_init_2(FS_EMU_INIT_EVERYTHING);

    // we initialize the recording module either it is used or not, so it
    // can delete state-specific recordings (if necessary) when states are
    // saved
    fs_uae_init_recording();

    int deterministic_mode = 0;
    const char* record_file = fs_config_get_const_string("record");
    if (record_file) {
        fs_log("record file specified: %s, forcing deterministic mode\n",
            record_file);
        deterministic_mode = 1;
        fs_uae_enable_recording(record_file);
    } else {
        fs_log("not running in record mode\n");
    }
    if (fs_emu_netplay_enabled() ||
            fs_config_get_boolean(OPTION_DETERMINISTIC) == 1) {
        deterministic_mode = 1;
    }
    if (deterministic_mode) {
        amiga_set_deterministic_mode();
    }

    if (logs_dir) {
        if (fs_emu_netplay_enabled()) {
            char *sync_log_file = g_build_filename(logs_dir,
                    "Synchronization.log", NULL);
            amiga_set_synchronization_log_file(sync_log_file);
            free(sync_log_file);
        }
    }

#ifdef FS_EMU_DRIVERS
    fs_emu_audio_stream_options **options = fs_emu_audio_alloc_stream_options(2);
    options[0]->frequency = fs_emu_audio_output_frequency();
    /* 12 * 2352 is CDDA_BUFFERS * 2352 (blkdev_cdimage.cpp) */
    options[1]->buffer_size = 12 * 2352;
    // begin playing with only one buffer queued
    options[1]->min_buffers = 1;
    fs_emu_audio_configure(options);
    amiga_set_audio_buffer_size(options[0]->buffer_size);
    fs_emu_audio_free_stream_options(options);
#else
    // this stream is for paula output and drive clicks
    // FIXME: could mix drive clicks in its own stream instead, -might
    // give higher quality mixing
    fs_emu_audio_stream_options options;
    options.struct_size = sizeof(fs_emu_audio_stream_options);
    fs_emu_init_audio_stream_options(&options);
    options.frequency = fs_emu_audio_output_frequency();
    fs_emu_init_audio_stream(0, &options);
    amiga_set_audio_buffer_size(options.buffer_size);

    // this stream is for CD audio output (CDTV/CD32)
    fs_emu_init_audio_stream_options(&options);
    // 12 * 2352 is CDDA_BUFFERS * 2352 (blkdev_cdimage.cpp)
    options.buffer_size = 12 * 2352;
    // begin playing with only one buffer queued
    options.min_buffers = 1;
    fs_emu_init_audio_stream(1, &options);
#endif

    amiga_set_audio_callback(audio_callback_function);
    amiga_set_cd_audio_callback(audio_callback_function);
    amiga_set_event_function(event_handler);

    amiga_set_led_function(led_function);
    amiga_on_update_leds(on_update_leds);

    amiga_set_media_function(media_function);
    amiga_set_init_function(on_init);

    if (fs_config_get_boolean(OPTION_JIT_COMPILER) == 1) {
        amiga_init_jit_compiler();
    }

#ifdef WITH_LUA
    amiga_init_lua(fs_emu_acquire_lua, fs_emu_release_lua);
    amiga_init_lua_state(fs_emu_get_lua_state());
    fs_uae_init_lua_state(fs_emu_get_lua_state());
#endif

    if (fs_emu_get_video_format() == FS_EMU_VIDEO_FORMAT_RGBA) {
        amiga_set_video_format(AMIGA_VIDEO_FORMAT_RGBA);
    } else if (fs_emu_get_video_format() == FS_EMU_VIDEO_FORMAT_BGRA) {
        amiga_set_video_format(AMIGA_VIDEO_FORMAT_BGRA);
    } else if (fs_emu_get_video_format() == FS_EMU_VIDEO_FORMAT_R5G6B5) {
        amiga_set_video_format(AMIGA_VIDEO_FORMAT_R5G6B5);
    } else if (fs_emu_get_video_format() == FS_EMU_VIDEO_FORMAT_R5G5B5A1) {
        amiga_set_video_format(AMIGA_VIDEO_FORMAT_R5G5B5A1);
    } else {
        fs_emu_warning("Unsupported video format requested");
    }
    amiga_add_rtg_resolution(672, 540);
    amiga_add_rtg_resolution(960, 540);
    amiga_add_rtg_resolution(672 * 2, 540 * 2);
    amiga_add_rtg_resolution(fs_emu_get_windowed_width(),
            fs_emu_get_windowed_height());
    amiga_add_rtg_resolution(fs_emu_get_fullscreen_width(),
            fs_emu_get_fullscreen_height());
    fs_uae_init_video();

    //fs_uae_init_keyboard();
    fs_uae_init_mouse();
    fs_uae_configure_menu();

    fs_emu_run(main_function);
    fs_log("fs-uae shutting down, fs_emu_run returned\n");
    if (g_rmdir(fs_uae_state_dir()) == 0) {
        fs_log("state dir %s was removed because it was empty\n",
                fs_uae_state_dir());
    }
    else {
        fs_log("state dir %s was not removed (non-empty)\n",
                fs_uae_state_dir());
    }
    fs_log("end of main function\n");
    cleanup_old_files();

#ifdef WITH_CEF
    cef_destroy();
#endif
    return 0;
}
 void CKeyboard::Update()
 {
     SDL_PumpEvents();
 }
Exemple #20
0
Sint16 get_mouse_state (Sint16 *mx, Sint16 *my, Sint16 *button, Uint8 wait_event)
{
	SDL_Event event;
	Uint8 buttonmask;
	
	Uint8 wait = 1;

	*button = 0;
	
	if (wait_event)
	{
		while (wait)
		{
			if (! SDL_WaitEvent (&event))
			{
				printf ("get_mouse_state: error can't wait for event!\n");
				return (1);
			}

			switch (event.type)
			{
				case SDL_MOUSEBUTTONDOWN:
					if (event.button.button == SDL_BUTTON_LEFT)
					{
						*mx = event.button.x;
						*my = event.button.y;
						*button = 1;
						
						wait = 0;
					}
					break;
					
					if (event.button.button == SDL_BUTTON_RIGHT)
					{
						*mx = event.button.x;
						*my = event.button.y;
						*button = 2;
						
						wait = 0;
					}
					break;
					
					if (event.button.button == SDL_BUTTON_MIDDLE)
					{
						*mx = event.button.x;
						*my = event.button.y;
						*button = 3;
						
						wait = 0;
					}
					break;
				
				case SDL_MOUSEBUTTONUP:
					*mx = event.button.x;
					*my = event.button.y;
					*button = 0;
					
					wait = 0;
					break;
				
				case SDL_MOUSEMOTION:
					*mx = event.motion.x;
					*my = event.motion.y;
					*button = -1; 
					
					wait = 0;
					break;
			}
		}
	}
	else
	{
		/* don't wait for event, get current mouse state */
		
		SDL_PumpEvents ();
		buttonmask = SDL_GetMouseState ((int *) mx, (int *) my);

		printf ("get_mouse_state: %i / %i\n", *mx, *my);
		
		if (buttonmask & SDL_BUTTON (SDL_BUTTON_LEFT))
		{
			*button = 1;
		}

		if (buttonmask & SDL_BUTTON (SDL_BUTTON_RIGHT))
		{
			*button = 2;
		}

		if (buttonmask & SDL_BUTTON (SDL_BUTTON_MIDDLE))
		{
			*button = 3;
		}
	}
	
	return (0);		/* no error */
}
Exemple #21
0
int main (int argc, char* argv[]) {

	SDL_Init(SDL_INIT_EVERYTHING);
	IMG_Init(IMG_INIT_PNG);

	const std::string IMAGE_DIRECTORY = "C:\\Users\\dK\\Documents\\Visual " \
		                                "Studio 2012\\Projects\\SdlDemoProject\\Debug\\resources\\";

	const std::string LINK_IMAGE = IMAGE_DIRECTORY + "KidLink-1.png";
	const std::string BACKGROUND = IMAGE_DIRECTORY + "TerribleBackground.png";

	Renderer* renderer = new Renderer("SdlDemo", 500, 500, SDL_WINDOW_SHOWN);

	renderer->clearRenderer(0xFF, 0xFF, 0xFF);

	Texture* background = new Texture();

	AnimatedTexture* linkTexture = loadLink(LINK_IMAGE, renderer->getRenderer());

	if (!background->loadFromFile(BACKGROUND, renderer->getRenderer())) {
		delete linkTexture;
		delete renderer;
		IMG_Quit();
		SDL_Quit();
		return 1;
	}

	SDL_Rect blocks[10];

	blocks[0].x = 0;
	blocks[0].y = 0;
	blocks[1].x = 50;
	blocks[1].y = 0;
	blocks[2].x = 0;
	blocks[2].y = 50;
	blocks[3].x = 200;
	blocks[3].y = 200;
	blocks[4].x = 250;
	blocks[4].y = 250;
	blocks[5].x = 450;
	blocks[5].y = 400;
	blocks[6].x = 450;
	blocks[6].y = 450;
	blocks[7].x = 400;
	blocks[7].y = 450;
	blocks[8].x = 450;
	blocks[8].y = 0;
	blocks[9].x = 0;
	blocks[9].y = 450;


	for (int i = 0; i < 10; i++) {
		blocks[i].w = 50;
		blocks[i].h = 50;
	}

	SDL_Rect linkLocation = {100, 100, 50, 87};
	SDL_Rect oldPosition;
	SDL_Rect frame = linkTexture->getCurrentFrame()->getDiminsions();
	SDL_Rect draw = {0, 0, 500, 500};

	SDL_Event events;

	int xAccelorator = 0; 
	int yAccelorator = 0;

	while (true) {

		SDL_PumpEvents();

		oldPosition = linkLocation;

		if (SDL_PeepEvents(&events, 1, SDL_GETEVENT, SDL_QUIT, SDL_KEYUP)) {

			if (events.type == SDL_QUIT || (events.key.type == SDL_KEYDOWN && events.key.keysym.scancode == SDL_SCANCODE_ESCAPE)) {
				break;
			}
			else if (events.key.type == SDL_KEYDOWN && events.key.keysym.scancode == SDL_SCANCODE_DOWN) {
				 yAccelorator = 5;
				 linkTexture->animate("WalkDown");
			}
			else if (events.key.type == SDL_KEYDOWN && events.key.keysym.scancode == SDL_SCANCODE_UP) {
				yAccelorator = -5;
				linkTexture->animate("WalkUp");
			}
			else if (events.key.type == SDL_KEYDOWN && events.key.keysym.scancode == SDL_SCANCODE_RIGHT) {
				xAccelorator = 5;
				linkTexture->animate("WalkRight");
			}
			else if (events.key.type == SDL_KEYDOWN && events.key.keysym.scancode == SDL_SCANCODE_LEFT) {
				xAccelorator = -5;
				linkTexture->animate("WalkLeft");
			}

			if (events.key.type == SDL_KEYUP) {
				frame = linkTexture->getIdleFrame()->getDiminsions();
				linkTexture->reset();
			} else {
				frame = linkTexture->getCurrentFrame()->getDiminsions();
			}

			linkLocation.x += xAccelorator;
			linkLocation.y += yAccelorator;

			if (linkLocation.x < 0 || linkLocation.x + linkLocation.w > 500) {
				linkLocation = oldPosition;
			}
			if (linkLocation.y < 0 || linkLocation.y + linkLocation.h > 500) {
				linkLocation = oldPosition;
			}

			for (int i = 0; i < 10; i++) {
				if ((blocks[i].x + blocks[i].w >= linkLocation.x && linkLocation.x + linkLocation.w >= blocks[i].x) &&
				    (blocks[i].y + blocks[i].h >= linkLocation.y && linkLocation.y + linkLocation.h >= blocks[i].y)) {
					   linkLocation = oldPosition;
				}
			}

			SDL_FlushEvents(SDL_QUIT, SDL_KEYUP);
			xAccelorator = 0;
			yAccelorator = 0;
		}
		renderer->clearRenderer(0xFF, 0xFF, 0xFF);

		renderer->drawToRenderer(background->getTexture(), draw);
		renderer->drawToRenderer(linkTexture->getTexture(), linkLocation, frame);

		SDL_SetRenderDrawColor(renderer->getRenderer(), 20, 100, 20, 0xFF);

		for (int i = 0; i < 10; i++) {
			SDL_RenderFillRect(renderer->getRenderer(), &blocks[i]);
		}

		renderer->update();
	}

	delete background;
	delete linkTexture;
	delete renderer;
	IMG_Quit();
	SDL_Quit();
	return 0;
}
int main(int argc, char *argv[])
{
    std::vector<std::string> args;
    for(int i = 0; i < argc; i++)
        args.emplace_back(argv[i]);

    #ifdef __EMSCRIPTEN__
    args.emplace_back(PGE_RUN_SINGLE_LEVEL);
    #endif

    // Parse --version or --install low args
    if(!PGEEngineApp::parseLowArgs(args))
        return 0;

    // RAII for loaded/initialized libraries and modules
    PGEEngineApp  app;
    //Initialize Qt's subsystem
    AppPathManager::initAppPath();
    //Load settings
    app.loadSettings();
    //Init log writer
    app.loadLogger();
    //Initialize translation sub-system
    app.loadTr();
    // Parse high arguments
    app.parseHighArgs(args);

    // Initializing SDL
    if(app.initSDL())
    {
        //% "Unable to init SDL!"
        PGE_Window::printSDLError(qtTrId("SDL_INIT_ERROR"));
        pLogDebug("<Application closed with failure>");
        return 1;
    }

    if(g_flags.audioEnabled && app.initAudio(g_flags.audioEnabled))
    {
        std::string msg = "Unable to load audio sub-system!\n";
        msg += app.errorAudio();
        msg += "\n\nContinuing without sound...";
        pLogWarning(msg.c_str());
        SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING,
                                 "Audio subsystem Error",
                                 msg.c_str(),
                                 nullptr);
        g_flags.audioEnabled = false;
    }

    if(app.initWindow(INITIAL_WINDOW_TITLE, g_flags.rendererType))
    {
        pLogDebug("<Application closed with failure>");
        return 1;
    }

    app.loadJoysticks();
    SDL_PumpEvents();

    if(g_AppSettings.fullScreen)
        pLogDebug("Toggle fullscreen...");

    #ifdef __APPLE__
    macosReceiveOpenFile();
    #endif

    PGE_Window::setFullScreen(g_AppSettings.fullScreen);
    GlRenderer::resetViewport();
    //Init font manager
    app.initFontBasics();
    pLogDebug("Showing window...");
    SDL_ShowWindow(PGE_Window::window);
    pLogDebug("Clear screen...");
    GlRenderer::clearScreen();
    GlRenderer::flush();
    GlRenderer::repaint();
    SDL_PumpEvents();
    /************************************************
     *      Check & ask for configuration pack      *
     ************************************************/
    //Process config manager screen
    {
        // Create configs folder if not exists
        app.createConfigsDir();
        // Initialize config selection screen
        ConfigSelectScene GOScene;

        // Are any config packs exists?
        if(!GOScene.hasConfigPacks())
        {
            pLogCritical("Config packs not found");
            SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
                                     //% "Config packs not found"
                                     qtTrId("ERROR_NO_CONFIG_PACKS_TTL").c_str(),
                                     /*% "Can't start game, because available\n"
                                         "configuration packages are not found!" */
                                     qtTrId("ERROR_NO_CONFIG_PACKS_TEXT").c_str(),
                                     PGE_Window::window);
            return 2;
        }

        std::string configPath_manager = GOScene.isPreLoaded();

        if(!g_fileToOpen.empty())
        {
            //% "Choose a game to test:"
            GOScene.setLabel(qtTrId("CONFIG_SELECT_TEST"));
        }

        //If application have ran a first time or target configuration is not exist
        if(configPath_manager.empty() && g_configPackPath.empty())
        {
            //Ask for configuration
            if(GOScene.exec() == 1)
                g_configPackPath = GOScene.currentConfigPath;
            else
                return 2;
        }
        else if(!configPath_manager.empty() && g_configPackPath.empty())
            g_configPackPath = GOScene.currentConfigPath;

        pLogDebug("Opening of the configuration package...");
        ConfigManager::setConfigPath(g_configPackPath);

        pLogDebug("Initialization of basic properties...");

        if(!ConfigManager::loadBasics())
        {
            pLogDebug("<Application closed with failure>");
            return 1;
        }

        app.enableConfigManager();

        if(!ConfigManager::config_name.empty())
            PGE_Window::setWindowTitle(ConfigManager::config_name);

        pLogDebug("Current scene resolution: %d x %d", PGE_Window::Width, PGE_Window::Height);
        pLogDebug("Config pack scene resolution: %d x %d", ConfigManager::viewport_width, ConfigManager::viewport_height);

        if(ConfigManager::viewport_width != static_cast<unsigned int>(PGE_Window::Width) ||
           ConfigManager::viewport_height != static_cast<unsigned int>(PGE_Window::Height))
        {
            PGE_Window::changeViewportResolution(ConfigManager::viewport_width, ConfigManager::viewport_height);
            pLogDebug("Using scene resolution: %d x %d", ConfigManager::viewport_width, ConfigManager::viewport_height);
        }

        pLogDebug("Configuration package successfully loaded!");

        if(g_flags.audioEnabled)
        {
            PGE_MusPlayer::setVolume(g_AppSettings.volume_music);
            pLogDebug("Build SFX index cache...");
            ConfigManager::buildSoundIndex(); //Load all sound effects into memory
        }

        //Init font manager
        app.initFontFull();
    }

    if(!g_fileToOpen.empty())
    {
        g_GameState.reset();
        //Apply custom game parameters from command line
        g_flags.applyTestSettings(g_GameState);

        if(Files::hasSuffix(g_fileToOpen, ".lvl") || Files::hasSuffix(g_fileToOpen, ".lvlx"))
        {
            g_GameState.LevelFile = g_fileToOpen;
            g_GameState.isEpisode = false;
            g_GameState.isTestingModeL = true;
            g_GameState.isTestingModeW = false;
            g_flags.testLevel = true;
            g_flags.testWorld = false;
            goto PlayLevel;
        }
        else if(Files::hasSuffix(g_fileToOpen, ".wld") || Files::hasSuffix(g_fileToOpen, ".wldx"))
        {
            g_Episode.character = 1;
            g_Episode.savefile = "save1.savx";
            g_Episode.worldfile = g_fileToOpen;
            g_GameState._episodePath = DirMan(Files::dirname(g_fileToOpen)).absolutePath() + "/";
            g_GameState.saveFileName = g_Episode.savefile;
            g_GameState.isEpisode = true;
            g_GameState.WorldFile = g_fileToOpen;
            g_GameState.isTestingModeL = false;
            g_GameState.isTestingModeW = true;
            g_flags.testLevel = false;
            g_flags.testWorld = true;
            goto PlayWorldMap;
        }
    }

    if(g_AppSettings.interprocessing)
    {
        //Apply custom game parameters from command line
        g_flags.applyTestSettings(g_GameState);
        goto PlayLevel;
    }

LoadingScreen:
    {
        LoadingScene ttl;
        ttl.setWaitTime(15000);
        ttl.init();
        ttl.m_fader.setFade(10, 0.0, 0.01);
        int ret = ttl.exec();

        if(ttl.doShutDown())
            ret = -1;

        if(ret == -1)
            goto ExitFromApplication;

        goto MainMenu;
    }
CreditsScreen:
    {
        CreditsScene ttl;
        ttl.setWaitTime(30000);
        ttl.init();
        ttl.m_fader.setFade(10, 0.0, 0.01);
        int ret = ttl.exec();

        if(ttl.doShutDown())
            ret = -1;

        if(ret == -1) goto ExitFromApplication;

        if(g_flags.testWorld)
            goto ExitFromApplication;

        goto MainMenu;
    }
GameOverScreen:
    {
        GameOverScene GOScene;
        int result = GOScene.exec();

        if(result == GameOverSceneResult::CONTINUE)
        {
            if(g_GameState.isHubLevel)
                goto PlayLevel;
            else
                goto PlayWorldMap;
        }

        if(g_flags.testWorld)
            goto ExitFromApplication;

        goto MainMenu;
    }
MainMenu:
    {
        g_GameState.reset();
        std::shared_ptr<TitleScene> iScene(new TitleScene());
        iScene->init();
        iScene->m_fader.setFade(10, 0.0, 0.02);
        int answer = iScene->exec();
        PlayLevelResult   res_level   = iScene->m_result_level;
        PlayEpisodeResult res_episode = iScene->m_result_episode;

        if(iScene->doShutDown())
            answer = TitleScene::ANSWER_EXIT;

        switch(answer)
        {
        case TitleScene::ANSWER_EXIT:
            goto ExitFromApplication;

        case TitleScene::ANSWER_CREDITS:
            goto CreditsScreen;

        case TitleScene::ANSWER_LOADING:
            goto LoadingScreen;

        case TitleScene::ANSWER_GAMEOVER:
            goto GameOverScreen;

        case TitleScene::ANSWER_PLAYLEVEL:
        {
            g_jumpOnLevelEndTo = RETURN_TO_MAIN_MENU;
            g_GameState.isEpisode = false;
            g_GameState.numOfPlayers = 1;
            g_GameState.LevelFile = res_level.levelfile;
            g_GameState._episodePath.clear();
            g_GameState.saveFileName.clear();
            g_GameState.isTestingModeL = true;
            goto PlayLevel;
        }

        case TitleScene::ANSWER_PLAYEPISODE:
        case TitleScene::ANSWER_PLAYEPISODE_2P:
        {
            g_jumpOnLevelEndTo = RETURN_TO_WORLDMAP;
            g_GameState.numOfPlayers = (answer == TitleScene::ANSWER_PLAYEPISODE_2P) ? 2 : 1;
            PlayerState plr;
            plr._chsetup = FileFormats::CreateSavCharacterState();
            plr.characterID = 1;
            plr.stateID = 1;
            plr._chsetup.id = 1;
            plr._chsetup.state = 1;
            g_GameState.setPlayerState(1, plr);
            plr.characterID = 2;
            plr.stateID = 1;
            plr._chsetup.id = 2;
            plr._chsetup.state = 1;
            g_GameState.setPlayerState(2, plr);
            g_GameState.isEpisode = true;
            g_Episode = res_episode;
            g_GameState._episodePath = DirMan(Files::dirname(g_Episode.worldfile)).absolutePath() + "/";
            g_GameState.saveFileName = g_Episode.savefile;
            g_GameState.load();
            goto PlayWorldMap;
        }

        default:
            goto PlayWorldMap;
        }

        //goto PlayLevel;
    }
PlayWorldMap:
    {
        WldExit::ExitWorldCodes wldExitCode = WldExit::EXIT_close;
        std::shared_ptr<WorldScene> wScene;
        wScene.reset(new WorldScene());
        bool sceneResult = true;

        if(g_Episode.worldfile.empty())
        {
            sceneResult = false;
            //% "No opened files"
            PGE_MsgBox::warn(qtTrId("ERROR_NO_OPEN_FILES_MSG"));

            if(g_AppSettings.debugMode || g_flags.testWorld)
                goto ExitFromApplication;
            else
                goto MainMenu;
        }
        else
        {
            sceneResult = wScene->loadFile(g_Episode.worldfile);
            wScene->setGameState(&g_GameState); //Load game state to the world map

            if(!sceneResult)
            {
                //% "ERROR:\nFail to start world map\n\n%1"
                PGE_MsgBox::error( fmt::qformat(qtTrId("ERROR_FAIL_START_WLD"), wScene->getLastError()) );
                wldExitCode = WldExit::EXIT_error;
            }
        }

        if(sceneResult)
            sceneResult = wScene->init();

        if(sceneResult)
            wScene->m_fader.setFade(10, 0.0, 0.02);

        if(sceneResult)
            wldExitCode = (WldExit::ExitWorldCodes)wScene->exec();

        if(!sceneResult)
        {
            wldExitCode = WldExit::EXIT_error;
            //% "World map was closed with error.\n%1"
            PGE_MsgBox::error( fmt::qformat(qtTrId("WLD_ERROR_LVLCLOSED"), wScene->errorString()) );
        }

        g_GameState._recent_ExitCode_world = (int)wldExitCode;

        if(wScene->doShutDown())
        {
            wScene.reset();
            goto ExitFromApplication;
        }

        if(g_AppSettings.debugMode)
        {
            if(wldExitCode == WldExit::EXIT_beginLevel)
            {
                std::string msg;
                //% "Start level\n%1"
                msg += fmt::qformat(qtTrId("MSG_START_LEVEL"), g_GameState.LevelFile) + "\n\n";
                //% "Type an exit code (signed integer)"
                msg += qtTrId("MSG_WLDTEST_EXIT_CODE");
                PGE_TextInputBox text(nullptr, msg, PGE_BoxBase::msg_info_light,
                                      PGE_Point(-1, -1),
                                      ConfigManager::setup_message_box.box_padding,
                                      ConfigManager::setup_message_box.sprite);
                text.exec();
                g_GameState._recent_ExitCode_level  = LvlExit::EXIT_Neutral;

                if(PGEFile::IsIntS(text.inputText()))
                    g_GameState._recent_ExitCode_level = SDL_atoi(text.inputText().c_str());

                if(g_GameState.isHubLevel)
                    goto ExitFromApplication;

                goto PlayWorldMap;
            }
            else
                goto ExitFromApplication;
        }

        switch(wldExitCode)
        {
        case WldExit::EXIT_beginLevel:
            goto PlayLevel;

        case WldExit::EXIT_close:
            break;

        case WldExit::EXIT_error:
            break;

        case WldExit::EXIT_exitNoSave:
            break;

        case WldExit::EXIT_exitWithSave:
            break;

        default:
            break;
        }

        if(g_flags.testWorld)
            goto ExitFromApplication;

        goto MainMenu;
    }
PlayLevel:
    {
        bool playAgain = true;
        unsigned long entranceID = 0;
        std::shared_ptr<LevelScene> lScene(nullptr);

        while(playAgain)
        {
            entranceID = g_GameState.LevelTargetWarp;

            if(g_GameState.LevelFile_hub == g_GameState.LevelFile)
            {
                g_GameState.isHubLevel = true;
                entranceID = g_GameState.game_state.last_hub_warp;
            }

            int levelExitCode = 0;
            lScene.reset(new LevelScene());

            if(g_AppSettings.interprocessing)
                g_GameState.isTestingModeL = true;

            lScene->setGameState(&g_GameState);
            bool sceneResult = true;

            if(g_GameState.LevelFile.empty())
            {
                if(g_AppSettings.interprocessing && IntProc::isEnabled())
                {
                    sceneResult = lScene->loadFileIP();

                    if((!sceneResult) && (!lScene->isExiting()))
                    {
                        //SDL_Delay(50);
                        levelExitCode = LvlExit::EXIT_Error;
                        PGE_MsgBox msgBox(nullptr, fmt::format_ne("ERROR:\nFail to start level\n\n{0}",
                                                lScene->getLastError()),
                                                PGE_MsgBox::msg_error);
                        msgBox.exec();
                    }
                }
                else
                {
                    sceneResult = false;
                    levelExitCode = LvlExit::EXIT_Error;
                    //% "No opened files"
                    PGE_MsgBox::warn(qtTrId("ERROR_NO_OPEN_FILES_MSG"));
                }
            }
            else
            {
                sceneResult = lScene->loadFile(g_GameState.LevelFile);

                if(!sceneResult)
                {
                    SDL_Delay(50);
                    PGE_MsgBox msgBox(nullptr,
                                      fmt::format_ne("ERROR:\nFail to start level\n\n"
                                                     "{0}", lScene->getLastError()),
                                      PGE_MsgBox::msg_error);
                    msgBox.exec();
                }
            }

            if(sceneResult)
                sceneResult = lScene->setEntrance(entranceID);

            if(sceneResult)
                sceneResult = lScene->init();

            if(sceneResult)
            {
                lScene->m_fader.setFade(10, 0.0, 0.02);
                levelExitCode = lScene->exec();
                g_GameState._recent_ExitCode_level = levelExitCode;
            }

            if(!sceneResult)
                levelExitCode = LvlExit::EXIT_Error;

            switch(levelExitCode)
            {
            case LvlExit::EXIT_Warp:
            {
                if(lScene->m_warpToWorld)
                {
                    g_GameState.game_state.worldPosX = lScene->toWorldXY().x();
                    g_GameState.game_state.worldPosY = lScene->toWorldXY().y();
                    g_GameState.LevelFile.clear();
                    entranceID = 0;
                    g_jumpOnLevelEndTo = g_GameState.isEpisode ? RETURN_TO_WORLDMAP : RETURN_TO_MAIN_MENU;
                }
                else
                {
                    g_GameState.LevelFile = lScene->toAnotherLevel();
                    g_GameState.LevelTargetWarp = lScene->toAnotherEntrance();
                    entranceID = g_GameState.LevelTargetWarp;

                    if(g_GameState.isHubLevel)
                    {
                        g_GameState.isHubLevel = false;
                        g_GameState.game_state.last_hub_warp = lScene->m_lastWarpID;
                    }
                }

                if(g_GameState.LevelFile.empty())
                    playAgain = false;

                if(g_AppSettings.debugMode)
                {
                    std::string target;

                    if(lScene->m_warpToWorld)
                    {
                        target = fmt::format_ne("X={0}, Y={1}",
                                 g_GameState.game_state.worldPosX,
                                 g_GameState.game_state.worldPosY);
                    }
                    else
                        target = g_GameState.LevelFile;

                    if(!target.empty())
                    {
                        //% "Warp exit\n\nExit into:\n%1\n\nEntrance point: %2"
                        PGE_MsgBox::warn( fmt::qformat(qtTrId("LVL_EXIT_WARP_INFO"), target, entranceID) );
                    }

                    playAgain = false;
                }
            }
            break;

            case LvlExit::EXIT_Closed:
            {
                g_jumpOnLevelEndTo = RETURN_TO_EXIT;
                playAgain = false;
            }
            break;

            case LvlExit::EXIT_ReplayRequest:
            {
                playAgain = true;
            }
            break;

            case LvlExit::EXIT_MenuExit:
            {
                g_jumpOnLevelEndTo = g_GameState.isEpisode ? RETURN_TO_WORLDMAP : RETURN_TO_MAIN_MENU;

                if(g_GameState.isHubLevel)
                    g_jumpOnLevelEndTo = g_flags.testLevel ? RETURN_TO_EXIT : RETURN_TO_MAIN_MENU;

                playAgain = false;
            }
            break;

            case LvlExit::EXIT_PlayerDeath:
            {
                playAgain = g_GameState.isEpisode ? g_GameState.replay_on_fail : true;
                g_jumpOnLevelEndTo = g_GameState.isEpisode ? RETURN_TO_WORLDMAP : RETURN_TO_MAIN_MENU;

                //check the number of player lives here and decided to return worldmap or gameover
                if(g_GameState.isEpisode)
                {
                    g_GameState.game_state.lives--;

                    if(g_GameState.game_state.lives < 0)
                    {
                        playAgain = false;
                        g_GameState.game_state.coins = 0;
                        g_GameState.game_state.points = 0;
                        g_GameState.game_state.lives = 3;
                        g_jumpOnLevelEndTo = RETURN_TO_GAMEOVER_SCREEN;
                    }
                }
            }
            break;

            case LvlExit::EXIT_Error:
            {
                g_jumpOnLevelEndTo = (g_GameState.isEpisode) ? RETURN_TO_WORLDMAP : RETURN_TO_MAIN_MENU;
                playAgain = false;
                //% "Level was closed with error.\n%1"
                PGE_MsgBox::error( fmt::qformat(qtTrId("LVL_ERROR_LVLCLOSED"), lScene->errorString()) );
            }
            break;

            default:
                g_jumpOnLevelEndTo = g_GameState.isEpisode ? RETURN_TO_WORLDMAP : RETURN_TO_MAIN_MENU;
                playAgain = false;
            }

            if(g_flags.testLevel || g_AppSettings.debugMode)
                g_jumpOnLevelEndTo = RETURN_TO_EXIT;

            ConfigManager::unloadLevelConfigs();
            lScene.reset();
        }

        if(g_AppSettings.interprocessing)
            goto ExitFromApplication;

        switch(g_jumpOnLevelEndTo)
        {
        case RETURN_TO_WORLDMAP:
            goto PlayWorldMap;

        case RETURN_TO_MAIN_MENU:
            goto MainMenu;

        case RETURN_TO_EXIT:
            goto ExitFromApplication;

        case RETURN_TO_GAMEOVER_SCREEN:
            goto GameOverScreen;

        case RETURN_TO_CREDITS_SCREEN:
            goto CreditsScreen;
        }
    }
ExitFromApplication:
    return 0;
}
Exemple #23
0
int main(int argc, char* args[])
{
	srand(time(NULL));
	Graphics grafika; //создаём экземпляр класса, отвечающего за инициализацию СДЛ
	grafika.instal_sdl(); //инициализируем СДЛ
	 
	hero Hero(10, 5, 90, IMG_LoadTexture(ren, "image/battlecity_playerA1.png"), tank_H, tank_W, 90, 100); //создаём персонажа, конструктор вида  (health, speed,anlge, texture, heigh, weight, x,y)

	int number = 4; //число танков противника

	//инициализируем БГ
	SDL_Texture *backgroundT = IMG_LoadTexture(ren, "image/background.png");
	SDL_Rect background;
	background.x = 0;   //Смещение полотна по Х
	background.y = 0;   //Смещение полотна по Y
	background.w = X_disp; //Ширина полотна
	background.h = Y_disp; //Высота полотна
	SDL_RenderClear(ren); //Очистка рендера
	SDL_RenderCopy(ren, backgroundT, NULL, &background); //отправляем в буффер
	//

	SDL_RenderPresent(ren);

	t.push_back(&Hero); //добавляем героя
	
	int j; 
	for (j=0; j<number; j++) //создаём и добавляем в лист танков противников, тестовая версия с рандомными координатами, конструктор такой же
		t.push_back(new bottanks(10, 20, (rand() % 4)*90, IMG_LoadTexture(ren,"image/battlecity_enemy1.png"), tank_H, tank_W, rand() % 500+100, rand() % 200+100));

	for (j=0; j<5; j++) //создаём и добавляем текстуры
		tex.push_back(new StaticTextures(13, IMG_LoadTexture(ren,"image/block_9.png"), text_H,text_W, rand() % 500+100, rand() % 200+100));

	//создаём объекты для обработки событий
	const Uint8 *keyboardState = SDL_GetKeyboardState(NULL);
	SDL_Event event;
	bool quit = false;
	//


	while(!quit) //бесконечный цикл обработки событий
	{
		SDL_RenderClear(ren); //очищаем буфер
		SDL_RenderCopy(ren, backgroundT, NULL, &background); //отправляем фон

		//захват и сдвиг очериди событий
		SDL_PollEvent(&event); 
		SDL_PumpEvents(); 
		//

		//player 
		if(event.type == SDL_QUIT) 
			exit(-1); 
		//считываем клавиатуру и подаем команду танку игрока
		// добавил else, чтобы не ездили по диагонале 
		if((keyboardState[SDL_SCANCODE_UP]))   
			Hero.moveTo('u');		
		else
			if((keyboardState[SDL_SCANCODE_DOWN]))
				Hero.moveTo('d');
			else
				if((keyboardState[SDL_SCANCODE_LEFT]))
					Hero.moveTo('l');
				else
					if((keyboardState[SDL_SCANCODE_RIGHT]))
						Hero.moveTo('r');

		if((keyboardState[SDL_SCANCODE_SPACE]))
			Hero.moveTo('f');
		//
		///

		//пробегаем по списку танков, куда входит и герой. У разных классов своя функция  draw 
		list<tanks*>::iterator k;
		for(list<tanks*>::iterator i=t.begin(); i!=t.end(); i++)
		{
			(*i)->Draw();
			if((*i)->am_i_dead())  // проверка на смерть танка
			{ 
				k=i;  
				k++;
				t.erase(i);
				i=k;
				i--;
			}
		}
		//пробегаем по текстурам
		list<StaticTextures*>::iterator m;
		for(list<StaticTextures*>::iterator i=tex.begin(); i!=tex.end(); i++)
		{
			(*i)->Draw();
			if((*i)->am_i_dead())  // проверка на удаление текстуры
			{ 
				m=i;  
				m++;
				tex.erase(i);
				i=m;
				i--;
			}
		}
		//
		//пробегаем по всем пулям
		list<bullets*>::iterator j;
		for(list<bullets*>::iterator i=b.begin(); i!=b.end(); i++)
		{

			(*i)->Draw(); //функция отрисовки (сичтает смещение и подаёт в буфер)
			if((*i)->dead_check() || (*i)->strike())  // проверка на вылет за экран и на попадание в объект(пока что танки)
			{ 
				j=i;  
				j++;
				b.erase(i);
				i=j;
				i--;
			}			 
		}
		//
		Sleep(100); //спим
		SDL_RenderPresent(ren); //вывод на экран
	}
	SDL_RenderClear(ren); //Очистка рендера

	// завершение работы
	t.clear();
	b.clear();
	tex.clear();
	SDL_DestroyRenderer(ren);
	SDL_DestroyWindow(grafika.win);
	SDL_Quit();

	return 0;
}
Exemple #24
0
int main(int argc, char *argv[]) {
   seed();
   // extern bool pause;

   SDL_Init(SDL_INIT_EVERYTHING);
   IMG_Init(IMG_INIT_PNG);
   TTF_Init();
   audio_engine::init();

   SDL_LogSetAllPriority(SDL_LOG_PRIORITY_WARN);
   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

   SDL_SetHint("SDL_HINT_ORIENTATIONS", "LandscapeRight");
   SDL_DisplayMode mode;
   SDL_GetDisplayMode(0, 0, &mode);

   int scale_factor = 1;
#if MOBILE
   SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
   SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
   SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
   pool::get().screen = vec2(mode.w, mode.h);
   // sw = mode.w;
   // sh = mode.h;
   cout << pool::get().screen.x << " sdf  " << pool::get().screen.y << endl;
   SDL_Window *window =
      SDL_CreateWindow(NULL, 0, 0, pool::get().screen.w, pool::get().screen.h,
                       SDL_WINDOW_OPENGL | SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALLOW_HIGHDPI);
   // sw *= 2;
   // sh *= 2;
   SDL_Joystick *accelerometer = SDL_JoystickOpen(0);
#elif __WINDOWS__
   pool::get().screen = vec2(1136, 640);
   SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
   SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
   // don't think about high dpi monitors on windows for now
   SDL_Window *window =
      SDL_CreateWindow(NULL, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, pool::get().screen.w,
                       pool::get().screen.h, SDL_WINDOW_OPENGL);

#elif __MACOSX__
   pool::get().screen = vec2(1136 * 1.5, 640 * 1.5);
   
   SDL_Window *window = SDL_CreateWindow(NULL, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                                         pool::get().screen.w / 2, pool::get().screen.h / 2,
                                         SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI);
   scale_factor = 2;
   #endif

   SDL_GLContext context = SDL_GL_CreateContext(window);
   if (!context) cout << "Couldn't create context: " << SDL_GetError() << endl;

#if __WINDOWS__
   // Initialize GLEW
   glewExperimental = GL_TRUE;
   GLenum glewError = glewInit();
   if (glewError != GLEW_OK) {
      printf("Error initializing GLEW! %s\n", glewGetErrorString(glewError));
   }
#endif

   SDL_GL_SetSwapInterval(1);
   SDL_Event event;
   int sw, sh;
   SDL_GL_GetDrawableSize(window, &sw, &sh);
   cout << "DRAWABLE SIZE: width: " << sw << "   height: " << sh
        << endl;

   // glClearColor(0.1, 0.3, 0.8, 1.0);
   glClearColor(0.1, 0.1, 0.18, 0.0);
   // glEnable(GL_CULL_FACE);
   glEnable(GL_BLEND);
   // glEnable(GL_DEPTH_TEST);
   // glEnable(GL_ALPHA_TEST);
   glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
   glViewport(0, 0, pool::get().screen.w, pool::get().screen.h);

   load_at_start(); // load the spritesheets required throught the game

   world *w;
   game_state game;	

   //game.set_next(GS_TITLE);
   game.set_next(GS_RUN);
   w = game.switch_state();

#if PC
   w->keys = SDL_GetKeyboardState(NULL);
#endif

   glClear(GL_COLOR_BUFFER_BIT);
   while (true) {
      renderer::frames++;
      Uint32 frame_time;
      Uint32 start_time;
      Uint32 end_time;
      
      SDL_PumpEvents();
      while (SDL_PollEvent(&event)) {
#if MOBILE
         if (event.type == SDL_FINGERDOWN) {
            w->touch_down(touchFromtfinger(event.tfinger));
         }
         if (event.type == SDL_FINGERUP) {
            w->touch_up(touchFromtfinger(event.tfinger));
         }
         if (event.type == SDL_FINGERMOTION) {
            w->touch_moved(touchFromtfinger(event.tfinger));
         }
#endif

#if PC
         if (event.type == SDL_MOUSEBUTTONUP) {
            int x, y;
            SDL_GetMouseState(&x, &y);
            x = x * scale_factor;
            y = (pool::get().screen.h / 2 - y) * scale_factor;
            
            touch t;
            t.pos = vec2(x, y);
            w->touch_up(t);
         }
         if (event.type == SDL_MOUSEBUTTONDOWN) {
            int x, y;
            SDL_GetMouseState(&x, &y);
            x = x * 2;
            y = (pool::get().screen.h / 2 - y) * scale_factor;
            // SDL_GetMouseState(&x, &y);
            touch t;
            t.pos = vec2(x, y);
            w->touch_down(t);
         }
         if (event.type == SDL_MOUSEMOTION) {
            int x, y;
            SDL_GetMouseState(&x, &y);
            x = x * scale_factor;
            y = (pool::get().screen.h / 2 - y) * scale_factor;
            touch t;
            t.pos = vec2(x, y);
            w->touch_moved(t);
         }
         if (event.type == SDL_KEYDOWN) {
            const Uint8 *state = SDL_GetKeyboardState(NULL);
            if (state[SDL_SCANCODE_P]) {
               cout << "Pause status1:efdff " << pause::value << endl;
               pause::toggle();
               // game.set_next(GS_PAUSE);
               cout << "Pause status1:efdff " << pause::value << endl;
            }
         }
#endif
         if (event.type == SDL_QUIT) goto quit;
      }

#if MOBILE
      SDL_TouchID tId = SDL_GetTouchDevice(0);
      int numTouches = SDL_GetNumTouchFingers(tId);
      w->touches.clear();
      for (int i = 0; i < numTouches; i++) {
         SDL_Finger *finger = SDL_GetTouchFinger(tId, i);
         touch t;
         t.pos = vec2(finger->x * pool::get().screen.w, (1 - finger->y) * pool::get().screen.h);
         w->touches.push_back(t);
      }
#endif
#if __IPHONEOS__
      float ax = SDL_JoystickGetAxis(accelerometer, 0);
      float ay = SDL_JoystickGetAxis(accelerometer, 1);
      float az = SDL_JoystickGetAxis(accelerometer, 2);
      float k = 0x7FFF;
      ax *= SDL_IPHONE_MAX_GFORCE / k;
      ay *= SDL_IPHONE_MAX_GFORCE / k;
      az *= SDL_IPHONE_MAX_GFORCE / k;
      w->accel_update(vec3(ax, ay, az));
#endif


// cout << "Pause status1:efdff " << pause << endl;
#if PC
      //if (!pause::value) {
         w->keyboard_update(w->keys);
      //}
#endif


      start_time = SDL_GetTicks();
      //if (!pause::value) {
         w->update();
         w->process_entities();
      //}
		 
		 if (pause::value) {
			 vec2 screen = pool::get().screen;
			 vec2 max_scale = screen / vec2(100.0f, 100.0f);

			 int x_center = pool::get().screen.x / 2;
			 int y_center = pool::get().screen.y / 2;
			 pool::get().draw("tap.png").pos(vec2(x_center, y_center)).scale(max_scale).cam(nullptr).alpha(pause::alpha);
			 pool::get().draw("pause.png").pos(vec2(x_center, y_center)).cam(nullptr);
		 }
		 if (pause::unpausing) {
			 cout << "unpausing " << pause::alpha << endl;
			 if (pause::alpha >= 1.0f)
			 {
				 pause::value = false;
				 pause::unpausing = false;
				 pause::alpha = 0.4f;
			 }
			 else
			 {
				 pause::alpha = pause::alpha+0.1f;
			 }
		 }

      end_time = SDL_GetTicks();
      frame_time = end_time - start_time;
      w->frame_time = frame_time;

      SDL_GL_SwapWindow(window);
      glClear(GL_COLOR_BUFFER_BIT);
      // glAlphaFunc(GL_GREATER, 0);

      if (tutorial_state::tutorial_level == 2) {
         game.set_next(GS_TUTORIAL2);
      } else if (tutorial_state::tutorial_level == 3) {
         game.set_next(GS_TUTORIAL3);
      } else if (tutorial_state::tutorial_level == 4) {
         tutorial_state::tutorial_level = 1;
         game.set_next(GS_RUN);
      }

      if (game.update(w)) {
         w = game.switch_state();
      }
   }
quit:
   io::save_settings();
   audio_engine::close();
   SDL_Quit();
   IMG_Quit();
   TTF_Quit();
   return 0;
}
/* w, h is layer resolution */
int plat_sdl_change_video_mode(int w, int h, int force)
{
  static int prev_w, prev_h;

  if (w == 0)
    w = prev_w;
  else
    prev_w = w;
  if (h == 0)
    h = prev_h;
  else
    prev_h = h;
plat_target.vout_method=vout_mode_overlay;
  // invalid method might come from config..
  if (plat_target.vout_method != 0
      && plat_target.vout_method != vout_mode_overlay
      && plat_target.vout_method != vout_mode_gl)
  {
    fprintf(stderr, "invalid vout_method: %d\n", plat_target.vout_method);
    plat_target.vout_method = 0;
  }

  // skip GL recreation if window doesn't change - avoids flicker
  if (plat_target.vout_method == vout_mode_gl && plat_sdl_gl_active
      && plat_target.vout_fullscreen == old_fullscreen && !force)
  {
    return 0;
  }

  if (plat_sdl_overlay != NULL) {
    SDL_FreeYUVOverlay(plat_sdl_overlay);
    plat_sdl_overlay = NULL;
  }
  if (plat_sdl_gl_active) {
    gl_finish();
    plat_sdl_gl_active = 0;
  }

  if (plat_target.vout_method != 0) {
    Uint32 flags = SDL_RESIZABLE | SDL_SWSURFACE;
    int win_w = window_w;
    int win_h = window_h;

    if (plat_target.vout_fullscreen) {
      flags |= SDL_FULLSCREEN;
      win_w = fs_w;
      win_h = fs_h;
    }

    // XXX: workaround some occasional mysterious deadlock in SDL_SetVideoMode
    // (seen on r-pi)
    SDL_PumpEvents();

unsigned int user_width = 0;
sscanf(getenv("PCSX_WIDTH"), "%d", &user_width);
if(user_width == 0)
	user_width=win_h;
    plat_sdl_screen = SDL_SetVideoMode(/*win_w*/ /*win_h*4/3*/ /*640*/ user_width*4/3, /*win_h*/ /*512*/ user_width, 0, flags);
    if (plat_sdl_screen == NULL) {
      fprintf(stderr, "SDL_SetVideoMode failed: %s\n", SDL_GetError());
      plat_target.vout_method = 0;
    }
  }

  if (plat_target.vout_method == vout_mode_overlay) {
    plat_sdl_overlay = SDL_CreateYUVOverlay(w, h, SDL_UYVY_OVERLAY, plat_sdl_screen);
    if (plat_sdl_overlay != NULL) {
      if ((long)plat_sdl_overlay->pixels[0] & 3)
        fprintf(stderr, "warning: overlay pointer is unaligned\n");

      plat_sdl_overlay_clear();
    }
    else {
      fprintf(stderr, "warning: could not create overlay.\n");
      plat_target.vout_method = 0;
    }
  }
  else if (plat_target.vout_method == vout_mode_gl) {
    plat_sdl_gl_active = (gl_init(display, window, &gl_quirks) == 0);
    if (!plat_sdl_gl_active) {
      fprintf(stderr, "warning: could not init GL.\n");
      plat_target.vout_method = 0;
    }
  }

  if (plat_target.vout_method == 0) {
    SDL_PumpEvents();

    plat_sdl_screen = SDL_SetVideoMode(w, h, 16, SDL_SWSURFACE);
    if (plat_sdl_screen == NULL) {
      fprintf(stderr, "SDL_SetVideoMode failed: %s\n", SDL_GetError());
      return -1;
    }
  }

  old_fullscreen = plat_target.vout_fullscreen;
  if (plat_sdl_resize_cb != NULL)
    plat_sdl_resize_cb(plat_sdl_screen->w, plat_sdl_screen->h);

  return 0;
}
Exemple #26
0
int PollEvent (SDL_Event *event, unsigned long mask)
{
	SDL_PumpEvents();
	/* We can't return -1, just return 0 (no event) on error */
	return (SDL_PeepEvents(event, 1, SDL_GETEVENT, mask) > 0);
}
Exemple #27
0
void gen_interupt()
{

    if(!__emulation_run)
      stop = 1;
      
    if (stop == 1)
    {
        vi_counter = 0; // debug
        dyna_stop();
    }
    if (savestates_job & LOADSTATE) 
    {
        savestates_load();
        savestates_job &= ~LOADSTATE;
        return;
    }
   
    if (skip_jump)
    {
        if (q->count > Count || (Count - q->count) < 0x80000000)
            next_interupt = q->count;
        else
            next_interupt = 0;
        if (interpcore)
        {
             interp_addr = skip_jump;
             last_addr = interp_addr;
        }
        else
        {
            unsigned int dest = skip_jump;
            skip_jump=0;
            jump_to(dest);
            last_addr = PC->addr;
        }
        skip_jump=0;
        return;
    } 

    switch(q->type)
    {
        case SPECIAL_INT:
            if (Count > 0x10000000) return;
            remove_interupt_event();
            add_interupt_event_count(SPECIAL_INT, 0);
            return;
            break;
        case VI_INT:
            if(vi_counter < 60)
            {
                if (vi_counter == 0)
                    cheat_apply_cheats(ENTRY_BOOT);
                vi_counter++;
            }
            else
            {
                cheat_apply_cheats(ENTRY_VI);
            }
            updateScreen();
#ifdef WITH_LIRC
            lircCheckInput();
#endif
            SDL_PumpEvents();
            refresh_stat();

            // if paused, poll for input events
            if(rompause)
            {
                osd_render();  // draw Paused message in case updateScreen didn't do it
                SDL_GL_SwapBuffers();
                while(rompause)
                {
#ifdef __WIN32__
                    Sleep(10);
#else
                    struct timespec ts;
                    ts.tv_sec = 0;
                    ts.tv_nsec = 10000000;
                    nanosleep(&ts, NULL); // sleep for 10 milliseconds
#endif
                    SDL_PumpEvents();
#ifdef WITH_LIRC
                    lircCheckInput();
#endif //WITH_LIRC
                }
            }

            new_vi();
            if (vi_register.vi_v_sync == 0) vi_register.vi_delay = 500000;
            else vi_register.vi_delay = ((vi_register.vi_v_sync + 1)*1500);
            next_vi += vi_register.vi_delay;
            if (vi_register.vi_status&0x40) vi_field=1-vi_field;
            else vi_field=0;

            remove_interupt_event();
            add_interupt_event_count(VI_INT, next_vi);
    
            MI_register.mi_intr_reg |= 0x08;
            if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                Cause = (Cause | 0x400) & 0xFFFFFF83;
            else
                return;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;
    
        case COMPARE_INT:
            remove_interupt_event();
            Count+=2;
            add_interupt_event_count(COMPARE_INT, Compare);
            Count-=2;
    
            Cause = (Cause | 0x8000) & 0xFFFFFF83;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;
    
        case CHECK_INT:
            remove_interupt_event();
            break;
    
        case SI_INT:
#ifdef WITH_LIRC
            lircCheckInput();
#endif //WITH_LIRC
            SDL_PumpEvents();
            PIF_RAMb[0x3F] = 0x0;
            remove_interupt_event();
            MI_register.mi_intr_reg |= 0x02;
            si_register.si_stat |= 0x1000;
            if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                Cause = (Cause | 0x400) & 0xFFFFFF83;
            else
                return;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;
    
        case PI_INT:
            remove_interupt_event();
            MI_register.mi_intr_reg |= 0x10;
            pi_register.read_pi_status_reg &= ~3;
            if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                Cause = (Cause | 0x400) & 0xFFFFFF83;
            else
                return;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;
    
        case AI_INT:
            if (ai_register.ai_status & 0x80000000) // full
            {
                unsigned int ai_event = get_event(AI_INT);
                remove_interupt_event();
                ai_register.ai_status &= ~0x80000000;
                ai_register.current_delay = ai_register.next_delay;
                ai_register.current_len = ai_register.next_len;
                add_interupt_event_count(AI_INT, ai_event+ai_register.next_delay);
         
                MI_register.mi_intr_reg |= 0x04;
                if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                    Cause = (Cause | 0x400) & 0xFFFFFF83;
                else
                    return;
                if ((Status & 7) != 1) return;
                if (!(Status & Cause & 0xFF00)) return;
            }
            else
            {
                remove_interupt_event();
                ai_register.ai_status &= ~0x40000000;

                //-------
                MI_register.mi_intr_reg |= 0x04;
                if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                    Cause = (Cause | 0x400) & 0xFFFFFF83;
                else
                    return;
                if ((Status & 7) != 1) return;
                if (!(Status & Cause & 0xFF00)) return;
            }
            break;

        case SP_INT:
            remove_interupt_event();
            sp_register.sp_status_reg |= 0x303;
            //sp_register.signal1 = 1;
            sp_register.signal2 = 1;
            sp_register.broke = 1;
            sp_register.halt = 1;
    
            if (!sp_register.intr_break) return;
            MI_register.mi_intr_reg |= 0x01;
            if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                Cause = (Cause | 0x400) & 0xFFFFFF83;
            else
                return;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;
    
        case DP_INT:
            remove_interupt_event();
            dpc_register.dpc_status &= ~2;
            dpc_register.dpc_status |= 0x81;
            MI_register.mi_intr_reg |= 0x20;
            if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                Cause = (Cause | 0x400) & 0xFFFFFF83;
            else
                return;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;

        case HW2_INT:
            // Hardware Interrupt 2 -- remove interrupt event from queue
            remove_interupt_event();
            // setup r4300 Status flags: reset TS, and SR, set IM2
            Status = (Status & ~0x00380000) | 0x1000;
            Cause = (Cause | 0x1000) & 0xFFFFFF83;
            /* the exception_general() call below will jump to the interrupt vector (0x80000180) and setup the
             * interpreter or dynarec
             */
            break;

        case NMI_INT:
            // Non Maskable Interrupt -- remove interrupt event from queue
            remove_interupt_event();
            // setup r4300 Status flags: reset TS and SR, set BEV, ERL, and SR
            Status = (Status & ~0x00380000) | 0x00500004;
            Cause  = 0x00000000;
            // simulate the soft reset code which would run from the PIF ROM
            r4300_reset_soft();
            // clear all interrupts, reset interrupt counters back to 0
            Count = 0;
            vi_counter = 0;
            init_interupt();
            // clear the audio status register so that subsequent write_ai() calls will work properly
            ai_register.ai_status = 0;
            // reset the r4300 internal state
            if (interpcore) /* pure interpreter only */
            {
                // set ErrorEPC with last instruction address and set next instruction address to reset vector
                ErrorEPC = interp_addr;
                interp_addr = 0xa4000040;
                last_addr = interp_addr;
            }
            else  /* decode-cached interpreter or dynamic recompiler */
            {
                int i;
                // clear all the compiled instruction blocks
                for (i=0; i<0x100000; i++)
                {
                    if (blocks[i])
                    {
                        if (blocks[i]->block) { free(blocks[i]->block); blocks[i]->block = NULL; }
                        if (blocks[i]->code) { free(blocks[i]->code); blocks[i]->code = NULL; }
                        if (blocks[i]->jumps_table) { free(blocks[i]->jumps_table); blocks[i]->jumps_table = NULL; }
                        if (blocks[i]->riprel_table) { free(blocks[i]->riprel_table); blocks[i]->riprel_table = NULL; }
                        free(blocks[i]);
                        blocks[i] = NULL;
                    }
                }
                // re-initialize
                init_blocks();
                // jump to the start
                ErrorEPC = PC->addr;
                jump_to(0xa4000040);
                last_addr = PC->addr;
            }
            // adjust ErrorEPC if we were in a delay slot, and clear the delay_slot and dyna_interp flags
            if(delay_slot==1 || delay_slot==3)
            {
                ErrorEPC-=4;
            }
            delay_slot = 0;
            dyna_interp = 0;
            return;

        default:
            remove_interupt_event();
            break;
    }

#ifdef NEW_DYNAREC
    EPC = pcaddr;
    pcaddr = 0x80000180;
    Status |= 2;
    Cause &= 0x7FFFFFFF;
    pending_exception=1;
#else
    exception_general();
#endif

    if (savestates_job & SAVESTATE) 
    {
        savestates_save();
        savestates_job &= ~SAVESTATE;
    }
}
Exemple #28
0
int 
main(int argc, char **argv)
{
    s32 result;
    result = SDL_Init(SDL_INIT_VIDEO);
    if(result)
    { ross_log("Failed to init SDL", LOG_ERROR); return(-1); }

    WindowDimension window_dimension;
    window_dimension.width = 800;
    window_dimension.height = 600;

    SDL_Window *window = SDL_CreateWindow("rossie",
            SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
            window_dimension.width, window_dimension.height,
            SDL_WINDOW_OPENGL | SDL_WINDOW_MAXIMIZED);
    if(window)
    { 

        SDL_GLContext context = SDL_GL_CreateContext(window);
        if(context)
        {

            if(glewInit() == GLEW_OK)
            {

                global_running = 1;

                GLuint shader_program = compile_shaders();
                ProgramBuffers program_buffers = setup_buffers();

                glEnableClientState(GL_VERTEX_ARRAY);
                glViewport(0, 0, window_dimension.width, window_dimension.height);

                Input last_input = {};
                while(global_running)
                {
                    SDL_PumpEvents();
                    Input new_input;
                    new_input = get_frame_input();

                    manage_events(new_input, window);

                    render(new_input, last_input, shader_program, program_buffers);

                    SDL_GL_SwapWindow(window);
                    last_input = new_input;
                }
            }
            else
            {
                ross_log("Failed to init glew", LOG_ERROR);
            }
            SDL_GL_DeleteContext(context);
        }
        else
        {
            ross_log("Failed to create SDL GL context", LOG_ERROR); 
        }
    }
    else
    {
        ross_log("Failed to create window", LOG_ERROR); 
    }

    SDL_DestroyWindow(window);
    SDL_Quit();
    return(0);
}
Exemple #29
0
int Core::ProcessSDLEvents() {
    SDL_Event eve;

	// まずマウス関係のイベントを処理する(なぜかPollEventでこない)
	SDL_PumpEvents();
	int mouseX, mouseY;
	SDL_GetMouseState(&mouseX, &mouseY);
	mouseBuffer.SetPosition((0.5 - (float)mouseX / width) * 2.0, (0.5 - (float)mouseY / height) * 2.0);

	keyBuffer.Clear();
    while (SDL_PollEvent(&eve)) {
        switch(eve.type) {
		case SDL_KEYDOWN:
			{
			Uint16 ch = eve.key.keysym.unicode;
			SDLKey key = isprint(ch) ? (SDLKey)ch : eve.key.keysym.sym;

			if (editMode)
				keyAnalyzer.KeyHit(&textEditor, key, eve.key.keysym.mod, EffectFileTable[nowEffect]);
			if (eve.key.keysym.sym == SDLK_ESCAPE)
				return -1;

			int ctrl = eve.key.keysym.mod & KMOD_CTRL;
			int alt = eve.key.keysym.mod & KMOD_ALT;

			if (SDLK_F1 <= eve.key.keysym.sym && eve.key.keysym.sym <= SDLK_F12 && eve.key.keysym.sym != SDLK_F11) {
				nowEffect = eve.key.keysym.sym - SDLK_F1;
				if (alt)
					nowEffect += 12;
				else if (ctrl)
					nowEffect += 24;

				shaderGL[nowEffect].CompileFromFile(EffectFileTable[nowEffect]);
				textEditor.Load(EffectFileTable[nowEffect]);
			}

			if (eve.key.keysym.sym == SDLK_F11) {
				if (editMode)
					editMode = false;
				else
					editMode = true;
			}

			if (eve.key.keysym.mod & KMOD_CTRL && eve.key.keysym.sym == SDLK_TAB) {
				errorHighlight = !errorHighlight;
			}
			if (eve.key.keysym.mod & KMOD_CTRL && eve.key.keysym.sym == SDLK_SPACE) {
				static bool cursor = true;
				cursor = !cursor;
				SDL_ShowCursor(cursor);
			}

			}
			break;

        case SDL_QUIT:
            return -1;
        }

    }

	return 0;
}
Exemple #30
0
void gen_interupt()
{
   //if (!skip_jump)
     //printf("interrupt:%x (%x)\n", q->type, Count);
   if (stop == 1) dyna_stop();
   if (savestates_job & LOADSTATE) 
     {
	savestates_load();
	savestates_job &= ~LOADSTATE;
	return;
     }
   
   if (skip_jump /*&& !dynacore*/)
     {
	if (q->count > Count || (Count - q->count) < 0x80000000)
	  next_interupt = q->count;
	else
	  next_interupt = 0;
	if (interpcore)
	  {
	     /*if ((Cause & (2 << 2)) && (Cause & 0x80000000))
	       interp_addr = skip_jump+4;
	     else*/
	       interp_addr = skip_jump;
	     last_addr = interp_addr;
	  }
	else
	  {
	     /*if ((Cause & (2 << 2)) && (Cause & 0x80000000))
	       jump_to(skip_jump+4);
	     else*/
	     unsigned long dest = skip_jump;
	     skip_jump=0;
	     jump_to(dest);
	     last_addr = PC->addr;
	  }
	skip_jump=0;
	return;
     } 
   
   switch(q->type)
     {
      case SPECIAL_INT:
	if (Count > 0x10000000) return;
	remove_interupt_event();
	add_interupt_event_count(SPECIAL_INT, 0);
	return;
	break;
	
      case VI_INT:
#ifdef VCR_SUPPORT
	VCR_updateScreen();
#else
	updateScreen();
#endif
#ifndef __WIN32__
	SDL_PumpEvents();
	refresh_stat();
#endif
	new_vi();
	if (vi_register.vi_v_sync == 0) vi_register.vi_delay = 500000;
	else vi_register.vi_delay = ((vi_register.vi_v_sync + 1)*1500);
	next_vi += vi_register.vi_delay;
	if (vi_register.vi_status&0x40) vi_field=1-vi_field;
	else vi_field=0;
	
	remove_interupt_event();
	add_interupt_event_count(VI_INT, next_vi);
	
	MI_register.mi_intr_reg |= 0x08;
	if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
	  Cause = (Cause | 0x400) & 0xFFFFFF83;
	else
	  return;
	if ((Status & 7) != 1) return;
	if (!(Status & Cause & 0xFF00)) return;
	break;
	
      case COMPARE_INT:
	remove_interupt_event();
	Count+=2;
	add_interupt_event_count(COMPARE_INT, Compare);
	Count-=2;
	
	Cause = (Cause | 0x8000) & 0xFFFFFF83;
	if ((Status & 7) != 1) return;
	if (!(Status & Cause & 0xFF00)) return;
	break;
	
      case CHECK_INT:
	remove_interupt_event();
	break;
	
      case SI_INT:
#ifndef __WIN32__
	SDL_PumpEvents();
#endif
	PIF_RAMb[0x3F] = 0x0;
	remove_interupt_event();
	MI_register.mi_intr_reg |= 0x02;
	si_register.si_status |= 0x1000;
	if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
	  Cause = (Cause | 0x400) & 0xFFFFFF83;
	else
	  return;
	if ((Status & 7) != 1) return;
	if (!(Status & Cause & 0xFF00)) return;
	break;
	
      case PI_INT:
	remove_interupt_event();
	MI_register.mi_intr_reg |= 0x10;
	pi_register.read_pi_status_reg &= ~3;
	if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
	  Cause = (Cause | 0x400) & 0xFFFFFF83;
	else
	  return;
	if ((Status & 7) != 1) return;
	if (!(Status & Cause & 0xFF00)) return;
	break;
	
      case AI_INT:
	if (ai_register.ai_status & 0x80000000) // full
	  {
	     unsigned long ai_event = get_event(AI_INT);
	     remove_interupt_event();
	     ai_register.ai_status &= ~0x80000000;
	     ai_register.current_delay = ai_register.next_delay;
	     ai_register.current_len = ai_register.next_len;
	     //add_interupt_event(AI_INT, ai_register.next_delay/**2*/);
	     add_interupt_event_count(AI_INT, ai_event+ai_register.next_delay);
	     
	     MI_register.mi_intr_reg |= 0x04;
	     if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
	       Cause = (Cause | 0x400) & 0xFFFFFF83;
	     else
	       return;
	     if ((Status & 7) != 1) return;
	     if (!(Status & Cause & 0xFF00)) return;
	  }
	else
	  {
	     remove_interupt_event();
	     ai_register.ai_status &= ~0x40000000;

	     //-------
	     MI_register.mi_intr_reg |= 0x04;
	      if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
	      Cause = (Cause | 0x400) & 0xFFFFFF83;
	      else
	      return;
	      if ((Status & 7) != 1) return;
	      if (!(Status & Cause & 0xFF00)) return;
	     //return;
	  }
	break;
	
      case SP_INT:
	remove_interupt_event();
	sp_register.sp_status_reg |= 0x303;
	//sp_register.signal1 = 1;
	sp_register.signal2 = 1;
	sp_register.broke = 1;
	sp_register.halt = 1;
	
	if (!sp_register.intr_break) return;
	MI_register.mi_intr_reg |= 0x01;
	if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
	  Cause = (Cause | 0x400) & 0xFFFFFF83;
	else
	  return;
	if ((Status & 7) != 1) return;
	if (!(Status & Cause & 0xFF00)) return;
	break;
	
      case DP_INT:
	remove_interupt_event();
	dpc_register.dpc_status &= ~2;
	dpc_register.dpc_status |= 0x81;
	MI_register.mi_intr_reg |= 0x20;
	if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
	  Cause = (Cause | 0x400) & 0xFFFFFF83;
	else
	  return;
	if ((Status & 7) != 1) return;
	if (!(Status & Cause & 0xFF00)) return;
	break;
	
      default:
	remove_interupt_event();
	break;
     }
   exception_general();
   if (savestates_job & SAVESTATE) 
     {
	savestates_save();
	savestates_job &= ~SAVESTATE;
     }

#ifdef __WIN32__
	extern BOOL emu_paused;
     while(emu_paused)
     {
		Sleep(10);
//		viStatusChanged();
////		processDList();
//		processRDPList();
//		updateScreen();

		processLuaMessages();
	 }
#endif
}