示例#1
0
int main(int argc, char *argv[])
{
	SDL_Surface *screen, *buffer;
	Uint32 videoflags;
	Uint32 ticks;
	SDL_TimerID refreshTimerID;
	SDL_Event event;
	int width, height, bpp, refresh, shift;
	int done;
	Uint8 *buffp;
	int i;
	int t, interval_stat;
	Uint32 startTimer, runTimer;

	/* timer event for regular refresh */
	redrawEvent.type = SDL_USEREVENT;
	redrawEvent.user.code = 1;
	redrawEvent.user.data1 = NULL;
	redrawEvent.user.data2 = NULL;

	/* Initialize SDL */
	if ( SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) < 0 ) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
		exit(1);
	}

	interval_stat = 0;
	t = 0;
	cycle = 0;

	machnum = MACHNUM;
	frequency = FREQUENCY;
	refresh = REFRESHRATE;

	width = 300;
	height = 200;
	bpp = 32;

	videoflags =  SDL_DOUBLEBUF|SDL_FULLSCREEN;

	while ( argc > 1 ) {
	  --argc;
	  if ( argv[argc-1] && (strcmp(argv[argc-1], "-w") == 0) ) {
	    width = atoi(argv[argc]);
	    --argc;
	  } 
	  else if ( argv[argc-1] && (strcmp(argv[argc-1], "-h") == 0) ) {
	    height = atoi(argv[argc]);
	    --argc;
	  } else if ( argv[argc-1] && (strcmp(argv[argc-1], "-num") == 0) ) {
	    machnum = atoi(argv[argc]);
	    --argc;
	  } else if ( argv[argc-1] && (strcmp(argv[argc-1], "-sfreq") == 0) ) {
	    frequency = atof(argv[argc]);
	    --argc;
	  } else if ( argv[argc-1] && (strcmp(argv[argc-1], "-bpp") == 0) ) {
	    bpp = atoi(argv[argc]);
	    --argc;
	  } else if ( argv[argc] && (strcmp(argv[argc], "-sw") == 0) ) {
	    videoflags |= SDL_SWSURFACE;
	  } else if ( argv[argc] && (strcmp(argv[argc], "-hw") == 0) ) {
	    videoflags |= SDL_HWSURFACE;
	  } else if ( argv[argc] && (strcmp(argv[argc], "-hwpalette") == 0) ) {
	    videoflags |= SDL_HWPALETTE;
	  } else if ( argv[argc] && (strcmp(argv[argc], "-window") == 0) ) {
	    videoflags ^= SDL_FULLSCREEN;
	  } else {
	    fprintf(stderr, "Usage: %s [-window] [-sw] [-hwpalette] [-w] [-h] [-swidth] [-sfreq] [-num]\n", argv[0]);
	    exit(1);
	  }
	}
	
	/* create the screen */
	screen = CreateScreen(width, height, bpp, videoflags);
	if ( screen == NULL ) {
		exit(2);
	}

	/* create a buffer where the stimulus is prepared */
	buffer = SDL_CreateRGBSurface(SDL_HWSURFACE|SDL_HWACCEL, width, height, bpp, 0,0,0,0);
	buffer = SDL_DisplayFormat(buffer);

	bpp = screen->format->BytesPerPixel;
	shift = (int)(frequency*refresh*screen->w/1000.0);
	printf("Setup:\nscreen size: %d %d\n",screen->w,screen->h);
	printf("bytes per pixel:%d\n",bpp);
	printf("shift:%d\n",shift);

	SDL_ShowCursor(SDL_DISABLE);
	refreshTimerID = SDL_AddTimer((int)(refresh), refreshTimer, (void *)screen);
	runTimer = SDL_GetTicks();

	/* MAIN LOOP, do screen refresh and wait for keys */
	done = 0;
	while ( !done && SDL_WaitEvent(&event) ) {
	  switch (event.type) {
	  case SDL_KEYDOWN:
	    if ( (event.key.keysym.sym == SDLK_LALT) ||
		 (event.key.keysym.sym == SDLK_TAB) ) {
	      break;
	    }
	  case SDL_QUIT:
	    done = 1;
	    break;
	  case SDL_USEREVENT:
	    i = runTimer;
	    runTimer = SDL_GetTicks();
	    startTimer = i;
	    interval_stat +=  runTimer - i;
	    t++;
	    SDL_LockSurface(buffer);
	    buffp = (Uint8 *)buffer->pixels;
	    for ( i=0; i<screen->h; ++i ) {
	      memcpy(buffp, &c[cycle%(buffer->w*bpp)], buffer->w*bpp);
	      buffp += buffer->pitch;
	    }
	    SDL_UnlockSurface(buffer);
	    SDL_BlitSurface(buffer, NULL, screen, NULL);
	    SDL_Flip(screen);
	    cycle += shift*bpp;
	    break;
	  default:
	    break;
	  }
	}
	SDL_RemoveTimer(refreshTimerID);
	SDL_ShowCursor(SDL_ENABLE);
	printf("mean display interval:%d\n", interval_stat/t);
	SDL_Quit();
	return(0);	

}
示例#2
0
void OsDependentSdl::FreeTimer() {
    SDL_RemoveTimer(TimerId);
}
示例#3
0
static int l_mainloop(lua_State *L)
{
    luaL_checktype(L, 1, LUA_TTHREAD);
    lua_State *dispatcher = lua_tothread(L, 1);

    fps_ctrl *fps_control = (fps_ctrl*)lua_touserdata(L, luaT_upvalueindex(1));
    SDL_TimerID timer = SDL_AddTimer(30, timer_frame_callback, NULL);
    SDL_Event e;

    while(SDL_WaitEvent(&e) != 0)
    {
        bool do_frame = false;
        bool do_timer = false;
        do
        {
            int nargs;
            switch(e.type)
            {
            case SDL_QUIT:
                goto leave_loop;
            case SDL_KEYDOWN:
                lua_pushliteral(dispatcher, "keydown");
                lua_pushstring(dispatcher, SDL_GetKeyName(e.key.keysym.sym));
                l_push_modifiers_table(dispatcher, e.key.keysym.mod);
                lua_pushboolean(dispatcher, e.key.repeat != 0);
                nargs = 4;
                break;
            case SDL_KEYUP:
                lua_pushliteral(dispatcher, "keyup");
                lua_pushstring(dispatcher, SDL_GetKeyName(e.key.keysym.sym));
                nargs = 2;
                break;
            case SDL_TEXTINPUT:
                lua_pushliteral(dispatcher, "textinput");
                lua_pushstring(dispatcher, e.text.text);
                nargs = 2;
                break;
            case SDL_TEXTEDITING:
                lua_pushliteral(dispatcher, "textediting");
                lua_pushstring(dispatcher, e.edit.text);
                lua_pushinteger(dispatcher, e.edit.start);
                lua_pushinteger(dispatcher, e.edit.length);
                nargs = 4;
                break;
            case SDL_MOUSEBUTTONDOWN:
                lua_pushliteral(dispatcher, "buttondown");
                lua_pushinteger(dispatcher, e.button.button);
                lua_pushinteger(dispatcher, e.button.x);
                lua_pushinteger(dispatcher, e.button.y);
                nargs = 4;
                break;
            case SDL_MOUSEBUTTONUP:
                lua_pushliteral(dispatcher, "buttonup");
                lua_pushinteger(dispatcher, e.button.button);
                lua_pushinteger(dispatcher, e.button.x);
                lua_pushinteger(dispatcher, e.button.y);
                nargs = 4;
                break;
            case SDL_MOUSEWHEEL:
                lua_pushliteral(dispatcher, "mousewheel");
                lua_pushinteger(dispatcher, e.wheel.x);
                lua_pushinteger(dispatcher, e.wheel.y);
                nargs = 3;
                break;
            case SDL_MOUSEMOTION:
                lua_pushliteral(dispatcher, "motion");
                lua_pushinteger(dispatcher, e.motion.x);
                lua_pushinteger(dispatcher, e.motion.y);
                lua_pushinteger(dispatcher, e.motion.xrel);
                lua_pushinteger(dispatcher, e.motion.yrel);
                nargs = 5;
                break;
            case SDL_WINDOWEVENT:
                switch (e.window.event) {
                    case SDL_WINDOWEVENT_FOCUS_GAINED:
                        lua_pushliteral(dispatcher, "active");
                        lua_pushinteger(dispatcher, 1);
                        nargs = 2;
                        break;
                    case SDL_WINDOWEVENT_FOCUS_LOST:
                        lua_pushliteral(dispatcher, "active");
                        lua_pushinteger(dispatcher, 0);
                        nargs = 2;
                        break;
                    default:
                        nargs = 0;
                        break;
                }
                break;
            case SDL_USEREVENT_MUSIC_OVER:
                lua_pushliteral(dispatcher, "music_over");
                nargs = 1;
                break;
            case SDL_USEREVENT_CPCALL:
                if(luaT_cpcall(L, (lua_CFunction)e.user.data1, e.user.data2))
                {
                    SDL_RemoveTimer(timer);
                    lua_pushliteral(L, "callback");
                    return 2;
                }
                nargs = 0;
                break;
            case SDL_USEREVENT_TICK:
                do_timer = true;
                nargs = 0;
                break;
            case SDL_USEREVENT_MOVIE_OVER:
                lua_pushliteral(dispatcher, "movie_over");
                nargs = 1;
                break;
            case SDL_USEREVENT_SOUND_OVER:
                lua_pushliteral(dispatcher, "sound_over");
                lua_pushinteger(dispatcher, *(static_cast<int*>(e.user.data1)));
                nargs = 2;
                break;
            default:
                nargs = 0;
                break;
            }
            if(nargs != 0)
            {
                if(luaT_resume(dispatcher, dispatcher, nargs) != LUA_YIELD)
                {
                    goto leave_loop;
                }
                do_frame = do_frame || (lua_toboolean(dispatcher, 1) != 0);
                lua_settop(dispatcher, 0);
            }
        } while(SDL_PollEvent(&e) != 0);
        if(do_timer)
        {
            lua_pushliteral(dispatcher, "timer");
            if(luaT_resume(dispatcher, dispatcher, 1) != LUA_YIELD)
            {
                break;
            }
            do_frame = do_frame || (lua_toboolean(dispatcher, 1) != 0);
            lua_settop(dispatcher, 0);
        }
        if(do_frame || !fps_control->limit_fps)
        {
            do
            {
                if(fps_control->track_fps)
                {
                    fps_control->count_frame();
                }
                lua_pushliteral(dispatcher, "frame");
                if(luaT_resume(dispatcher, dispatcher, 1) != LUA_YIELD)
                {
                    goto leave_loop;
                }
                lua_settop(dispatcher, 0);
            } while(fps_control->limit_fps == false && SDL_PollEvent(NULL) == 0);
        }

        // No events pending - a good time to do a bit of garbage collection
        lua_gc(L, LUA_GCSTEP, 2);
    }

leave_loop:
    SDL_RemoveTimer(timer);
    int n = lua_gettop(dispatcher);
    if(lua_status(dispatcher) >= LUA_ERRRUN)
    {
        n = 1;
    }
    lua_checkstack(L, n);
    lua_xmove(dispatcher, L, n);
    return n;
}
示例#4
0
int
main(int argc, char *argv[])
{
	SDL_Surface *screen, *sprite, *door;
	SDL_Rect rcSprite, rcWall, rcFloor, rcStatus;
	TTF_Font *fntText;
	SDL_Surface *sText;
	SDL_Rect rcText = { 5, 290, 0, 0 };
	SDL_Color clrText = { 192, 192, 192, 0 };
	char debug[100];
	unsigned int colorkey;


	/* Initialize the SDL library: */
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) {
		printf("%s: SDL_Init(): %s\n", argv[0], SDL_GetError());
		exit(EXIT_FAILURE);
	}
	/* Clean up SDL on exit: */
	if (atexit(SDL_Quit) != 0) {
		printf("%s: Cannot register exit function SDL_Quit().\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	/* Initialize SDL TTF engine: */
	if (TTF_Init() != 0) {
		printf("%s: TTF_Init(): %s\n", argv[0], TTF_GetError());
		exit(EXIT_FAILURE);
	}
	/* Clean up TTF on exit: */
	if (atexit(TTF_Quit) != 0) {
		printf("%s: Cannot register exit function TTF_Quit().\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	/* Set up video: */
	screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0);
	if (screen == NULL) {
		printf("%s: SDL_SetVideoMode: %s\n", argv[0], SDL_GetError());
		exit(EXIT_FAILURE);
	}

	/* Set the title bar: */
	SDL_WM_SetCaption("Open Paradise Cafe", NULL);

	/* set keyboard repeat */
	SDL_EnableKeyRepeat(70, 70);

	/* load sprite damatta */
	sprite = load_surface("sprites.bmp");

	/* load door */
	door = load_surface("porta.bmp");

	/* setup sprite colorkey and turn on RLE */
	colorkey = SDL_MapRGB(screen->format, 255, 0, 255);
	SDL_SetColorKey(sprite, SDL_SRCCOLORKEY | SDL_RLEACCEL, colorkey);
	SDL_SetColorKey(door, SDL_SRCCOLORKEY | SDL_RLEACCEL, colorkey);

	/* posicao inicial do damatta */
	rcSprite.x = 150;
	rcSprite.y = 150;

	/* define o tamanho e o *frame* do boneco */
	rcSrc.x = 0;
	rcSrc.y = 0;
	rcSrc.w = SPRITE_WIDTH;
	rcSrc.h = SPRITE_HEIGHT;
	/*printf("sprite w=%d %d h=%d %d\n", sprite->w, SPRITE_WIDTH, sprite->h, SPRITE_HEIGHT);*/

	/* define o tamanho das portas */
	rcSrcDoor.x = 0;
	rcSrcDoor.y = 0;
	rcSrcDoor.w = 56; /* so a primeira frame */
	rcSrcDoor.h = door->h;
	/*printf("door w=%d h=%d\n", door->w, door->h);*/

	/* posicao inicial da porta */
	rcDoor.x = 350;
	rcDoor.y = 126;

	/* Wall: */
	rcWall.x = 0;
	rcWall.y = 0;
	rcWall.w = SCREEN_WIDTH;
	rcWall.h = SCREEN_HEIGHT;

	/* Floor:  */
	rcFloor.x = 0;
	rcFloor.y = 262;
	rcFloor.w = SCREEN_WIDTH;
	rcFloor.h = 24;

	/* Status: */
	rcStatus.x = 0;
	rcStatus.y = 262 + 24;
	rcStatus.w = SCREEN_WIDTH;
	rcStatus.h = SCREEN_HEIGHT - 262 - 24;

	/* load a font and give it a point-size */
	fntText = TTF_OpenFont("arial.ttf", 12);
	if (fntText == NULL) {
		printf("TTF_OpenFont: %s\n", TTF_GetError());
		exit(EXIT_FAILURE);
	}

	gameover = 0; /* usada pra sair */

	jewish_param.lol = SDLK_RIGHT;
	jewish_timer = SDL_AddTimer(100, jewish_timer_callback, &jewish_param);

	while (!gameover) {
		SDL_Event event;
		SDL_WaitEvent(NULL); /* para nao consumir 100% do cpu */

		/* /!\ ACHTUNG: DOOR /!\ */
		if (rcSprite.x + SPRITE_WIDTH == rcDoor.x && door_closed) {
			door_closed = 0;
			door_param.frame = 1;
			door_param.timer = SDL_AddTimer(250, door_timer_callback, &door_param);

			SDL_RemoveTimer(jewish_timer);
			jewish_timer = NULL;
			
			event.type = SDL_USEREVENT;
			event.user.code = USEREVENT_DOOR;
			event.user.data1 = 0;
			event.user.data2 = 0;
			SDL_PushEvent(&event);
		}

		/* Ao sair da porta a porta tem que se fechar */
		if (rcSprite.x == rcDoor.x + 50) {
			printf("dead by dawn");
		}

		/* look for an event */
		if (SDL_PollEvent(&event))
			HandleEvent(event);

		/* Draw the wall (red): */
		SDL_FillRect(screen, &rcWall, SDL_MapRGB(screen->format, 0xc8, 0x41, 0x34));

		/* Draw the floor (purple f*g): */
		SDL_FillRect(screen, &rcFloor, SDL_MapRGB(screen->format, 0xc6, 0x0, 0xc6));

		/* Draw the status line (blue): */
		SDL_FillRect(screen, &rcStatus, SDL_MapRGB(screen->format, 0x0, 0x0, 0xc6));

		/* Draw the door: */
		SDL_BlitSurface(door, &rcSrcDoor, screen, &rcDoor);

		/* Draw the sprite: */
		SDL_BlitSurface(sprite, &rcSrc, screen, &rcSprite);

		/* render text to an SDL_Surface */
		sprintf(debug, "src(x=%d y=%d) door(x=%d y=%d w=%d h=%d) srcdoor(x=%d y=%d w=%d h=%d)",
			rcSrc.x, rcSrc.y, rcDoor.x, rcDoor.y, rcDoor.w, rcDoor.h, rcSrcDoor.x, rcSrcDoor.y, rcSrcDoor.w, rcSrcDoor.h);
		sText = TTF_RenderText_Solid(fntText, debug, clrText);
		SDL_BlitSurface(sText, NULL, screen, &rcText);

		/* Update the screen: */
		SDL_UpdateRect(screen, 0, 0, 0, 0);
	}

	/* Clean up: */
	SDL_FreeSurface(sprite);
	SDL_FreeSurface(door);

	return 0;
}
示例#5
0
void RecurrentObject::clean()
{
	if (timerID != 0)
		SDL_RemoveTimer( timerID );
}
示例#6
0
void start_freehand_drawing(void)
{
    FreehandGeometry geometry;

    int oldmouse_x, oldmouse_y;
    int offsetx = cxoff + canvas->get_absxpos();
    int offsety = cyoff + canvas->get_absypos();
    //SDL_Surface *sur = canvas->get_image(canvas->get_active_image_n());

    SDL_Surface *behind = SDLGui::createSurface(screen->w, screen->h);
    blit(screen, behind, 0, 0, 0, 0, screen->w, screen->h);
                
    SDL_Event event;
    oldmouse_x = mouse.x;
    oldmouse_y = mouse.y;
    
    unsigned processed = 0;
    StlStroke& stroke = *(geometry.currStroke);


    while(mouse.b == SDL_BUTTON_LEFT)
    {
        // Update the screen with the last round of geometry read from the 
        // event queue.
        SDL_PumpEvents();
        for (unsigned i = processed; i < stroke.size(); i++)
        {
            if (i == 0)
            {
                //putpixel(screen, stroke[i].x + offsetx,
                //        stroke[i].y + offsety, BLACK);
                continue;
            }

            aalineRGBA(screen, (int) stroke[i - 1].x + offsetx,
                    (int) stroke[i - 1].y + offsety, 
                    (int) stroke[i].x + offsetx,
                    (int) stroke[i].y + offsety, 0, 0, 0, 128);
            processed++;
        }
        SDL_PumpEvents();
        SDL_Flip(screen);

        // Wait for a new event.
        SDL_WaitEvent(&event);
        // Process all events in the queue.
        do
        {
            switch (event.type)
            {
                case SDL_MOUSEMOTION:
                    mouse.x = event.motion.x;
                    mouse.y = event.motion.y;
                    if ((oldmouse_x != mouse.x) || (oldmouse_y != mouse.y))
                    {
                        geometry.addPoint(mouse.x - offsetx, mouse.y - offsety);
                        oldmouse_x = mouse.x;
                        oldmouse_y = mouse.y;
                    }
                    break;
                case SDL_MOUSEBUTTONUP:
                    mouse.b = 0;
                    break;
                case SDL_QUIT:
                    mouse.kill_sig = 1;
                    break;
                default:
                    break;
            }
        }
        while ((mouse.b != 0) && SDL_PollEvent(&event));
    }

    //qDebug("Points: %d", (int) points.size());
    SDL_FastBlit(behind, screen, 0, 0, 0, 0, screen->w, screen->h);
    SDL_FreeSurface(behind);
   
    if (lastFreehand == NULL)
    {
        strokeTimerID = SDL_AddTimer(strokeTimeout, freehand_timer_callback, 
                NULL);
        
        lastFreehand = new Freehand(geometry);
        // Visibility graph stuff:
        visalgo->obj_add(lastFreehand);

        //QT canvas_deselect_shapes();
    }
    else
    {
        SDL_RemoveTimer(strokeTimerID);
        strokeTimerID = SDL_AddTimer(strokeTimeout, freehand_timer_callback, 
                NULL);
        lastFreehand->addStroke(geometry);
        visalgo->obj_resize(lastFreehand);
    }
#if defined(__APPLE__)
    // After using carbon for mouse input, we need to resync the sdl mouse.
    GUI_DummyMouseEvent();
    while(SDL_PollEvent(&event));
        // noop;
    reset_mouse();
    mouse.bstate = mouse.b = 0;
#endif
    repaint_canvas();
}
示例#7
0
int start_rendering()
{
	static int done = 0;
	static void * network_thread_data[2] = { NULL, NULL };
	static Uint32 last_frame_and_command_update = 0;

	SDL_Thread *network_thread;
	queue_t *message_queue;

#ifndef WINDOWS
	SDL_EventState(SDL_SYSWMEVENT,SDL_ENABLE);
#endif
	queue_initialise(&message_queue);
	network_thread_data[0] = message_queue;
	network_thread_data[1] = &done;
	network_thread = SDL_CreateThread(get_message_from_server, network_thread_data);

	/* Loop until done. */
	while( !done )
		{
			SDL_Event event;

			// handle SDL events
			in_main_event_loop = 1;
			while( SDL_PollEvent( &event ) )
				{
					done = HandleEvent(&event);
				}
			in_main_event_loop = 0;

			//advance the clock
			cur_time = SDL_GetTicks();

			//check for network data
			if(!queue_isempty(message_queue)) {
				message_t *message;

				while((message = queue_pop(message_queue)) != NULL)
				{
#ifdef OTHER_LIFE
					handle_extended_protocol_message(message->data, message->length);
#else
					process_message_from_server(message->data, message->length);
#endif
					free(message->data);
					free(message);
				}
			}
#ifdef	OLC
			olc_process();
#endif	//OLC
			my_tcp_flush(my_socket);    // make sure the tcp output buffer is set
			
			if (have_a_map && cur_time > last_frame_and_command_update + 60) {
				LOCK_ACTORS_LISTS();
				next_command();
				UNLOCK_ACTORS_LISTS();
				move_to_next_frame();
				last_frame_and_command_update = cur_time;
			}

			while (cur_time > next_second_time && real_game_second < 59)
			{
				real_game_second += 1;
				new_second();
				next_second_time += 1000;
			}

#ifdef NEW_SOUND
			weather_sound_control();
#endif	//NEW_SOUND

			if(!limit_fps || (cur_time-last_time && 1000/(cur_time-last_time) <= limit_fps))
			{
				weather_update();

                animate_actors();
				//draw everything
				draw_scene();
				last_time=cur_time;
			}
			else {
				SDL_Delay(1);//give up timeslice for anyone else
			}

#ifdef TIMER_CHECK
			//Check the timers to make sure that they are all still alive...
			check_timers();
#endif

			//cache handling
			if(cache_system)cache_system_maint();
			//see if we need to exit
			if(exit_now) {
				done = 1;
				break;
			}
		}
	if(!done) {
		done = 1;
	}
	LOG_INFO("Client closed");
	SDL_WaitThread(network_thread,&done);
	queue_destroy(message_queue);
	if(pm_log.ppl)free_pm_log();

	//save all local data
	save_local_data(NULL, 0);

#ifdef PAWN
	cleanup_pawn ();
#endif

#ifdef NEW_SOUND
	destroy_sound();		// Cleans up physical elements of the sound system and the streams thread
	clear_sound_data();		// Cleans up the config data
#endif // NEW_SOUND
	ec_destroy_all_effects();
	if (have_a_map)
	{
		destroy_map();
		free_buffers();
	}
	unload_questlog();
	save_item_lists();
	free_emotes();
	free_actor_defs();
	free_books();
	free_vars();
	cleanup_rules();
	save_exploration_map();
	cleanup_counters();
	cleanup_chan_names();
	cleanup_hud();
	destroy_all_root_windows();
	SDL_RemoveTimer(draw_scene_timer);
	SDL_RemoveTimer(misc_timer);
	end_particles ();
	free_bbox_tree(main_bbox_tree);
	main_bbox_tree = NULL;
	free_astro_buffer();
	free_translations();
	free_skybox();
	/* Destroy our GL context, etc. */
	SDL_QuitSubSystem(SDL_INIT_AUDIO);
	SDL_QuitSubSystem(SDL_INIT_TIMER);
/*#ifdef WINDOWS
	// attempt to restart if requested
	if(restart_required > 0){
		LOG_INFO("Restarting %s", win_command_line);
		SDL_CreateThread(system, win_command_line);
	}
#endif  //WINDOWS
*/
#ifdef NEW_SOUND
	final_sound_exit();
#endif
#ifdef	CUSTOM_UPDATE
	stopp_custom_update();
#endif	/* CUSTOM_UPDATE */
	clear_zip_archives();
	clean_update();

	cleanup_tcp();

	if (use_frame_buffer) free_reflection_framebuffer();

	cursors_cleanup();

	printf("doing SDL_Quit\n");
	fflush(stderr);
	SDL_Quit( );
	printf("done SDL_Quit\n");
	fflush(stderr);
	cleanup_mem();
	xmlCleanupParser();
	FreeXML();

	exit_logging();

	return(0);
}
示例#8
0
int main ( int argc, char** argv )
{
	/* initialize random seed: */
	  srand (time(NULL));

    // initialize SDL video
    if ( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        printf( "Unable to init SDL: %s\n", SDL_GetError() );
        return 1;
    }
    /*//Initialize SDL_ttf
	if( TTF_Init() == -1 )
	{
		printf( "SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError() );
		return 1;
	}

	 Sans = TTF_OpenFont("lazy.ttf", 28);
	if( Sans == NULL )
	{
		printf( "Unable to open Font! SDL Error: %s\n", SDL_GetError() );
	}*/

    // make sure SDL cleans up before exit
    atexit(SDL_Quit);

    //Set texture filtering to linear
    if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
    {
        printf( "Warning: Linear texture filtering not enabled!" );
    }

    // create a new window
    SDL_Window *win = SDL_CreateWindow("Tetris", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
    if (win == nullptr){
        std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
        SDL_Quit();
        return 1;
    }

    gRenderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (gRenderer == nullptr){
        SDL_DestroyWindow(win);
        std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
        SDL_Quit();
        return 1;
    }

    bool quit = false;	//Main loop flag
    SDL_Event e;	//Event handler

    CurPiece= new Piece(static_cast<TetrisPieces>(rand()%7),80,Block::Blocksize,gRenderer); //currently existing piece
    //blocks.push_back(Block(Block::Blocksize*5,Block::Blocksize*10,gRenderer,{100,80,70,0xFF}));

    //Set callback
    SDL_TimerID timerID = SDL_AddTimer( 1000, callback,NULL);

    while( !quit )	//While application is running
    {
        //Handle events on queue
        while( SDL_PollEvent( &e ))
        {
            //User requests quit
            if( e.type == SDL_QUIT )
            {
                quit = true;
            }//User presses a key
            else if( e.type == SDL_KEYDOWN )
            {
				if(e.key.keysym.sym == SDLK_LEFT)
				{
					CurPiece->Move(-Block::Blocksize,0);
					if(checkEdgeCollision()||CheckCollision())
						CurPiece->Move(Block::Blocksize,0);
				}
				if(e.key.keysym.sym == SDLK_RIGHT)
				{
					CurPiece->Move(Block::Blocksize,0);
					if(checkEdgeCollision()||CheckCollision())
						CurPiece->Move(-Block::Blocksize,0);
				}
				if(e.key.keysym.sym == SDLK_DOWN)
				{
					CurPiece->Move(0,Block::Blocksize);
					if(checkEdgeCollision()||CheckCollision())
						CurPiece->Move(0,-Block::Blocksize);
				}
				if(e.key.keysym.sym == SDLK_SPACE)
				{
					CurPiece->Rotate();
				}
            }
        }

        //Clear screen
        SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
        SDL_RenderClear( gRenderer );

        //DisplayText("score:",outlineRect.w+outlineRect.x+20,50,{0x00,0x00,0x00,0xFF});
		SDL_SetRenderDrawColor( gRenderer, 0x00, 0x00, 0x00, 0xFF );
		SDL_RenderDrawRect( gRenderer, &outlineRect );

		for_each (blocks.begin(), blocks.end(), std::mem_fun_ref(&Block::Draw));
		CurPiece->Draw();
        //Update screen
        SDL_RenderPresent( gRenderer );
        //SDL_Delay(100);
    }

    delete CurPiece;

    //Free global font
	TTF_CloseFont( Sans );

    //Destroy window
	SDL_DestroyRenderer( gRenderer );
	SDL_DestroyWindow( win );

	SDL_RemoveTimer( timerID );
	//Quit SDL subsystems
	SDL_Quit();
    // all is well ;)
    printf("Exited cleanly\n");
    return 0;
}
示例#9
0
int main(int argc, char *argv[])
{
    SDL_Event       event;
    SDL_TimerID     timer = 0;

    /* nacteni modelu */
    polymodel = modLoad((argc == 2) ? argv[1] : DEFAULT_MODEL);
    IZG_CHECK(polymodel, "Failed to read input model");

    /* vytvoreni default SW rendereru */
#ifdef USE_STUDENT_RENDERER
    renderer = studrenCreate();
#else
    renderer = renCreate();
#endif /* USE_STUDENT_RENDERER */

    /* pocatecni velikost bufferu */
    renderer->createBuffersFunc(renderer, DEFAULT_WIDTH, DEFAULT_HEIGHT);

    /* inicializace SDL knihovny */
    if( SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) == -1 )
    {
        IZG_SDL_ERROR("Could not initialize SDL library");
    }

    /* nastaveni titulku okna */
#ifdef USE_STUDENT_RENDERER
    SDL_WM_SetCaption(PROGRAM_TITLE_STUDENT, 0);
#else
    SDL_WM_SetCaption(PROGRAM_TITLE, 0);
#endif // USE_STUDENT_RENDERER

    /* screen */
    screen = SDL_SetVideoMode(DEFAULT_WIDTH, DEFAULT_HEIGHT, 32, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_RESIZABLE);

    /* enable Unicode translation */
    SDL_EnableUNICODE(1);

    /* dalsi inicializace */
    onInit(renderer, polymodel);

    /* nastavime timer, ktery bude volat zadanou callback fci */
    timer = SDL_AddTimer(TIMER_INTERVAL, timerCallback, NULL);

    /* kreslime dokud nenarazime na SDL_QUIT event */
    while( !quit )
    {
        /* vycteni udalosti */
        while( SDL_PollEvent(&event) )
        {
            switch( event.type )
            {
                /* udalost klavesnice */
                case SDL_KEYDOWN:
                    onKeyboard(&event.key);
                    break;

                /* zmena velikosti okna */
                case SDL_VIDEORESIZE:
                    onResize(&event.resize);
                    break;

                /* udalost mysi - pohyb */
                case SDL_MOUSEMOTION:
                    onMouseMotion(&event.motion);
                    break;

                /* udalost mysi - tlacitka */
                case SDL_MOUSEBUTTONDOWN:
                case SDL_MOUSEBUTTONUP:
                    onMouseButton(&event.button);
                    break;

                /* tiknuti timeru */
                case SDL_USEREVENT:
                    if( event.user.code == IZG_TIMER_EVENT )
                    {
                        onTimer((int)SDL_GetTicks());
                    }
                    break;

                /* SDL_QUIT event */
                case SDL_QUIT:
                    quit = 1;
                    break;

                default:
                    break;
            }
        }

        /* vykresleni pres SDL knihovnu */
        draw();
    }

    /* ukonceni timeru */
    SDL_RemoveTimer(timer);

    /* ukonceni SDL */
    SDL_FreeSurface(screen);

    /* shutdown all SDL subsystems */
    SDL_Quit();

    /* zrusime co jsme vytvorili a ukoncime program */
    modRelease(&polymodel);
    renderer->releaseFunc(&renderer);

    return 0;
}
示例#10
0
文件: game.c 项目: sbusard/testris
/* ----- [ add ] ------------------------------------------------------------ */
void add(struct Var_conf *config)
{
    int timer = 1; // Fix bug of timer
    int random = 0;
    SDL_Rect pos;
    // Pieces id's
    enum Piece_bloc pieces[PC_NB] = {	SQR1,SQR1,SQR1,SQR1,
    					BAR1,BAR1,BAR2,BAR2,
					L1,L2,L3,L4,
					LINV1,LINV2,LINV3,LINV4,
					S1,S1,S2,S2,
					SINV1,SINV1,SINV2,SINV2,
					DP1,DP2,DP3,DP4 };

    // Disable timer
    config->state = J_PAUSE;
    if(!config->dropping && !config->down_pressed && !SDL_RemoveTimer(config->timer))
    {
	fprintf(stderr,
		"[ERROR] Cannot remove timer in %s at line %d.\n",
		__FILE__,__LINE__);
	timer = 0;
    }

    // Get a random piece
    random = rand() % PC_NB + 1;

    // Copy next piece in current piece
    config->pc_cur_id = config->pc_next_id;
    
    // Copy random piece in next piece
    config->pc_next_id = pieces[random - 1];

    // Check position
    pos.x = (PNL_LB / 2) - (PC_NB_LBLC / 2);
    pos.y = 1;

	// Dynamic height panel management
	if(ENABLE_DYNPNL)
	{
		// Empty lines check
		int r = 0;
		int s = 0;
		int empty = 1;

		// Check if half the panel is empty
		for(r = 0;r < 2 * PC_NB_HBLC && empty;r++)
		{
			for(s = 0;s < model_width(config->model) && empty;s++)
			{
				if(model_get(config->model,r,s) != CL_MPT)
					empty = 0;
			}
		}

		// If a quarter of the panel is not empty, add a quarter of empty lines
		if(!empty)
			for(r = 0;r < 2 * PC_NB_HBLC;r++)
				model_add_first(config->model,CL_MPT);

	}	

    // Position is good
    if(check_pc(config,config->model,config->pieces[config->pc_cur_id],pos))
    {
    	config->piece_pos.x = pos.x;
		config->piece_pos.y = pos.y;

		// Piece ghost
		pos.x = config->piece_pos.x;
		pos.y = config->piece_pos.y;
		while(check_pc(config,
				   config->model,
				   config->pieces[config->pc_cur_id],
				   pos)
			  && pos.y != model_height(config->model))
			pos.y++;
		pos.y--;
		config->ghost_pos.x = config->piece_pos.x;
		config->ghost_pos.y = pos.y;
		
		// Display next piece
		disp_next_pc(config);

		// Trigger AI if launched
		if(config->ai_started)
			config->ai_trigger = 1;

		// Enable timer
		config->state = J_PLAY;
		if(timer)
			if(!config->dropping && !config->down_pressed 
			   && (config->timer = SDL_AddTimer(config->interv,
							step,config)) == NULL)
			fprintf(stderr,
				"[ERROR] Cannot initialize timer in %s at line %d.\n",
				__FILE__,__LINE__);

		return;
    }
    // Game Over
    else
    {
    	config->pc_cur_id = PCMPTY;
		lost(config);
		return;
    }
}
void SDLStub::removeTimer(void *timerId) {
	SDL_RemoveTimer((SDL_TimerID)timerId);
}
示例#12
0
int main()
{

  Scene *scene = NULL;
  LSystems lsystems;
  Turtle turtle;
  SDL_Window*window = NULL;
  SDL_GLContext Context;

  //Use OpenGL 3.1 core
  SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
  SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
  SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);

  window = SDL_CreateWindow( "L-Systems",
                                200,
                                100,
                                WINDOWWIDTH,
                                WINDOWHEIGHT,
                                SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);

  if( window == NULL )
  {
    printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() );
    return EXIT_FAILURE;
  }
  Context = SDL_GL_CreateContext( window );

  scene = new Scene();

  scene->init();


  bool quit = false;

  SDL_Event event;
  SDL_TimerID Update = SDL_AddTimer(500,UpdateIteration,&lsystems);

  while(quit!=true)
  {
    while( SDL_PollEvent(&event) != 0)
    {
      if(event.type == SDL_QUIT)
      {
        quit=true;
      }
      //If esc pressed exit window
      if(event.type == SDL_KEYDOWN)
      {
        switch (event.key.keysym.sym)
        {
          case SDLK_ESCAPE:
          {
            quit=true; break;
          }

          // if 1 is pressed draw 1st tree type
          case SDLK_1:
          {
            lsystems.selectTree(1);lsystems.m_iterations=0; break;
          }

          // if 2 is pressed draw 2ns tree type
          case SDLK_2:
          {
            lsystems.selectTree(2); lsystems.m_iterations=0 ; break;
          }

          // press up to increase angle
          case SDLK_UP:
          {
            turtle.m_angle+=5; break;
          }

          // press down to decrease angle
          case SDLK_DOWN:
          {
            turtle.m_angle -=5; break;
          }

          // if right pressed increase max increments (max growth)
          case SDLK_RIGHT:
          {
            lsystems.m_maxIterations+=1; lsystems.m_iterations=0; break;
          }

          // if left pressed decrease max increments (min graowth)
          case SDLK_LEFT:
          {
            lsystems.m_maxIterations-=1; lsystems.m_iterations=0; break;
          }

          default:
          {
            break;
          }
        }
      }
    }

    scene->drawScene();

    //lsystems.createLeaf();
    lsystems.setAxiom();
    lsystems.setRule();
    lsystems.setAlphabet();
    lsystems.setAlphabetRule();
    turtle.setAngle(turtle.m_angle);


    // number of iterations
    lsystems.productions(lsystems.m_iterations);
    lsystems.getDrawingRule();

    // width and height. width increases with each iteration
    turtle.Draw(lsystems,lsystems.m_iterations*0.008,0.20);

    SDL_GL_SwapWindow( window);
  }

  // Delete our scene
  delete scene;

  //Destroy window
  SDL_DestroyWindow( window );

  // Disable our timer
  SDL_RemoveTimer(Update);

  //Quit SDL subsystems
  SDL_Quit();

  return EXIT_SUCCESS;
}
示例#13
0
	bool SDLApplication::Update () {
		
		SDL_Event event;
		event.type = -1;
		
		#if (!defined (IPHONE) && !defined (EMSCRIPTEN))
		
		if (active && (firstTime || SDL_WaitEvent (&event))) {
			
			firstTime = false;
			
			HandleEvent (&event);
			event.type = -1;
			if (!active)
				return active;
			
		#endif
			
			while (SDL_PollEvent (&event)) {
				
				HandleEvent (&event);
				event.type = -1;
				if (!active)
					return active;
				
			}
			
			currentUpdate = SDL_GetTicks ();
			
		#if defined (IPHONE)
			
			if (currentUpdate >= nextUpdate) {
				
				event.type = SDL_USEREVENT;
				HandleEvent (&event);
				event.type = -1;
				
			}
		
		#elif defined (EMSCRIPTEN)
			
			event.type = SDL_USEREVENT;
			HandleEvent (&event);
			event.type = -1;
		
		#else
			
			if (currentUpdate >= nextUpdate) {
				
				SDL_RemoveTimer (timerID);
				OnTimer (0, 0);
				
			} else if (!timerActive) {
				
				timerActive = true;
				timerID = SDL_AddTimer (nextUpdate - currentUpdate, OnTimer, 0);
				
			}
			
		}
		
		#endif
		
		return active;
		
	}
