Ejemplo n.º 1
0
bool InitJoysticks ()
{
    HRESULT hr;

    // Enumerate the joystick devices
    if (FAILED(hr = pdi->EnumDevices(DIDEVTYPE_JOYSTICK, EnumJoystickProc, NULL, DIEDFL_ATTACHEDONLY)))
        TRACE("!!! Failed to enumerate joystick devices (%#08lx)\n", hr);

    // Initialise matched joysticks
    if (pdidJoystick1) InitJoystick(pdidJoystick1);
    if (pdidJoystick2) InitJoystick(pdidJoystick2);

    return true;
}
Ejemplo n.º 2
0
/*
** SWimp_Init
**
** This routine is responsible for initializing the implementation
** specific stuff in a software rendering subsystem.
*/
int SWimp_Init( void *hInstance, void *wndProc )
{
	if (SDL_WasInit(SDL_INIT_AUDIO|SDL_INIT_CDROM|SDL_INIT_VIDEO) == 0) {
		if (SDL_Init(SDL_INIT_VIDEO) < 0) {
			Sys_Error("SDL Init failed: %s\n", SDL_GetError());
			return false;
		}
	} else if (SDL_WasInit(SDL_INIT_VIDEO) == 0) {
		if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) {
			Sys_Error("SDL Init failed: %s\n", SDL_GetError());
			return false;
		}
	}

//	SDL_EnableKeyRepeat(0, SDL_DEFAULT_REPEAT_INTERVAL);
	
// catch signals so i can turn on auto-repeat
#if 0
 	{
		struct sigaction sa;
		sigaction(SIGINT, 0, &sa);
		sa.sa_handler = TragicDeath;
		sigaction(SIGINT, &sa, 0);
		sigaction(SIGTERM, &sa, 0);
	}
#endif
#ifdef Joystick
	InitJoystick();
#endif
	return true;
}
Ejemplo n.º 3
0
void CWinsys::Init () {
	Uint32 sdl_flags = SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE | SDL_INIT_TIMER;
	if (SDL_Init (sdl_flags) < 0) Message ("Could not initialize SDL");

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_EGL, 1);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1); 
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); 

	SDL_GL_SetAttribute (SDL_GL_DOUBLEBUFFER, 1);
#if defined (USE_STENCIL_BUFFER)
	SDL_GL_SetAttribute (SDL_GL_STENCIL_SIZE, 8);
#endif
#ifdef USE_GLES
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
	glHint(GL_LINE_SMOOTH_HINT, GL_FASTEST);
#endif

	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

	SetupVideoMode (GetResolution (param.res_type));
	context = SDL_GL_CreateContext(window);
	SetOrient(param.orient >= 0 ? param.orient : resolution.width < resolution.height);
	Reshape (resolution.width, resolution.height);

	//SDL_WM_SetCaption (WINDOW_TITLE, WINDOW_TITLE);
	KeyRepeat (false);
	if (USE_JOYSTICK) InitJoystick ();
//	SDL_EnableUNICODE (1);
}
Ejemplo n.º 4
0
/**
 * Version of the constructor to be called by sub-classes.
 * 
 * This constructor allows the subclass to configure the number of constants
 * for axes and buttons.
 * 
 * @param port The port on the driver station that the joystick is plugged into.
 * @param numAxisTypes The number of axis types in the enum.
 * @param numButtonTypes The number of button types in the enum.
 */
Joystick::Joystick(uint32_t port, uint32_t numAxisTypes, uint32_t numButtonTypes)
	: m_ds (NULL)
	, m_port (port)
	, m_axes (NULL)
	, m_buttons (NULL)
{
	InitJoystick(numAxisTypes, numButtonTypes);
}
Ejemplo n.º 5
0
/**
 * Version of the constructor to be called by sub-classes.
 * 
 * This constructor allows the subclass to configure the number of constants
 * for axes and buttons.
 * 
 * @param port The port on the driver station that the joystick is plugged into.
 * @param numAxisTypes The number of axis types in the enum.
 * @param numButtonTypes The number of button types in the enum.
 */
