Beispiel #1
0
void SetupSound(void) {
	SDL_AudioSpec				spec;

	if (pSndBuffer != NULL) return;

	InitSDL();

	spec.freq = 44100;
	spec.format = AUDIO_S16SYS;
	spec.channels = iDisStereo ? 1 : 2;
	spec.samples = 512;
	spec.callback = SOUND_FillAudio;

	if (SDL_OpenAudio(&spec, NULL) < 0) {
		DestroySDL();
		return;
	}

	iBufSize = BUFFER_SIZE;
	if (iDisStereo) iBufSize /= 2;

	pSndBuffer = (short *)malloc(iBufSize * sizeof(short));
	if (pSndBuffer == NULL) {
		SDL_CloseAudio();
		return;
	}

	iReadPos = 0;
	iWritePos = 0;

	SDL_PauseAudio(0);
}
int main(int argc, char **argv)
{
	FILE *f;
	double atk,def;
	int t=0;
	
	InitSystem();
	
	Bpp=4;
	XRes=800+XR; YRes=400; 

	ScreenBuf=(unsigned char*)malloc(XRes*YRes*Bpp);
	memset(ScreenBuf,0,XRes*YRes*Bpp);
	InitSDL();	
	
	while (1)
	{
		int Ch=ReadKey();
		
		if (Ch=='q') exit(0);
		Iterate();
		Survey(&atk,&def);
		
		f=fopen("output.txt","a");
		fprintf(f,"%d %.6g %.6g\n",t,atk,def);
		fclose(f);
		t++;
	}
}
Beispiel #3
0
// 主程序
int main(int argc, char *argv[])
{
	lua_State *pL_main;

	remove(DEBUG_FILE);
    freopen(ERROR_FILE,"wt",stderr);    //设置stderr输出到文件

	//初始化lua
	pL_main=luaL_newstate();
    luaL_openlibs(pL_main);

    Lua_Config(pL_main,CONFIG_FILE);        //读取lua配置文件,设置参数

    InitSDL();           //初始化SDL

	InitGame();          //初始化游戏数据 

    Lua_Main(pL_main);          //调用Lua主函数,开始游戏

   //关闭lua
    lua_close(pL_main);

	ExitGame();       //释放游戏数据
 
    ExitSDL();        //退出SDL 

    return 0;
}
Beispiel #4
0
int main(int argc, char *argv[])
{
    Context context;
    Context *pContext = &context;
    pContext->pCodecCtx = NULL;
    pContext->pFormatCtx = NULL;
    pContext->screen = NULL;
    pContext->videoName = NULL;
    if(argc < 2)
    {
        fprintf(stderr, "Please provide a movie file\n");
        return 1;
    }
    pContext->videoName = argv[1];
    if(InitFFmpeg(pContext) != 0)
    {
        fprintf(stderr, "Error initializing FFmpeg\n");
        return 1;
    }
    if(InitSDL(pContext) != 0)
    {
        fprintf(stderr, "Error initializing SDL\n");
        return 1;
    }
    if(Play(pContext) != 0)
    {
        fprintf(stderr, "Error playing video\n");
        return 1;
    }
    return 0;
}
Beispiel #5
0
int main(int argc, char* argv[])
{
	InitSDL();
	InitConfig();

	DataXchg *dataXchg = new DataXchg(config_->GetTdsIf());
	HudWnd *hud = new HudWnd();

	while (MessageProcessing())
	{
		UAVDATA uavData;
		dataXchg->GetData(uavData);
		hud->SetUavData(uavData);

		if (!hud->Update())
		{
			std::cerr << "Error!" << std::endl;
			exit(1);
		}

		SDL_Delay(1);
	}

	delete hud;
	delete dataXchg;

	return 0;
}
Beispiel #6
0
/**
 * InitEverything: Initializes the SDL2 library and all graphical components: font, window, renderer
 * \param width width in px of the window
 * \param height height in px of the window
 * \param _img surface to be created with the table background and IST logo
 * \param _window represents the window of the application
 * \param _renderer renderer to handle all rendering in a window
 */
