Example #1
0
WiimoteWindows::~WiimoteWindows()
{
	Shutdown();
	CloseHandle(m_hid_overlap_read.hEvent);
	CloseHandle(m_hid_overlap_write.hEvent);
}
Example #2
0
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
    boost::thread_group threadGroup;
    boost::thread* detectShutdownThread = NULL;

    bool fRet = false;
    try
    {
        //
        // Parameters
        //
        // If Qt is used, parameters/unicoin.conf are parsed in qt/bitcoin.cpp's main()
        ParseParameters(argc, argv);
        if (!boost::filesystem::is_directory(GetDataDir(false)))
        {
            fprintf(stderr, "Error: Specified directory does not exist\n");
            Shutdown();
        }
        ReadConfigFile(mapArgs, mapMultiArgs);

        if (mapArgs.count("-?") || mapArgs.count("--help"))
        {
            // First part of help message is specific to unicoind / RPC client
            std::string strUsage = _("UniCoin version") + " " + FormatFullVersion() + "\n\n" +
                _("Usage:") + "\n" +
                  "  unicoind [options]                     " + "\n" +
                  "  unicoind [options] <command> [params]  " + _("Send command to -server or unicoind") + "\n" +
                  "  unicoind [options] help                " + _("List commands") + "\n" +
                  "  unicoind [options] help <command>      " + _("Get help for a command") + "\n";

            strUsage += "\n" + HelpMessage();

            fprintf(stdout, "%s", strUsage.c_str());
            return false;
        }

        // Command-line RPC
        for (int i = 1; i < argc; i++)
            if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "unicoin:"))
                fCommandLine = true;

        if (fCommandLine)
        {
            if (!SelectParamsFromCommandLine()) {
                fprintf(stderr, "Error: invalid combination of -regtest and -testnet.\n");
                return false;
            }
            int ret = CommandLineRPC(argc, argv);
            exit(ret);
        }
#if !defined(WIN32)
        fDaemon = GetBoolArg("-daemon", false);
        if (fDaemon)
        {
            // Daemonize
            pid_t pid = fork();
            if (pid < 0)
            {
                fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
                return false;
            }
            if (pid > 0) // Parent process, pid is child process id
            {
                CreatePidFile(GetPidFile(), pid);
                return true;
            }
            // Child process falls through to rest of initialization

            pid_t sid = setsid();
            if (sid < 0)
                fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
        }
#endif

        detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
        fRet = AppInit2(threadGroup);
    }
    catch (std::exception& e) {
        PrintExceptionContinue(&e, "AppInit()");
    } catch (...) {
        PrintExceptionContinue(NULL, "AppInit()");
    }
    if (!fRet) {
        if (detectShutdownThread)
            detectShutdownThread->interrupt();
        threadGroup.interrupt_all();
    }

    if (detectShutdownThread)
    {
        detectShutdownThread->join();
        delete detectShutdownThread;
        detectShutdownThread = NULL;
    }
    Shutdown();

    return fRet;
}
// Handle keyboard events
//-----------------------------------------------------------------------------
CPUTEventHandledCode MySample::HandleKeyboardEvent(CPUTKey key)
{
    static bool panelToggle = false;
    CPUTEventHandledCode    handled = CPUT_EVENT_UNHANDLED;
    cString fileName;
    CPUTGuiControllerDX11*  pGUI = CPUTGetGuiController();

    switch(key)
    {
    case KEY_F1:
        panelToggle = !panelToggle;
        if(panelToggle)
        {
            pGUI->SetActivePanel(ID_SECONDARY_PANEL);
        }
        else
        {
            pGUI->SetActivePanel(ID_MAIN_PANEL);
        }
        handled = CPUT_EVENT_HANDLED;
        break;
    case KEY_L:
        {
            static int cameraObjectIndex = 0;
            CPUTRenderNode *pCameraList[] = { mpCamera, mpShadowCamera };
            cameraObjectIndex = (++cameraObjectIndex) % (sizeof(pCameraList)/sizeof(*pCameraList));
            CPUTRenderNode *pCamera = pCameraList[cameraObjectIndex];
            mpCameraController->SetCamera( pCamera );
        }
        handled = CPUT_EVENT_HANDLED;
        break;
    case KEY_ESCAPE:
        handled = CPUT_EVENT_HANDLED;
        Shutdown();
        break;

	case KEY_1:
		{
			CPUTToggleFullScreenMode();
			break;
		}
	case KEY_2:
		{
			mEnableCulling = !mEnableCulling;
			CPUTCheckboxState state;
			if(mEnableCulling)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else 
			{
				state = CPUT_CHECKBOX_UNCHECKED;
				memset(mpCPUDepthBuf[mCurrId], 0, SCREENW * SCREENH *4);

				mpOccludersR2DBText->SetText(         _L("\tDepth rasterized models: 0"));
				mpOccluderRasterizedTrisText->SetText(_L("\tDepth rasterized tris: \t0"));
				mpRasterizeTimeText->SetText(         _L("\tDepth rasterizer time: \t0 ms"));

				mpCulledText->SetText(       _L("\tModels culled: \t\t0"));
				mpVisibleText->SetText(      _L("\tModels visible: \t\t0"));
				mpCulledTrisText->SetText(   _L("\tCulled tris: \t\t0"));
				mpVisibleTrisText->SetText(   _L("\tVisible tris: \t\t0"));
				mpDepthTestTimeText->SetText(_L("\tDepth test time: \t0 ms"));
			}
			mpCullingCheckBox->SetCheckboxState(state);
			break;
		}
	case KEY_3:
		{
			mEnableFCulling = !mEnableFCulling;
			CPUTCheckboxState state;
			if(mEnableFCulling)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else
			{
				state = CPUT_CHECKBOX_UNCHECKED;
				mpDBR->ResetInsideFrustum();
				mpAABB->ResetInsideFrustum();
			}
			mpFCullingCheckBox->SetCheckboxState(state);
			break;			
		}
	case KEY_4:
		{
			mViewDepthBuffer = !mViewDepthBuffer;
			CPUTCheckboxState state;
			if(mViewDepthBuffer)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else 
			{
				state = CPUT_CHECKBOX_UNCHECKED;
			}
			mpDBCheckBox->SetCheckboxState(state);
			break;
		}
	case KEY_5:
		{
			mViewBoundingBox = !mViewBoundingBox;
			CPUTCheckboxState state;
			if(mViewBoundingBox)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else
			{
				state = CPUT_CHECKBOX_UNCHECKED;
			}
			mpBBCheckBox->SetCheckboxState(state);
			break;
		}
	case KEY_6:
		{
			TaskCleanUp();
			mEnableTasks = !mEnableTasks;
			CPUTCheckboxState state;
			
			SAFE_DELETE_ARRAY(mpDBR);
			SAFE_DELETE_ARRAY(mpAABB);

			if(mEnableTasks)
			{
				state = CPUT_CHECKBOX_CHECKED;
				mpPipelineCheckBox->SetVisibility(true);
				mpDepthTestTaskSlider->SetVisibility(true);

				wchar_t string[CPUT_MAX_STRING_LENGTH];
				swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("Depth Test Task: \t%d"), mNumDepthTestTasks);
				mpDepthTestTaskSlider->SetText(string);
			
				if(mSOCType == SCALAR_TYPE)
				{
					mpDBRScalarMT = new DepthBufferRasterizerScalarMT;
					mpDBR = mpDBRScalarMT;

					mpAABBScalarMT = new AABBoxRasterizerScalarMT;
					mpAABB = mpAABBScalarMT;
				}
				else if(mSOCType == SSE_TYPE)
				{
					mpDBRSSEMT = new DepthBufferRasterizerSSEMT;
					mpDBR = mpDBRSSEMT;
					
					mpAABBSSEMT = new AABBoxRasterizerSSEMT;
					mpAABB = mpAABBSSEMT;
				}
				mpAABB->SetDepthTestTasks(mNumDepthTestTasks);
			}
			else
			{
				state = CPUT_CHECKBOX_UNCHECKED;
				mpPipelineCheckBox->SetVisibility(false);
				mpDepthTestTaskSlider->SetVisibility(false);
				if(mSOCType == SCALAR_TYPE)
				{
					mpDBRScalarST = new DepthBufferRasterizerScalarST;
					mpDBR = mpDBRScalarST;
	
					mpAABBScalarST = new AABBoxRasterizerScalarST;
					mpAABB = mpAABBScalarST;
				}
				else if(mSOCType == SSE_TYPE)
				{
					mpDBRSSEST = new DepthBufferRasterizerSSEST;
					mpDBR = mpDBRSSEST;
					
					mpAABBSSEST = new AABBoxRasterizerSSEST;
					mpAABB = mpAABBSSEST;
				}	
			}
			mpDBR->CreateTransformedModels(mpAssetSetDBR, OCCLUDER_SETS);		
			mpDBR->SetOccluderSizeThreshold(mOccluderSizeThreshold);
			mpAABB->CreateTransformedAABBoxes(mpAssetSetAABB, OCCLUDEE_SETS);
			mpAABB->SetOccludeeSizeThreshold(mOccludeeSizeThreshold);
			mpTasksCheckBox->SetCheckboxState(state);
			break;
		}
	case KEY_7:
		{
			if(mSyncInterval == 1)
			{
				mSyncInterval = 0;
			}
			else 
			{
				mSyncInterval = 1;
			}
			CPUTCheckboxState state;
			if(mSyncInterval == 1)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else
			{
				state = CPUT_CHECKBOX_UNCHECKED;
			}
			mpVsyncCheckBox->SetCheckboxState(state);
			break;
		}
	case KEY_8:
		{
			TaskCleanUp();
			mPipeline = !mPipeline;
			CPUTCheckboxState state;
			if(mPipeline)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else
			{
				state = CPUT_CHECKBOX_UNCHECKED;
			}
			mpPipelineCheckBox->SetCheckboxState(state);
			break;
		}
    }
	

    // pass it to the camera controller
    if(handled == CPUT_EVENT_UNHANDLED)
    {
        handled = mpCameraController->HandleKeyboardEvent(key);
    }
    return handled;
}
Example #4
0
/*
============
idAASBuild::Build
============
*/
bool idAASBuild::Build( const idStr &fileName, const idAASSettings *settings ) {
	int i, bit, mask, startTime;
	idMapFile * mapFile;
	idBrushList brushList;
	idList<idBrushList*> expandedBrushes;
	idBrush *b;
	idBrushBSP bsp;
	idStr name;
	idAASReach reach;
	idAASCluster cluster;
	idStrList entityClassNames;

	startTime = sys->Milliseconds();

	Shutdown();

	aasSettings = settings;

	name = fileName;
	name.SetFileExtension( "map" );

	mapFile = new idMapFile;
	if ( !mapFile->Parse( name ) ) {
		delete mapFile;
		common->Error( "Couldn't load map file: '%s'", name.c_str() );
		return false;
	}

	// check if this map has any entities that use this AAS file
	if ( !CheckForEntities( mapFile, entityClassNames ) ) {
		delete mapFile;
		common->Printf( "no entities in map that use %s\n", settings->fileExtension.c_str() );
		return true;
	}

	// load map file brushes
	brushList = AddBrushesForMapFile( mapFile, brushList );

	// if empty map
	if ( brushList.Num() == 0 ) {
		delete mapFile;
		common->Error( "%s is empty", name.c_str() );
		return false;
	}

	// merge as many brushes as possible before expansion
	brushList.Merge( MergeAllowed );

	// if there is a .proc file newer than the .map file
	if ( LoadProcBSP( fileName, mapFile->GetFileTime() ) ) {
		ClipBrushSidesWithProcBSP( brushList );
		DeleteProcBSP();
	}

	// make copies of the brush list
	expandedBrushes.Append( &brushList );
	for ( i = 1; i < aasSettings->numBoundingBoxes; i++ ) {
		expandedBrushes.Append( brushList.Copy() );
	}

	// expand brushes for the axial bounding boxes
	mask = AREACONTENTS_SOLID;
	for ( i = 0; i < expandedBrushes.Num(); i++ ) {
		for ( b = expandedBrushes[i]->Head(); b; b = b->Next() ) {
			b->ExpandForAxialBox( aasSettings->boundingBoxes[i] );
			bit = 1 << ( i + AREACONTENTS_BBOX_BIT );
			mask |= bit;
			b->SetContents( b->GetContents() | bit );
		}
	}

	// move all brushes back into the original list
	for ( i = 1; i < aasSettings->numBoundingBoxes; i++ ) {
		brushList.AddToTail( *expandedBrushes[i] );
		delete expandedBrushes[i];
	}

	if ( aasSettings->writeBrushMap ) {
		bsp.WriteBrushMap( fileName, "_" + aasSettings->fileExtension, AREACONTENTS_SOLID );
	}

	// build BSP tree from brushes
	bsp.Build( brushList, AREACONTENTS_SOLID, ExpandedChopAllowed, ExpandedMergeAllowed );

	// only solid nodes with all bits set for all bounding boxes need to stay solid
	ChangeMultipleBoundingBoxContents_r( bsp.GetRootNode(), mask );

	// portalize the bsp tree
	bsp.Portalize();

	// remove subspaces not reachable by entities
	if ( !bsp.RemoveOutside( mapFile, AREACONTENTS_SOLID, entityClassNames ) ) {
		bsp.LeakFile( name );
		delete mapFile;
		common->Printf( "%s has no outside", name.c_str() );
		return false;
	}

	// gravitational subdivision
	GravitationalSubdivision( bsp );

	// merge portals where possible
	bsp.MergePortals( AREACONTENTS_SOLID );

	// melt portal windings
	bsp.MeltPortals( AREACONTENTS_SOLID );

	if ( aasSettings->writeBrushMap ) {
		WriteLedgeMap( fileName, "_" + aasSettings->fileExtension + "_ledge" );
	}

	// ledge subdivisions
	LedgeSubdivision( bsp );

	// merge leaf nodes
	MergeLeafNodes( bsp );

	// merge portals where possible
	bsp.MergePortals( AREACONTENTS_SOLID );

	// melt portal windings
	bsp.MeltPortals( AREACONTENTS_SOLID );

	// store the file from the bsp tree
	StoreFile( bsp );
	file->settings = *aasSettings;

	// calculate reachability
	reach.Build( mapFile, file );

	// build clusters
	cluster.Build( file );

	// optimize the file
	if ( !aasSettings->noOptimize ) {
		file->Optimize();
	}

	// write the file
	name.SetFileExtension( aasSettings->fileExtension );
	file->Write( name, mapFile->GetGeometryCRC() );

	// delete the map file
	delete mapFile;

	common->Printf( "%6d seconds to create AAS\n", (sys->Milliseconds() - startTime) / 1000 );

	return true;
}
Example #5
0
/*
============
idAASLocal::~idAASLocal
============
*/
idAASLocal::~idAASLocal( void )
{
	Shutdown();
}
Example #6
0
Keyboard::~Keyboard() { 
	Shutdown(); 
}
 void Engine::fatalerror(std::string message, std::string title)
 {
     this->message(message,title);
     Shutdown();
 }