Joystick::Joystick(UINT32 port, UINT32 numAxisTypes, UINT32 numButtonTypes)
	: m_ds (NULL)
	, m_port (port)
	, m_axes (NULL)
	, m_buttons (NULL)
{
	InitJoystick(numAxisTypes, numButtonTypes);
}
Ejemplo n.º 6
0
void Init(std::vector<Core::Device*>& devices, HWND hwnd)
{
	IDirectInput8* idi8;
	if (FAILED(DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (LPVOID*)&idi8, NULL)))
		return;

	InitKeyboardMouse(idi8, devices, hwnd);
	InitJoystick(idi8, devices, hwnd);

	idi8->Release();

}
Ejemplo n.º 7
0
void PopulateDevices(HWND hwnd)
{
  IDirectInput8* idi8;
  if (FAILED(DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8,
                                (LPVOID*)&idi8, nullptr)))
  {
    return;
  }

  InitKeyboardMouse(idi8, hwnd);
  InitJoystick(idi8, hwnd);

  idi8->Release();
}
Ejemplo n.º 8
0
void Init(std::vector<ControllerInterface::Device*>& devices, HWND hwnd)
{
	IDirectInput8* idi8;
	if (FAILED(DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (LPVOID*)&idi8, NULL)))
		return;

#ifdef CIFACE_USE_DINPUT_KBM
	InitKeyboardMouse(idi8, devices, hwnd);
#endif
#ifdef CIFACE_USE_DINPUT_JOYSTICK
	InitJoystick(idi8, devices, hwnd);
#endif

	idi8->Release();

}
Ejemplo n.º 9
0
/**
 * Construct an instance of a joystick.
 * The joystick index is the usb port on the drivers station.
 * 
 * @param port The port on the driver station that the joystick is plugged into.
 */
Joystick::Joystick(UINT32 port)
	: m_ds (NULL)
	, m_port (port)
	, m_axes (NULL)
	, m_buttons (NULL)
{
	InitJoystick(kNumAxisTypes, kNumButtonTypes);

	m_axes[kXAxis] = kDefaultXAxis;
	m_axes[kYAxis] = kDefaultYAxis;
	m_axes[kZAxis] = kDefaultZAxis;
	m_axes[kTwistAxis] = kDefaultTwistAxis;
	m_axes[kThrottleAxis] = kDefaultThrottleAxis;
	
	m_buttons[kTriggerButton] = kDefaultTriggerButton;
	m_buttons[kTopButton] = kDefaultTopButton;
}
Ejemplo n.º 10
0
//===============================================
//DirectInputの初期化
//===============================================
//[input]
//	なし
//[return]
//	hr:結果
//===============================================
HRESULT CInput::CreateDevice()
{
	HRESULT hr;
	
	/*デバイスの生成*/
	hr = DirectInput8Create(Joker::GetHInst(), DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID**)&m_pDirectInput, NULL);
	
	if(FAILED(hr) )
	{
		return hr;
	}
	
	InitKeyboard();
	InitJoystick();
	
	return S_OK;
	
}
Ejemplo n.º 11
0
static void SetJoystickButtonLabel(void)
{
    char *name;

    InitJoystick();

    name = "None set";

    if (joystick_initted
     && joystick_index >= 0 && joystick_index < SDL_NumJoysticks())
    {
        name = (char *) SDL_JoystickName(joystick_index);
    }

    TXT_SetButtonLabel(joystick_button, name);

    UnInitJoystick();
}
Ejemplo n.º 12
0
/**
 * Construct an instance of a joystick.
 * The joystick index is the usb port on the drivers station.
 * 
 * @param port The port on the driver station that the joystick is plugged into.
 */