void PonscripterLabel::flushEventSub(SDL_Event &event)
{
    if (event.type == ONS_SOUND_EVENT) {
        if (music_play_loop_flag) {
            stopBGM(true);
            if (music_file_name)
                playSound(music_file_name, SOUND_OGG_STREAMING | SOUND_MP3, true);
        }
        else {
            stopBGM(false);
        }
    }
// The event handler for the mp3 fadeout event itself.  Simply sets the volume of the mp3 being played lower and lower until it's 0,
// and until the requisite mp3 fadeout time has passed.  Recommend for integration.  [Seung Park, 20060621]
    else if (event.type == ONS_FADE_EVENT) {
        if (skip_flag || draw_one_page_flag ||
            ctrl_pressed_status || skip_to_wait)
        {
            mp3fadeout_duration = 0;
            if (mp3_sample) SMPEG_setvolume(mp3_sample, 0);
        }

        Uint32 tmp = SDL_GetTicks() - mp3fadeout_start;
        if (tmp < mp3fadeout_duration) {
            tmp  = mp3fadeout_duration - tmp;
            tmp *= music_volume;
            tmp /= mp3fadeout_duration;

            if (mp3_sample) SMPEG_setvolume(mp3_sample, tmp);
        }
        else {
            SDL_RemoveTimer(timer_mp3fadeout_id);
            timer_mp3fadeout_id = 0;

            event_mode &= ~WAIT_TIMER_MODE;
            stopBGM(false);
            advancePhase();
        }
    }
    else if (event.type == ONS_MIDI_EVENT) {
#ifdef MACOSX
        if (!Mix_PlayingMusic()) {
            ext_music_play_once_flag = !midi_play_loop_flag;
            Mix_FreeMusic(midi_info);
            playMIDI(midi_play_loop_flag);
        }

#else
        ext_music_play_once_flag = !midi_play_loop_flag;
        Mix_FreeMusic(midi_info);
        playMIDI(midi_play_loop_flag);
#endif
    }
    else if (event.type == ONS_MUSIC_EVENT) {
        ext_music_play_once_flag = !music_play_loop_flag;
        Mix_FreeMusic(music_info);
        playExternalMusic(music_play_loop_flag);
    }
    else if (event.type == ONS_WAVE_EVENT) { // for processing btntim2 and automode correctly
        if (wave_sample[event.user.code]) {
            Mix_FreeChunk(wave_sample[event.user.code]);
            wave_sample[event.user.code] = NULL;
            if (event.user.code == MIX_LOOPBGM_CHANNEL0
                && loop_bgm_name[1]
                && wave_sample[MIX_LOOPBGM_CHANNEL1])
                Mix_PlayChannel(MIX_LOOPBGM_CHANNEL1,
                    wave_sample[MIX_LOOPBGM_CHANNEL1], -1);
        }
    }
}
示例#15
0
int main(int argc,char *argv[])
{


    timers timer;
    int lflag=0;
    int		num;
    int i;//cnum繰り返すため
    char	name[MAX_CLIENTS][MAX_NAME_SIZE];
    char	localHostName[]="localhost";
    char	*serverName;
    char	data[MAX_DATA];
    //int		clientID;

//    SDL_TimerID timer_id1;	// タイマ割り込みを行うためのタイマのID

    // SDL初期化
    if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
        printf("failed to initialize SDL.\n");
        exit(-1);
    }

    /* 引き数チェック */
    if(argc == 2){
    	serverName = localHostName;
        if (wiimote_connect(&wiimote, argv[1]) < 0) {	// コマンド引数に指定したWiiリモコン識別情報を渡して接続
            printf("unable to open wiimote: %s\n", wiimote_get_error());
            exit(1);
    }
    }
    else if(argc == 3){
    	serverName = argv[1];
        if (wiimote_connect(&wiimote, argv[2]) < 0) {	// コマンド引数に指定したWiiリモコン識別情報を渡して接続
            printf("unable to open wiimote: %s\n", wiimote_get_error());
            exit(1);
    }
    }
    else{
		fprintf(stderr, "Usage: %s, Cannot find a Server Name.\n", argv[0]);
		return -1;
    }

    /* サーバーとの接続 */
    if(SetUpClient(serverName,&clientID,name)==-1){
		fprintf(stderr,"setup failed : SetUpClient\n");
		return -1;
	}

    printf("clientnum=%d\n",cnum);

    /* スタート画面の初期化 */
    /*if(InitWindows()==-1){
		fprintf(stderr,"setup failed : InitWindows\n");
		return -1;
                }*/
    
   /*ゲームウィンドウの初期化*/
    /*  if(GameWindows(clientID,name,loop)==-1){
	fprintf(stderr,"setup failed : GameWindows\n");
		return -1;

                }*/

        printf("clientnum=%d\n",cnum);

        wiimote.mode.acc = 1;

        switch(clientID){
        case 0: wiimote.led.one =   1; break;
        case 1: wiimote.led.two   = 1; break; 
        case 2 :wiimote.led.three = 1; break;

        default: break;
        }

    /*wiiリモコンの入力受付開始*/

    // SDL_GetTicks関数を用いる時間管理
	Uint32 next_frame=SDL_GetTicks();	// SDLライブラリの初期化からの経過ミリ秒数を取得
        
        //dflag = 0;
        game.flag = 0;
        thr_net=SDL_CreateThread(thread_net,NULL);
        //thr_time=SDL_CreateThread(thread_time,NULL);
        timer_id1=SDL_AddTimer(100, callbackfunc, NULL);
    /* メインイベントループ */
    while(endFlag){
/*
        timer.now=SDL_GetTicks();//現在時間を取得
        timer.wit=timer.now-timer.lev;//待ち時間を計算

        if(dflag == 0)
        {
            WindowEvent(clientID);
            //timer.lev=SDL_GetTicks();//経過時間を更新
        }
        else if(timer.wit > 16){
            WindowEvent(clientID);
            dflag = 0;
            timer.lev=SDL_GetTicks();//経過時間を更新
        }
*/
        timer.wit=timer.now-timer.lev;//待ち時間を計算

        /*if(timer.wit > 1000){
            game.restTime--;
            timer.lev=SDL_GetTicks();//経過時間を更新
            }*/


        /********メイン画面ループ**************/
        if(game.flag == 0){
            loop=1;
            gametimes=3;
            TopWindow();
            printf("now==%d\n\n",game.flag);
            while(game.flag == 0){
                WindowEvent(clientID,ima);
                if(endFlag == 0)
                    break;
            }
        }
        else if(game.flag == 1){//ゲーム画面作成
            
            if(GameWindows(clientID,name,loop)==-1){
                fprintf(stderr,"setup failed : GameWindows\n");
		return -1;}
        }
        /*********ゲーム画面ループ************/
        else if(game.restTime > 0 && game.flag == 2){
            WindowEvent(clientID,ima);  
            ima=SDL_GetTicks();//現在時間を取得
            //printf("game.restTime:%d\n",game.restTime);
//>>>>>>> color
            DrawChara(clientID,cnum);
        }
        
        else if(game.flag == 3 || game.restTime <= 0)
        {
            game.flag = 3;
            if(gClients[clientID].ADsta==1 && game.restTime<=0){
                gClients[clientID].score -= gClients[clientID].Bflag;
                sprintf(data,"kabaddi,%d,%d,%d,%d,%d,%d,%d,%d\0",SCORE,clientID,gClients[clientID].score,0,0,0,0,0);
                SendData(data);
                }
            WinDisplay(clientID);
            
            printf("now==%dloop==%dcnum==%dgametimes=%d\n\n",game.flag,loop,cnum,gametimes);
            while(game.flag == 3){
                WindowEvent(clientID,ima);
                if(endFlag == 0)
                    break;
            }
        }
        else if(game.flag == 4){
            //loop=0;
            EndWindow();
            for(i=0;i<cnum;i++){
                gClients[i].score=0;
                //gClients[i].restart=0;
                // gametimes=3;
            }
            while(game.flag == 4){
                WindowEvent(clientID,ima);
                if(endFlag == 0)
                    break;
            }    
            
        }
        
        timer.lev=SDL_GetTicks();//経過時間を更新
        
        
        
        
        // timer.now=SDL_GetTicks();//現在時間を取得
        //timer.wit=timer.now-timer.lev;//待ち時間を計算
        
        // if(timer.wit<16)
            //    SDL_Delay(16-timer.wit);//16以下ならCPUを休ませる
        
        //timer.lev=SDL_GetTicks();//経過時間を更新
        
    }
    
    /* 終了処理 */
    SDL_RemoveTimer(timer_id1);
    DestroyWindow();
    CloseSoc();
    
    return 0;
}
示例#16
0
 ~RedrawTimer()
 {
     if(id != NULL) SDL_RemoveTimer(id);
 }