Example #8
0
short dlgStartupShowModal(void){
  WndProperty* wp;

  #if TESTBENCH
  StartupStore(TEXT(". Startup dialog, RUN_MODE=%d %s"),RUN_MODE,NEWLINE);
  #endif

  char filename[MAX_PATH];
  strcpy(filename,"");

  // FLY SIM PROFILE EXIT
  if (RUN_MODE==RUN_WELCOME) {
	if (!ScreenLandscape) {
		LocalPathS(filename, TEXT("dlgFlySim_L.xml"));
		wf = dlgLoadFromXML(CallBackTable, filename, hWndMainWindow, TEXT("IDR_XML_FLYSIM_L"));
	} else {
		LocalPathS(filename, TEXT("dlgFlySim.xml"));
		wf = dlgLoadFromXML(CallBackTable, filename, hWndMainWindow, TEXT("IDR_XML_FLYSIM"));
	}
	if (!wf) {
		return 0;
	}
  }

  //  PROFILE AIRCRAFT  CLOSE
  if (RUN_MODE==RUN_DUALPROF) {
	if (!ScreenLandscape) {
		LocalPathS(filename, TEXT("dlgDualProfile_L.xml"));
		wf = dlgLoadFromXML(CallBackTable, filename, hWndMainWindow, TEXT("IDR_XML_DUALPROFILE_L"));
	} else {
		LocalPathS(filename, TEXT("dlgDualProfile.xml"));
		wf = dlgLoadFromXML(CallBackTable, filename, hWndMainWindow, TEXT("IDR_XML_DUALPROFILE"));
	}
	if (!wf) return 0;
  }

  // CHOOSE PROFILE
  if (RUN_MODE==RUN_PROFILE || RUN_MODE==RUN_AIRCRAFT || RUN_MODE==RUN_PILOT) {
	if (!ScreenLandscape) {
		LocalPathS(filename, TEXT("dlgStartup_L.xml"));
		wf = dlgLoadFromXML(CallBackTable, filename, hWndMainWindow, TEXT("IDR_XML_STARTUP_L"));
	} else {
		LocalPathS(filename, TEXT("dlgStartup.xml"));
		wf = dlgLoadFromXML(CallBackTable, filename, hWndMainWindow, TEXT("IDR_XML_STARTUP"));
	}
	if (!wf) return 0;
  }

  wSplash = (WndOwnerDrawFrame*)wf->FindByName(TEXT("frmSplash")); 
  wSplash->SetWidth(ScreenSizeX);


  int  PROFWIDTH=0, PROFACCEPTWIDTH=0, PROFHEIGHT=0, PROFSEPARATOR=0;

  if (RUN_MODE==RUN_WELCOME) {
	((WndButton *)wf->FindByName(TEXT("cmdFLY"))) ->SetOnClickNotify(OnFLYClicked);
	((WndButton *)wf->FindByName(TEXT("cmdSIM"))) ->SetOnClickNotify(OnSIMClicked);
	((WndButton *)wf->FindByName(TEXT("cmdDUALPROFILE"))) ->SetOnClickNotify(OnDUALPROFILEClicked);
	((WndButton *)wf->FindByName(TEXT("cmdEXIT"))) ->SetOnClickNotify(OnEXITClicked);
	if (ScreenLandscape) {
		
		PROFWIDTH=(ScreenSizeX-IBLSCALE(320))/3; 


		switch(ScreenSize) {
			case ss800x480:
			case ss400x240:
				((WndButton *)wf->FindByName(TEXT("cmdFLY"))) ->SetWidth(IBLSCALE(110));
				((WndButton *)wf->FindByName(TEXT("cmdSIM"))) ->SetWidth(IBLSCALE(110));
				((WndButton *)wf->FindByName(TEXT("cmdSIM"))) ->SetLeft(IBLSCALE(208)+PROFWIDTH*3);
				((WndButton *)wf->FindByName(TEXT("cmdDUALPROFILE"))) ->SetLeft(IBLSCALE(88)+PROFWIDTH);
				((WndButton *)wf->FindByName(TEXT("cmdDUALPROFILE"))) ->SetWidth(IBLSCALE(92)+PROFWIDTH/6);
				((WndButton *)wf->FindByName(TEXT("cmdEXIT"))) ->SetLeft(IBLSCALE(161)+PROFWIDTH*2);
				((WndButton *)wf->FindByName(TEXT("cmdEXIT"))) ->SetWidth(IBLSCALE(65)+PROFWIDTH/5);
				break;
			case ss480x272:
				((WndButton *)wf->FindByName(TEXT("cmdFLY"))) ->SetWidth(IBLSCALE(117));
				((WndButton *)wf->FindByName(TEXT("cmdFLY"))) ->SetHeight(IBLSCALE(38));
				((WndButton *)wf->FindByName(TEXT("cmdFLY"))) ->SetTop(IBLSCALE(197));
				((WndButton *)wf->FindByName(TEXT("cmdSIM"))) ->SetWidth(IBLSCALE(117));
				((WndButton *)wf->FindByName(TEXT("cmdSIM"))) ->SetLeft(IBLSCALE(201)+PROFWIDTH*3);
				((WndButton *)wf->FindByName(TEXT("cmdSIM"))) ->SetHeight(IBLSCALE(38));
				((WndButton *)wf->FindByName(TEXT("cmdSIM"))) ->SetTop(IBLSCALE(197));
				((WndButton *)wf->FindByName(TEXT("cmdDUALPROFILE"))) ->SetLeft(IBLSCALE(88)+PROFWIDTH);
				((WndButton *)wf->FindByName(TEXT("cmdDUALPROFILE"))) ->SetWidth(IBLSCALE(99)+PROFWIDTH/6);
				((WndButton *)wf->FindByName(TEXT("cmdDUALPROFILE"))) ->SetHeight(IBLSCALE(38));
				((WndButton *)wf->FindByName(TEXT("cmdDUALPROFILE"))) ->SetTop(IBLSCALE(197));
				((WndButton *)wf->FindByName(TEXT("cmdEXIT"))) ->SetLeft(IBLSCALE(161)+PROFWIDTH*2);
				((WndButton *)wf->FindByName(TEXT("cmdEXIT"))) ->SetWidth(IBLSCALE(65)+PROFWIDTH/5);
				((WndButton *)wf->FindByName(TEXT("cmdEXIT"))) ->SetHeight(IBLSCALE(38));
				((WndButton *)wf->FindByName(TEXT("cmdEXIT"))) ->SetTop(IBLSCALE(197));
				break;
			case ss640x480:
			case ss320x240:
				((WndButton *)wf->FindByName(TEXT("cmdDUALPROFILE"))) ->SetLeft(IBLSCALE(93)+PROFWIDTH);
				((WndButton *)wf->FindByName(TEXT("cmdDUALPROFILE"))) ->SetWidth(IBLSCALE(73)+PROFWIDTH/6);
				((WndButton *)wf->FindByName(TEXT("cmdEXIT"))) ->SetLeft(IBLSCALE(166)+PROFWIDTH*2);
				((WndButton *)wf->FindByName(TEXT("cmdEXIT"))) ->SetWidth(IBLSCALE(60)+PROFWIDTH/5);
				((WndButton *)wf->FindByName(TEXT("cmdSIM"))) ->SetLeft(IBLSCALE(228)+PROFWIDTH*3);
				((WndButton *)wf->FindByName(TEXT("cmdSIM"))) ->SetWidth(IBLSCALE(88));
				break;
			default:
				((WndButton *)wf->FindByName(TEXT("cmdDUALPROFILE"))) ->SetLeft(IBLSCALE(93)+PROFWIDTH);
				((WndButton *)wf->FindByName(TEXT("cmdDUALPROFILE"))) ->SetWidth(IBLSCALE(73)+PROFWIDTH/6);
				((WndButton *)wf->FindByName(TEXT("cmdEXIT"))) ->SetLeft(IBLSCALE(166)+PROFWIDTH*2);
				((WndButton *)wf->FindByName(TEXT("cmdEXIT"))) ->SetWidth(IBLSCALE(60)+PROFWIDTH/5);
				((WndButton *)wf->FindByName(TEXT("cmdSIM"))) ->SetLeft(IBLSCALE(228)+PROFWIDTH*3);
				break;
		}	
	} else {
		PROFWIDTH=IBLSCALE(236);
		PROFACCEPTWIDTH=NIBLSCALE(45);
		PROFHEIGHT=NIBLSCALE(25);
		PROFSEPARATOR=NIBLSCALE(2);
	}
  }

  if (RUN_MODE==RUN_DUALPROF) {
	((WndButton *)wf->FindByName(TEXT("cmdAIRCRAFT"))) ->SetOnClickNotify(OnAIRCRAFTClicked);
	((WndButton *)wf->FindByName(TEXT("cmdPROFILE"))) ->SetOnClickNotify(OnPROFILEClicked);
	((WndButton *)wf->FindByName(TEXT("cmdPILOT"))) ->SetOnClickNotify(OnPILOTClicked);
	((WndButton *)wf->FindByName(TEXT("cmdCLOSE"))) ->SetOnClickNotify(OnCloseClicked);

	//((WndButton *)wf->FindByName(TEXT("cmdFLY"))) ->SetOnClickNotify(OnFLYClicked);
	//((WndButton *)wf->FindByName(TEXT("cmdSIM"))) ->SetOnClickNotify(OnSIMClicked);
	//((WndButton *)wf->FindByName(TEXT("cmdDUALPROFILE"))) ->SetOnClickNotify(OnDUALPROFILEClicked);
	//((WndButton *)wf->FindByName(TEXT("cmdEXIT"))) ->SetOnClickNotify(OnEXITClicked);
	if (ScreenLandscape) {
		
		PROFWIDTH=(ScreenSizeX-IBLSCALE(320))/3; 


		switch(ScreenSize) {
			case ss800x480:
			case ss400x240:
				((WndButton *)wf->FindByName(TEXT("cmdAIRCRAFT"))) ->SetWidth(IBLSCALE(110));
				((WndButton *)wf->FindByName(TEXT("cmdCLOSE"))) ->SetWidth(IBLSCALE(110));
				((WndButton *)wf->FindByName(TEXT("cmdCLOSE"))) ->SetLeft(IBLSCALE(208)+PROFWIDTH*3);
				((WndButton *)wf->FindByName(TEXT("cmdPROFILE"))) ->SetLeft(IBLSCALE(88)+PROFWIDTH);
				((WndButton *)wf->FindByName(TEXT("cmdPROFILE"))) ->SetWidth(IBLSCALE(92)+PROFWIDTH/6);
				((WndButton *)wf->FindByName(TEXT("cmdPILOT"))) ->SetLeft(IBLSCALE(161)+PROFWIDTH*2);
				((WndButton *)wf->FindByName(TEXT("cmdPILOT"))) ->SetWidth(IBLSCALE(65)+PROFWIDTH/5);
				break;
			case ss480x272:
				((WndButton *)wf->FindByName(TEXT("cmdAIRCRAFT"))) ->SetWidth(IBLSCALE(117));
				((WndButton *)wf->FindByName(TEXT("cmdAIRCRAFT"))) ->SetHeight(IBLSCALE(38));
				((WndButton *)wf->FindByName(TEXT("cmdAIRCRAFT"))) ->SetTop(IBLSCALE(197));
				((WndButton *)wf->FindByName(TEXT("cmdCLOSE"))) ->SetWidth(IBLSCALE(117));
				((WndButton *)wf->FindByName(TEXT("cmdCLOSE"))) ->SetLeft(IBLSCALE(201)+PROFWIDTH*3);
				((WndButton *)wf->FindByName(TEXT("cmdCLOSE"))) ->SetHeight(IBLSCALE(38));
				((WndButton *)wf->FindByName(TEXT("cmdCLOSE"))) ->SetTop(IBLSCALE(197));
				((WndButton *)wf->FindByName(TEXT("cmdPROFILE"))) ->SetLeft(IBLSCALE(88)+PROFWIDTH);
				((WndButton *)wf->FindByName(TEXT("cmdPROFILE"))) ->SetWidth(IBLSCALE(99)+PROFWIDTH/6);
				((WndButton *)wf->FindByName(TEXT("cmdPROFILE"))) ->SetHeight(IBLSCALE(38));
				((WndButton *)wf->FindByName(TEXT("cmdPROFILE"))) ->SetTop(IBLSCALE(197));
				((WndButton *)wf->FindByName(TEXT("cmdPILOT"))) ->SetLeft(IBLSCALE(161)+PROFWIDTH*2);
				((WndButton *)wf->FindByName(TEXT("cmdPILOT"))) ->SetWidth(IBLSCALE(65)+PROFWIDTH/5);
				((WndButton *)wf->FindByName(TEXT("cmdPILOT"))) ->SetHeight(IBLSCALE(38));
				((WndButton *)wf->FindByName(TEXT("cmdPILOT"))) ->SetTop(IBLSCALE(197));
				break;
			case ss640x480:
			case ss320x240:
				((WndButton *)wf->FindByName(TEXT("cmdPROFILE"))) ->SetLeft(IBLSCALE(93)+PROFWIDTH);
				((WndButton *)wf->FindByName(TEXT("cmdPROFILE"))) ->SetWidth(IBLSCALE(73)+PROFWIDTH/6);
				((WndButton *)wf->FindByName(TEXT("cmdPILOT"))) ->SetLeft(IBLSCALE(166)+PROFWIDTH*2);
				((WndButton *)wf->FindByName(TEXT("cmdPILOT"))) ->SetWidth(IBLSCALE(60)+PROFWIDTH/5);
				((WndButton *)wf->FindByName(TEXT("cmdCLOSE"))) ->SetLeft(IBLSCALE(228)+PROFWIDTH*3);
				((WndButton *)wf->FindByName(TEXT("cmdCLOSE"))) ->SetWidth(IBLSCALE(88));
				break;
			default:
				((WndButton *)wf->FindByName(TEXT("cmdPROFILE"))) ->SetLeft(IBLSCALE(93)+PROFWIDTH);
				((WndButton *)wf->FindByName(TEXT("cmdPROFILE"))) ->SetWidth(IBLSCALE(73)+PROFWIDTH/6);
				((WndButton *)wf->FindByName(TEXT("cmdPILOT"))) ->SetLeft(IBLSCALE(166)+PROFWIDTH*2);
				((WndButton *)wf->FindByName(TEXT("cmdPILOT"))) ->SetWidth(IBLSCALE(60)+PROFWIDTH/5);
				((WndButton *)wf->FindByName(TEXT("cmdCLOSE"))) ->SetLeft(IBLSCALE(228)+PROFWIDTH*3);
				break;
		}	
	} else {
		PROFWIDTH=IBLSCALE(236);
		PROFACCEPTWIDTH=NIBLSCALE(45);
		PROFHEIGHT=NIBLSCALE(25);
		PROFSEPARATOR=NIBLSCALE(2);
	}
  }



  if (RUN_MODE==RUN_PROFILE || RUN_MODE==RUN_AIRCRAFT || RUN_MODE==RUN_PILOT) {
	((WndButton *)wf->FindByName(TEXT("cmdClose"))) ->SetOnClickNotify(OnCloseClicked);
	if (ScreenLandscape) {
		PROFWIDTH=IBLSCALE(256);
		PROFACCEPTWIDTH=NIBLSCALE(60);
		PROFHEIGHT=NIBLSCALE(30);
		PROFSEPARATOR=NIBLSCALE(4);
		((WndButton *)wf->FindByName(TEXT("cmdClose"))) ->SetWidth(PROFACCEPTWIDTH);
		((WndButton *)wf->FindByName(TEXT("cmdClose"))) ->
			SetLeft((((ScreenSizeX-PROFWIDTH-PROFSEPARATOR-PROFACCEPTWIDTH)/2)+PROFSEPARATOR+PROFWIDTH)-NIBLSCALE(2));
		((WndButton *)wf->FindByName(TEXT("cmdClose"))) ->SetHeight(PROFHEIGHT-NIBLSCALE(4));
	} else {
		PROFWIDTH=IBLSCALE(236);
		PROFACCEPTWIDTH=NIBLSCALE(45);
		PROFHEIGHT=NIBLSCALE(25);
		PROFSEPARATOR=NIBLSCALE(2);
		((WndButton *)wf->FindByName(TEXT("cmdClose"))) ->SetWidth(ScreenSizeX-NIBLSCALE(6));
		((WndButton *)wf->FindByName(TEXT("cmdClose"))) -> SetLeft(NIBLSCALE(2));
	}
  }

  TCHAR temp[MAX_PATH];

  wf->SetHeight(ScreenSizeY);
  wf->SetWidth(ScreenSizeX);

  wp = ((WndProperty *)wf->FindByName(TEXT("prpProfile")));
  if (wp) {
    DataFieldFileReader* dfe;
    dfe = (DataFieldFileReader*)wp->GetDataField();

    if (RUN_MODE==RUN_PROFILE) {
	    _stprintf(temp,_T("*%S"),LKS_PRF); 
	    dfe->ScanDirectoryTop(_T(LKD_CONF),temp); 
	    dfe->addFile(gettext(_T("_@M1741_")),_T("PROFILE_RESET")); 
	    dfe->Lookup(startProfileFile);
    } 
    if (RUN_MODE==RUN_AIRCRAFT) {
	    _stprintf(temp,_T("*%S"),LKS_AIRCRAFT); 
	    dfe->ScanDirectoryTop(_T(LKD_CONF),temp); 
	    dfe->Lookup(startAircraftFile);
    }
    if (RUN_MODE==RUN_PILOT) {
	    _stprintf(temp,_T("*%S"),LKS_PILOT); 
	    dfe->ScanDirectoryTop(_T(LKD_CONF),temp); 
	    dfe->Lookup(startPilotFile);
    }

    wp->SetHeight(PROFHEIGHT);
    wp->SetWidth(PROFWIDTH);
    if (ScreenLandscape)
    	wp->SetLeft(((ScreenSizeX-PROFWIDTH-PROFSEPARATOR-PROFACCEPTWIDTH)/2)-NIBLSCALE(2));
    else
    	wp->SetLeft(0);

    wp->RefreshDisplay();
  }



  if  (!CheckRootDir()) {
	TCHAR mydir[MAX_PATH];
	TCHAR mes[MAX_PATH];

	LocalPath(mydir,_T(""));
	_stprintf(mes,_T("%s"),mydir);
	MessageBoxX(hWndMainWindow, _T("NO LK8000 DIRECTORY\nCheck Installation!"), _T("FATAL ERROR 000"), MB_OK|MB_ICONQUESTION);
	MessageBoxX(hWndMainWindow, mes, _T("NO LK8000 DIRECTORY"), MB_OK|MB_ICONQUESTION, true);
	RUN_MODE=RUN_EXIT;
	Shutdown();
	goto _exit;
  }

  if  (!CheckDataDir()) {
	TCHAR mydir[MAX_PATH];
	TCHAR mes[MAX_PATH];

	LocalPath(mydir,_T(LKD_SYSTEM));
	_stprintf(mes,_T("%s"),mydir);
	MessageBoxX(hWndMainWindow, _T("NO SYSTEM DIRECTORY\nCheck Installation!"), _T("FATAL ERROR 001"), MB_OK|MB_ICONQUESTION);
	MessageBoxX(hWndMainWindow, mes, _T("NO SYSTEM DIRECTORY"), MB_OK|MB_ICONQUESTION, true);
	RUN_MODE=RUN_EXIT;
	Shutdown();
	goto _exit;
  }

  if  (!CheckLanguageDir()) {
	TCHAR mydir[MAX_PATH];
	TCHAR mes[MAX_PATH];
	StartupStore(_T("... CHECK LANGUAGE DIRECTORY FAILED!%s"),NEWLINE);

	LocalPath(mydir,_T(LKD_LANGUAGE));
	_stprintf(mes,_T("%s"),mydir);
	MessageBoxX(hWndMainWindow, _T("LANGUAGE DIRECTORY CHECK FAIL\nCheck Language Install"), _T("FATAL ERROR 002"), MB_OK|MB_ICONQUESTION);
	MessageBoxX(hWndMainWindow, mes, _T("NO LANGUAGE DIRECTORY"), MB_OK|MB_ICONQUESTION, true);
	RUN_MODE=RUN_EXIT;
	Shutdown();
	goto _exit;
  }
  if  (!CheckLanguageEngMsg()) {
	TCHAR mydir[MAX_PATH];
	TCHAR mes[MAX_PATH];
	StartupStore(_T("... CHECK LANGUAGE ENG_MSG FAILED!%s"),NEWLINE);
	LocalPath(mydir,_T(LKD_LANGUAGE));
	_stprintf(mes,_T("%s/ENG_MSG.TXT"),mydir);
	MessageBoxX(hWndMainWindow, _T("ENG_MSG.TXT MISSING in LANGUAGE\nCheck Language Install"), _T("FATAL ERROR 012"), MB_OK|MB_ICONQUESTION);
	MessageBoxX(hWndMainWindow, mes, _T("MISSING FILE!"), MB_OK|MB_ICONQUESTION, true);
	RUN_MODE=RUN_EXIT;
	Shutdown();
	goto _exit;
  }
  if  (!CheckSystemDefaultMenu()) {
	TCHAR mydir[MAX_PATH];
	TCHAR mes[MAX_PATH];
	StartupStore(_T("... CHECK SYSTEM DEFAULT_MENU.TXT FAILED!%s"),NEWLINE);
	LocalPath(mydir,_T(LKD_SYSTEM));
	_stprintf(mes,_T("%s/DEFAULT_MENU.TXT"),mydir);
	MessageBoxX(hWndMainWindow, _T("DEFAULT_MENU.TXT MISSING in SYSTEM\nCheck System Install"), _T("FATAL ERROR 022"), MB_OK|MB_ICONQUESTION);
	MessageBoxX(hWndMainWindow, mes, _T("MISSING FILE!"), MB_OK|MB_ICONQUESTION, true);
	RUN_MODE=RUN_EXIT;
	Shutdown();
	goto _exit;
  }

  if  (!CheckSystemBitmaps()) {
	TCHAR mydir[MAX_PATH];
	TCHAR mes[MAX_PATH];
	StartupStore(_T("... CHECK SYSTEM _BITMAPSH FAILED!%s"),NEWLINE);
	LocalPath(mydir,_T(LKD_BITMAPS));
	_stprintf(mes,_T("%s/_BITMAPSH"),mydir);
	MessageBoxX(hWndMainWindow, _T("_BITMAPSH MISSING in SYSTEM Bitmaps\nCheck System Install"), _T("FATAL ERROR 032"), MB_OK|MB_ICONQUESTION);
	MessageBoxX(hWndMainWindow, mes, _T("MISSING FILE!"), MB_OK|MB_ICONQUESTION, true);
	RUN_MODE=RUN_EXIT;
	Shutdown();
	goto _exit;
  }

  if  (!CheckPolarsDir()) {
	TCHAR mydir[MAX_PATH];
	TCHAR mes[MAX_PATH];
	StartupStore(_T("... CHECK POLARS DIRECTORY FAILED!%s"),NEWLINE);

	LocalPath(mydir,_T(LKD_POLARS));
	_stprintf(mes,_T("%s"),mydir);
	MessageBoxX(hWndMainWindow, _T("NO POLARS DIRECTORY\nCheck Install"), _T("FATAL ERROR 003"), MB_OK|MB_ICONQUESTION);
	MessageBoxX(hWndMainWindow, mes, _T("NO POLARS DIRECTORY"), MB_OK|MB_ICONQUESTION, true);
	RUN_MODE=RUN_EXIT;
	Shutdown();
	goto _exit;
  }


  // Standby for a system request to close the application during this phase.
  wf->SetTimerNotify(OnTimerNotify);
  #if 0
  srand(GetTickCount());
  #endif

  wf->ShowModal();
  if (RUN_MODE==RUN_SHUTDOWN) goto _exit;

  wp = (WndProperty*)wf->FindByName(TEXT("prpProfile"));
  if (wp) {
	DataFieldFileReader* dfe;
	dfe = (DataFieldFileReader*)wp->GetDataField();

	if (RUN_MODE==RUN_PROFILE) {
		if (_tcslen(dfe->GetPathFile())>0) {
			if (_tcscmp(dfe->GetPathFile(),startProfileFile) ) { // if they are not the same
				_tcscpy(startProfileFile,dfe->GetPathFile());
				if (_tcscmp(startProfileFile,_T("PROFILE_RESET"))==0) {
					#if TESTBENCH
					StartupStore(_T("... Selected FULL RESET virtual profile\n"));
					#endif
					if (MessageBoxX(NULL, gettext(TEXT("_@M1758_")), 
						gettext(TEXT("_@M1757_")), MB_OK|MB_ICONQUESTION));
					fullresetasked=true;
				} else {
					#if TESTBENCH
					StartupStore(_T("... Selected new profile, preloading..\n"));
					#endif
					LKProfileLoad(startProfileFile);
					fullresetasked=false;
				}
			}
		}
	}
	if (RUN_MODE==RUN_AIRCRAFT) {
		if (_tcslen(dfe->GetPathFile())>0) {
			if (_tcscmp(dfe->GetPathFile(),startAircraftFile) ) { // if they are not the same
				_tcscpy(startAircraftFile,dfe->GetPathFile());
				#if TESTBENCH
				StartupStore(_T("... Selected new aircraft, preloading..\n"));
				#endif
				LKProfileLoad(startAircraftFile);
			}
		}
	}
	if (RUN_MODE==RUN_PILOT) {
		if (_tcslen(dfe->GetPathFile())>0) {
			if (_tcscmp(dfe->GetPathFile(),startPilotFile) ) { // if they are not the same
				_tcscpy(startPilotFile,dfe->GetPathFile());
				#if TESTBENCH
				StartupStore(_T("... Selected new pilot, preloading..\n"));
				#endif
				LKProfileLoad(startPilotFile);
			}
		}
	}
	RUN_MODE=RUN_DUALPROF;
  }
  if (RUN_MODE==RUN_EXIT) {
	if (EnableSoundModes) LKSound(_T("LK_SLIDE.WAV"));
	if (MessageBoxX(hWndMainWindow, 
	// LKTOKEN  _@M198_ = "Confirm Exit?" 
		gettext(TEXT("_@M198_")), 
		TEXT("LK8000"), MB_YESNO|MB_ICONQUESTION) == IDYES) {
		Shutdown();
	} else
		RUN_MODE=RUN_WELCOME;
  }


_exit:
  if (wf!=NULL) {
	delete wf;
	wf = NULL;
  }

  if (RUN_MODE==RUN_FLY || RUN_MODE==RUN_SIM) {
	if (EnableSoundModes) LKSound(_T("LK_SLIDE.WAV"));
	return 0;	// do not repeat dialog
  }

  if (RUN_MODE==RUN_EXIT || RUN_MODE==RUN_SHUTDOWN)
	return -1;	// terminate
  else
	return 1;	// repeat dialog

}
Example #9
0
int
main(int argc, char *argv[])
{
    int		sts;
    int		nport = 0;
    char	*envstr;
#ifdef HAVE_SA_SIGINFO
    static struct sigaction act;
#endif

    umask(022);
    __pmProcessDataSize(NULL);
    __pmGetUsername(&username);
    __pmSetInternalState(PM_STATE_PMCS);
    __pmServerSetFeature(PM_SERVER_FEATURE_DISCOVERY);
    __pmServerSetFeature(PM_SERVER_FEATURE_CONTAINERS);

    if ((envstr = getenv("PMCD_PORT")) != NULL)
	nport = __pmServerAddPorts(envstr);
    ParseOptions(argc, argv, &nport);
    if (nport == 0)
	__pmServerAddPorts(TO_STRING(SERVER_PORT));

    /* Set the local socket path. A message will be generated into the log
     * if this fails, but it is not fatal, since other connection options
     * may exist. 
     */
    __pmServerSetLocalSocket(sockpath);

    /* Set the service spec. This will cause our service to be advertised on
     * the network if that is supported.
     */
    __pmServerSetServiceSpec(PM_SERVER_SERVICE_SPEC);

    if (run_daemon) {
	fflush(stderr);
	StartDaemon(argc, argv);
    }

#ifdef HAVE_SA_SIGINFO
    act.sa_sigaction = SigIntProc;
    act.sa_flags = SA_SIGINFO;
    sigaction(SIGINT, &act, NULL);
    sigaction(SIGTERM, &act, NULL);
#else
    __pmSetSignalHandler(SIGINT, SigIntProc);
    __pmSetSignalHandler(SIGTERM, SigIntProc);
#endif
    __pmSetSignalHandler(SIGHUP, SigHupProc);
    __pmSetSignalHandler(SIGBUS, SigBad);
    __pmSetSignalHandler(SIGSEGV, SigBad);

    if ((sts = __pmServerOpenRequestPorts(&clientFds, MAXPENDING)) < 0)
	DontStart();
    maxReqPortFd = maxClientFd = sts;

    __pmOpenLog(pmProgname, logfile, stderr, &sts);
    /* close old stdout, and force stdout into same stream as stderr */
    fflush(stdout);
    close(fileno(stdout));
    sts = dup(fileno(stderr));
    /* if this fails beware of the sky falling in */
    assert(sts >= 0);

    sts = pmLoadASCIINameSpace(pmnsfile, dupok);
    if (sts < 0) {
	fprintf(stderr, "Error: pmLoadASCIINameSpace(%s, %d): %s\n",
	    (pmnsfile == PM_NS_DEFAULT) ? "DEFAULT" : pmnsfile, dupok, pmErrStr(sts));
	DontStart();
    }

    if (ParseInitAgents(configFileName) < 0) {
	/* error already reported in ParseInitAgents() */
	DontStart();
    }

    if (nAgents <= 0) {
	fprintf(stderr, "Error: No PMDAs found in the configuration file \"%s\"\n",
		configFileName);
	DontStart();
    }

    if (run_daemon) {
	if (__pmServerCreatePIDFile(PM_SERVER_SERVICE_SPEC, PM_FATAL_ERR) < 0)
	    DontStart();
	if (__pmSetProcessIdentity(username) < 0)
	    DontStart();
    }

    if (__pmSecureServerSetup(certdb, dbpassfile) < 0)
	DontStart();

    PrintAgentInfo(stderr);
    __pmAccDumpLists(stderr);
    fprintf(stderr, "\npmcd: PID = %" FMT_PID, getpid());
    fprintf(stderr, ", PDU version = %u\n", PDU_VERSION);
    __pmServerDumpRequestPorts(stderr);
    fflush(stderr);

    /* all the work is done here */
    ClientLoop();

    Shutdown();
    exit(0);
}
Example #10
0
Cobolt::~Cobolt()
{
    Shutdown();
}
FVoiceCaptureWindows::~FVoiceCaptureWindows()
{
	Shutdown();
}
//===============================================================================================================================
OceanEnvironment::~OceanEnvironment()
{
	Shutdown();
}
void FMessageBridge::HandleMessageBusShutdown( )
{
	Shutdown();
	Bus.Reset();
}
Example #14
0
int
main(int argc, char *argv[])
{
    int		sts;
    int		nport = 0;
    int		localhost = 0;
    int		maxpending = MAXPENDING;
    char	*envstr;

    umask(022);
    __pmGetUsername(&username);
    __pmSetInternalState(PM_STATE_PMCS);
    __pmServerSetFeature(PM_SERVER_FEATURE_DISCOVERY);

    if ((envstr = getenv("PMPROXY_PORT")) != NULL)
        nport = __pmServerAddPorts(envstr);
    if ((envstr = getenv("PMPROXY_LOCAL")) != NULL)
        if ((localhost = atoi(envstr)) != 0)
            __pmServerSetFeature(PM_SERVER_FEATURE_LOCAL);
    if ((envstr = getenv("PMPROXY_MAXPENDING")) != NULL)
        maxpending = atoi(envstr);
    ParseOptions(argc, argv, &nport);
    if (localhost)
        __pmServerAddInterface("INADDR_LOOPBACK");
    if (nport == 0)
        __pmServerAddPorts(TO_STRING(PROXY_PORT));
    GetProxyHostname();

    __pmServerSetServiceSpec(PM_SERVER_PROXY_SPEC);
    if (run_daemon) {
        fflush(stderr);
        StartDaemon(argc, argv);
        __pmServerCreatePIDFile(PM_SERVER_PROXY_SPEC, 0);
    }

    __pmSetSignalHandler(SIGHUP, SIG_IGN);
    __pmSetSignalHandler(SIGINT, SigIntProc);
    __pmSetSignalHandler(SIGTERM, SigIntProc);
    __pmSetSignalHandler(SIGBUS, SigBad);
    __pmSetSignalHandler(SIGSEGV, SigBad);

    /* Open request ports for client connections */
    if ((sts = __pmServerOpenRequestPorts(&sockFds, maxpending)) < 0)
        DontStart();
    maxReqPortFd = maxSockFd = sts;

    __pmOpenLog(pmProgname, logfile, stderr, &sts);
    /* close old stdout, and force stdout into same stream as stderr */
    fflush(stdout);
    close(fileno(stdout));
    if (dup(fileno(stderr)) == -1) {
        fprintf(stderr, "Warning: dup() failed: %s\n", pmErrStr(-oserror()));
    }

    fprintf(stderr, "pmproxy: PID = %" FMT_PID, getpid());
    fprintf(stderr, ", PDU version = %u\n", PDU_VERSION);
    __pmServerDumpRequestPorts(stderr);
    fflush(stderr);

    /* lose root privileges if we have them */
    __pmSetProcessIdentity(username);

    if (__pmSecureServerSetup(certdb, dbpassfile) < 0)
        DontStart();

    /* all the work is done here */
    ClientLoop();

    Shutdown();
    exit(0);
}
// This test verifies that a re-registering slave sends the terminal
// unacknowledged tasks for a terminal executor. This is required
// for the master to correctly reconcile it's view with the slave's
// view of tasks. This test drops a terminal update to the master
// and then forces the slave to re-register.
TEST_F(MasterSlaveReconciliationTest, SlaveReregisterTerminatedExecutor)
{
  Try<PID<Master> > master = StartMaster();
  ASSERT_SOME(master);

  MockExecutor exec(DEFAULT_EXECUTOR_ID);
  TestContainerizer containerizer(&exec);

  StandaloneMasterDetector detector(master.get());

  Try<PID<Slave> > slave = StartSlave(&containerizer, &detector);
  ASSERT_SOME(slave);

  MockScheduler sched;
  MesosSchedulerDriver driver(
      &sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL);

  Future<FrameworkID> frameworkId;
  EXPECT_CALL(sched, registered(&driver, _, _))
    .WillOnce(FutureArg<1>(&frameworkId));

  EXPECT_CALL(sched, resourceOffers(&driver, _))
    .WillOnce(LaunchTasks(DEFAULT_EXECUTOR_INFO, 1, 1, 512, "*"))
    .WillRepeatedly(Return()); // Ignore subsequent offers.

  ExecutorDriver* execDriver;
  EXPECT_CALL(exec, registered(_, _, _, _))
    .WillOnce(SaveArg<0>(&execDriver));

  EXPECT_CALL(exec, launchTask(_, _))
    .WillOnce(SendStatusUpdateFromTask(TASK_RUNNING));

  Future<TaskStatus> status;
  EXPECT_CALL(sched, statusUpdate(&driver, _))
    .WillOnce(FutureArg<1>(&status));

  Future<StatusUpdateAcknowledgementMessage> statusUpdateAcknowledgementMessage
    = FUTURE_PROTOBUF(
        StatusUpdateAcknowledgementMessage(), master.get(), slave.get());

  driver.start();

  AWAIT_READY(status);
  EXPECT_EQ(TASK_RUNNING, status.get().state());

  // Make sure the acknowledgement reaches the slave.
  AWAIT_READY(statusUpdateAcknowledgementMessage);

  // Drop the TASK_FINISHED status update sent to the master.
  Future<StatusUpdateMessage> statusUpdateMessage =
    DROP_PROTOBUF(StatusUpdateMessage(), _, master.get());

  Future<ExitedExecutorMessage> executorExitedMessage =
    FUTURE_PROTOBUF(ExitedExecutorMessage(), _, _);

  TaskStatus finishedStatus;
  finishedStatus = status.get();
  finishedStatus.set_state(TASK_FINISHED);
  execDriver->sendStatusUpdate(finishedStatus);

  // Ensure the update was sent.
  AWAIT_READY(statusUpdateMessage);

  // Now kill the executor.
  containerizer.destroy(frameworkId.get(), DEFAULT_EXECUTOR_ID);

  Future<TaskStatus> status2;
  EXPECT_CALL(sched, statusUpdate(&driver, _))
    .WillOnce(FutureArg<1>(&status2));

  // We drop the 'UpdateFrameworkMessage' from the master to slave to
  // stop the status update manager from retrying the update that was
  // already sent due to the new master detection.
  DROP_PROTOBUFS(UpdateFrameworkMessage(), _, _);

  detector.appoint(master.get());

  AWAIT_READY(status2);
  EXPECT_EQ(TASK_FINISHED, status2.get().state());

  driver.stop();
  driver.join();

  Shutdown();
}
Example #16
0
	// ********************************************************************* //
	Logger::~Logger()
	{
		Shutdown();
	}