Joystick::Joystick(UINT32 port)
	: m_ds (NULL)
	, m_port (port)
	, m_axes (NULL)
	, m_buttons (NULL)
{
	InitJoystick(kNumAxisTypes, kNumButtonTypes);

	m_axes[kXAxis] = kDefaultXAxis;
	m_axes[kYAxis] = kDefaultYAxis;
	m_axes[kZAxis] = kDefaultZAxis;
	m_axes[kTwistAxis] = kDefaultTwistAxis;
	m_axes[kThrottleAxis] = kDefaultThrottleAxis;
	
	m_buttons[kTriggerButton] = kDefaultTriggerButton;
	m_buttons[kTopButton] = kDefaultTopButton;

	nUsageReporting::report(nUsageReporting::kResourceType_Joystick, port);
}
Ejemplo n.º 13
0
/*
    put here anything you need to do when the program is started. Return 0 if 
    initialization was successful, nonzero otherwise.
*/
static int DIJoystick_init(void)
{
	DWORD i;
	HRESULT hr;
	LPDIRECTINPUT di = GetDirectInput();

	This.use_count++;

	This.num_joysticks = 0;

	if (di == NULL)
	{
		ErrorMsg("DirectInput not initialized");
		return 0;
	}

	/* enumerate for joystick devices */
	hr = IDirectInput_EnumDevices(di, DIDEVTYPE_JOYSTICK,
				 (LPDIENUMDEVICESCALLBACK)DIJoystick_EnumDeviceProc,
				 NULL,
				 DIEDFL_ATTACHEDONLY  );
	if (FAILED(hr))
	{
		ErrorMsg("DirectInput EnumDevices() failed: %s", DirectXDecodeError(hr));
		return 0;
	}

	/* create each joystick device, enumerate each joystick for axes, etc */
	for (i = 0; i < This.num_joysticks; i++)
	{
		InitJoystick(&This.joysticks[i]);
	}

	/* Are there any joysticks attached? */
	if (This.num_joysticks < 1)
	{
		/*ErrorMsg("DirectInput EnumDevices didn't find any joysticks");*/
		return 0;
	}
	
	return 0;
}
Ejemplo n.º 14
0
static int OpenAllJoysticks(void)
{
    int i;
    int num_joysticks;
    int result;

    InitJoystick();

    // SDL_JoystickOpen() all joysticks.

    num_joysticks = SDL_NumJoysticks();

    all_joysticks = malloc(sizeof(SDL_Joystick *) * num_joysticks);

    result = 0;

    for (i=0; i<num_joysticks; ++i) 
    {
        all_joysticks[i] = SDL_JoystickOpen(i);

        // If any joystick is successfully opened, return true.

        if (all_joysticks[i] != NULL)
        {
            result = 1;
        }
    }

    // Success? Turn on joystick events.

    if (result)
    {
        SDL_JoystickEventState(SDL_ENABLE);
    }
    else
    {
        free(all_joysticks);
        all_joysticks = NULL;
    }

    return result;
}
Ejemplo n.º 15
0
void init_board()
{
  // Stop watchdog timer
    WDTCTL = WDTPW + WDTHOLD;

    // External oscilator 8MHz
    FLL_CTL0 = XCAP0PF;
    // Stop DCO
    _BIS_SR(SCG1);
    FLL_CTL1 &= ~XT2OFF;
    // Wait for xtal to stabilize
    do {
        IFG1 &= ~OFIFG;  // Clear OSCFault flag
        for (int i = 5; i > 0; i--) {
            ;    // Time for flag to set
        }
    } while ((IFG1 & OFIFG));
    FLL_CTL1 = SELM1 + SELS + FLL_DIV_1;

    Delay(50000);

    // Ports P1.6, P1.7 as input
    P1DIR   &= ~((1<<6)|(1<<7));

    // Clear all interrupts flag
    P1IFG = 0x0;
    P2IFG = 0x0;

    // Center Button as input
    // gpio
    P2SEL &= ~BIT6;
    // input
    P2DIR &= ~BIT6;
    
    InitJoystick();
    InitBoutons();
}
Ejemplo n.º 16
0
/**
 * @brief Initializes the SpringApp instance
 * @return whether initialization was successful
 */