示例#17
0
文件: glib.cpp 项目: fluxer/warmux
static void remove_timer() {
  if (timer_id != 0) {
    SDL_RemoveTimer(timer_id);
    timer_id = 0;
  }
}
示例#18
0
int main(int argc, char *argv[])
#endif
{
	SDL_Event event;
	char *loadFile = 0;
	
	pp_int32 defaultBPP = -1;
	PPDisplayDevice::Orientations orientation = PPDisplayDevice::ORIENTATION_NORMAL;
	bool swapRedBlue = false, noSplash = false;
	bool recVelocity = false;
	
	// Parse command line
	while ( argc > 1 )
	{
		--argc;

#ifdef __APPLE__
		// OSX: Swallow "-psn_xxx" argument passed by Finder on OSX <10.9
		if ( strncmp(argv[argc], "-psn", 4) == 0 )
		{
			continue;
		}
		else
#endif
		if ( strcmp(argv[argc-1], "-bpp") == 0 )
		{
			defaultBPP = atoi(argv[argc]);
			--argc;
		}
		else if ( strcmp(argv[argc], "-nosplash") == 0 ) 
		{
			noSplash = true;
		} 
		else if ( strcmp(argv[argc], "-swap") == 0 ) 
		{
			swapRedBlue = true;
		}
		else if ( strcmp(argv[argc-1], "-orientation") == 0 ) 
		{
			if (strcmp(argv[argc], "NORMAL") == 0)
			{
				orientation = PPDisplayDevice::ORIENTATION_NORMAL;
			}
			else if (strcmp(argv[argc], "ROTATE90CCW") == 0)
			{
				orientation = PPDisplayDevice::ORIENTATION_ROTATE90CCW;
			}
			else if (strcmp(argv[argc], "ROTATE90CW") == 0)
			{
				orientation = PPDisplayDevice::ORIENTATION_ROTATE90CW;
			}
			else 
				goto unrecognizedCommandLineSwitch;
			--argc;
		} 
		else if ( strcmp(argv[argc], "-nonstdkb") == 0)
		{
			stdKb = false;
		}
		else if ( strcmp(argv[argc], "-recvelocity") == 0)
		{
			recVelocity = true;
		}
		else 
		{
unrecognizedCommandLineSwitch:
			if (argv[argc][0] == '-') 
			{
				fprintf(stderr, 
						"Usage: %s [-bpp N] [-swap] [-orientation NORMAL|ROTATE90CCW|ROTATE90CW] [-nosplash] [-nonstdkb] [-recvelocity]\n", argv[0]);
				exit(1);
			} 
			else 
			{
				loadFile = argv[argc];
			}
		}
	}

	globalMutex = new PPMutex();
	
	// Store current working path (init routine is likely to change it)
	PPPath_POSIX path;	
	PPSystemString oldCwd = path.getCurrent();
	
	globalMutex->lock();
	initTracker(defaultBPP, orientation, swapRedBlue, noSplash);
	globalMutex->unlock();

#ifdef HAVE_LIBASOUND
	if (myMidiReceiver && recVelocity)
	{
		myMidiReceiver->setRecordVelocity(true);
	}
#endif

	if (loadFile) 
	{
		PPSystemString newCwd = path.getCurrent();
		path.change(oldCwd);
		SendFile(loadFile);
		path.change(newCwd);
		pp_uint16 chr[3] = {VK_RETURN, 0, 0};
		PPEvent event(eKeyDown, &chr, sizeof(chr));
		RaiseEventSerialized(&event);
	}
	
	// Main event loop
	done = 0;
	while (!done && SDL_WaitEvent(&event)) 
	{
		switch (event.type) 
		{
			case SDL_QUIT:
				exitSDLEventLoop(false);
				break;
			case SDL_MOUSEMOTION:
			{
				// Ignore old mouse motion events in the event queue
				SDL_Event new_event;
				
				if (SDL_PeepEvents(&new_event, 1, SDL_GETEVENT, SDL_MOUSEMOTION, SDL_MOUSEMOTION) > 0)
				{
					while (SDL_PeepEvents(&new_event, 1, SDL_GETEVENT, SDL_MOUSEMOTION, SDL_MOUSEMOTION) > 0);
					processSDLEvents(new_event);
				} 
				else 
				{
					processSDLEvents(event);
				}
				break;
			}

			// Open modules drag 'n dropped onto MilkyTracker (currently only works on Dock icon, OSX)
			case SDL_DROPFILE:
				SendFile(event.drop.file);
				SDL_free(event.drop.file);
				break;

			// Refresh GUI if window resized
			case SDL_WINDOWEVENT:
				switch (event.window.event) {
					case SDL_WINDOWEVENT_RESIZED:
						myTrackerScreen->update();
				}
				break;

			case SDL_USEREVENT:
				processSDLUserEvents((const SDL_UserEvent&)event);
				break;

			default:
				processSDLEvents(event);
				break;
		}
	}

	ticking = false;
	SDL_RemoveTimer(timer);
	
	globalMutex->lock();
#ifdef HAVE_LIBASOUND
	delete myMidiReceiver;
#endif
	delete myTracker;
	myTracker = NULL;
	delete myTrackerScreen;
	myTrackerScreen = NULL;
	delete myDisplayDevice;
	globalMutex->unlock();
	SDL_Quit();
	delete globalMutex;
	
	return 0;
}
示例#19
0
void stopTimer()
{
	SDL_RemoveTimer(timer);
}
示例#20
0
int main(int argc, char* argv[]) {
    init_random_gen();
    //SDL init;
    std::cout<<"init sdl"<<std::endl;
    if (SDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO|SDL_OPENGL|SDL_INIT_TIMER)==-1) {
        std::cerr<<"sdl init failed..."<<SDL_GetError()<<std::endl;
        return 1;
    }

    IMG_Init(IMG_INIT_PNG);

    std::cout<<"init video"<<std::endl;
    screen=SDL_SetVideoMode(SCREEN_W,SCREEN_H,SCREEN_DEPTH,SDL_OPENGL|SDL_DOUBLEBUF);
    if (!screen) {
        std::cerr<<"video init failed..."<<std::endl;
        return 1;
    }
    SDL_WM_SetCaption("FrEEsIegE FiGHt",NULL);
    TextureIds texture_ids=init_opengl(screen->w,screen->h,N_TEXTURE);

    //object init
    std::string base_dir=get_base_dir();
    SpriteCollection spr_coll(base_dir+"sprites.cfg",base_dir+"anims.cfg",base_dir,texture_ids);
    std::cout<<spr_coll<<std::endl;

    Background background(&spr_coll);
    Foreground foreground(&spr_coll);
    LifeBar life_bar1(&spr_coll,PLAYER_1);
    LifeBar life_bar2(&spr_coll,PLAYER_2);
    BattleField battlefield(&spr_coll,&life_bar1,&life_bar2,&foreground);

    //mutex timer init
    counter_reset_mutex=SDL_CreateMutex();
    SDL_TimerID counter_reset_id=SDL_AddTimer(1000,counter_reset_callback,NULL);

    bool quit=false;
    SDL_Event event;
    Uint32 ticks=SDL_GetTicks();
    while (!quit) {
        //draw
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        background.draw();
        life_bar1.draw();
        life_bar2.draw();
        battlefield.refresh();
        battlefield.draw();
        foreground.draw();
        SDL_GL_SwapBuffers();
        SDL_Flip(screen);
        //logic

        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_KEYDOWN:
                if (event.key.keysym.sym!=SDLK_ESCAPE) {
                    switch (event.key.keysym.sym) {
                    //unit spawn keys
                    case SDLK_a:
                        battlefield.spawn(SOLDIER,PLAYER_1);
                        break;
                    case SDLK_q:
                        battlefield.spawn(SOLDIER,PLAYER_2);
                        break;
                    case SDLK_z:
                        battlefield.spawn(DRUID,PLAYER_1);
                        break;
                    case SDLK_s:
                        battlefield.spawn(DRUID,PLAYER_2);
                        break;
                    case SDLK_e:
                        battlefield.spawn(KNIGHT,PLAYER_1);
                        break;
                    case SDLK_d:
                        battlefield.spawn(KNIGHT,PLAYER_2);
                        break;
                    case SDLK_r:
                        battlefield.spawn(GOLEM,PLAYER_1);
                        break;
                    case SDLK_f:
                        battlefield.spawn(GOLEM,PLAYER_2);
                        break;
                    case SDLK_t:
                        battlefield.spawn(PLANT,PLAYER_1);
                        break;
                    case SDLK_g:
                        battlefield.spawn(PLANT,PLAYER_2);
                        break;
                    case SDLK_y:
                        battlefield.spawn(DRAGON,PLAYER_1);
                        break;
                    case SDLK_h:
                        battlefield.spawn(DRAGON,PLAYER_2);
                        break;
                    case SDLK_u:
                        battlefield.spawn(FLOWER,PLAYER_2);
                        break;
                    case SDLK_j:
                        battlefield.spawn(FLOWER,PLAYER_1);
                        break;
                    case SDLK_o:
                        battlefield.spawn(VETERAN,PLAYER_2);
                        break;
                    case SDLK_l:
                        battlefield.spawn(VETERAN,PLAYER_1);
                        break;
                    default:
                        break;
                    }
                    break;
                }
            case SDL_QUIT:
                quit=true;
                break;
            default:
                break;
            }
        }

        while (ticks>(SDL_GetTicks()-1000/FPS)) SDL_Delay(3);
        ticks=SDL_GetTicks();

        current_fps++;
    }

    SDL_RemoveTimer(counter_reset_id);
    SDL_DestroyMutex(counter_reset_mutex);

    IMG_Quit();

    SDL_Quit();
    return 0;
}
示例#21
0
文件: testtimer.c 项目: bohwaz/ozex
int main(int argc, char *argv[])
{
	int desired;
	SDL_TimerID t1, t2, t3;

	if ( SDL_Init(SDL_INIT_TIMER) < 0 ) {
		fprintf(stderr, "Couldn't load SDL: %s\n", SDL_GetError());
		exit(1);
	}
	atexit(SDL_Quit);

	/* Start the timer */
	desired = 0;
	if ( argv[1] ) {
		desired = atoi(argv[1]);
	}
	if ( desired == 0 ) {
		desired = DEFAULT_RESOLUTION;
	}
	SDL_SetTimer(desired, ticktock);

	/* Wait 10 seconds */
	printf("Waiting 10 seconds\n");
	SDL_Delay(10*1000);

	/* Stop the timer */
	SDL_SetTimer(0, NULL);

	/* Print the results */
	if ( ticks ) {
		fprintf(stderr,
		"Timer resolution: desired = %d ms, actual = %f ms\n",
					desired, (double)(10*1000)/ticks);
	}
	
	/* Test multiple timers */
	printf("Testing multiple timers...\n");
	t1 = SDL_AddTimer(100, callback, (void*)1);
	if(!t1)
	  fprintf(stderr,"Could not create timer 1\n");
	t2 = SDL_AddTimer(50, callback, (void*)2);
	if(!t2)
	  fprintf(stderr,"Could not create timer 2\n");
	t3 = SDL_AddTimer(233, callback, (void*)3);
	if(!t3)
	  fprintf(stderr,"Could not create timer 3\n");
	
	/* Wait 10 seconds */
	printf("Waiting 10 seconds\n");
	SDL_Delay(10*1000);

	printf("Removing timer 1 and waiting 5 more seconds\n");
	SDL_RemoveTimer(t1);

	SDL_Delay(5*1000);

	SDL_RemoveTimer(t2);
	SDL_RemoveTimer(t3);

	return(0);
}
示例#22
0
int main(int argc, char *argv[])
{
   {//иницилизация
      ShowFPS=true;            //
      ShowFPSInWinCap=true;    //
      fullscreen=false;        //
      ShowCursor=false;         //
      width=800;               //
      height=600;              //
      bpp=32;                  //
      FPS=0;
      FPS_caunter=0;
      WinCaption=new char[20] ;
      strcpy(WinCaption, "My App");
      //    *WinIconCaption;         //
      //    *WinIcon,                //髮 﫭͊      //鮨鬨衶鿠SDL
      if ( SDL_Init( ShowFPS ? SDL_INIT_TIMER|SDL_INIT_VIDEO : SDL_INIT_VIDEO ) < 0 )
      {
        fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError() );
        return 1;
      }
      //
      //atexit(SDL_Quit);
      //
      SDL_WM_SetCaption(WinCaption,WinIconCaption);
      SDL_WM_SetIcon(WinIcon, NULL);
      //
      Screen = SDL_SetVideoMode( width, height, bpp, fullscreen ? SDL_HWSURFACE|SDL_DOUBLEBUF|SDL_FULLSCREEN : SDL_HWSURFACE|SDL_DOUBLEBUF);
      if ( Screen == NULL )
      {
        fprintf(stderr, "Unable to set %d x %d - %d video: %s\n", width, height, bpp, SDL_GetError());
        exit(1);
      }
      //
      SDL_ShowCursor(ShowCursor);
      // FPS
      if (ShowFPS)
        FPS_timer_id = SDL_AddTimer(1000, ShowFPS_func, NULL);
      //

      my_timer_id = SDL_AddTimer(10, my_callbackfunc, NULL);



      if (TTF_Init() == -1)
      {
        fprintf(stderr, "Unable to initialize SDL_ttf: %s \n", TTF_GetError());
      }
      main_font = TTF_OpenFont("LucidaSansDemiBold.ttf", 16); // 䱳詬 鵲
      if (main_font == NULL)
      {  //  NULL
         fprintf(stderr, "Unable to load font: %s \n", TTF_GetError());
         return false;
      }

   }//иницилизация SDL


   //
   cSpriteRepository *Repository=new cSpriteRepository((char*)"Sprites.info");
   srand((1));
   cSpriteEngine *sEn= new cSpriteEngine(Screen);
   cBackGround *back_ground = new cBackGround(Screen, Repository->Image[0].Anim[0].image);
   //


   cPlayer *player=new cPlayer(Repository, 4);
   player->x = (Screen->w-player->w)/2;
   player->y = (Screen->h-player->h);
   player->z =50;
   player->wearon=new cWearon(Repository, 6);
   sEn->add(player);


   for(int i=0;i<9;i++)
   {
      sEn->add(new cEnemy(Repository, 5),rand() % (800),rand() % (600),rand() % (49));
   }

   cSprite *mouse = new cSprite(Repository, 7);