void InitEverything(int width, int height, TTF_Font **_font, SDL_Surface *_img[], SDL_Window** _window, SDL_Renderer** _renderer)
{
    InitSDL();
    InitFont();
    *_window = CreateWindow(width, height);
    *_renderer = CreateRenderer(width, height, *_window);

    // load the table texture
    _img[0] = IMG_Load("assets//table_texture.png");
    if (_img[0] == NULL) {
        fprintf(stderr, "Unable to load image: %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }

    // load IST logo
    _img[1] = SDL_LoadBMP("assets//ist_logo.bmp");
    if (_img[1] == NULL) {
        fprintf(stderr, "Unable to load bitmap: %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }

    // this opens (loads) a font file and sets a size
    *_font = TTF_OpenFont("assets//FreeSerif.ttf", 16);
    if(*_font == NULL) {
        fprintf(stderr, "TTF_OpenFont: %s\n", TTF_GetError());
        exit(EXIT_FAILURE);
    }
}
Beispiel #7
0
QuickVec<int>* CapabilitiesGetScreenResolutions()
{	
	InitSDL();
	QuickVec<int> *out = new QuickVec<int>();
	/*
	// Get available fullscreen/hardware modes
	SDL_Rect** modes = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_HWSURFACE);
	
	// Check if there are any modes available
	if (modes == (SDL_Rect**)0) {
		 return out;
	}
	
	// Check if our resolution is unrestricted
	if (modes == (SDL_Rect**)-1) {
		 return out;
	}
	else{
		 // Print valid modes 
		 
		 for ( int i=0; modes[i]; ++i) {
			 out->push_back( modes[ i ]->w );
			 out->push_back( modes[ i ]->h );
		 }
			 
	}
	*/
	return out;
}
Beispiel #8
0
GameApp::GameApp(int _width,
                 int _height) : width(_width),
                                height(_height) {
    InitSDL();
    //InitGL(); - initting GL Seems to kill TTF!
    TTF_Init();
    instance = this;
};
Beispiel #9
0
	bool Engine::InitSystems()
	{
        if (!InitSDL() || !InitSDLWindow() ||
            !InitGLContext() || !InitGLEW())
            return false;
		InitOpenGLSettings();
        return true;
	}
Beispiel #10
0
static void InitSystem(int width, int height)
{
	SDL_Init(SDL_INIT_EVERYTHING);
	atexit(SDL_Quit);
	InitSDL();
  if (NULL == SDL_SetVideoMode(width, height, 32, SDL_OPENGL | SDL_HWSURFACE))
  {
    exit(EXIT_FAILURE);
  }
	InitSDL(); // workaround for occassional bug in some SDL implementations
	ogl_LoadFunctions();
  LOG("GL v%d.%d\n", ogl_GetMajorVersion(), ogl_GetMinorVersion());
  LOG("GLSL version: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
	InitGL();

	glViewport(0, 0, (GLsizei)width, (GLsizei)height);
}
Beispiel #11
0
bool InitEverything(SDL_GLContext& g_Context, SDL_Window*& g_Window, std::unique_ptr<Scene>& pScene) {
	if (InitSDL())
		if (InitGL(g_Context, g_Window))
			if (InitSound())
				if (InitPython())
					if (InitScene(pScene))
						return true;
	return false;
}
SDLBackend::SDLBackend(SDLBackendSettings const& settings)
  : camera_({settings.camera_x, settings.camera_y, settings.width, settings.height})
  , width_ (settings.width)
  , height_(settings.height)
  , world_width_ (settings.world_width)
  , world_height_(settings.world_height)
  , title_ (settings.title)
{
  InitSDL();
  CreateWindow();
  CreateRenderer();
}
Beispiel #13
0
//
// WinMain
//
// Application entry point.
//
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    // Initialize SDL
    if (!InitSDL())
        return -1;

    // Initialize RPC Server
    if (!MidiRPC_InitServer())
        return -1;

    return 0;
}
Beispiel #14
0
int main(int argc, char* args[]) {

//====== Инициализация ==============================================================
	SDL_Surface *screen = NULL;
	TTF_Font	*font	= NULL;		// Шрифт
	// SDL_Surface буквально есть поверхность окна,
	// на ней мы проделываем все действия по отрисовке,
	// а затем ф-ией SDL_Flip(...) показываем нужную
	// поверхность в окне. (см. реализацию в SDLVisualSort.h)


	screen = InitSDL(); // Инициализация основного окна
	InitFont();			// ... шрифта
//====================================================================================

	// Пример Гномьей сортировки
	const unsigned size = 36;
	float arr[size] =	{10, 15, 0, -5, 20, 12, 50, 3, -34, 21, 33, 1, 2, 3,5, 9, 8, 7,
						-20, -15, 0, -5, 2, 12, 45, 23, -8, -24, 32, 7, 41,33, 1,50, 3, -34};
	float temp;
	int i = 1;
    int j = 2;
	while (i < size) {
		// DrawSort (см.выше)
		DrawSort(arr, size, screen, i);
	
		SDL_Delay(50); //пауза (чтобы замедлить процесс отображения сортировки)
		if (arr[i - 1] <= arr[i]) {
            i = j;
            j = j + 1;
		}
		else {
            //swap a[i - 1] and a[i]
			temp = arr[i-1];
			arr[i-1] = arr[i];
			arr[i] = temp;

            i = i - 1;
			if (i == 0) {
                i = j;
                j = j + 1;
			}
		}
	}
/*
	Если массив сильно большой и отображается так мелко, что не видно цифр,
	можно увеличить размеры окна: WIDTH(ширина) и HEIGHT(высота) в самом
	верху SDLVisualSort.h
*/	
	system ("pause");
	return 0;
}
Beispiel #15
0
int InitAllSDL()
{
	if ( !InitSDL() )
		return 0;

	if ( !InitSDL_image() )
		return 0;

	if ( !InitSDL_ttf() )
		return 0;

	if ( !InitSDL_mixer() )
		return 0;
	return 1;
}
Beispiel #16
0
/* Function that initializes the renderer, the window and all fonts
    param: width of the window
    param: height of the window
    param: font serif
    param: font Demonized
    param: font Queen
    param: the window for the game
    param: the renderer to handle all rendering in the window
*/
void InitEverything(int width, int height, TTF_Font **_font, TTF_Font **_font2, TTF_Font **_font3,
                    TTF_Font **_font4, TTF_Font **_font5, SDL_Window** _window, SDL_Renderer** _renderer)
{
    InitSDL();
    InitFont();
    *_window = CreateWindow(width, height);
    *_renderer = CreateRenderer(width, height, *_window);

    *_font = TTF_OpenFont("FreeSerif.ttf", 16);
    if(!*_font)
    {
        printf("TTF_OpenFont: %s\n", TTF_GetError());
        exit(EXIT_FAILURE);
    }

    *_font2 = TTF_OpenFont("Demonized.ttf", 15);
    if(!* _font2)
    {
        printf("TTF_OpenFont: %s\n", TTF_GetError());
        exit(EXIT_FAILURE);
    }

    *_font3 = TTF_OpenFont("Queen.ttf", 18);
    if(!* _font3)
    {
        printf("TTF_OpenFont: %s\n", TTF_GetError());
        exit(EXIT_FAILURE);
    }

    *_font4 = TTF_OpenFont("Queen.ttf", 40);
    if(!* _font4)
    {
        printf("TTF_OpenFont: %s\n", TTF_GetError());
        exit(EXIT_FAILURE);
    }

    *_font5 = TTF_OpenFont("Targa.ttf", 18);
    if(!* _font5)
    {
        printf("TTF_OpenFont: %s\n", TTF_GetError());
        exit(EXIT_FAILURE);
    }
}
Beispiel #17
0
bool Graphics::InitGraphics(int scale, int row, int col)
{
    mRow            = row;
    mCol            = col;
    mScale          = scale;
    mScreenWidth    = col * scale;
    mScreenHeight   = row * scale;

    if(!InitSDL()) return false;
    if(!InitOpenGL()) return false;

    mShaderProgramId = LoadShaders("data/main.vs", "data/main.fs");

    mMVPuniformLocation = glGetUniformLocation(mShaderProgramId, "MVP");

	glGenBuffers(1, &mVertexBufferId);
	glGenBuffers(1, &mColorBufferId);

    return true;
}
Beispiel #18
0
// 主程序
int SDL_main(int argc, char *argv[])
{
	remove_file(DEBUG_FILE);
    freopen_file(ERROR_FILE,"wt",stderr);    //设置stderr输出到文件

	//初始化lua
	g_pL_main=lua_open();
    luaL_openlibs(g_pL_main);

    Lua_Config(g_pL_main,CONFIG_FILE);        //读取lua配置文件,设置参数

    InitSDL();           //初始化SDL

	InitGame();          //初始化游戏数据

#ifdef WIN32
	SDL_mainLoop();
#endif
    return 0;
}
Beispiel #19
0
/**
 * This function starts the extraction process without
 * the display option.
 *
 * @param infos Informations about the launch process.
 */
void launchProgramWithoutDisplay(t_launch_infos *infos)
{
  SDL_Surface *screen;

  screen = NULL;
  if (infos->inFile != NULL && infos->outFile != NULL)
    {
      if (is_bmp(infos->inFile))
	{
	  InitSDL(screen);
	  processAll(infos);
	  SDL_Quit();
	}
      else
	{
	  help("learn");
	  wfree(infos);
	  exit(EXIT_SUCCESS);
	}
    }
}
Beispiel #20
0
/**
 * This function starts the extraction process with
 * the display option.
 * @param infos Informations about the launch process.
 */
void launchProgramWithDisplay(t_launch_infos *infos)
{
  SDL_Surface *screen;

  screen = NULL;
  if (infos->inFile != NULL && infos->outFile != NULL)
    {
      if (is_bmp(infos->inFile))
	{
	  InitSDL(screen,1);
	  /* Process */
	  waitLoop();
	  SDL_Quit();
	}
      else
	{
	  help("extract");
	  wfree(infos);
	  exit(EXIT_SUCCESS);
	}
    }
}
Beispiel #21
0
void CWindow::CreateRenderWindow(const char* title, int posX, int posY, const int &C_WIDTH, const int &C_HEIGHT, VSYNC syncState, Uint32 flags)
{
	InitSDL();
	mWindowWidth = C_WIDTH;
	mWindowHeight = C_HEIGHT;

	//Set texture filtering to linear
	if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"))
	{
		std::cout << "Warning: Linear texture filtering not enabled." << std::endl;
	}

	mWindow = SDL_CreateWindow(title, posX, posY, mWindowWidth, mWindowHeight, SDL_WINDOW_OPENGL);
	if (mWindow == nullptr)
	{
		std::cout << "Could not create window! SDL Error: " << SDL_GetError() << std::endl;
	}

	InitRenderer(syncState);

	std::cout << "Render window successfully created." << std::endl;
}
Beispiel #22
0
int InitGame()
{
  //Init SDL
  if(!InitSDL())
    return 0;

  //Load Files
  if(!LoadFiles())
    return 0;

  //Initiatialize game variables

  //Set scores to 0
  PlayerScore = 0;
  EnemyScore = 0;

  //This can also set the initial variables
  ResetGame();

  //Play Music
  Mix_PlayMusic(GameMusic, -1);

  return 1;
}
Beispiel #23
0
int main(int argc, char *argv[]) 
{
	
	// Initalizing these to NULL prevents segfaults!
	AVFormatContext   *pFormatCtx = NULL;
	int               i, videoStream;
	AVCodecContext    *pCodecCtxOrig = NULL;
	AVCodecContext    *pCodecCtx = NULL; // 코덱 컨트롤러(?) 이걸 자주 쓴다.
	AVCodec           *pCodec = NULL; // 영상을 디코딩할 코덱
	AVFrame           *pFrame = NULL; // 영상데이터 라고 보면됨.
	AVPacket          packet;
	int               frameFinished;
	struct SwsContext *sws_ctx = NULL; // Convert the image into YUV format that SDL uses

	//SDL 관련 변수
	SDL_Overlay     *bmp;
	SDL_Surface     *screen;
	SDL_Rect        rect;
	SDL_Event       event;

	CVideoSocket videoSocket;
	
	//줌인 줌 아웃을 위한 변수
	int rect_w = 0;
	int rect_h = 0;
	
	// We catch any exceptions that might occur below -- see the catch statement for more details.
	try 
	{
	// 여기부터 마이오 초기화
	// First, we create a Hub with our application identifier. Be sure not to use the com.example namespace when
	// publishing your application. The Hub provides access to one or more Myos.
	// 마이오에서 제공하는 어플리케이션과 연결하는 허브 생성
	myo::Hub hub("com.example.hello-myo");

	// 마이오 찾는중 ...
	std::cout << "Attempting to find a Myo..." << std::endl;

	// Next, we attempt to find a Myo to use. If a Myo is already paired in Myo Connect, this will return that Myo
	// immediately.
	// waitForMyo() takes a timeout value in milliseconds. In this case we will try to find a Myo for 10 seconds, and
	// if that fails, the function will return a null pointer.
	// 마이오를 찾는 동안 대기하는 소스코드
	myo::Myo* myo = hub.waitForMyo(10000);

	// If waitForMyo() returned a null pointer, we failed to find a Myo, so exit with an error message.
	// 마이오가 존재하지 않을경우 예외처리
	if (!myo) 
	{
		throw std::runtime_error("Unable to find a Myo!");
	}

	// We've found a Myo.
	std::cout << "Connected to a Myo armband!" << std::endl << std::endl;

	// Next we construct an instance of our DeviceListener, so that we can register it with the Hub.
	// 마이오에서 얻은 데이터를 가공해주는 클래스
	DataCollector collector;

	// Hub::addListener() takes the address of any object whose class inherits from DeviceListener, and will cause
	// Hub::run() to send events to all registered device listeners.
	// 데이터를 지속적으로 받아온다.
	hub.addListener(&collector);

	//---여기까지 마이오 초기화
	
	// SDL 초기화
	InitSDL();

	// Open video file
	// 파일 또는 데이터 스트림을 연다.
	if (avformat_open_input(&pFormatCtx, videoSocket.videoStreamUrl, NULL, NULL) != 0)
	{
		return -1; // Couldn't open file
	}
	// Retrieve stream information
	// 데이터 스트림의 정보를 얻어온다.
	if (avformat_find_stream_info(pFormatCtx, NULL) < 0)
	{
		return -1; // Couldn't find stream information
	}
	// Dump information about file onto standard error
	av_dump_format(pFormatCtx, 0, videoSocket.videoStreamUrl, 0);

	// Find the first video stream
	// 비디로 스트림을 찾는과정 - 어떤 형식의 데이터 스트림인지 판별 ( 우리는 h.264로 고정되어있지만...)
	videoStream = -1;
	for (i = 0; (unsigned)i < pFormatCtx->nb_streams; i++)
	{
		if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) 
		{
			videoStream = i;
			break;
		}
	}	
	if (videoStream == -1)
	{
		return -1; // Didn't find a video stream
	}
	// Get a pointer to the codec context for the video stream
	pCodecCtxOrig = pFormatCtx->streams[videoStream]->codec;
	// Find the decoder for the video stream
	pCodec = avcodec_find_decoder(pCodecCtxOrig->codec_id);
	if (pCodec == NULL) 
	{
		fprintf(stderr, "Unsupported codec!\n");
		return -1; // Codec not found
	}
	// Copy context
	// 왜 인지 모르겠지만 그냥 쓰지 않고 복사해서 사용한다.
	pCodecCtx = avcodec_alloc_context3(pCodec);
	if (avcodec_copy_context(pCodecCtx, pCodecCtxOrig) != 0) 
	{
		fprintf(stderr, "Couldn't copy codec context");
		return -1; // Error copying codec context
	}

	// Open codec
	if (avcodec_open2(pCodecCtx, pCodec, NULL)<0)
	{
		return -1; // Could not open codec
	}
	
	// Allocate video frame
	pFrame = av_frame_alloc();

	// Make a screen to put our video
	// 스크린을 생성
#ifndef __DARWIN__
	screen = SDL_SetVideoMode(pCodecCtx->width, pCodecCtx->height, 0, 0);
#else
	screen = SDL_SetVideoMode(pCodecCtx->width, pCodecCtx->height, 24, 0);
#endif
	if (!screen) 
	{
		fprintf(stderr, "SDL: could not set video mode - exiting\n");
		exit(1);
	}

	// Allocate a place to put our YUV image on that screen
	// 이미지를 스크린에 그림
	bmp = SDL_CreateYUVOverlay(pCodecCtx->width,
		pCodecCtx->height,
		SDL_YV12_OVERLAY,
		screen);

	// initialize SWS context for software scaling
	sws_ctx = sws_getContext(pCodecCtx->width,
		pCodecCtx->height,
		pCodecCtx->pix_fmt,
		pCodecCtx->width,
		pCodecCtx->height,
		AV_PIX_FMT_YUV420P,
		SWS_BILINEAR,
		NULL,
		NULL,
		NULL
		);

	while (av_read_frame(pFormatCtx, &packet) >= 0) 
	{
		// 메인 루프

		// In each iteration of our main loop, we run the Myo event loop for a set number of milliseconds.
		// 데이터를 어느정도 주기로 받아올지 정하는 소스
		// 이 값이 낮아지면 영상을 받아오는데도 딜레이가 걸리기때문에 원하는 fps를 고려해야한다.
		hub.run(1000 / 500);
		// After processing events, we call the print() member function we defined above to print out the values we've
		// obtained from any events that have occurred.
		// 마이오 상태 모니터링 코드
		collector.print();

		// 마이오 루프 여기까지


		// Is this a packet from the video stream?
		if (packet.stream_index == videoStream) 
		{
			// Decode video frame
			avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);

			// Did we get a video frame?
			// 비디오 프레임을 비트맵 이미지로 변환
			if (frameFinished) 
			{
				SDL_LockYUVOverlay(bmp);

				AVPicture pict;
				pict.data[0] = bmp->pixels[0];
				pict.data[1] = bmp->pixels[2];
				pict.data[2] = bmp->pixels[1];

				pict.linesize[0] = bmp->pitches[0];
				pict.linesize[1] = bmp->pitches[2];
				pict.linesize[2] = bmp->pitches[1];

				
				// Convert the image into YUV format that SDL uses
				sws_scale(sws_ctx, (uint8_t const * const *)pFrame->data,
					pFrame->linesize, 0, pCodecCtx->height,
					pict.data, pict.linesize);

				SDL_UnlockYUVOverlay(bmp);

				// 소프트웨어상으로 줌인 줌아웃을 하기위해 영상프레임의 사이즈를 조절
				rect.x = -rect_w/2;
				rect.y = -rect_h/2;
				rect.w = pCodecCtx->width + rect_w;
				rect.h = pCodecCtx->height + rect_h;
				SDL_DisplayYUVOverlay(bmp, &rect);

			}
		}

		// Free the packet that was allocated by av_read_frame
		av_free_packet(&packet);
		SDL_PollEvent(&event);

		//// 마이오의 동작을 체크해서 메시지 송신
		//// 좌우 카메라 컨트롤
		if (collector.currentPose == myo::Pose::waveOut)
		{
			SendData(videoSocket.ClientSocket, "right", videoSocket.ToServer);
			rest = true;
		}	
		if (collector.currentPose == myo::Pose::waveIn)
		{
			SendData(videoSocket.ClientSocket, "left", videoSocket.ToServer);
			rest = true;
		}
		// 상하 카메라 컨트롤
		if (collector.currentPose == myo::Pose::fingersSpread && collector.pitch_w > 10)
		{
			SendData(videoSocket.ClientSocket, "up", videoSocket.ToServer);
			rest = true;
		}
		if (collector.currentPose == myo::Pose::fingersSpread && collector.pitch_w < 6)
		{
			SendData(videoSocket.ClientSocket, "down", videoSocket.ToServer);
			rest = true;
		}
		if (collector.currentPose == myo::Pose::rest &&rest == true)
		{
			SendData(videoSocket.ClientSocket, "stop", videoSocket.ToServer);
			rest = false;
		}
		if (collector.currentPose == myo::Pose::doubleTap && collector.roll_w <= 5)
		{
			collector.currentPose = myo::Pose::rest;
			rest = true;
			myo->lock();						
		}
		if (collector.currentPose == myo::Pose::doubleTap && collector.roll_w > 5)
		{
			rest = true;
			myo->unlock(myo::Myo::unlockHold);
		}
		// 마이오의 동작을 체크해서 줌인 줌 아웃
		if (collector.currentPose == myo::Pose::fist && collector.roll_w < 6)
		{
			ZoomOut(rect_w, rect_h, 0);
		}
		if (collector.currentPose == myo::Pose::fist && collector.roll_w > 8)
		{
			ZoomIn(rect_w, rect_h, 300);
		}
		// 키 이벤트를 받는 함수
		switch (event.type) 
		{
		case SDL_QUIT:
			SDL_Quit();
			exit(0);
			break;
		case SDL_KEYDOWN:
			/* Check the SDLKey values and move change the coords */
			switch (event.key.keysym.sym){
			case SDLK_LEFT:
				// 문자열 송신
				SendData(videoSocket.ClientSocket, "left", videoSocket.ToServer);
				break;
			case SDLK_RIGHT:
				// 문자열 송신
				SendData(videoSocket.ClientSocket, "right", videoSocket.ToServer);
				break;
			case SDLK_UP:
				SendData(videoSocket.ClientSocket, "up", videoSocket.ToServer);
				break;
			case SDLK_DOWN:
				SendData(videoSocket.ClientSocket, "down", videoSocket.ToServer);
				break;
			case SDLK_q: // 줌 인
				ZoomIn(rect_w,rect_h,300);			
				break;
			case SDLK_w: // 줌 아웃
				ZoomOut(rect_w, rect_h, 0);								
				break;
			case SDLK_s: // 모터 stop
				SendData(videoSocket.ClientSocket, "stop", videoSocket.ToServer);
				break;
			case SDLK_x: // 플그램 종료
				SDL_Quit();
				exit(0);
				break;
			default:
				break;
			}
		default:
			break;
		}

	}
	
	// Free the YUV frame
	av_frame_free(&pFrame);

	// Close the codecs
	avcodec_close(pCodecCtx);
	avcodec_close(pCodecCtxOrig);

	// Close the video file
	avformat_close_input(&pFormatCtx);

	// 소켓 닫기
	closesocket(videoSocket.ClientSocket);
	WSACleanup();

	return 0;

	}
	// 개인적으로 exception handling을 이렇게하는걸 좋아하지 않지만...
	// 예제에서 이렇게 사용하였기에 일단 이렇게 두었다.
	catch (const std::exception& e) 
	{
		std::cerr << "Error: " << e.what() << std::endl;
		std::cerr << "Press enter to continue.";
		std::cin.ignore();
		return 1;
	}
	
}
Beispiel #24
0
void InitGraphics(const CmdLineArgs& args, int flags)
{
	const bool setup_vmode = (flags & INIT_HAVE_VMODE) == 0;

	if(setup_vmode)
	{
		InitSDL();

		if (!g_VideoMode.InitSDL())
			throw PSERROR_System_VmodeFailed(); // abort startup

#if !SDL_VERSION_ATLEAST(2, 0, 0)
		SDL_WM_SetCaption("0 A.D.", "0 A.D.");
#endif
	}

	RunHardwareDetection();

	const int quality = SANE_TEX_QUALITY_DEFAULT;	// TODO: set value from config file
	SetTextureQuality(quality);

	ogl_WarnIfError();

	// Optionally start profiler GPU timings automatically
	// (By default it's only enabled by a hotkey, for performance/compatibility)
	bool profilerGPUEnable = false;
	CFG_GET_VAL("profiler2.autoenable", profilerGPUEnable);
	if (profilerGPUEnable)
		g_Profiler2.EnableGPU();

	if(!g_Quickstart)
	{
		WriteSystemInfo();
		// note: no longer vfs_display here. it's dog-slow due to unbuffered
		// file output and very rarely needed.
	}

	if(g_DisableAudio)
		ISoundManager::SetEnabled(false);

	g_GUI = new CGUIManager();

	// (must come after SetVideoMode, since it calls ogl_Init)
	if (ogl_HaveExtensions(0, "GL_ARB_vertex_program", "GL_ARB_fragment_program", NULL) != 0 // ARB
		&& ogl_HaveExtensions(0, "GL_ARB_vertex_shader", "GL_ARB_fragment_shader", NULL) != 0) // GLSL
	{
		DEBUG_DISPLAY_ERROR(
			L"Your graphics card doesn't appear to be fully compatible with OpenGL shaders."
			L" In the future, the game will not support pre-shader graphics cards."
			L" You are advised to try installing newer drivers and/or upgrade your graphics card."
			L" For more information, please see http://www.wildfiregames.com/forum/index.php?showtopic=16734"
		);
		// TODO: actually quit once fixed function support is dropped
	}

	const char* missing = ogl_HaveExtensions(0,
		"GL_ARB_multitexture",
		"GL_EXT_draw_range_elements",
		"GL_ARB_texture_env_combine",
		"GL_ARB_texture_env_dot3",
		NULL);
	if(missing)
	{
		wchar_t buf[500];
		swprintf_s(buf, ARRAY_SIZE(buf),
			L"The %hs extension doesn't appear to be available on your computer."
			L" The game may still work, though - you are welcome to try at your own risk."
			L" If not or it doesn't look right, upgrade your graphics card.",
			missing
		);
		DEBUG_DISPLAY_ERROR(buf);
		// TODO: i18n
	}

	if (!ogl_HaveExtension("GL_ARB_texture_env_crossbar"))
	{
		DEBUG_DISPLAY_ERROR(
			L"The GL_ARB_texture_env_crossbar extension doesn't appear to be available on your computer."
			L" Shadows are not available and overall graphics quality might suffer."
			L" You are advised to try installing newer drivers and/or upgrade your graphics card.");
		g_Shadows = false;
	}

	ogl_WarnIfError();
	InitRenderer();

	InitInput();

	ogl_WarnIfError();

	try
	{
		if (!Autostart(args))
		{
			const bool setup_gui = ((flags & INIT_NO_GUI) == 0);
			// We only want to display the splash screen at startup
			shared_ptr<ScriptInterface> scriptInterface = g_GUI->GetScriptInterface();
			JSContext* cx = scriptInterface->GetContext();
			JSAutoRequest rq(cx);
			JS::RootedValue data(cx);
			if (g_GUI)
			{
				scriptInterface->Eval("({})", &data);
				scriptInterface->SetProperty(data, "isStartup", true);
			}
			InitPs(setup_gui, L"page_pregame.xml", g_GUI->GetScriptInterface().get(), data);
		}
	}
	catch (PSERROR_Game_World_MapLoadFailed& e)
	{
		// Map Loading failed

		// Start the engine so we have a GUI
		InitPs(true, L"page_pregame.xml", NULL, JS::UndefinedHandleValue);

		// Call script function to do the actual work
		//	(delete game data, switch GUI page, show error, etc.)
		CancelLoad(CStr(e.what()).FromUTF8());
	}
}
Beispiel #25
0
void InitGraphics(const CmdLineArgs& args, int flags)
{
	const bool setup_vmode = (flags & INIT_HAVE_VMODE) == 0;

	if(setup_vmode)
	{
		InitSDL();

		if (!g_VideoMode.InitSDL())
			throw PSERROR_System_VmodeFailed(); // abort startup

#if !SDL_VERSION_ATLEAST(2, 0, 0)
		SDL_WM_SetCaption("0 A.D.", "0 A.D.");
#endif
	}

	RunHardwareDetection();

	tex_codec_register_all();

	const int quality = SANE_TEX_QUALITY_DEFAULT;	// TODO: set value from config file
	SetTextureQuality(quality);

	ogl_WarnIfError();

	// Optionally start profiler GPU timings automatically
	// (By default it's only enabled by a hotkey, for performance/compatibility)
	bool profilerGPUEnable = false;
	CFG_GET_VAL("profiler2.gpu.autoenable", Bool, profilerGPUEnable);
	if (profilerGPUEnable)
		g_Profiler2.EnableGPU();

	if(!g_Quickstart)
	{
		WriteSystemInfo();
		// note: no longer vfs_display here. it's dog-slow due to unbuffered
		// file output and very rarely needed.
	}

	if(g_DisableAudio)
	{
		// speed up startup by disabling all sound
		// (OpenAL init will be skipped).
		// must be called before first snd_open.
#if CONFIG2_AUDIO
		CSoundManager::SetEnabled(false);
#endif
	}

	g_GUI = new CGUIManager(g_ScriptingHost.GetScriptInterface());

	// (must come after SetVideoMode, since it calls ogl_Init)
	const char* missing = ogl_HaveExtensions(0,
		"GL_ARB_multitexture",
		"GL_EXT_draw_range_elements",
		"GL_ARB_texture_env_combine",
		"GL_ARB_texture_env_dot3",
		NULL);
	if(missing)
	{
		wchar_t buf[500];
		swprintf_s(buf, ARRAY_SIZE(buf),
			L"The %hs extension doesn't appear to be available on your computer."
			L" The game may still work, though - you are welcome to try at your own risk."
			L" If not or it doesn't look right, upgrade your graphics card.",
			missing
		);
		DEBUG_DISPLAY_ERROR(buf);
		// TODO: i18n
	}

	if (!ogl_HaveExtension("GL_ARB_texture_env_crossbar"))
	{
		DEBUG_DISPLAY_ERROR(
			L"The GL_ARB_texture_env_crossbar extension doesn't appear to be available on your computer."
			L" Shadows are not available and overall graphics quality might suffer."
			L" You are advised to try installing newer drivers and/or upgrade your graphics card.");
		g_Shadows = false;
	}

	ogl_WarnIfError();
	InitRenderer();

	InitInput();

	ogl_WarnIfError();

	try
	{
		if (!Autostart(args))
		{
			const bool setup_gui = ((flags & INIT_NO_GUI) == 0);
			// We only want to display the splash screen at startup
			CScriptValRooted data;
			if (g_GUI)
			{
				ScriptInterface& scriptInterface = g_GUI->GetScriptInterface();
				scriptInterface.Eval("({})", data);
				scriptInterface.SetProperty(data.get(), "isStartup", true);
			}
			InitPs(setup_gui, L"page_pregame.xml", data.get());
		}
	}
	catch (PSERROR_Game_World_MapLoadFailed e)
	{
		// Map Loading failed

		// Start the engine so we have a GUI
		InitPs(true, L"page_pregame.xml", JSVAL_VOID);

		// Call script function to do the actual work
		//	(delete game data, switch GUI page, show error, etc.)
		CancelLoad(CStr(e.what()).FromUTF8());
	}
}
Beispiel #26
0
//=============================================================================
int main(int argc, char *argv[])
{
	printf("INFO: Monster Outrage v %d\n", VERSION);

	try
	{
		InitSDL();
		LoadMedia();
		InitGame();

		bool quit = false;
		uint ticks = SDL_GetTicks();

		while(!quit)
		{
			// handle events
			SDL_Event e;
			while(SDL_PollEvent(&e) != 0)
			{
				if(e.type == SDL_QUIT)
					quit = true;
				else if(e.type == SDL_KEYDOWN)
				{
					if(e.key.state == SDL_PRESSED)
						ProcessKey(e.key.keysym.scancode, true);
				}
				else if(e.type == SDL_KEYUP)
				{
					if(e.key.state == SDL_RELEASED)
						ProcessKey(e.key.keysym.scancode, false);
				}
				else if(e.type == SDL_MOUSEMOTION || e.type == SDL_MOUSEBUTTONDOWN || e.type == SDL_MOUSEBUTTONUP)
				{
					SDL_GetMouseState(&cursor_pos.x, &cursor_pos.y);
					if(e.type == SDL_MOUSEBUTTONDOWN)
					{
						if(e.button.state == SDL_PRESSED && e.button.button < MAX_BUTTON)
							ProcessButton(e.button.button, true);
					}
					else if(e.type == SDL_MOUSEBUTTONUP)
					{
						if(e.button.state == SDL_RELEASED && e.button.button < MAX_BUTTON)
							ProcessButton(e.button.button, false);
					}
				}
			}

			// calculate dt
			uint new_ticks = SDL_GetTicks();
			float dt = float(new_ticks - ticks)/1000.f;
			ticks = new_ticks;

			Draw();
			Update(dt);
			UpdateInput();
		}

		CleanGame();
		CleanMedia();
		CleanSDL();
	}
	catch(cstring err)
	{
		printf("%s\nERROR: Read error and press any key to exit.\n", err);
		_getch();
		return 1;
	}

	return 0;
}
Beispiel #27
0
	bool Gravity::OnInit() {
		return InitSDL() && InitOpenGL();
	}
Beispiel #28
0
int main(int argc, char ** argv)
{
  SDL_Surface * psdlsScreen     = NULL;
  SDL_Surface * psdlsWMIcon     = NULL;
  int           nVideoMode      = MODE_WINDOWED;
  bool          bDone           = false;
  char          szFilename[512] = {"default.lvl\0"};
  
  Level         level("fuckyou");
  Cursor        cursor(0, 0);
  Hud           hud;


  // deal with command line shit
  if(argc > 2)
  {
    ShowUsage();
    exit(1);
  }
  if(argc == 2)
  {
    if(!strcmp("--help", argv[1]) || !strcmp("-h", argv[1]) || !strcmp("-help", argv[1]))
    {
      ShowUsage();
      exit(0);
    }
    sprintf(szFilename, "%s", argv[1]);
    if(!level.ReadFromFile(szFilename))
      fprintf(stderr, "Couldn't read level from: %s, assuming file doesn't exist yet\n", szFilename);
    else
      fprintf(stderr, "Level read successfully from: %s\n", szFilename);
  }
  else
    fprintf(stderr, "No file name specified, using: %s\n", szFilename);
  
  InitSDL();
//  SetVideoMode(psdlsScreen, nVideoMode);

  fprintf(stderr, "Setting window icon... ");
  psdlsWMIcon = SDL_LoadBMP(LoadResource("bomn32.bmp", RESOURCE_GRAPHIC));
  if(psdlsWMIcon)
  {
    Uint32 colorkey;
    colorkey = SDL_MapRGB(psdlsWMIcon->format, 0, 0, 0);
    SDL_SetColorKey(psdlsWMIcon, SDL_SRCCOLORKEY, colorkey);
    SDL_WM_SetIcon(psdlsWMIcon, NULL);
    fprintf(stderr, "Success!\n");
  }
  else
    fprintf(stderr, "AW JUNK! Something fishy happened...\n");
  
  // can't f*****g use SetVideoMode here, for SOME REASON
  fprintf(stderr, "Setting video mode to 800x600 %s mode... ", (nVideoMode == MODE_WINDOWED ? "windowed" : "fullscreen"));
  SDL_WM_SetCaption("Bomns for Linux Level Editor", "Bomns for Linux Level Editor");
  if(nVideoMode == MODE_WINDOWED)
    psdlsScreen = SDL_SetVideoMode(800, 600, 0, SDL_HWSURFACE | SDL_DOUBLEBUF); 
  else if(nVideoMode == MODE_FULLSCREEN)
    psdlsScreen = SDL_SetVideoMode(800, 600, 0, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_FULLSCREEN);
  else
    QuitWithError("Que?\n");
  if(!psdlsScreen)
    QuitWithError("Error setting GODDAM VIDEO MODE... for some f*****g reason!\n");
  else
    fprintf(stderr, "Success!\n");
  SDL_ShowCursor(false);

  // do this here so the surfaces can read the display format
  cursor.CreateSurfaces();
  hud.CreateSurfaces();
  level.CreateSurfaces();
  
  // main input loop
  while(!bDone)
  {
    SDL_Event sdleEvent;
    Uint8 *   anKeyState  = NULL;
    Uint8     nMouseState = 0;

    while(SDL_PollEvent(&sdleEvent))
    {
      if(sdleEvent.type == SDL_QUIT)
        bDone = true;

      // TODO: use relative mouse motion so it doesn't jump around
      if(sdleEvent.type == SDL_MOUSEMOTION)
        cursor.SetPosition(sdleEvent.motion.x / 10, sdleEvent.motion.y / 10);

      // process mouse input
      nMouseState = SDL_GetMouseState(NULL, NULL);
      if(nMouseState & SDL_BUTTON_LMASK)
        cursor.StampCurrentObject(&level);
      if(nMouseState & SDL_BUTTON_RMASK)
        cursor.DeleteUnderCursor(&level);

      if(sdleEvent.type == SDL_MOUSEBUTTONDOWN)
      {
        switch(sdleEvent.button.button)
        {
          case SDL_BUTTON_WHEELUP:
            cursor.ForwardObject();
            break;
          case SDL_BUTTON_WHEELDOWN:
            cursor.BackwardObject();
            break;
        }
      }
      
      // process keyboard state data
      anKeyState = SDL_GetKeyState(NULL);
      
      if(anKeyState[SDLK_UP])
        cursor.MoveUp();
      if(anKeyState[SDLK_DOWN])
        cursor.MoveDown();
      if(anKeyState[SDLK_LEFT])
        cursor.MoveLeft();
      if(anKeyState[SDLK_RIGHT])
        cursor.MoveRight();

      if(anKeyState[SDLK_SPACE] || anKeyState[SDLK_RETURN] || anKeyState[SDLK_s])
        cursor.StampCurrentObject(&level);
      if(anKeyState[SDLK_DELETE] || anKeyState[SDLK_d])
        cursor.DeleteUnderCursor(&level);

      if(anKeyState[SDLK_PAGEUP])
        cursor.ForwardObject();
      if(anKeyState[SDLK_PAGEDOWN])
        cursor.BackwardObject();

      // 1 - 9 keys select object
      if(anKeyState[SDLK_1])
        cursor.SelectObject(0);
      if(anKeyState[SDLK_2])
        cursor.SelectObject(1);
      if(anKeyState[SDLK_3])
        cursor.SelectObject(2);
      if(anKeyState[SDLK_4])
        cursor.SelectObject(3);
      if(anKeyState[SDLK_5])
        cursor.SelectObject(4);
      if(anKeyState[SDLK_6])
        cursor.SelectObject(5);
      if(anKeyState[SDLK_7])
        cursor.SelectObject(6);
      if(anKeyState[SDLK_8])
        cursor.SelectObject(7);
      if(anKeyState[SDLK_9])
        cursor.SelectObject(8);

      // buttons that should only be pressed, never held down (keyboard event data)
      if(sdleEvent.key.state == SDL_PRESSED)
      {
        switch(sdleEvent.key.keysym.sym)
        {
          case SDLK_ESCAPE:
            bDone = true;
            break;

          case SDLK_f:
            nVideoMode = !nVideoMode;
            SetVideoMode(psdlsScreen, nVideoMode);
            break;

          case SDLK_l:
            char szTmp[520];
            sprintf(szTmp, "bomns %s", szFilename);
            if(!level.WriteToFile(szFilename))
              fprintf(stderr, "Error writing level to: %s\n", szFilename);
            else
              fprintf(stderr, "Level written successfully to: %s\n", szFilename);

            // can't do this while editor is in fullscreen without a pretty big crash
            if(nVideoMode == MODE_FULLSCREEN) // not changing the nVideoMode variable so down there...
              SetVideoMode(psdlsScreen, MODE_WINDOWED);
            
            fprintf(stderr, "Launching level in bomns...\n");
            system(szTmp);
            fprintf(stderr, "Back to editing!\n");
            
            if(nVideoMode == MODE_FULLSCREEN)  // ...we can just read it again and change accordingly
              SetVideoMode(psdlsScreen, nVideoMode);
            break;

          case SDLK_F2:
            if(!level.WriteToFile(szFilename))
              fprintf(stderr, "Error writing level to: %s\n", szFilename);
            else
              fprintf(stderr, "Level successfully written to: %s\n", szFilename);
            break;

          case SDLK_F12: // clear the level... F12 is hard to hit by mistake, right?
            level.DeleteLevel();
            break;

          default:
            break;
        }
      }
    } // SDL_PollEvent

    ClearSurface(psdlsScreen);

    if(!level.DrawLevel(psdlsScreen))
      QuitWithError("Error drawing level to screen!\n");

    if(!hud.DrawHUD(psdlsScreen, 0, 580))
      QuitWithError("Error drawing HUD to screen!\n");

    if(!cursor.DrawCursor(psdlsScreen))
      QuitWithError("Error drawing cursor to screen!\n");

    SDL_Flip(psdlsScreen);

  } // while(!bDone)
  
  ShutDown();

  return 0;
}
Beispiel #29
0
//------------------------------------------------------------------------------
void Platform::init()
{
    Con::printf("Initializing platform...");

    // Set the platform variable for the scripts
    Con::setVariable( "$platform", "x86UNIX" );
#if defined(__linux__)
    Con::setVariable( "$platformUnixType", "Linux" );
#elif defined(__OpenBSD__)
    Con::setVariable( "$platformUnixType", "OpenBSD" );
#else
    Con::setVariable( "$platformUnixType", "Unknown" );
#endif

    StdConsole::create();

    Input::init();

    //installRedBookDevices();

#if 0
#ifndef TORQUE_DEDICATED
    // if we're not dedicated do more initialization
    if (!x86UNIXState->isDedicated())
    {
        // init SDL
        if (!InitSDL())
        {
            DisplayErrorAlert("Unable to initialize SDL.");
            ImmediateShutdown(1);
        }

        Con::printf( "Video Init:" );

        // load gl library
        if (!GLLoader::OpenGLInit())
        {
            DisplayErrorAlert("Unable to initialize OpenGL.");
            ImmediateShutdown(1);
        }

        // initialize video
        Video::init();
        if ( Video::installDevice( OpenGLDevice::create() ) )
            Con::printf( "   OpenGL display device detected." );
        else
            Con::printf( "   OpenGL display device not detected." );

        Con::printf(" ");
    }
#endif
    // if we are dedicated, do sleep timing and display results
    if (x86UNIXState->isDedicated())
    {
        const S32 MaxSleepIter = 10;
        U32 totalSleepTime = 0;
        U32 start;
        for (S32 i = 0; i < MaxSleepIter; ++i)
        {
            start = Platform::getRealMilliseconds();
            Sleep(0, 1000000);
            totalSleepTime += Platform::getRealMilliseconds() - start;
        }
        U32 average = static_cast<U32>(totalSleepTime / MaxSleepIter);

        Con::printf("Sleep latency: %ums", average);
        // dPrintf as well, since console output won't be visible yet
        dPrintf("Sleep latency: %ums\n", average);
        if (!x86UNIXState->getDSleep() && average < 10)
        {
            const char* msg = "Sleep latency ok, enabling dsleep for lower cpu " \
                              "utilization";
            Con::printf("%s", msg);
            dPrintf("%s\n", msg);
            x86UNIXState->setDSleep(true);
        }
    }
#endif
}
//Basic Init, create the font, backbuffer, etc
WINDOW *curses_init(void)
{
    lastchar = -1;
    inputdelay = -1;

    std::string typeface = "Terminus";
    std::string blending = "solid";
    std::ifstream fin;
    int faceIndex = 0;
    int fontsize = 0; //actuall size
    fin.open("data/FONTDATA");
    if (!fin.is_open()){
        fontwidth = 8;
        fontheight = 16;
        std::ofstream fout;//create data/FONDATA file
        fout.open("data/FONTDATA");
        if(fout.is_open()) {
            fout << typeface << "\n";
            fout << fontwidth << "\n";
            fout << fontheight;
            fout.close();
        }
    } else {
        getline(fin, typeface);
        fin >> fontwidth;
        fin >> fontheight;
        fin >> fontsize;
        fin >> blending;
        if ((fontwidth <= 4) || (fontheight <= 4)) {
            fontheight = 16;
            fontwidth = 8;
        }
        fin.close();
    }

    fontblending = (blending=="blended");

    halfwidth=fontwidth / 2;
    halfheight=fontheight / 2;

    if(!InitSDL()) {
        DebugLog() << (std::string)"Failed to initialize SDL!\n";
    }

    #ifdef SDLTILES
    DebugLog() << "Initializing SDL Tiles context\n";
    tilecontext = new cata_tiles;
    tilecontext->init("gfx");
    #endif // SDLTILES
    DebugLog() << (std::string)"Tiles initialized successfully.\n";
    WindowWidth= OPTIONS["TERMINAL_X"];
    if (WindowWidth < FULL_SCREEN_WIDTH) WindowWidth = FULL_SCREEN_WIDTH;
    WindowWidth *= fontwidth;
    WindowHeight = OPTIONS["TERMINAL_Y"] * fontheight;
    if(!WinCreate()) {
        DebugLog() << (std::string)"Failed to create game window!\n";
        return NULL;
    }
    #ifdef SDLTILES
    tilecontext->set_screen(screen);

    while(!strcasecmp(typeface.substr(typeface.length()-4).c_str(),".bmp") ||
          !strcasecmp(typeface.substr(typeface.length()-4).c_str(),".png")) {
        SDL_Surface *asciiload;
        typeface = "data/font/" + typeface;
        asciiload = IMG_Load(typeface.c_str());
        if(!asciiload || asciiload->w*asciiload->h < (fontwidth * fontheight * 256)) {
            SDL_FreeSurface(asciiload);
            break;
        }
        Uint32 key = SDL_MapRGB(asciiload->format, 0xFF, 0, 0xFF);
        SDL_SetColorKey(asciiload,SDL_SRCCOLORKEY,key);
        ascii[0] = SDL_DisplayFormat(asciiload);
        SDL_FreeSurface(asciiload);
        for(int a = 1; a < 16; a++) {
            ascii[a]=SDL_ConvertSurface(ascii[0],ascii[0]->format,ascii[0]->flags);
        }

        init_colors();
        for(int a = 0; a < 15; a++) {
            SDL_LockSurface(ascii[a]);
            int size = ascii[a]->h * ascii[a]->w;
            Uint32 *pixels = (Uint32 *)ascii[a]->pixels;
            Uint32 color = (windowsPalette[a].r << 16) | (windowsPalette[a].g << 8) | windowsPalette[a].b;
            for(int i=0;i<size;i++) {
                if(pixels[i] == 0xFFFFFF)
                    pixels[i] = color;
            }
            SDL_UnlockSurface(ascii[a]);
        }
        if(fontwidth)tilewidth=ascii[0]->w/fontwidth;
        OutputChar = &OutputImageChar;

        mainwin = newwin(OPTIONS["TERMINAL_Y"], OPTIONS["TERMINAL_X"],0,0);
        return mainwin;
    }
    #endif // SDLTILES

    std::string sysfnt = find_system_font(typeface, faceIndex);
    if(sysfnt != "") typeface = sysfnt;

    //make fontdata compatible with wincurse
    if(!fexists(typeface.c_str())) {
        faceIndex = 0;
        typeface = "data/font/" + typeface + ".ttf";
    }

    //different default font with wincurse
    if(!fexists(typeface.c_str())) {
        faceIndex = 0;
        typeface = "data/font/fixedsys.ttf";
    }

    if(fontsize <= 0) fontsize = fontheight - 1;

    // SDL_ttf handles bitmap fonts size incorrectly
    if(0 == strcasecmp(typeface.substr(typeface.length() - 4).c_str(), ".fon"))
        faceIndex = test_face_size(typeface, fontsize, faceIndex);

    font = TTF_OpenFontIndex(typeface.c_str(), fontsize, faceIndex);

    //if(!font) something went wrong

    TTF_SetFontStyle(font, TTF_STYLE_NORMAL);

    // glyph height hack by utunnels
    // SDL_ttf doesn't use FT_HAS_VERTICAL for function TTF_GlyphMetrics
    // this causes baseline problems for certain fonts
    // I can only guess by check a certain tall character...
    cache_glyphs();
    init_colors();

    OutputChar = &OutputFontChar;

    mainwin = newwin(OPTIONS["TERMINAL_Y"], OPTIONS["TERMINAL_X"],0,0);
    return mainwin;   //create the 'stdscr' window and return its ref
}