bool SpringApp::Initialize()
{
#if !(defined(WIN32) || defined(__APPLE__) || defined(HEADLESS))
	//! this MUST run before any other X11 call (esp. those by SDL!)
	//! we need it to make calls to X11 threadsafe
	if (!XInitThreads()) {
		LOG_L(L_FATAL, "Xlib is not thread safe");
		return false;
	}
#endif

#if defined(_WIN32) && defined(__GNUC__)
	// load QTCreator's gdb helper dll; a variant of this should also work on other OSes
	{
		// don't display a dialog box if gdb helpers aren't found
		UINT olderrors = SetErrorMode(SEM_FAILCRITICALERRORS);
		if (LoadLibrary("gdbmacros.dll")) {
			LOG("QT Creator's gdbmacros.dll loaded");
		}
		SetErrorMode(olderrors);
	}
#endif

	// Initialize class system
	creg::System::InitializeClasses();

	// Initialize crash reporting
	CrashHandler::Install();

	globalRendering = new CGlobalRendering();

	ParseCmdLine();
	CMyMath::Init();
	good_fpu_control_registers("::Run");

	Watchdog::Install();
	//! register (this) mainthread
	Watchdog::RegisterThread(WDT_MAIN, true);

	// log OS version
	LOG("OS: %s", Platform::GetOS().c_str());
	if (Platform::Is64Bit())
		LOG("OS: 64bit native mode");
	else if (Platform::Is32BitEmulation())
		LOG("OS: emulated 32bit mode");
	else
		LOG("OS: 32bit native mode");

	FileSystemInitializer::Initialize();

	UpdateOldConfigs();

	if (!InitWindow(("Spring " + SpringVersion::GetSync()).c_str())) {
		SDL_Quit();
		return false;
	}

	mouseInput = IMouseInput::GetInstance();
	keyInput = KeyInput::GetInstance();
	input.AddHandler(boost::bind(&SpringApp::MainEventHandler, this, _1));

	// Global structures
	gs = new CGlobalSynced();
	gu = new CGlobalUnsynced();

	// Initialize GLEW
	LoadExtensions();

	//! check if FSAA init worked fine
	if (globalRendering->FSAA && !MultisampleVerify())
		globalRendering->FSAA = 0;

	InitOpenGL();
	agui::InitGui();
	LoadFonts();

	globalRendering->PostInit();

	// Initialize named texture handler
	CNamedTextures::Init();

	// Initialize Lua GL
	LuaOpenGL::Init();

	// Sound
	ISound::Initialize();
	InitJoystick();

	SetProcessAffinity(configHandler->GetInt("SetCoreAffinity"));

	// Create CGameSetup and CPreGame objects
	Startup();

	return true;
}
Ejemplo n.º 17
0
/**
 * @brief Initializes the SpringApp instance
 * @return whether initialization was successful
 */