//   mouse->x = (Screen->w-mouse->w)/2;
//   mouse->y = (Screen->h-mouse->h)/2;
   int x,y;
   Uint8 mause_stay;
   mause_stay=SDL_GetMouseState(&x,&y);
   mouse->x = x;
   mouse->y = y;

   mouse->z =500;
   sEn->add(mouse);


   //главный цикл
   bool done = false;
   bool focus=true;
   while (!done)
   {
      // обработка событий
      SDL_Event event;
      while (SDL_PollEvent(&event))
      {
         switch (event.type)
         {
         case SDL_QUIT: //выход
            done = true;
            break;

         case SDL_USEREVENT: //пользовательское событие


            break;

         case SDL_KEYDOWN: // клавиша ESC
            if (event.key.keysym.sym == SDLK_ESCAPE)
                done = true;
            break;

         case SDL_ACTIVEEVENT: //теряем фокус
            if (!event.active.state&&SDL_APPMOUSEFOCUS)
               focus = (event.active.gain==1);
            break;
         }
      } // обработка событий

      if ( focus) //event.active.gain==1& event.active.state==SDL_APPINPUTFOCUS
      {
             //проверка клавиш
         Uint8* keys;
         keys=SDL_GetKeyState(NULL);
         if(keys[SDLK_LEFT])
         {
           player->dx(-1);
         }
         if(keys[SDLK_RIGHT])
         {
          player->dx(1);
         }
         if(keys[SDLK_UP])
         {
          player->dy(-1);
         }
         if(keys[SDLK_DOWN])
         {
            player->dy(1);
         }
         if(keys[SDLK_SPACE])
         {
            //огонь
            player->fire();
         }

         mause_stay=SDL_GetMouseState(&x,&y);
         mouse->x = x;
         mouse->y = y;

         sEn->process();
      }





      // рисование
      back_ground->draw();
      sEn->draw();

//         char text_tmp[100];
//         sprintf(text_tmp, "gain: %d, INPUT %d ACTIVE %d" ,event.active.gain, event.active.state&SDL_APPINPUTFOCUS, event.active.state&SDL_APPACTIVE);
//         TipeText(text_tmp, 00, 100, 240, 240, 0);

      if (ShowFPSInWinCap) //
      {
         char text_tmp[100];
         sprintf(text_tmp, "FPS: %d, спрайтов : %d" ,FPS, sEn->GetCount());
         TipeText(text_tmp, 0, 0, 240, 240, 0);
      }
      SDL_UpdateRect(Screen, 0, 0, 0, 0);
      SDL_Flip(Screen);
      FPS_caunter++;

   } //главный цикл

   //очистка памяти
   delete back_ground;
   delete player;
   delete sEn;
   delete Repository;

   SDL_RemoveTimer(FPS_timer_id);

   TTF_CloseFont(main_font); //
   TTF_Quit(); //
   SDL_Quit(); //
   return 0;
}
示例#23
0
void TimerManager::removeTimer(TimerID &id) {
	if (id._id == 0)
		return;

	SDL_RemoveTimer(id._id);
}
示例#24
0
void ONScripter::flushEventSub( SDL_Event &event )
{
    if ( event.type == ONS_MUSIC_EVENT ){
        if ( music_play_loop_flag ||
             (cd_play_loop_flag && !cdaudio_flag ) ){
            stopBGM( true );
            if (music_file_name)
                playSound(music_file_name, SOUND_MUSIC, true);
            else
                playCDAudio();
        }
        else{
            stopBGM( false );
        }
    }
    else if ((event.type == ONS_BGMFADE_EVENT) &&
             (event.user.code == BGM_FADEOUT)){
        Uint32 cur_fade_duration = mp3fadeout_duration_internal;
        if (skip_mode & (SKIP_NORMAL | SKIP_TO_EOP) ||
            ctrl_pressed_status) {
            cur_fade_duration = 0;
            Mix_VolumeMusic( 0 );
        }
        Uint32 tmp = SDL_GetTicks() - mp3fade_start;
        if ( tmp < cur_fade_duration ) {
            tmp = cur_fade_duration - tmp;
            tmp *= music_volume;
            tmp /= cur_fade_duration;

            Mix_VolumeMusic( tmp * MIX_MAX_VOLUME / 100 );
        } else {
            char *ext = NULL;
            if (music_file_name) ext = strrchr(music_file_name, '.');
            if (ext && (strcmp(ext+1, "OGG") && strcmp(ext+1, "ogg"))){
                // set break event to return to script processing when playing music other than ogg
                SDL_RemoveTimer( break_id );
                break_id = NULL;

                SDL_Event event;
                event.type = ONS_BREAK_EVENT;
                SDL_PushEvent( &event );
            }

            stopBGM( false );
        }
    }
    else if ((event.type == ONS_BGMFADE_EVENT) &&
             (event.user.code == BGM_FADEIN)){
        Uint32 cur_fade_duration = mp3fadein_duration_internal;
        if (skip_mode & (SKIP_NORMAL | SKIP_TO_EOP) ||
            ctrl_pressed_status) {
            cur_fade_duration = 0;
            Mix_VolumeMusic( music_volume * MIX_MAX_VOLUME / 100 );
        }
        Uint32 tmp = SDL_GetTicks() - mp3fade_start;
        if ( tmp < cur_fade_duration ) {
            tmp *= music_volume;
            tmp /= cur_fade_duration;

            Mix_VolumeMusic( tmp * MIX_MAX_VOLUME / 100 );
        } else {
            if (timer_bgmfade_id) SDL_RemoveTimer( timer_bgmfade_id );
            timer_bgmfade_id = NULL;
            mp3fadeout_duration_internal = 0;

            char *ext = NULL;
            if (music_file_name) ext = strrchr(music_file_name, '.');
            if (ext && (strcmp(ext+1, "OGG") && strcmp(ext+1, "ogg"))){
                // set break event to return to script processing when playing music other than ogg
                SDL_RemoveTimer( break_id );
                break_id = NULL;

                SDL_Event event;
                event.type = ONS_BREAK_EVENT;
                SDL_PushEvent( &event );
            }
        }
    }
    else if ( event.type == ONS_CDAUDIO_EVENT ){
        if ( cd_play_loop_flag ){
            stopBGM( true );
            playCDAudio();
        }
        else{
            stopBGM( false );
        }
    }
    else if ( event.type == ONS_MIDI_EVENT ){
        ext_music_play_once_flag = !midi_play_loop_flag;
        Mix_FreeMusic( midi_info );
        playMIDI(midi_play_loop_flag);
    }
    else if ( event.type == ONS_CHUNK_EVENT ){ // for processing btntim2 and automode correctly
        if ( wave_sample[event.user.code] ){
            Mix_FreeChunk( wave_sample[event.user.code] );
            wave_sample[event.user.code] = NULL;
            if (event.user.code == MIX_LOOPBGM_CHANNEL0 && 
                loop_bgm_name[1] &&
                wave_sample[MIX_LOOPBGM_CHANNEL1])
                Mix_PlayChannel(MIX_LOOPBGM_CHANNEL1, 
                                wave_sample[MIX_LOOPBGM_CHANNEL1], -1);
        }
    }
}
示例#25
0
void HardwareLayer::SDLDigitalPin::DisableInterrupt()
{
	SDL_RemoveTimer(m_TimerID);
}
示例#26
0
void
HandleEvent(const SDL_Event event)
{
	int i;


	switch (event.type) {
		/* Close button clicked: */
		case SDL_QUIT:
			gameover = 1;
			break;

		/* Handle keyboard: */
		case SDL_KEYDOWN:
			switch (event.key.keysym.sym) {
				case SDLK_ESCAPE:
				case SDLK_q:
					gameover = 1;
					break;
					/*
				case SDLK_LEFT:

					if (rcSrcDoor.w < 56) {
						rcSrcDoor.w += 10;
					} else {
						rcSrc.x = (rcSrc.x + (160 - 40)) % 160;
						rcDoor.x += 10;
					}

					if (rcDoor.x >= SCREEN_WIDTH)
						rcDoor.x = 0;
					break;
*/
				case SDLK_RIGHT:
					rcSrc.x = (rcSrc.x + 40) % 160;
					rcDoor.x -= 10;

					if (rcDoor.x < 0) {
						rcDoor.x = 0;
						if (rcSrcDoor.w <= 5) {
							rcSrcDoor.w = 56;
							rcSrcDoor.x = 0;
							rcDoor.x = SCREEN_WIDTH;
							door_closed = 1;
						} else {
							if (rcSrcDoor.w == 6)
								rcSrcDoor.w -= 6;
							else
								rcSrcDoor.w -= 10;
						}
					}
					break;

				case SDLK_PAGEUP:
					jewish_param.lol = SDLK_RIGHT;

				case SDLK_PAGEDOWN:
					if (event.key.keysym.sym == SDLK_PAGEDOWN)
						jewish_param.lol = SDLK_LEFT;

					if (jewish_timer == NULL)
						jewish_timer = SDL_AddTimer(100, jewish_timer_callback, &jewish_param);
					else {
						SDL_RemoveTimer(jewish_timer);
						jewish_timer = NULL;
					}

				default:
					printf("bleh\n");
					break;
			}
			break;

		case SDL_USEREVENT:
			switch (event.user.code) {
				case USEREVENT_REDRAW:
					break;

				case USEREVENT_DOOR:
					printf("wtc\n");
					if (rcSrcDoor.x == 0) 
					for (i = 0; i <= 4; i++) {
						/*
						rcSrcDoor.x = i * 56;
						rcSrcDoor.y = 0;
						rcSrcDoor.w = 56;
						rcSrcDoor.h = 136;
						*/
					}
					break;
				case USEREVENT_AFTERDOOR:
					break;
			}
	}
}
示例#27
0
/**
* \brief Execute a test using the given execution key.
*
* \param testSuite Suite containing the test case.
* \param testCase Case to execute.
* \param execKey Execution key for the fuzzer.
* \param forceTestRun Force test to run even if test was disabled in suite.
*
* \returns Test case result.
*/
int
SDLTest_RunTest(SDLTest_TestSuiteReference *testSuite, SDLTest_TestCaseReference *testCase, Uint64 execKey, SDL_bool forceTestRun)
{
    SDL_TimerID timer = 0;
    int testCaseResult = 0;
    int testResult = 0;
    int fuzzerCount;

    if (testSuite==NULL || testCase==NULL || testSuite->name==NULL || testCase->name==NULL)
    {
        SDLTest_LogError("Setup failure: testSuite or testCase references NULL");
        return TEST_RESULT_SETUP_FAILURE;
    }

	if (!testCase->enabled && forceTestRun == SDL_FALSE)
    {
        SDLTest_Log((char *)SDLTest_FinalResultFormat, "Test", testCase->name, "Skipped (Disabled)");
        return TEST_RESULT_SKIPPED;
    }

    /* Initialize fuzzer */
    SDLTest_FuzzerInit(execKey);

    /* Reset assert tracker */
    SDLTest_ResetAssertSummary();

    /* Set timeout timer */
    timer = SDLTest_SetTestTimeout(SDLTest_TestCaseTimeout, SDLTest_BailOut);

    /* Maybe run suite initalizer function */
    if (testSuite->testSetUp) {
        testSuite->testSetUp(0x0);
        if (SDLTest_AssertSummaryToTestResult() == TEST_RESULT_FAILED) {
            SDLTest_LogError((char *)SDLTest_FinalResultFormat, "Suite Setup", testSuite->name, "Failed");
            return TEST_RESULT_SETUP_FAILURE;
        }
    }

    /* Run test case function */
    testCaseResult = testCase->testCase(0x0);

    /* Convert test execution result into harness result */
    if (testCaseResult == TEST_SKIPPED) {
        /* Test was programatically skipped */
        testResult = TEST_RESULT_SKIPPED;
    } else if (testCaseResult == TEST_STARTED) {
        /* Test did not return a TEST_COMPLETED value; assume it failed */
        testResult = TEST_RESULT_FAILED;
    } else if (testCaseResult == TEST_ABORTED) {
        /* Test was aborted early; assume it failed */
        testResult = TEST_RESULT_FAILED;
    } else {
        /* Perform failure analysis based on asserts */
        testResult = SDLTest_AssertSummaryToTestResult();
    }

    /* Maybe run suite cleanup function (ignore failed asserts) */
    if (testSuite->testTearDown) {
        testSuite->testTearDown(0x0);
    }

    /* Cancel timeout timer */
    if (timer) {
        SDL_RemoveTimer(timer);
    }

    /* Report on asserts and fuzzer usage */
    fuzzerCount = SDLTest_GetFuzzerInvocationCount();
    if (fuzzerCount > 0) {
        SDLTest_Log("Fuzzer invocations: %d", fuzzerCount);
    }

    /* Final log based on test execution result */
    if (testCaseResult == TEST_SKIPPED) {
        /* Test was programatically skipped */
        SDLTest_Log((char *)SDLTest_FinalResultFormat, "Test", testCase->name, "Skipped (Programmatically)");
    } else if (testCaseResult == TEST_STARTED) {
        /* Test did not return a TEST_COMPLETED value; assume it failed */
        SDLTest_LogError((char *)SDLTest_FinalResultFormat, "Test", testCase->name, "Failed (test started, but did not return TEST_COMPLETED)");
    } else if (testCaseResult == TEST_ABORTED) {
        /* Test was aborted early; assume it failed */
        SDLTest_LogError((char *)SDLTest_FinalResultFormat, "Test", testCase->name, "Failed (Aborted)");
    } else {
        SDLTest_LogAssertSummary();
    }

    return testResult;
}