//===============================================================================================================================
IndoorEnvironment::~IndoorEnvironment()
{
	Shutdown();
}
Example #18
0
//++ ------------------------------------------------------------------------------------
// Details:	CMICmnStreamStderr destructor.
// Type:	Overridable.
// Args:	None.
// Return:	None.
// Throws:	None.
//--
CMICmnStreamStderr::~CMICmnStreamStderr( void )
{
    Shutdown();
}
Example #19
0
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
    boost::thread_group threadGroup;

    bool fRet = false;
    try
    {
        //
        // Parameters
        //
        // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
        ParseParameters(argc, argv);
        if (!boost::filesystem::is_directory(GetDataDir(false)))
        {
            fprintf(stderr, "Error: Specified directory does not exist\n");
            Shutdown();
        }
        ReadConfigFile(mapArgs, mapMultiArgs);

        if (mapArgs.count("-?") || mapArgs.count("--help"))
        {
            // First part of help message is specific to bitcoind / RPC client
            std::string strUsage = _("DIBBITS version") + " " + FormatFullVersion() + "\n\n" +
                _("Usage:") + "\n" +
                  "  DIBBITSd [options]                     " + "\n" +
                  "  DIBBITSd [options] <command> [params]  " + _("Send command to -server or DIBBITSd") + "\n" +
                  "  DIBBITSd [options] help                " + _("List commands") + "\n" +
                  "  DIBBITSd [options] help <command>      " + _("Get help for a command") + "\n";

            strUsage += "\n" + HelpMessage();

            fprintf(stdout, "%s", strUsage.c_str());
            return false;
        }

        // Command-line RPC
        for (int i = 1; i < argc; i++)
            if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "DIBBITS:"))
                fCommandLine = true;

        if (fCommandLine)
        {
            if (!SelectParamsFromCommandLine()) {
                fprintf(stderr, "Error: invalid combination of -regtest and -testnet.\n");
                return false;
            }
            int ret = CommandLineRPC(argc, argv);
            exit(ret);
        }