bool SpringApp::Initialize()
{
	assert(cmdline != NULL);
	assert(configHandler != NULL);

	// list user's config
	LOG("============== <User Config> ==============");
	const std::map<std::string, std::string> settings = configHandler->GetDataWithoutDefaults();
	for (auto& it: settings) {
		// exclude non-engine configtags
		if (ConfigVariable::GetMetaData(it.first) == nullptr)
			continue;

		LOG("%s = %s", it.first.c_str(), it.second.c_str());
	}
	LOG("============== </User Config> ==============");

	FileSystemInitializer::InitializeLogOutput();
	CLogOutput::LogSystemInfo();
	LOG("         CPU Clock: %s", spring_clock::GetName());
	LOG("Physical CPU Cores: %d", Threading::GetPhysicalCpuCores());
	LOG(" Logical CPU Cores: %d", Threading::GetLogicalCpuCores());
	CMyMath::Init();

	globalRendering = new CGlobalRendering();
	globalRendering->SetFullScreen(configHandler->GetBool("Fullscreen"), cmdline->IsSet("window"), cmdline->IsSet("fullscreen"));

#if !(defined(WIN32) || defined(__APPLE__) || defined(HEADLESS))
	// this MUST run before any other X11 call (esp. those by SDL!)
	// we need it to make calls to X11 threadsafe
	if (!XInitThreads()) {
		LOG_L(L_FATAL, "Xlib is not thread safe");
		return false;
	}
#endif

#if defined(WIN32) && defined(__GNUC__)
	// load QTCreator's gdb helper dll; a variant of this should also work on other OSes
	{
		// don't display a dialog box if gdb helpers aren't found
		UINT olderrors = SetErrorMode(SEM_FAILCRITICALERRORS);
		if (LoadLibrary("gdbmacros.dll")) {
			LOG_L(L_DEBUG, "QT Creator's gdbmacros.dll loaded");
		}
		SetErrorMode(olderrors);
	}
#endif
	// Initialize crash reporting
	CrashHandler::Install();
	good_fpu_control_registers(__FUNCTION__);

	// CREG & GlobalConfig
	creg::System::InitializeClasses();
	GlobalConfig::Instantiate();

	// Create Window
	if (!InitWindow(("Spring " + SpringVersion::GetSync()).c_str())) {
		SDL_Quit();
		return false;
	}

	// Init OpenGL
	LoadExtensions(); // Initialize GLEW
	globalRendering->PostInit();
	InitOpenGL();

	// Install Watchdog (must happen after time epoch is set)
	Watchdog::Install();
	Watchdog::RegisterThread(WDT_MAIN, true);

	// ArchiveScanner uses for_mt --> needs thread-count set
	// (use all threads available, later switch to less)
	ThreadPool::SetThreadCount(ThreadPool::GetMaxThreads());
	FileSystemInitializer::Initialize();

	mouseInput = IMouseInput::GetInstance();
	input.AddHandler(boost::bind(&SpringApp::MainEventHandler, this, _1));

	// Global structures
	gs = new CGlobalSynced();
	gu = new CGlobalUnsynced();

	// GUIs
	agui::InitGui();
	LoadFonts();
	CNamedTextures::Init();
	LuaOpenGL::Init();
	ISound::Initialize();
	InitJoystick();

	// Lua socket restrictions
	luaSocketRestrictions = new CLuaSocketRestrictions();

	// Multithreading & Affinity
	Threading::SetThreadName("unknown"); // set default threadname
	Threading::InitThreadPool();
	Threading::SetThreadScheduler();
	battery = new CBattery();

	// Create CGameSetup and CPreGame objects
	Startup();

	return true;
}
Ejemplo n.º 18
0
int main(int argc, char *argv[])
{
	char cfg[MAX_FILE_NAME_SIZE]="config.json";
	
	float lPow,rPow;
	int state=STOP, stoppedState=RUN;
	int beaconToFollow=0;
	int ret = 0;
	rob_cfg_t rob_cfg;
	rob_state_t rob_state;
	struct beaconMeasure beacon;
	int totalBeacons = 0,curGroundSensor = -1;
	double elapsed1 = 0.0, elapsed2 = 0.0, realTotal = 0.0;
	struct timeval t1, t2, t3;
	bool firstTimeStart = 1;

	memset(&rob_state, 0, sizeof(rob_state_t));


	 /* processing arguments */
	while (argc > 2)
	{
		if (strcmp(argv[1], "-cfg") == 0)
		{
		   strncpy(cfg, argv[2], 99);
		   cfg[MAX_FILE_NAME_SIZE-1]='\0';
		}
		else
		{
				break; /* the while */
		}
		argc -= 2;
		argv += 2;
	}

	cfg_parser_parse(cfg, &rob_cfg);
	// int i;
	// for(i = 0; i < rob_cfg.rob_viewer_size; i++)
	// 	printf("Viewer: %s:%d\n", rob_cfg.rob_viewers[i].hostname, rob_cfg.rob_viewers[i].port);

	InitJoystick(rob_cfg.joys_dev);

	cfg_parser_connect_viewers(&rob_cfg);

	/* Connect Robot to simulator */
	if( InitRobot(rob_cfg.robo_name, rob_cfg.robo_pos, rob_cfg.hostname) == -1)
	{
		ret = 1;
		printf( "%s Failed to connect\n", rob_cfg.robo_name);
	}

	else
	{
		totalBeacons = GetNumberOfBeacons();

		printf( "Connected: %s, Total beacons: %d\n", rob_cfg.robo_name, totalBeacons);

		state=STOP;
		while(1)
		{
			/* Reading next values from Sensors */
			ReadSensors();

			if(GetFinished()) /* Simulator has received Finish() or Robot Removed */
			{
				printf(  "Exiting: %s\n", rob_cfg.robo_name );
				state = FINISHED;

				gettimeofday(&t3, NULL);

				elapsed2 = _get_elapsed_secs(&t2, &t3);
				realTotal = _get_elapsed_secs(&t1, &t3);

				printf("to beacon | to start | total | real total\n");
				printf("& %.2f & %.2f & %.2f & %.2f \n", elapsed1, elapsed2, elapsed1 + elapsed2, realTotal);

				break;
			}

			if(state==STOP && GetStartButton()) 
			{
				state=stoppedState;  /* Restart     */

				if( firstTimeStart )
				{
					firstTimeStart = 0;
					printf("Started counting elapsed time\n");
					
					gettimeofday(&t1, NULL);
				}
			}
			if(state!=STOP && GetStopButton())  {
				stoppedState=state;
				state=STOP; /* Interrupt */
			}

			curGroundSensor = GetGroundSensor();

			switch (state)
			{
				case RUN:    /* Go */
					
					if( GetVisitingLed() )
					{
						gettimeofday(&t2, NULL);

						elapsed1 = _get_elapsed_secs(&t1, &t2);

						printf("Elapsed from origin to beacon: %f\n", elapsed1);


						state = WAIT;
						DriveMotors(0.0,0.0);
					}
					else
					{
						if( curGroundSensor == beaconToFollow )
						{
							beaconToFollow++;
							SetVisitingLed(1);
							printf("%s visited target at %d\n", rob_cfg.robo_name, GetTime());
						}
						else {

							DetermineAction(beaconToFollow, &lPow, &rPow);
							DriveMotors(lPow, rPow);
						}
					}
				
					break;

				case RETURN:    /* Go */

					if( curGroundSensor == totalBeacons )
					{
						printf("%s found home at %d\n", rob_cfg.robo_name, GetTime());
						Finish();
					}
					else {
						DetermineAction(beaconToFollow, &lPow, &rPow);
						DriveMotors(lPow, rPow);
					}
				
					break;

				case WAIT: /* Wait for others to visit target */

					if(GetReturningLed())
					{
						SetVisitingLed(0);
						state = RETURN;

						gettimeofday(&t2, NULL);
					}

					DriveMotors(0.0,0.0);

					break;
			}

			//Say(rob_cfg.robo_name);


			rob_state.state = state;

			if( (rob_state.leftAvail = IsObstacleReady(LEFT)) )
				rob_state.left = GetObstacleSensor(LEFT);

			if( (rob_state.rightAvail = IsObstacleReady(RIGHT)) )
				rob_state.right = GetObstacleSensor(RIGHT);

			if( (rob_state.centerAvail = IsObstacleReady(CENTER)) )
				rob_state.center = GetObstacleSensor(CENTER);


			if(IsGPSReady())
			{
				rob_state.x = GetX();
				rob_state.y = GetY();
			}

			// if( IsGPSDirReady() )
			// 	rob_state.dir = GetDir();

			if( IsCompassReady() )
				rob_state.dir = GetCompassSensor();


			if( ( rob_state.beaconVis = IsBeaconReady(beaconToFollow) ) )
			{
				beacon = GetBeaconSensor(beaconToFollow);

				if( ( rob_state.beaconVis = beacon.beaconVisible ) )
					rob_state.beaconDir = beacon.beaconDir;
			}

			send_all_viewer_state_message(&rob_cfg, &rob_state);


			RequestCompassSensor();

			//Request Sensors for next cycle
			if(GetTime() % 2 == 0) {

				RequestObstacleSensor(CENTER);

				if(    (GetTime() % 8) == 0
					|| beaconToFollow == totalBeacons )
					RequestGroundSensor();
				else
					RequestBeaconSensor(beaconToFollow);

			}
			else {
				RequestSensors(2, "IRSensor1", "IRSensor2");
			}
		}

		send_all_viewer_state_message(&rob_cfg, &rob_state);

	}

	printf("Doing cleanup: %s\n", rob_cfg.robo_name);

	CloseAndFreeJoystick();

	cfg_parser_close(&rob_cfg);

	return ret;
}
Ejemplo n.º 19
0
/**
 * @brief Initializes the SpringApp instance
 * @return whether initialization was successful
 */
bool SpringApp::Initialize()
{
#if !(defined(WIN32) || defined(__APPLE__) || defined(HEADLESS))
	//! this MUST run before any other X11 call (esp. those by SDL!)
	//! we need it to make calls to X11 threadsafe
	if (!XInitThreads()) {
		LOG_L(L_FATAL, "Xlib is not thread safe");
		return false;
	}
#endif

#if defined(_WIN32) && defined(__GNUC__)
	// load QTCreator's gdb helper dll; a variant of this should also work on other OSes
	{
		// don't display a dialog box if gdb helpers aren't found
		UINT olderrors = SetErrorMode(SEM_FAILCRITICALERRORS);
		if (LoadLibrary("gdbmacros.dll")) {
			LOG("QT Creator's gdbmacros.dll loaded");
		}
		SetErrorMode(olderrors);
	}
#endif

	// Initialize class system
	creg::System::InitializeClasses();

	// Initialize crash reporting
	CrashHandler::Install();

	globalRendering = new CGlobalRendering();

	ParseCmdLine();
	CMyMath::Init();
	good_fpu_control_registers("::Run");

	// log OS version
	LOG("OS: %s", Platform::GetOS().c_str());
	if (Platform::Is64Bit())
		LOG("OS: 64bit native mode");
	else if (Platform::Is32BitEmulation())
		LOG("OS: emulated 32bit mode");
	else
		LOG("OS: 32bit native mode");

	// Rename Threads
	// We give the process itself the name `unknown`, htop & co. will still show the binary's name.
	// But all child threads copy by default the name of their parent, so all threads that don't set
	// their name themselves will show up as 'unknown'.
	Threading::SetThreadName("unknown");
#ifdef _OPENMP
	#pragma omp parallel
	{
		int i = omp_get_thread_num();
		if (i != 0) { // 0 is the source thread
			std::ostringstream buf;
			buf << "omp" << i;
			Threading::SetThreadName(buf.str().c_str());
		}
	}
#endif

	// Install Watchdog
	Watchdog::Install();
	Watchdog::RegisterThread(WDT_MAIN, true);

	FileSystemInitializer::Initialize();

	// Create Window
	if (!InitWindow(("Spring " + SpringVersion::GetSync()).c_str())) {
		SDL_Quit();
		return false;
	}

	mouseInput = IMouseInput::GetInstance();
	keyInput = KeyInput::GetInstance();
	input.AddHandler(boost::bind(&SpringApp::MainEventHandler, this, _1));

	// Global structures
	gs = new CGlobalSynced();
	gu = new CGlobalUnsynced();

	// Initialize GLEW
	LoadExtensions();

	//! check if FSAA init worked fine
	if (globalRendering->FSAA && !MultisampleVerify())
		globalRendering->FSAA = 0;

	InitOpenGL();
	agui::InitGui();
	LoadFonts();

	globalRendering->PostInit();

	// Initialize named texture handler
	CNamedTextures::Init();

	// Initialize Lua GL
	LuaOpenGL::Init();

	// Sound & Input
	ISound::Initialize();
	InitJoystick();

	// Multithreading & Affinity
	LOG("CPU Cores: %d", Threading::GetAvailableCores());
	const uint32_t affinity = configHandler->GetUnsigned("SetCoreAffinity");
	const uint32_t cpuMask  = Threading::SetAffinity(affinity);
	if (cpuMask == 0xFFFFFF) {
		LOG("CPU affinity not set");
	}
	else if (cpuMask != affinity) {
		LOG("CPU affinity mask set: %d (config is %d)", cpuMask, affinity);
	}
	else if (cpuMask == 0) {
		LOG_L(L_ERROR, "Failed to CPU affinity mask <%d>", affinity);
	}
	else {
		LOG("CPU affinity mask set: %d", cpuMask);
	}

	// Create CGameSetup and CPreGame objects
	Startup();

	return true;
}