#if !defined(WIN32)
        fDaemon = GetBoolArg("-daemon", false);
        if (fDaemon)
        {
            // Daemonize
            pid_t pid = fork();
            if (pid < 0)
            {
                fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
                return false;
            }
            if (pid > 0) // Parent process, pid is child process id
            {
                CreatePidFile(GetPidFile(), pid);
                return true;
            }
            // Child process falls through to rest of initialization

            pid_t sid = setsid();
            if (sid < 0)
                fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
        }
#endif

        fRet = AppInit2(threadGroup);
    }
    catch (std::exception& e) {
        PrintException(&e, "AppInit()");
    } catch (...) {
        PrintException(NULL, "AppInit()");
    }

    if (!fRet)
    {
        threadGroup.interrupt_all();
        // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
        // the startup-failure cases to make sure they don't result in a hang due to some
        // thread-blocking-waiting-for-another-thread-during-startup case
    } else {
        WaitForShutdown(&threadGroup);
    }
    Shutdown();

    return fRet;
}
bool
GMPVideoDecoderParent::RecvShutdown()
{
    Shutdown();
    return true;
}
Example #21
0
/*
============
idAASBuild::~idAASBuild
============
*/
idAASBuild::~idAASBuild( void ) {
	Shutdown();
}
// This test verifies that the master reconciles tasks that are
// missing from a re-registering slave. In this case, we drop the
// RunTaskMessage so the slave should send TASK_LOST.
TEST_F(MasterSlaveReconciliationTest, ReconcileLostTask)
{
  Try<PID<Master> > master = StartMaster();
  ASSERT_SOME(master);

  StandaloneMasterDetector detector(master.get());

  Try<PID<Slave> > slave = StartSlave(&detector);
  ASSERT_SOME(slave);

  MockScheduler sched;
  MesosSchedulerDriver driver(
      &sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL);

  EXPECT_CALL(sched, registered(&driver, _, _));

  Future<vector<Offer> > offers;
  EXPECT_CALL(sched, resourceOffers(&driver, _))
    .WillOnce(FutureArg<1>(&offers))
    .WillRepeatedly(Return()); // Ignore subsequent offers.

  driver.start();

  AWAIT_READY(offers);

  EXPECT_NE(0u, offers.get().size());

  TaskInfo task;
  task.set_name("test task");
  task.mutable_task_id()->set_value("1");
  task.mutable_slave_id()->MergeFrom(offers.get()[0].slave_id());
  task.mutable_resources()->MergeFrom(offers.get()[0].resources());
  task.mutable_executor()->MergeFrom(DEFAULT_EXECUTOR_INFO);

  // We now launch a task and drop the corresponding RunTaskMessage on
  // the slave, to ensure that only the master knows about this task.
  Future<RunTaskMessage> runTaskMessage =
    DROP_PROTOBUF(RunTaskMessage(), _, _);

  driver.launchTasks(offers.get()[0].id(), {task});

  AWAIT_READY(runTaskMessage);

  Future<SlaveReregisteredMessage> slaveReregisteredMessage =
    FUTURE_PROTOBUF(SlaveReregisteredMessage(), _, _);

  Future<StatusUpdateMessage> statusUpdateMessage =
    FUTURE_PROTOBUF(StatusUpdateMessage(), _, master.get());

  Future<TaskStatus> status;
  EXPECT_CALL(sched, statusUpdate(&driver, _))
    .WillOnce(FutureArg<1>(&status));

  // Simulate a spurious master change event (e.g., due to ZooKeeper
  // expiration) at the slave to force re-registration.
  detector.appoint(master.get());

  AWAIT_READY(slaveReregisteredMessage);

  // Make sure the slave generated the TASK_LOST.
  AWAIT_READY(statusUpdateMessage);

  AWAIT_READY(status);

  ASSERT_EQ(task.task_id(), status.get().task_id());
  ASSERT_EQ(TASK_LOST, status.get().state());

  // Before we obtain the metrics, ensure that the master has finished
  // processing the status update so metrics have been updated.
  Clock::pause();
  Clock::settle();
  Clock::resume();

  // Check metrics.
  JSON::Object stats = Metrics();
  EXPECT_EQ(1u, stats.values.count("master/tasks_lost"));
  EXPECT_EQ(1u, stats.values["master/tasks_lost"]);
  EXPECT_EQ(
      1u,
      stats.values.count(
          "master/task_lost/source_slave/reason_reconciliation"));
  EXPECT_EQ(
      1u,
      stats.values["master/task_lost/source_slave/reason_reconciliation"]);

  driver.stop();
  driver.join();

  Shutdown();
}
Example #23
0
Database::~Database()
{
	Shutdown();
}
// This test verifies that the master reconciles tasks that are
// missing from a re-registering slave. In this case, we trigger
// a race between the slave re-registration message and the launch
// message. There should be no TASK_LOST.
// This was motivated by MESOS-1696.
TEST_F(MasterSlaveReconciliationTest, ReconcileRace)
{
  Try<PID<Master> > master = StartMaster();
  ASSERT_SOME(master);

  MockExecutor exec(DEFAULT_EXECUTOR_ID);

  StandaloneMasterDetector detector(master.get());

  Future<SlaveRegisteredMessage> slaveRegisteredMessage =
    FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get(), _);

  Try<PID<Slave> > slave = StartSlave(&exec, &detector);
  ASSERT_SOME(slave);

  AWAIT_READY(slaveRegisteredMessage);

  MockScheduler sched;
  MesosSchedulerDriver driver(
      &sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL);

  EXPECT_CALL(sched, registered(&driver, _, _));

  Future<vector<Offer> > offers;
  EXPECT_CALL(sched, resourceOffers(&driver, _))
    .WillOnce(FutureArg<1>(&offers))
    .WillRepeatedly(Return()); // Ignore subsequent offers.

  driver.start();

  // Trigger a re-registration of the slave and capture the message
  // so that we can spoof a race with a launch task message.
  DROP_PROTOBUFS(ReregisterSlaveMessage(), slave.get(), master.get());

  Future<ReregisterSlaveMessage> reregisterSlaveMessage =
    DROP_PROTOBUF(ReregisterSlaveMessage(), slave.get(), master.get());

  detector.appoint(master.get());

  AWAIT_READY(reregisterSlaveMessage);

  AWAIT_READY(offers);
  EXPECT_NE(0u, offers.get().size());

  TaskInfo task;
  task.set_name("test task");
  task.mutable_task_id()->set_value("1");
  task.mutable_slave_id()->MergeFrom(offers.get()[0].slave_id());
  task.mutable_resources()->MergeFrom(offers.get()[0].resources());
  task.mutable_executor()->MergeFrom(DEFAULT_EXECUTOR_INFO);

  ExecutorDriver* executorDriver;
  EXPECT_CALL(exec, registered(_, _, _, _))
    .WillOnce(SaveArg<0>(&executorDriver));

  // Leave the task in TASK_STAGING.
  Future<Nothing> launchTask;
  EXPECT_CALL(exec, launchTask(_, _))
    .WillOnce(FutureSatisfy(&launchTask));

  EXPECT_CALL(sched, statusUpdate(&driver, _))
    .Times(0);

  driver.launchTasks(offers.get()[0].id(), {task});

  AWAIT_READY(launchTask);

  // Send the stale re-registration message, which does not contain
  // the task we just launched. This will trigger a reconciliation
  // by the master.
  Future<SlaveReregisteredMessage> slaveReregisteredMessage =
    FUTURE_PROTOBUF(SlaveReregisteredMessage(), _, _);

  // Prevent this from being dropped per the DROP_PROTOBUFS above.
  FUTURE_PROTOBUF(ReregisterSlaveMessage(), slave.get(), master.get());

  process::post(slave.get(), master.get(), reregisterSlaveMessage.get());

  AWAIT_READY(slaveReregisteredMessage);

  // Neither the master nor the slave should not send a TASK_LOST
  // as part of the reconciliation. We check this by calling
  // Clock::settle() to flush all pending events.
  Clock::pause();
  Clock::settle();
  Clock::resume();

  // Now send TASK_FINISHED and make sure it's the only message
  // received by the scheduler.
  Future<TaskStatus> status;
  EXPECT_CALL(sched, statusUpdate(&driver, _))
    .WillOnce(FutureArg<1>(&status));

  TaskStatus taskStatus;
  taskStatus.mutable_task_id()->CopyFrom(task.task_id());
  taskStatus.set_state(TASK_FINISHED);
  executorDriver->sendStatusUpdate(taskStatus);

  AWAIT_READY(status);
  ASSERT_EQ(TASK_FINISHED, status.get().state());

  EXPECT_CALL(exec, shutdown(_))
    .Times(AtMost(1));

  driver.stop();
  driver.join();

  Shutdown();
}
ServerSocketInConnection::~ServerSocketInConnection()
{
	Shutdown();
}
// This test verifies that the slave reports pending tasks when
// re-registering, otherwise the master will report them as being
// lost.
TEST_F(MasterSlaveReconciliationTest, SlaveReregisterPendingTask)
{
  Try<PID<Master> > master = StartMaster();
  ASSERT_SOME(master);

  StandaloneMasterDetector detector(master.get());

  Try<PID<Slave> > slave = StartSlave(&detector);
  ASSERT_SOME(slave);

  MockScheduler sched;
  MesosSchedulerDriver driver(
      &sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL);

  EXPECT_CALL(sched, registered(&driver, _, _));

  Future<vector<Offer> > offers;
  EXPECT_CALL(sched, resourceOffers(&driver, _))
    .WillOnce(FutureArg<1>(&offers))
    .WillRepeatedly(Return()); // Ignore subsequent offers.

  driver.start();

  AWAIT_READY(offers);
  EXPECT_NE(0u, offers.get().size());

  // No TASK_LOST updates should occur!
  EXPECT_CALL(sched, statusUpdate(&driver, _))
    .Times(0);

  // We drop the _runTask dispatch to ensure the task remains
  // pending in the slave.
  Future<Nothing> _runTask = DROP_DISPATCH(slave.get(), &Slave::_runTask);

  TaskInfo task1;
  task1.set_name("test task");
  task1.mutable_task_id()->set_value("1");
  task1.mutable_slave_id()->MergeFrom(offers.get()[0].slave_id());
  task1.mutable_resources()->MergeFrom(offers.get()[0].resources());
  task1.mutable_executor()->MergeFrom(DEFAULT_EXECUTOR_INFO);

  driver.launchTasks(offers.get()[0].id(), {task1});

  AWAIT_READY(_runTask);

  Future<SlaveReregisteredMessage> slaveReregisteredMessage =
    FUTURE_PROTOBUF(SlaveReregisteredMessage(), _, _);

  // Simulate a spurious master change event (e.g., due to ZooKeeper
  // expiration) at the slave to force re-registration.
  detector.appoint(master.get());

  AWAIT_READY(slaveReregisteredMessage);

  Clock::pause();
  Clock::settle();
  Clock::resume();

  driver.stop();
  driver.join();

  Shutdown();
}
Example #27
0
File: main.cpp Project: 2asoft/0ad
// moved into a helper function to ensure args is destroyed before
// exit(), which may result in a memory leak.
static void RunGameOrAtlas(int argc, const char* argv[])
{
	CmdLineArgs args(argc, argv);

	g_args = args;

	if (args.Has("version") || args.Has("-version"))
	{
		debug_printf("Pyrogenesis %s\n", engine_version);
		return;
	}

	const bool isVisualReplay = args.Has("replay-visual");
	const bool isNonVisualReplay = args.Has("replay");

	const CStr replayFile =
		isVisualReplay ? args.Get("replay-visual") :
		isNonVisualReplay ? args.Get("replay") : "";

	if (isVisualReplay || isNonVisualReplay)
	{
		if (!FileExists(OsPath(replayFile)))
		{
			debug_printf("ERROR: The requested replay file '%s' does not exist!\n", replayFile.c_str());
			return;
		}
		if (DirectoryExists(OsPath(replayFile)))
		{
			debug_printf("ERROR: The requested replay file '%s' is a directory!\n", replayFile.c_str());
			return;
		}
	}

	// We need to initialize SpiderMonkey and libxml2 in the main thread before
	// any thread uses them. So initialize them here before we might run Atlas.
	ScriptEngine scriptEngine;
	CXeromyces::Startup();

	if (ATLAS_RunIfOnCmdLine(args, false))
	{
		CXeromyces::Terminate();
		return;
	}

	if (isNonVisualReplay)
	{
		if (!args.Has("mod"))
		{
			LOGERROR("At least one mod should be specified! Did you mean to add the argument '-mod=public'?");
			CXeromyces::Terminate();
			return;
		}

		Paths paths(args);
		g_VFS = CreateVfs(20 * MiB);
		g_VFS->Mount(L"cache/", paths.Cache(), VFS_MOUNT_ARCHIVABLE);
		MountMods(paths, GetMods(args, INIT_MODS));

		{
			CReplayPlayer replay;
			replay.Load(replayFile);
			replay.Replay(
				args.Has("serializationtest"),
				args.Has("rejointest") ? args.Get("rejointest").ToInt() : -1,
				args.Has("ooslog"));
		}

		g_VFS.reset();

		CXeromyces::Terminate();
		return;
	}

	// run in archive-building mode if requested
	if (args.Has("archivebuild"))
	{
		Paths paths(args);

		OsPath mod(args.Get("archivebuild"));
		OsPath zip;
		if (args.Has("archivebuild-output"))
			zip = args.Get("archivebuild-output");
		else
			zip = mod.Filename().ChangeExtension(L".zip");

		CArchiveBuilder builder(mod, paths.Cache());

		// Add mods provided on the command line
		// NOTE: We do not handle mods in the user mod path here
		std::vector<CStr> mods = args.GetMultiple("mod");
		for (size_t i = 0; i < mods.size(); ++i)
			builder.AddBaseMod(paths.RData()/"mods"/mods[i]);

		builder.Build(zip, args.Has("archivebuild-compress"));

		CXeromyces::Terminate();
		return;
	}

	const double res = timer_Resolution();
	g_frequencyFilter = CreateFrequencyFilter(res, 30.0);

	// run the game
	int flags = INIT_MODS;
	do
	{
		restart = false;
		quit = false;
		if (!Init(args, flags))
		{
			flags &= ~INIT_MODS;
			Shutdown(SHUTDOWN_FROM_CONFIG);
			continue;
		}
		InitGraphics(args, 0);
		MainControllerInit();
		while (!quit)
			Frame();
		Shutdown(0);
		MainControllerShutdown();
		flags &= ~INIT_MODS;
	} while (restart);

	if (restart_in_atlas)
		ATLAS_RunIfOnCmdLine(args, true);

	CXeromyces::Terminate();
}
// This test verifies that when the slave re-registers, the master
// does not send TASK_LOST update for a task that has reached terminal
// state but is waiting for an acknowledgement.
TEST_F(MasterSlaveReconciliationTest, SlaveReregisterTerminalTask)
{
  Try<PID<Master> > master = StartMaster();
  ASSERT_SOME(master);

  MockExecutor exec(DEFAULT_EXECUTOR_ID);

  StandaloneMasterDetector detector(master.get());

  Try<PID<Slave> > slave = StartSlave(&exec, &detector);
  ASSERT_SOME(slave);

  MockScheduler sched;
  MesosSchedulerDriver driver(
      &sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL);

  EXPECT_CALL(sched, registered(&driver, _, _));

  Future<vector<Offer> > offers;
  EXPECT_CALL(sched, resourceOffers(&driver, _))
    .WillOnce(FutureArg<1>(&offers))
    .WillRepeatedly(Return()); // Ignore subsequent offers.

  driver.start();

  AWAIT_READY(offers);
  EXPECT_NE(0u, offers.get().size());

  TaskInfo task;
  task.set_name("test task");
  task.mutable_task_id()->set_value("1");
  task.mutable_slave_id()->MergeFrom(offers.get()[0].slave_id());
  task.mutable_resources()->MergeFrom(offers.get()[0].resources());
  task.mutable_executor()->MergeFrom(DEFAULT_EXECUTOR_INFO);

  EXPECT_CALL(exec, registered(_, _, _, _));

  // Send a terminal update right away.
  EXPECT_CALL(exec, launchTask(_, _))
    .WillOnce(SendStatusUpdateFromTask(TASK_FINISHED));

  // Drop the status update from slave to the master, so that
  // the slave has a pending terminal update when it re-registers.
  DROP_PROTOBUF(StatusUpdateMessage(), _, master.get());

  Future<Nothing> _statusUpdate = FUTURE_DISPATCH(_, &Slave::_statusUpdate);

  Future<TaskStatus> status;
  EXPECT_CALL(sched, statusUpdate(&driver, _))
    .WillOnce(FutureArg<1>(&status))
    .WillRepeatedly(Return()); // Ignore retried update due to update framework.

  driver.launchTasks(offers.get()[0].id(), {task});

  AWAIT_READY(_statusUpdate);

  Future<SlaveReregisteredMessage> slaveReregisteredMessage =
    FUTURE_PROTOBUF(SlaveReregisteredMessage(), _, _);

  // Simulate a spurious master change event (e.g., due to ZooKeeper
  // expiration) at the slave to force re-registration.
  detector.appoint(master.get());

  AWAIT_READY(slaveReregisteredMessage);

  // The master should not send a TASK_LOST after the slave
  // re-registers. We check this by calling Clock::settle() so that
  // the only update the scheduler receives is the retried
  // TASK_FINISHED update.
  // NOTE: The status update manager resends the status update when
  // it detects a new master.
  Clock::pause();
  Clock::settle();

  AWAIT_READY(status);
  ASSERT_EQ(TASK_FINISHED, status.get().state());

  EXPECT_CALL(exec, shutdown(_))
    .Times(AtMost(1));

  driver.stop();
  driver.join();

  Shutdown();
}
Server::~Server(){
    Shutdown();
}
Example #30
0
bool CGameApp::Init()
{	
// plasma 2005.07.06 - 디버그 모드에선 그냥 직접 읽고, 릴리즈 모드에선 pak 파일에서 추출해서 사용한다.
#ifdef _DEBUG
//	if( !g_TextManager.Load("text_data/text.dat") ) 
	if( !g_TextManager.LoadPack("text.dat", "text_data") ) 
	{
		MessageBox( NULL, "Text.Dat load fail", "Error", MB_OK );
	}
#else
	if( !g_TextManager.LoadPack("text.dat", "text_data") ) 
	{
		MessageBox( NULL, "Text.Dat load fail", "Error", MB_OK );
	}
#endif
	
	// Create game all systems.
	m_pGSystem  = new CSystemWin32Imp;
	m_pGSystem->Init(m_pProcessInfo);

	// 2003/11/19 by impurity create xml system
	MSXML2::IXMLDOMDocument2Ptr pDoc = NULL;
//#ifdef _DEBUG
//	CFileSys::ConvertBinaryXML("script\\window.xml","script\\window.bml");
//	FILE* fIn;
//	if(NULL!=(fIn=fopen("script\\window.bml","rb")))
//	{
//		CFileSys::LoadBinaryXML(pDoc, fIn);
//	}	
//	fclose( fIn );
//#else 
	DFileGPack packFile;
	packFile.Open(SFullName("script","window.bml"));
	CFileSys::LoadBinaryXML(pDoc, packFile.GetFile(), packFile.GetSize());
	packFile.Close();
//#endif
	
	
	MSXML2::IXMLDOMNodePtr pNode = NULL;
	
	if(pNode=pDoc->selectSingleNode(L"./root/window/bitperpixel"))
	{
		m_DisplayMode.iBitPerPixel = (short)pNode->GetnodeTypedValue();
	}
	else
	{
		m_DisplayMode.iBitPerPixel = 16;
	}
	
	m_DisplayMode.iDeviceType = 0;
	
	//if(pNode=pDoc->selectSingleNode(L"./root/window/fullmode"))
	//{
	//	m_DisplayMode.iFullScreen = (bool)pNode->GetnodeTypedValue();
	//	((CProcessInfoWin32Imp *)m_pProcessInfo)->m_bFullScreen = true;
	//}
	//else
	{
		m_DisplayMode.iFullScreen = false;
		((CProcessInfoWin32Imp *)m_pProcessInfo)->m_bFullScreen = false;
	}
	
	m_DisplayMode.iRefreshRate = 0;
	m_DisplayMode.iZBufferDepth = 32;
	
	if(pNode=pDoc->selectSingleNode(L"./root/window/width"))
	{
		m_DisplayMode.iWidth = (short)pNode->GetnodeTypedValue();
	}
	else
	{
		m_DisplayMode.iWidth = 800;
	}
	
	if(pNode=pDoc->selectSingleNode(L"./root/window/height"))
	{
		m_DisplayMode.iHeight = (short)pNode->GetnodeTypedValue();
	}
	else
	{
		m_DisplayMode.iHeight = 600;
	}
	
	CFileSys::UnloadXML(pDoc);
	


	m_pGameFactory = new CGameFactoryImp;
	// Register Game factory to Factory System.
	m_pGSystem->GetFactorySys()->RegisterGameFactory( m_pGameFactory );


	// 3d base initial.
	InitPhysics();

	CWindowSysWin32Imp* pWindowSysWin32Imp = (CWindowSysWin32Imp*)m_pGSystem->GetWindowSys();

	if( !m_pGSystem->GetGControlSys()->Create( pWindowSysWin32Imp->m_hWnd, 
		                                       m_DisplayMode ) )
	{
		// Device create error 
		DLogWriteSystem("Create Device Error");
		Shutdown();
	}

	int Xplus = GetSystemMetrics(SM_CXBORDER)*2*GetSystemMetrics(SM_CXFIXEDFRAME);
	int Yplus = GetSystemMetrics(SM_CYBORDER)*2*GetSystemMetrics(SM_CYFIXEDFRAME) +
				GetSystemMetrics(SM_CYCAPTION);
	SetWindowPos(pWindowSysWin32Imp->m_hWnd, HWND_NOTOPMOST, (GetSystemMetrics(SM_CXSCREEN)-m_DisplayMode.iWidth)/2,
				(GetSystemMetrics(SM_CYSCREEN)-m_DisplayMode.iHeight)/2
				, m_DisplayMode.iWidth+Xplus, m_DisplayMode.iHeight+Yplus, SWP_SHOWWINDOW);


	m_pGSystem->GetGControlSys()->GetDevice()->SetRenderState( D3DRS_AMBIENT, 0xAAAAAA );

	m_pGSystem->GetGControlSys()->SetTextureAutoCompress( true );
	DLogEnable(true);

	// 우선 모든 Layer 들을 생성한다.
	CResourceSysWin32Imp *pResourceSys = (CResourceSysWin32Imp *)m_pGSystem->GetResourceSys();
	pResourceSys->CreateLayerAll();
	pResourceSys->CreateTask(FACTORY_ID_TASK_FRAME_PLAYER);

	CFrameTask *pTask = (CFrameTask *)pResourceSys->GetTask(FACTORY_ID_TASK_FRAME_PLAYER);
	m_pGSystem->GetTaskSys()->PostTaskCommand(CTaskCommand::FRAMESYNC_PUSH_BACK, pTask);
	pWindowSysWin32Imp->SetWndProcTask(pTask);


	// insert only game layer to task.
	CQuickConnection::Instance.Initial();

	// 욕설 필터링을 작동한다.
	LoadCurses("curse.pak");

	// 2006.4.23 doo 메크로채팅 텍스트를 로드한다.
	g_pMacroChatFinder = new CMacroChat;
	g_pMacroChatFinder->Init();
	
	// Login Server 의 ip, port 를 저장한다.
	// 임시로 CQuickConnection 에서 ip, port 를 가져오도록 하였다.
	CInfoSys *pInfoSys = m_pGSystem->GetInfoSys();
	pInfoSys->SetLoginServerAddress((LPCTSTR)CQuickConnection::Instance.m_sServerAddr, CQuickConnection::Instance.m_iServerPort);	
	
	//m_pGSystem->GetInfoSys()->SetPPLName(SName("ppl_ting"));

	// Reject Popup
	CInfoSys::SGameIDInfo *pGameIDInfo;
	pGameIDInfo = m_pGSystem->GetInfoSys()->GetGameIDInfo();
	pGameIDInfo->bRejectPopup = false;
	pGameIDInfo->bObserverChar = false;

	CQuickConnection::Instance.m_nIsQuickMode = 1;
	CQuickConnection::Instance.m_nIsHost = 1;
	CQuickConnection::Instance.m_sServerAddr = "127.0.0.1";
	CQuickConnection::Instance.m_iServerPort = 10000;
	CQuickConnection::Instance.m_nIsFullCourt = 0;
	CQuickConnection::Instance.m_nFrameSpeedOn = 1;
	CQuickConnection::Instance.m_nHostPort = 10001;
	CQuickConnection::Instance.m_nPlayerOn = 1;
	CQuickConnection::Instance.m_sPlayMode = "auto";
	CQuickConnection::Instance.m_vecPos[0] = SVector(1,0,0);
	CQuickConnection::Instance.m_vecPos[1] = SVector(0,0,1);
	CQuickConnection::Instance.m_vecPos[2] = SVector(2,0,0);
	CQuickConnection::Instance.m_vecPos[3] = SVector(0,0,2);
	CQuickConnection::Instance.m_vecPos[4] = SVector(3,0,0);
	CQuickConnection::Instance.m_vecPos[5] = SVector(0,0,3);

	CQuickConnection::Instance.m_sConnectAddr = "127.0.0.1";
	CQuickConnection::Instance.m_sConnectionId = "c1test45";
	CQuickConnection::Instance.m_nClientPort = 10000;
	CQuickConnection::Instance.m_nCharID = 5;
	CQuickConnection::Instance.m_nCharType = 5;
	CQuickConnection::Instance.m_dwTeamID = 0;
	//CQuickConnection::Instance.m_dwMyId = 1;

	if( CQuickConnection::Instance.m_nIsQuickMode )
	{
		CFrameTask* pFrameTask = (CFrameTask*)pTask;
		// game render layer.
		CRenderLayer_Game* pRenderLayer = (CRenderLayer_Game *)pResourceSys->GetRenderLayer( FACTORY_ID_RENDERLAYER_GAME );
		pFrameTask->PostRenderLayerCommand( CRenderLayerCommand::PUSH_BACK, pRenderLayer );
		pRenderLayer->ResourceLoad(m_pGSystem, NULL);

		// game logic layer.
		CLogicLayer* pLogicLayer = pResourceSys->GetLogicLayer( FACTORY_ID_LOGICLAYER_GAME );
		pFrameTask->PostLogicLayerCommand( CLogicLayerCommand::PUSH_BACK, pLogicLayer );

		// host logic layer.
		if( CQuickConnection::Instance.m_nIsHost )
		{
			pLogicLayer = pResourceSys->GetLogicLayer( FACTORY_ID_LOGICLAYER_HOST );
			CLogicLayer_Host* pHostLogicLayer = (CLogicLayer_Host*)pLogicLayer;
			pHostLogicLayer->InitHost(CQuickConnection::Instance.m_nHostPort, 1 );
			pFrameTask->PostLogicLayerCommand( CLogicLayerCommand::PUSH_BACK, pLogicLayer );
		}
		
		m_pGSystem->GetInfoSys()->LoadGameOption("game.cfg");
		
	}
	else // insert all layer to excute game.
	{
		// lobby layer.
//		CInterfaceLayer *pInterfaceLayer_Login = pResourceSys->GetInterfaceLayer(FACTORY_ID_INTERFACELAYER_CREATECHAR);
//		pTask->PostInterfaceLayerCommand(CInterfaceLayerCommand::PUSH_BACK, pInterfaceLayer_Login);
		
		// room layer.
	}

	// plasma 2005.07.06 - Resource Table
#ifdef _DEBUG
/*	CTableResource* pItemRsc = new CTableResource;
	std::vector<std::string> ItemCustomKey;
	ItemCustomKey.push_back("ItemCode");
	pItemRsc->SetCustomKey(ItemCustomKey);
	pItemRsc->Load("text_data/ItemShop.txt");
	CTableRscManager::Instance().AddTableResource( "item", pItemRsc );
		
	CTableResource* pSkillRsc = new CTableResource;
	std::vector<std::string> SkillCustomKey;
	SkillCustomKey.push_back("SkillNo");
	SkillCustomKey.push_back("Kind");
	pSkillRsc->SetCustomKey(SkillCustomKey);
	pSkillRsc->Load("text_data/skillshop.txt");
	CTableRscManager::Instance().AddTableResource( "skill", pSkillRsc );

	CTableResource* pTrainingRsc = new CTableResource;
	std::vector<std::string> TrainingCustomKey;
	TrainingCustomKey.push_back("TrainingNo");
	pTrainingRsc->SetCustomKey(TrainingCustomKey);
	pTrainingRsc->Load("text_data/TrainingShop.txt");
	CTableRscManager::Instance().AddTableResource( "training", pTrainingRsc );
*/
	CTableResource* pItemRsc = new CTableResource;
	std::vector<std::string> ItemCustomKey;
	ItemCustomKey.push_back("ItemCode");
	pItemRsc->SetCustomKey(ItemCustomKey);
	pItemRsc->LoadPack("text_data", "ItemShop.txt");
	CTableRscManager::Instance().AddTableResource( "item", pItemRsc );
		
	CTableResource* pSkillRsc = new CTableResource;
	std::vector<std::string> SkillCustomKey;
	SkillCustomKey.push_back("SkillNo");
	SkillCustomKey.push_back("Kind");
	pSkillRsc->SetCustomKey(SkillCustomKey);
	pSkillRsc->LoadPack("text_data", "skillshop.txt");
	CTableRscManager::Instance().AddTableResource( "skill", pSkillRsc );

	CTableResource* pTrainingRsc = new CTableResource;
	std::vector<std::string> TrainingCustomKey;
	TrainingCustomKey.push_back("TrainingNo");
	pTrainingRsc->SetCustomKey(TrainingCustomKey);
	pTrainingRsc->LoadPack("text_data", "TrainingShop.txt");
	CTableRscManager::Instance().AddTableResource( "training", pTrainingRsc );

#else
	CTableResource* pItemRsc = new CTableResource;
	std::vector<std::string> ItemCustomKey;
	ItemCustomKey.push_back("ItemCode");
	pItemRsc->SetCustomKey(ItemCustomKey);
	pItemRsc->LoadPack("text_data", "ItemShop.txt");
	CTableRscManager::Instance().AddTableResource( "item", pItemRsc );
		
	CTableResource* pSkillRsc = new CTableResource;
	std::vector<std::string> SkillCustomKey;
	SkillCustomKey.push_back("SkillNo");
	SkillCustomKey.push_back("Kind");
	pSkillRsc->SetCustomKey(SkillCustomKey);
	pSkillRsc->LoadPack("text_data", "skillshop.txt");
	CTableRscManager::Instance().AddTableResource( "skill", pSkillRsc );

	CTableResource* pTrainingRsc = new CTableResource;
	std::vector<std::string> TrainingCustomKey;
	TrainingCustomKey.push_back("TrainingNo");
	pTrainingRsc->SetCustomKey(TrainingCustomKey);
	pTrainingRsc->LoadPack("text_data", "TrainingShop.txt");
	CTableRscManager::Instance().AddTableResource( "training", pTrainingRsc );
#endif

	return true;
}