示例#1
0
int WINAPI WinMain(HINSTANCE _hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow)
{
	Common::EnableCrashingOnCrashes();

	const char *fileToStart = NULL;
	const char *fileToLog = NULL;
	const char *stateToLoad = NULL;
	bool hideLog = true;

#ifdef _DEBUG
	hideLog = false;
#endif

	g_Config.Load();
	VFSRegister("", new DirectoryAssetReader("assets/"));
	VFSRegister("", new DirectoryAssetReader(""));

	for (int i = 1; i < __argc; ++i)
	{
		if (__argv[i][0] == '\0')
			continue;

		if (__argv[i][0] == '-')
		{
			switch (__argv[i][1])
			{
			case 'j':
				g_Config.bJit = true;
				g_Config.bSaveSettings = false;
				break;
			case 'i':
				g_Config.bJit = false;
				g_Config.bSaveSettings = false;
				break;
			case 'l':
				hideLog = false;
				break;
			case 's':
				g_Config.bAutoRun = false;
				g_Config.bSaveSettings = false;
				break;
			case '-':
				if (!strcmp(__argv[i], "--log") && i < __argc - 1)
					fileToLog = __argv[++i];
				if (!strncmp(__argv[i], "--log=", strlen("--log=")) && strlen(__argv[i]) > strlen("--log="))
					fileToLog = __argv[i] + strlen("--log=");
				if (!strcmp(__argv[i], "--state") && i < __argc - 1)
					stateToLoad = __argv[++i];
				if (!strncmp(__argv[i], "--state=", strlen("--state=")) && strlen(__argv[i]) > strlen("--state="))
					stateToLoad = __argv[i] + strlen("--state=");
				break;
			}
		}
		else if (fileToStart == NULL)
		{
			fileToStart = __argv[i];
			if (!File::Exists(fileToStart))
			{
				fprintf(stderr, "File not found: %s\n", fileToStart);
				exit(1);
			}
		}
		else
		{
			fprintf(stderr, "Can only boot one file");
			exit(1);
		}
	}

	//Windows, API init stuff
	INITCOMMONCONTROLSEX comm;
	comm.dwSize = sizeof(comm);
	comm.dwICC = ICC_BAR_CLASSES | ICC_LISTVIEW_CLASSES | ICC_TAB_CLASSES;
	InitCommonControlsEx(&comm);
	timeBeginPeriod(1);
	MainWindow::Init(_hInstance);

	HACCEL hAccelTable = LoadAccelerators(_hInstance, (LPCTSTR)IDR_ACCELS);
	g_hPopupMenus = LoadMenu(_hInstance, (LPCSTR)IDR_POPUPMENUS);

	MainWindow::Show(_hInstance, iCmdShow);
	host = new WindowsHost(MainWindow::GetHWND(), MainWindow::GetDisplayHWND());

	HWND hwndMain = MainWindow::GetHWND();
	HMENU menu = GetMenu(hwndMain);

	//initialize custom controls
	CtrlDisAsmView::init();
	CtrlMemView::init();
	CtrlRegisterList::init();

	DialogManager::AddDlg(memoryWindow[0] = new CMemoryDlg(_hInstance, hwndMain, currentDebugMIPS));
	DialogManager::AddDlg(vfpudlg = new CVFPUDlg(_hInstance, hwndMain, currentDebugMIPS));

	MainWindow::Update();
	MainWindow::UpdateMenus();

	LogManager::Init();
	if (fileToLog != NULL)
		LogManager::GetInstance()->ChangeFileLog(fileToLog);
	LogManager::GetInstance()->GetConsoleListener()->Open(hideLog, 150, 120, "PPSSPP Debug Console");
	LogManager::GetInstance()->SetLogLevel(LogTypes::G3D, LogTypes::LERROR);
	if (fileToStart != NULL)
	{
		MainWindow::SetPlaying(fileToStart);
		MainWindow::Update();
		MainWindow::UpdateMenus();
	}

	// Emu thread is always running!
	EmuThread_Start();

	if (g_Config.bBrowse)
		MainWindow::BrowseAndBoot("");

	if (!hideLog)
		SetForegroundWindow(hwndMain);

	if (fileToStart != NULL && stateToLoad != NULL)
		SaveState::Load(stateToLoad);

	//so.. we're at the message pump of the GUI thread
	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0))	//while no quit
	{
		//DSound_UpdateSound();

		//hack to make it possible to get to main window from floating windows with Esc
		if (msg.hwnd != hwndMain && msg.message==WM_KEYDOWN && msg.wParam==VK_ESCAPE)
			BringWindowToTop(hwndMain);

		//Translate accelerators and dialog messages...
		if (!TranslateAccelerator(hwndMain, hAccelTable, &msg))
		{
			if (!DialogManager::IsDialogMessage(&msg))
			{
				//and finally translate and dispatch
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}
	}

	VFSShutdown();

	LogManager::Shutdown();
	DialogManager::DestroyAll();
	timeEndPeriod(1);
	g_Config.Save();
	delete host;
	return 0;
}
示例#2
0
//Basic Init, create the font, backbuffer, etc
WINDOW *curses_init(void)
{
   // _windows = new WINDOW[20];         //initialize all of our variables
    lastchar=-1;
    inputdelay=-1;

    std::string typeface = "Terminus";
    char * typeface_c = 0;
    std::ifstream fin;
    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;
        if ((fontwidth <= 4) || (fontheight <=4)){
            MessageBox(WindowHandle, "Invalid font size specified!", NULL, 0);
            fontheight = 16;
            fontwidth  = 8;
        }
    }
    typeface_c = new char [typeface.size()+1];
    strcpy (typeface_c, typeface.c_str());

    halfwidth=fontwidth / 2;
    halfheight=fontheight / 2;
    WindowWidth= (55 + (OPTIONS["VIEWPORT_X"] * 2 + 1)) * fontwidth;
    WindowHeight = (OPTIONS["VIEWPORT_Y"] * 2 + 1) *fontheight;

    WinCreate();    //Create the actual window, register it, etc
    timeBeginPeriod(1); // Set Sleep resolution to 1ms
    CheckMessages();    //Let the message queue handle setting up the window

    WindowDC   = GetDC(WindowHandle);
    backbuffer = CreateCompatibleDC(WindowDC);

    BITMAPINFO bmi = BITMAPINFO();
    bmi.bmiHeader.biSize         = sizeof(BITMAPINFOHEADER);
    bmi.bmiHeader.biWidth        = WindowWidth;
    bmi.bmiHeader.biHeight       = -WindowHeight;
    bmi.bmiHeader.biPlanes       = 1;
    bmi.bmiHeader.biBitCount     = 8;
    bmi.bmiHeader.biCompression  = BI_RGB; // Raw RGB
    bmi.bmiHeader.biSizeImage    = WindowWidth * WindowHeight * 1;
    bmi.bmiHeader.biClrUsed      = 16; // Colors in the palette
    bmi.bmiHeader.biClrImportant = 16; // Colors in the palette
    backbit = CreateDIBSection(0, &bmi, DIB_RGB_COLORS, (void**)&dcbits, NULL, 0);
    DeleteObject(SelectObject(backbuffer, backbit));//load the buffer into DC

    // Load private fonts
    if (SetCurrentDirectory("data\\font")){
        WIN32_FIND_DATA findData;
        for (HANDLE findFont = FindFirstFile(".\\*", &findData); findFont != INVALID_HANDLE_VALUE; )
        {
            if (!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)){ // Skip folders
                AddFontResourceExA(findData.cFileName, FR_PRIVATE,NULL);
            }
            if (!FindNextFile(findFont, &findData)){
                FindClose(findFont);
                break;
            }
        }
        SetCurrentDirectory("..\\..");
    }

    // Use desired font, if possible
    font = CreateFont(fontheight, fontwidth, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
                      ANSI_CHARSET, OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,
                      PROOF_QUALITY, FF_MODERN, typeface_c);

    SetBkMode(backbuffer, TRANSPARENT);//Transparent font backgrounds
    SelectObject(backbuffer, font);//Load our font into the DC
//    WindowCount=0;

    delete typeface_c;
    mainwin = newwin((OPTIONS["VIEWPORT_Y"] * 2 + 1),(55 + (OPTIONS["VIEWPORT_Y"] * 2 + 1)),0,0);
    return mainwin;   //create the 'stdscr' window and return its ref
}
示例#3
0
void Sys_Init( void ) {

	CoInitialize( NULL );

	// make sure the timer is high precision, otherwise
	// NT gets 18ms resolution
	timeBeginPeriod( 1 );

	// get WM_TIMER messages pumped every millisecond
//	SetTimer( NULL, 0, 100, NULL );

	cmdSystem->AddCommand( "in_restart", Sys_In_Restart_f, CMD_FL_SYSTEM, "restarts the input system" );
#ifdef DEBUG
	cmdSystem->AddCommand( "createResourceIDs", CreateResourceIDs_f, CMD_FL_TOOL, "assigns resource IDs in _resouce.h files" );
#endif
#if 0
	cmdSystem->AddCommand( "setAsyncSound", Sys_SetAsyncSound_f, CMD_FL_SYSTEM, "set the async sound option" );
#endif

	//
	// Windows user name
	//
	win32.win_username.SetString( Sys_GetCurrentUser() );

	//
	// Windows version
	//
	win32.osversion.dwOSVersionInfoSize = sizeof( win32.osversion );

	if ( !GetVersionEx( (LPOSVERSIONINFO)&win32.osversion ) )
		Sys_Error( "Couldn't get OS info" );

	if ( win32.osversion.dwMajorVersion < 4 ) {
		Sys_Error( GAME_NAME " requires Windows version 4 (NT) or greater" );
	}
	if ( win32.osversion.dwPlatformId == VER_PLATFORM_WIN32s ) {
		Sys_Error( GAME_NAME " doesn't run on Win32s" );
	}

	if( win32.osversion.dwPlatformId == VER_PLATFORM_WIN32_NT ) {
		if( win32.osversion.dwMajorVersion <= 4 ) {
			win32.sys_arch.SetString( "Windows NT (NT)" );
		} else if( win32.osversion.dwMajorVersion == 5 && win32.osversion.dwMinorVersion == 0 ) {
			win32.sys_arch.SetString( "Windows 2K (NT)" );
		} else if( win32.osversion.dwMajorVersion == 5 && win32.osversion.dwMinorVersion == 1 ) {
			win32.sys_arch.SetString( "Windows XP (NT)" );
		} else if ( win32.osversion.dwMajorVersion == 6 ) {
			// jkrige - windows version
			//win32.sys_arch.SetString( "Vista" );
			if( win32.osversion.dwMinorVersion == 0 ) {
				win32.sys_arch.SetString( "Windows Vista" );
			} else if ( win32.osversion.dwMinorVersion == 1 ) {
				win32.sys_arch.SetString( "Windows 7" );
			} else if ( win32.osversion.dwMinorVersion == 2 ) {
				win32.sys_arch.SetString( "Windows 8" );
			} else if ( win32.osversion.dwMinorVersion == 3 ){
				win32.sys_arch.SetString( "Windows 8.1" );
			} else {
				win32.sys_arch.SetString( "Unknown NT 6.x variant" );
			}
			// jkrige - windows version
		} else {
			win32.sys_arch.SetString( "Unknown NT variant" );
		}
	} else if( win32.osversion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ) {
		if( win32.osversion.dwMajorVersion == 4 && win32.osversion.dwMinorVersion == 0 ) {
			// Win95
			if( win32.osversion.szCSDVersion[1] == 'C' ) {
				win32.sys_arch.SetString( "Win95 OSR2 (95)" );
			} else {
				win32.sys_arch.SetString( "Win95 (95)" );
			}
		} else if( win32.osversion.dwMajorVersion == 4 && win32.osversion.dwMinorVersion == 10 ) {
			// Win98
			if( win32.osversion.szCSDVersion[1] == 'A' ) {
				win32.sys_arch.SetString( "Win98SE (95)" );
			} else {
				win32.sys_arch.SetString( "Win98 (95)" );
			}
		} else if( win32.osversion.dwMajorVersion == 4 && win32.osversion.dwMinorVersion == 90 ) {
			// WinMe
		  	win32.sys_arch.SetString( "WinMe (95)" );
		} else {
		  	win32.sys_arch.SetString( "Unknown 95 variant" );
		}
	} else {
		win32.sys_arch.SetString( "unknown Windows variant" );
	}

	//
	// CPU type
	//
	if ( !idStr::Icmp( win32.sys_cpustring.GetString(), "detect" ) ) {
		idStr string;

		common->Printf( "%1.0f MHz ", Sys_ClockTicksPerSecond() / 1000000.0f );

		win32.cpuid = Sys_GetCPUId();

		string.Clear();

		if ( win32.cpuid & CPUID_AMD ) {
			string += "AMD CPU";
		} else if ( win32.cpuid & CPUID_INTEL ) {
			string += "Intel CPU";
		} else if ( win32.cpuid & CPUID_UNSUPPORTED ) {
			string += "unsupported CPU";
		} else {
			string += "generic CPU";
		}

		string += " with ";
		if ( win32.cpuid & CPUID_MMX ) {
			string += "MMX & ";
		}
		if ( win32.cpuid & CPUID_3DNOW ) {
			string += "3DNow! & ";
		}
		if ( win32.cpuid & CPUID_SSE ) {
			string += "SSE & ";
		}
		if ( win32.cpuid & CPUID_SSE2 ) {
            string += "SSE2 & ";
		}
		if ( win32.cpuid & CPUID_SSE3 ) {
			string += "SSE3 & ";
		}
		if ( win32.cpuid & CPUID_HTT ) {
			string += "HTT & ";
		}
		string.StripTrailing( " & " );
		string.StripTrailing( " with " );
		win32.sys_cpustring.SetString( string );
	} else {
		common->Printf( "forcing CPU type to " );
		idLexer src( win32.sys_cpustring.GetString(), idStr::Length( win32.sys_cpustring.GetString() ), "sys_cpustring" );
		idToken token;

		int id = CPUID_NONE;
		while( src.ReadToken( &token ) ) {
			if ( token.Icmp( "generic" ) == 0 ) {
				id |= CPUID_GENERIC;
			} else if ( token.Icmp( "intel" ) == 0 ) {
				id |= CPUID_INTEL;
			} else if ( token.Icmp( "amd" ) == 0 ) {
				id |= CPUID_AMD;
			} else if ( token.Icmp( "mmx" ) == 0 ) {
				id |= CPUID_MMX;
			} else if ( token.Icmp( "3dnow" ) == 0 ) {
				id |= CPUID_3DNOW;
			} else if ( token.Icmp( "sse" ) == 0 ) {
				id |= CPUID_SSE;
			} else if ( token.Icmp( "sse2" ) == 0 ) {
				id |= CPUID_SSE2;
			} else if ( token.Icmp( "sse3" ) == 0 ) {
				id |= CPUID_SSE3;
			} else if ( token.Icmp( "htt" ) == 0 ) {
				id |= CPUID_HTT;
			}
		}
		if ( id == CPUID_NONE ) {
			common->Printf( "WARNING: unknown sys_cpustring '%s'\n", win32.sys_cpustring.GetString() );
			id = CPUID_GENERIC;
		}
		win32.cpuid = (cpuid_t) id;
	}

	common->Printf( "%s\n", win32.sys_cpustring.GetString() );
	common->Printf( "%d MB System Memory\n", Sys_GetSystemRam() );
	common->Printf( "%d MB Video Memory\n", Sys_GetVideoRam() );
}
示例#4
0
void mp_raw_time_init(void)
{
    // request 1ms timer resolution
    timeBeginPeriod(1);
}
示例#5
0
文件: main.c 项目: Davier/WildForest
int main()
{
    // Ressources
    unsigned long t_debut, t_fin;
    float dt, waitShoot = 0;
    BITMAP *buffer;
    int fin = 0, v = 200;
    Map *map;
    DepthList *depthList;
    Rect screen_pos, map_pos;
    Actor *joueur;

    // Initialisation
    fprintf(stderr,"Initialisation ...\n");
    timeBeginPeriod(1);
    set_uformat(U_ASCII);
    set_color_depth(32);
    allegro_init();
    install_keyboard();
    install_mouse();
    srand(time(NULL));

    if(set_gfx_mode(GFX_AUTODETECT_WINDOWED, 1024, 768, 0, 0))
        ERREUR("Echec du lancement du mode graphique.");
    buffer = create_bitmap(SCREEN_W, SCREEN_H);
    resman_loadSprites();

    fprintf(stderr,"Chargement des ressources ...\n");
    map = new_map("media/map/test1");
    map_pos.x = map_pos.y = 0;
    map_pos.w = map->w;
    map_pos.h = map->h;
    actList = new_glist();
    root = new_tree(map_pos);
    map_addEntities(map, actList, root);
    depthList = new_dlist();
    screen_pos.w = SCREEN_W;
    screen_pos.h = SCREEN_H;

    // Ajout du joueur
    joueur = actor_addJoueur(actList, root, 500, 500);

    // Intro
    debut();

    // Boucle principale
    fprintf(stderr,"Debut !\n");
    t_debut = timeGetTime();
    while(!fin)
    {
        // Gestion clavier
        if(key[KEY_ESC])
        {
            fin = 1;
        }
        if(key[KEY_W])
        {
            joueur->vit_y = -v;
            joueur->direction_regard = HAUT;
            joueur->etat = ETAT_MARCHE;
        }
        else if(key[KEY_S])
        {
            joueur->vit_y = v;
            joueur->direction_regard = BAS;
            joueur->etat = ETAT_MARCHE;
        }
        else
            joueur->vit_y = 0;
        if(key[KEY_A])
        {
            joueur->vit_x = -v;
            joueur->direction_regard = GAUCHE;
            joueur->etat = ETAT_MARCHE;
        }
        else if(key[KEY_D])
        {
            joueur->vit_x = v;
            joueur->direction_regard = DROITE;
            joueur->etat = ETAT_MARCHE;
        }
        else
            joueur->vit_x = 0;
        if(joueur->vit_x != 0 && joueur->vit_y != 0)
        {
            joueur->vit_x /= sqrt(2);
            joueur->vit_y /= sqrt(2);
        }
        if(!key[KEY_W] && !key[KEY_D] && !key[KEY_S] && !key[KEY_A])
            joueur->etat = ETAT_REPOS;
        if(key[KEY_Q])
        {
            if(waitShoot <= 0)
            {
                waitShoot = .1;
                actor_addTree(actList, root, mouse_x + screen_pos.x, mouse_y + screen_pos.y);
            }
        }
        waitShoot -= dt;
        if(mouse_b&1)
        {
            float vx, vy, v;
            if(waitShoot <= 0)
            {
                waitShoot = .3;
                vx = mouse_x - (joueur->pos_x - screen_pos.x);
                vy = mouse_y - (joueur->pos_y - screen_pos.y);
                v = sqrt(vx*vx + vy*vy);
                vx = vx/v;
                vy = vy/v;
                actor_addMissile(actList, root, joueur->pos_x + vx*joueur->w*1.5, joueur->pos_y + vy*joueur->h*1.5, vx*300, vy*300);
            }
        }
        if(key[KEY_P])
        {
            FILE *fd = fopen("arbres.txt", "w+");
            Actor *act;
            glist_startIter(actList);
            while(!glist_endIter(actList))
            {
                act = glist_getCurrentData(actList);
                if(act->type == ACT_TREE)
                    fprintf(fd, "%d\n%d\n", (int) act->pos_x, (int) act->pos_y);
                glist_iter(actList);
            }
            fclose(fd);
        }


        // Double buffer
        clear_bitmap(buffer);
        render_map(buffer, map, screen_pos.x, screen_pos.y);


        // Mises à jour
        resman_updateSprites(&dt);
        actor_spawnMonster(actList, root);
        actor_ia(actList, joueur);
        // Deplacement
        glist_startIter(actList);
        while(!glist_endIter(actList))
        {
            actor_update(glist_getCurrentData(actList), map_pos, map, dt);
            if( ((Actor*) glist_getCurrentData(actList))->deleting)
            {
                glist_remCell(actList, glist_getCurrentId(actList));
            }
            else
                glist_iter(actList);
        }
        // Cadrage ecran
        screen_pos.x = joueur->pos_x - SCREEN_W/2;
        screen_pos.y = joueur->pos_y - SCREEN_H/2;

        // Collision
        tree_collisionDetection(root);

        // Affichage
        tree_update(root);
        dlist_getActorsFromTree(depthList, root, screen_pos);
        dlist_update(depthList, screen_pos);
        dlist_blit(depthList, buffer, screen_pos);
        draw_cursor(buffer);
        textprintf_centre_ex(buffer, font, SCREEN_W/2, 5, makecol(0, 0, 0), makecol(255, 0, 0), "   Vies restantes : %d   |   Score : %d   ", joueur->vie, score);

        // Rafraichissement écran
        vsync();
        blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H);

        // Gestion du temps
        t_fin = timeGetTime();
        dt = ((float)t_fin - t_debut)/1000;
        t_debut = t_fin;

        // Test fin de jeu
        if(joueur->deleting)
            fin = 1;
        resman_freeList();
    }
    // Game over
    gameover();

    // Fin
    timeEndPeriod(1);
    delete_map(map);
    del_tree(root);
    del_dlist(depthList);
    del_glist(actList);
    destroy_bitmap(buffer);
    resman_freeSprites();
    allegro_exit();
    return 0;
}
示例#6
0
Boolean DirectSoundInit(MADDriverRec* WinMADDriver)
{
	WinMADDriver->OnOff					= false;
	
	WinMADDriver->WIN95BUFFERSIZE = WinMADDriver->BufSize;
	WinMADDriver->WIN95BUFFERSIZE *= 2L;								// double buffer system
	
	WinMADDriver->currentBuf 		= (Ptr)calloc(WinMADDriver->WIN95BUFFERSIZE, 1);
	
	WinMADDriver->hwnd = GetForegroundWindow();	//GetForegroundWindow();
	if (!WinMADDriver->hwnd) return false;
	
	if(DS_OK == DirectSoundCreate(NULL, &WinMADDriver->lpDirectSound, NULL))
	{
		if (!AppCreateWritePrimaryBuffer(WinMADDriver->lpDirectSound, &WinMADDriver->lpDirectSoundBuffer, WinMADDriver->hwnd, WinMADDriver))
		{
			WinMADDriver->lpDirectSound->lpVtbl->Release(WinMADDriver->lpDirectSound);
			WinMADDriver->lpDirectSound = NULL;
			return false;
		}
		if (!WinMADDriver->lpDirectSoundBuffer) return false;
		
		// Creation succeeded.
		WinMADDriver->lpDirectSound->lpVtbl->SetCooperativeLevel(WinMADDriver->lpDirectSound, WinMADDriver->hwnd, DSSCL_NORMAL);
		
		WinMADDriver->lpSwSamp = NULL;
		if (!LoadSamp(WinMADDriver->lpDirectSound, &WinMADDriver->lpSwSamp, NULL, WinMADDriver->WIN95BUFFERSIZE, DSBCAPS_LOCSOFTWARE, WinMADDriver))
		{
			//DEBUG debugger("Error 2\n"); //DSBCAPS_LOCSOFTWARE
			WinMADDriver->lpDirectSound->lpVtbl->Release(WinMADDriver->lpDirectSound);
			WinMADDriver->lpDirectSound = NULL;
			return false;
		}
		
		if (!WinMADDriver->lpSwSamp) 
		{
			WinMADDriver->lpDirectSound->lpVtbl->Release(WinMADDriver->lpDirectSound);
			return false;
		}
		WinMADDriver->lpSwSamp->lpVtbl->Play(WinMADDriver->lpSwSamp, 0, 0, DSBPLAY_LOOPING);
		
		///////////
		
		timeBeginPeriod(20);      /* set the minimum resolution */
		
		/*  Set up the callback event.  The callback function
		 *  MUST be in a FIXED CODE DLL!!! -> not in Win95
		 */
		 
		// debugger("timeSetEvent\n");
		 
		WinMADDriver->gwID = timeSetEvent(40,   							/* how often					*/
										  40,   							/* timer resolution				*/
										  TimeProc,  						/* callback function			*/
										  (unsigned long) WinMADDriver,		/* info to pass to callback		*/
										  TIME_PERIODIC); 					/* oneshot or periodic?			*/
		
		if (WinMADDriver->gwID == 0) return false;
		else return true;
	}
	
	WinMADDriver->lpDirectSound = NULL;
	
	return false;
}
示例#7
0
/******************************************************************************
Function Name   : TransmissionThreadProc
Input(s)        : pVoid -
Output          :
Functionality   : Transmit thread for the sending waveform messages.
Member of       : Global
Friend of       : -
Author(s)       : Arunkumar K.
Date Created    : 26.08.2010
Modification    :
******************************************************************************/
DWORD WINAPI TransmissionThreadProc(LPVOID pVoid)
{
    pThreadParam = (CPARAM_THREADPROC*) pVoid;
    ASSERT(NULL != pThreadParam);

    CWaveformTransmitter* pCurrObj = static_cast<CWaveformTransmitter*> (pThreadParam->m_pBuffer);
    ASSERT(NULL != pCurrObj);

    UINT SamplingRate = pCurrObj->shGetSamplingTimePeriod();
    int nIterLimit = pCurrObj->nGetIterationLimit();

    TIMECAPS time;
    if (timeGetDevCaps(&time, sizeof(TIMECAPS)) == TIMERR_NOERROR)
    {
        if (time.wPeriodMin <= SamplingRate)
        {
            MMRESULT mmResult = timeBeginPeriod(time.wPeriodMin);
            if (TIMERR_NOCANDO == mmResult)
            {
                // TBD
            }
        }
        else
        {
            ASSERT(FALSE); // Unexpected situation.
        }
    }

    // As thread parameter we need an auto-reset event.
    pThreadParam->m_unActionCode = INVOKE_FUNCTION;
    pThreadParam->m_hActionEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

    MMRESULT Result = timeSetEvent(SamplingRate, SamplingRate /*time.wPeriodMin*/,
                                   (LPTIMECALLBACK) pThreadParam->m_hActionEvent, NULL,
                                   TIME_CALLBACK_EVENT_SET | TIME_PERIODIC);
    ASSERT(NULL != Result);

    bool bLoopON = true;
    int i = 0;

    while (bLoopON)
    {
        WaitForSingleObject(pThreadParam->m_hActionEvent, INFINITE);

        switch (pThreadParam->m_unActionCode)
        {
            case INVOKE_FUNCTION:
            {
                // Calculate signal values at the curent iteration and transmit
                // the message(s).
                pCurrObj->vProcessWaveForm(i);
            }
            break;
            case EXIT_THREAD:
            {
                bLoopON = false;
            }
            break;
            default:
            case INACTION:
            {
                // nothing right at this moment
            }
            break;
        }
        i = (i < nIterLimit) ? ++i : 0;
    }
    SetEvent(pThreadParam->hGetExitNotifyEvent());

    if(Result != 0)
    {
        Result = timeKillEvent(Result);
    }

    pThreadParam = NULL; //thread terminated

    return 0;
}
示例#8
0
int WINAPI WinMain(HINSTANCE _hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow)
{
	Common::EnableCrashingOnCrashes();

	wchar_t modulePath[MAX_PATH];
	GetModuleFileName(NULL, modulePath, MAX_PATH);
	for (size_t i = wcslen(modulePath) - 1; i > 0; i--) {
		if (modulePath[i] == '\\') {
			modulePath[i] = 0;
			break;
		}
	}
	SetCurrentDirectory(modulePath);
	// GetCurrentDirectory(MAX_PATH, modulePath);  // for checking in the debugger
#ifndef _DEBUG
	bool hideLog = true;
#else
	bool hideLog = false;
#endif

	VFSRegister("", new DirectoryAssetReader("assets/"));
	VFSRegister("", new DirectoryAssetReader(""));

	wchar_t lcCountry[256];

	// LOCALE_SNAME is only available in WinVista+
	// Really should find a way to do this in XP too :/
	if (0 != GetLocaleInfo(LOCALE_NAME_USER_DEFAULT, LOCALE_SNAME, lcCountry, 256)) {
		langRegion = ConvertWStringToUTF8(lcCountry);
		for (size_t i = 0; i < langRegion.size(); i++) {
			if (langRegion[i] == '-')
				langRegion[i] = '_';
		}
	} else {
		langRegion = "en_US";
	}

	std::string configFilename;
	const char *configOption = "--config=";

	std::string controlsConfigFilename;
	const char *controlsOption = "--controlconfig=";

	for (int i = 1; i < __argc; ++i)
	{
		if (__argv[i][0] == '\0')
			continue;
		if (__argv[i][0] == '-')
		{
			if (!strncmp(__argv[i], configOption, strlen(configOption)) && strlen(__argv[i]) > strlen(configOption)) {
				configFilename = __argv[i] + strlen(configOption);
			}
			if (!strncmp(__argv[i], controlsOption, strlen(controlsOption)) && strlen(__argv[i]) > strlen(controlsOption)) {
				controlsConfigFilename = __argv[i] + strlen(controlsOption);
			}
		}
	}

	if(configFilename.empty())
		configFilename = "ppsspp.ini";

	if(controlsConfigFilename.empty())
		controlsConfigFilename = "controls.ini";

	// Load config up here, because those changes below would be overwritten
	// if it's not loaded here first.
	g_Config.Load(configFilename.c_str(), controlsConfigFilename.c_str());

	// The rest is handled in NativeInit().
	for (int i = 1; i < __argc; ++i)
	{
		if (__argv[i][0] == '\0')
			continue;

		if (__argv[i][0] == '-')
		{
			switch (__argv[i][1])
			{
			case 'l':
				hideLog = false;
				break;
			case 's':
				g_Config.bAutoRun = false;
				g_Config.bSaveSettings = false;
				break;
			}

			if (!strncmp(__argv[i], "--fullscreen", strlen("--fullscreen")))
				g_Config.bFullScreen = true;

			if (!strncmp(__argv[i], "--windowed", strlen("--windowed")))
				g_Config.bFullScreen = false;
		}
	}

	LogManager::Init();
	LogManager::GetInstance()->GetConsoleListener()->Open(hideLog, 150, 120, "PPSSPP Debug Console");


	//Windows, API init stuff
	INITCOMMONCONTROLSEX comm;
	comm.dwSize = sizeof(comm);
	comm.dwICC = ICC_BAR_CLASSES | ICC_LISTVIEW_CLASSES | ICC_TAB_CLASSES;
	InitCommonControlsEx(&comm);
	timeBeginPeriod(1);
	MainWindow::Init(_hInstance);

	g_hPopupMenus = LoadMenu(_hInstance, (LPCWSTR)IDR_POPUPMENUS);

	MainWindow::Show(_hInstance, iCmdShow);

	HWND hwndMain = MainWindow::GetHWND();
	HWND hwndDisplay = MainWindow::GetDisplayHWND();
	
	//initialize custom controls
	CtrlDisAsmView::init();
	CtrlMemView::init();
	CtrlRegisterList::init();
	CGEDebugger::Init();

	DialogManager::AddDlg(memoryWindow[0] = new CMemoryDlg(_hInstance, hwndMain, currentDebugMIPS));
	DialogManager::AddDlg(vfpudlg = new CVFPUDlg(_hInstance, hwndMain, currentDebugMIPS));

	host = new WindowsHost(hwndMain, hwndDisplay);
	host->SetWindowTitle(0);

	MainWindow::CreateDebugWindows();

	// Emu thread is always running!
	EmuThread_Start();

	HACCEL hAccelTable = LoadAccelerators(_hInstance, (LPCTSTR)IDR_ACCELS);
	HACCEL hDebugAccelTable = LoadAccelerators(_hInstance, (LPCTSTR)IDR_DEBUGACCELS);

	//so.. we're at the message pump of the GUI thread
	for (MSG msg; GetMessage(&msg, NULL, 0, 0); )	// for no quit
	{
		//DSound_UpdateSound();

		if (msg.message == WM_KEYDOWN)
		{
			//hack to enable/disable menu command accelerate keys
			MainWindow::UpdateCommands();

			//hack to make it possible to get to main window from floating windows with Esc
			if (msg.hwnd != hwndMain && msg.wParam == VK_ESCAPE)
				BringWindowToTop(hwndMain);
		}

		//Translate accelerators and dialog messages...
		HWND wnd;
		HACCEL accel;
		if (g_debuggerActive) {
			wnd = disasmWindow[0]->GetDlgHandle();
			accel = hDebugAccelTable;
		} else {
			wnd = hwndMain;
			accel = hAccelTable;
		}

		if (!TranslateAccelerator(wnd, accel, &msg))
		{
			if (!DialogManager::IsDialogMessage(&msg))
			{
				//and finally translate and dispatch
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}
	}

	VFSShutdown();

	EmuThread_Stop();

	DialogManager::DestroyAll();
	timeEndPeriod(1);
	delete host;
	g_Config.Save();
	LogManager::Shutdown();
	return 0;
}
示例#9
0
static int set_high_prio(MSTicker *obj){
	int precision=2;
	int result=0;
	char* env_prio_c=NULL;
	//int min_prio, max_prio, env_prio;
	int prio=obj->prio;
	
	if (prio>MS_TICKER_PRIO_NORMAL){
#ifdef WIN32
		MMRESULT mm;
		TIMECAPS ptc;
		mm=timeGetDevCaps(&ptc,sizeof(ptc));
		if (mm==0){
			if (ptc.wPeriodMin<(UINT)precision)
				ptc.wPeriodMin=precision;
			else
				precision = ptc.wPeriodMin;
			mm=timeBeginPeriod(ptc.wPeriodMin);
			if (mm!=TIMERR_NOERROR){
				ms_warning("timeBeginPeriod failed.");
			}
			ms_message("win32 timer resolution set to %i ms",ptc.wPeriodMin);
		}else{
			ms_warning("timeGetDevCaps failed.");
		}

		if(!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST)){
			ms_warning("SetThreadPriority() failed (%d)\n", GetLastError());
		}
#else
		struct sched_param param;
		int policy=SCHED_RR;
		memset(&param,0,sizeof(param));

		if (prio==MS_TICKER_PRIO_REALTIME)
			policy=SCHED_FIFO;
		
		min_prio = sched_get_priority_min(policy);
		max_prio = sched_get_priority_max(policy);
		env_prio_c = getenv("MS_TICKER_SCHEDPRIO");

		env_prio = (env_prio_c == NULL)?max_prio:atoi(env_prio_c);

		env_prio = MAX(MIN(env_prio, max_prio), min_prio);
		ms_message("Priority used: %d", env_prio);

		param.sched_priority=env_prio;
		if((result=pthread_setschedparam(pthread_self(),policy, &param))) {
			if (result==EPERM){
				/*
					The linux kernel has 
					sched_get_priority_max(SCHED_OTHER)=sched_get_priority_max(SCHED_OTHER)=0.
					As long as we can't use SCHED_RR or SCHED_FIFO, the only way to increase priority of a calling thread
					is to use setpriority().
				*/
				if (setpriority(PRIO_PROCESS,0,-20)==-1){
					ms_message("%s setpriority() failed: %s, nevermind.",obj->name,strerror(errno));
				}else{
					ms_message("%s priority increased to maximum.",obj->name);
				}
			}else ms_warning("%s: Set pthread_setschedparam failed: %s",obj->name,strerror(result));
		} else {
			ms_message("%s priority set to %s and value (%i)",obj->name,
			           policy==SCHED_FIFO ? "SCHED_FIFO" : "SCHED_RR", param.sched_priority);
		}
#endif
	}
	return precision;
}
示例#10
0
//-----------------------------------------------------------------------------
// Name: WinMain()
// Desc: The application's entry point
//-----------------------------------------------------------------------------
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR commandLine, INT)
{
  // this fixes crash if OPENSSL_CONF is set to existed openssl.cfg  
  // need to set it as soon as possible  
  CEnvironment::unsetenv("OPENSSL_CONF");

  // Initializes CreateMiniDump to handle exceptions.
  char ver[100];
  if (strlen(CCompileInfo::GetSuffix()) > 0)
    sprintf_s(ver, "%d.%d-%s Git:%s", CCompileInfo::GetMajor(),
    CCompileInfo::GetMinor(), CCompileInfo::GetSuffix(), CCompileInfo::GetSCMID());
  else
    sprintf_s(ver, "%d.%d Git:%s", CCompileInfo::GetMajor(),
    CCompileInfo::GetMinor(), CCompileInfo::GetSCMID());

  win32_exception::set_version(std::string(ver));
  SetUnhandledExceptionFilter(CreateMiniDump);

  // check if Kodi is already running
  std::string appName = CCompileInfo::GetAppName();
  CreateMutex(nullptr, FALSE, (appName + " Media Center").c_str());
  if (GetLastError() == ERROR_ALREADY_EXISTS)
  {
    HWND hwnd = FindWindow(appName.c_str(), appName.c_str());
    if (hwnd != NULL)
    {
      // switch to the running instance
      ShowWindow(hwnd, SW_RESTORE);
      SetForegroundWindow(hwnd);
    }
    return 0;
  }

  if ((g_cpuInfo.GetCPUFeatures() & CPU_FEATURE_SSE2) == 0)
  {
    MessageBox(NULL, "No SSE2 support detected", (appName + ": Fatal Error").c_str(), MB_OK | MB_ICONERROR);
    return 0;
  }

  //Initialize COM
  CoInitializeEx(nullptr, COINIT_MULTITHREADED);


  int argc;
  LPWSTR* argvW = CommandLineToArgvW(GetCommandLineW(), &argc);

  char** argv = new char*[argc];

  for (int i = 0; i < argc; ++i)
  {
    int size = WideCharToMultiByte(CP_UTF8, 0, argvW[i], -1, nullptr, 0, nullptr, nullptr);
    if (size > 0)
    {
      argv[i] = new char[size];
      int result = WideCharToMultiByte(CP_UTF8, 0, argvW[i], -1, argv[i], size, nullptr, nullptr);
    }
  }

  // Initialise Winsock
  WSADATA wd;
  WSAStartup(MAKEWORD(2, 2), &wd);

  // use 1 ms timer precision - like SDL initialization used to do
  timeBeginPeriod(1);

#ifndef _DEBUG
  // we don't want to see the "no disc in drive" windows message box
  SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
#endif

  // Create and run the app
  int status = main(argc, argv);

  for (int i = 0; i < argc; ++i)
    delete[] argv[i];
  delete[] argv;

  // clear previously set timer resolution
  timeEndPeriod(1);

  WSACleanup();
  CoUninitialize();

  return status;
}
示例#11
0
HRESULT Scheduler::StartScheduler(IMFClock *pClock)
{
    if (m_hSchedulerThread != NULL)
    {
        return E_UNEXPECTED;
    }

    HRESULT hr = S_OK;
    DWORD dwID = 0;

    CopyComPointer(m_pClock, pClock);

    // Set a high the timer resolution (ie, short timer period).
    timeBeginPeriod(1);

    // Create an event to wait for the thread to start.
    m_hThreadReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (m_hThreadReadyEvent == NULL)
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        goto done;
    }

    // Create an event to wait for flush commands to complete.
    m_hFlushEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (m_hFlushEvent == NULL)
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        goto done;
    }

    // Create the scheduler thread.
    m_hSchedulerThread = CreateThread(NULL, 0, SchedulerThreadProc, (LPVOID)this, 0, &dwID);
    if (m_hSchedulerThread == NULL)
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        goto done;
    }

    HANDLE hObjects[] = { m_hThreadReadyEvent, m_hSchedulerThread };
    DWORD dwWait = 0;

    // Wait for the thread to signal the "thread ready" event.
    dwWait = WaitForMultipleObjects(2, hObjects, FALSE, INFINITE);  // Wait for EITHER of these handles.
    if (WAIT_OBJECT_0 != dwWait)
    {
        // The thread terminated early for some reason. This is an error condition.
        CloseHandle(m_hSchedulerThread);
        m_hSchedulerThread = NULL;
        
        hr = E_UNEXPECTED;
        goto done;
    }

    m_dwThreadID = dwID;

done:
    // Regardless success/failure, we are done using the "thread ready" event.
    if (m_hThreadReadyEvent)
    {
        CloseHandle(m_hThreadReadyEvent);
        m_hThreadReadyEvent = NULL;
    }
    return hr;
}
示例#12
0
bool ZApplication::OnCreate(ZLoadingProgress *pLoadingProgress)
{	
	string strFileNameZItem(FILENAME_ZITEM_DESC);
	string strFileNameZItemLocale(FILENAME_ZITEM_DESC_LOCALE);
	string strFileNameZBuff(FILENAME_BUFF_DESC);
	string strFileNameWorlditem(FILENAME_WORLDITEM);
	string strFileNameAbuse(FILENAME_ABUSE);

// #ifndef _DEBUG
// 	strFileNameZItem += ".mef";
// 	strFileNameZItemLocale += ".mef";
// 	strFileNameZBuff += ".mef";
// 	strFileNameWorlditem += ".mef";
// 	strFileNameAbuse += ".mef";
// #endif

	MInitProfile();

	// 멀티미디어 타이머 초기화
	TIMECAPS tc;

	mlog("ZApplication::OnCreate : begin\n");

	//ZGetSoundEngine()->Enumerate();
	//for( int i = 0 ; i < ZGetSoundEngine()->GetEnumDeviceCount() ; ++i)
	//{
	//	sprintf(szDesc, "Sound Device %d = %s\n", i, ZGetSoundEngine()->GetDeviceDescription( i ) );
	//	mlog(szDesc);
	//}

	__BP(2000,"ZApplication::OnCreate");

#define MMTIMER_RESOLUTION	1
	if (TIMERR_NOERROR == timeGetDevCaps(&tc,sizeof(TIMECAPS)))
	{
		m_nTimerRes = min(max(tc.wPeriodMin,MMTIMER_RESOLUTION),tc.wPeriodMax);
		timeBeginPeriod(m_nTimerRes);
	}

	// 한국도 서버리스트 선택 과정이 추가된다.
	// IP가 없으면 로그인화면으로 이동, IP가 있으면 바로 캐릭터 선택창으로 이동
	if (ZApplication::GetInstance()->GetLaunchMode() == ZApplication::ZLAUNCH_MODE_NETMARBLE)
		m_nInitialState = GUNZ_DIRECTLOGIN;

	if (ZGameInterface::m_sbRemainClientConnectionForResetApp == true)
		m_nInitialState = GUNZ_LOBBY;	// if during reload client for changing language, pass login step.

	DWORD _begin_time,_end_time;
#define BEGIN_ { _begin_time = timeGetTime(); }
#define END_(x) { _end_time = timeGetTime(); float f_time = (_end_time - _begin_time) / 1000.f; mlog("\n-------------------> %s : %f \n\n", x,f_time ); }

	__BP(2001,"m_SoundEngine.Create");

	ZLoadingProgress soundLoading("Sound",pLoadingProgress,.12f);
	BEGIN_;
#ifdef _BIRDSOUND
	m_SoundEngine.Create(RealSpace2::g_hWnd, 44100, Z_AUDIO_HWMIXING, GetFileSystem());
#else
	m_SoundEngine.Create(RealSpace2::g_hWnd, Z_AUDIO_HWMIXING, &soundLoading );
#endif
	END_("Sound Engine Create");
	soundLoading.UpdateAndDraw(1.f);

	__EP(2001);

	// mlog("ZApplication::OnCreate : m_SoundEngine.Create\n");
	mlog( "sound engine create.\n" );

//	ZGetInitialLoading()->SetPercentage( 15.0f );
//	ZGetInitialLoading()->Draw( MODE_DEFAULT, 0 , true );

//	loadingProgress.UpdateAndDraw(.3f);

	RegisterForbidKey();

	__BP(2002,"m_pInterface->OnCreate()");

	ZLoadingProgress giLoading("GameInterface",pLoadingProgress,.35f);

	BEGIN_;
	m_pGameInterface=new ZGameInterface("GameInterface",Mint::GetInstance()->GetMainFrame(),Mint::GetInstance()->GetMainFrame());
	m_pGameInterface->m_nInitialState = m_nInitialState;
	if(!m_pGameInterface->OnCreate(&giLoading))
	{
		mlog("Failed: ZGameInterface OnCreate\n");
		SAFE_DELETE(m_pGameInterface);
		return false;
	}

	// mlog("Bird : 5\n");

	m_pGameInterface->SetBounds(0,0,MGetWorkspaceWidth(),MGetWorkspaceHeight());
	END_("GameInterface Create");

	giLoading.UpdateAndDraw(1.f);

	m_pStageInterface = new ZStageInterface();
	m_pOptionInterface = new ZOptionInterface;

	__EP(2002);

#ifdef _BIRDTEST
	goto BirdGo;
#endif

//	ZGetInitialLoading()->SetPercentage( 30.0f );
//	ZGetInitialLoading()->Draw( MODE_DEFAULT, 0 , true );
//	loadingProgress.UpdateAndDraw(.7f);

	__BP(2003,"Character Loading");

	ZLoadingProgress meshLoading("Mesh",pLoadingProgress,.41f);
	BEGIN_;
	// zip filesystem 을 사용하기 때문에 꼭 ZGameInterface 다음에 사용한다...
//	if(m_MeshMgr.LoadXmlList("model/character_lobby.xml")==-1) return false;
	if(m_MeshMgr.LoadXmlList("model/character.xml",ZProgressCallBack,&meshLoading)==-1)	
		return false;

	mlog( "Load character.xml success,\n" );

	END_("Character Loading");
	meshLoading.UpdateAndDraw(1.f);

//	ZLoadingProgress npcLoading("NPC",pLoadingProgress,.1f);
#ifdef _QUEST
	//if(m_NPCMeshMgr.LoadXmlList("model/npc.xml",ZProgressCallBack,&npcLoading) == -1)
	if(m_NPCMeshMgr.LoadXmlList("model/npc.xml") == -1)
		return false;
#endif

	__EP(2003);

	// 모션에 연결된 사운드 파일중 없는것을 제거한다.. 
	// 엔진에서는 사운드에 접근할수없어서.. 
	// 파일체크는 부담이크고~

	CheckSound();

//	npcLoading.UpdateAndDraw(1.f);
	__BP(2004,"WeaponMesh Loading");

	BEGIN_;

	string strFileNameWeapon("model/weapon.xml");
// #ifndef _DEBUG
// 	strFileNameWeapon += ".mef";
// #endif
	if(m_WeaponMeshMgr.LoadXmlList((char*)strFileNameWeapon.c_str())==-1) 
		return false;

	END_("WeaponMesh Loading");

	__EP(2004);

	__BP(2005,"Worlditem Loading");

	ZLoadingProgress etcLoading("etc",pLoadingProgress,.02f);
	BEGIN_;

#ifdef	_WORLD_ITEM_
	m_MeshMgr.LoadXmlList((char*)strFileNameWorlditem.c_str());
#endif

	mlog("Load weapon.xml success. \n");

//*/
	END_("Worlditem Loading");
	__EP(2005);


#ifdef _BIRDTEST
BirdGo:
#endif

	__BP(2006,"ETC .. XML");

	BEGIN_;
	CreateConsole(ZGetGameClient()->GetCommandManager());

	// mlog("ZApplication::OnCreate : CreateConsole \n");

	m_pLogFrame = new MCommandLogFrame("Command Log", Mint::GetInstance()->GetMainFrame(), Mint::GetInstance()->GetMainFrame());
	int nHeight = MGetWorkspaceHeight()/3;
	m_pLogFrame->SetBounds(0, MGetWorkspaceHeight()-nHeight-1, MGetWorkspaceWidth()-1, nHeight);
	m_pLogFrame->Show(false);

	m_pGameInterface->SetFocusEnable(true);
	m_pGameInterface->SetFocus();
	m_pGameInterface->Show(true);


	if (!MGetMatchItemDescMgr()->ReadCache())
	{
		if (!MGetMatchItemDescMgr()->ReadXml(GetFileSystem(), strFileNameZItem.c_str()))
		{
			MLog("Error while Read Item Descriptor %s\n", strFileNameZItem.c_str());
		}
		if (!MGetMatchItemDescMgr()->ReadXml(GetFileSystem(), strFileNameZItemLocale.c_str()))
		{
			MLog("Error while Read Item Descriptor %s\n", strFileNameZItemLocale.c_str());
		}

		MGetMatchItemDescMgr()->WriteCache();
	}
	mlog("Load zitem info success.\n");

	if( !MGetMatchBuffDescMgr()->ReadXml(GetFileSystem(), strFileNameZBuff.c_str()) )
	{
		MLog("Error while Read Buff Descriptor %s\n", strFileNameZBuff.c_str());
	}
	mlog("Load zBuff info success.\n");


//	if (!MGetMatchItemEffectDescMgr()->ReadXml(GetFileSystem(), FILENAME_ZITEMEFFECT_DESC))
//	{
//		MLog("Error while Read Item Descriptor %s\n", FILENAME_ZITEMEFFECT_DESC);
//	}
//	mlog("Init effect manager success.\n");

	if (!MGetMatchWorldItemDescMgr()->ReadXml(GetFileSystem(), strFileNameWorlditem.c_str() ))
	{
		MLog("Error while Read Item Descriptor %s\n", strFileNameWorlditem.c_str());
	}
	mlog("Init world item manager success.\n");

	
	if (!MGetMapDescMgr()->Initialize(GetFileSystem(), "system/map.xml"))
	{
		MLog("Error while Read map Descriptor %s\n", "system/map.xml");
	}
	mlog("Init map Descriptor success.\n");


	string strFileChannelRule("system/channelrule.xml");
// #ifndef _DEBUG
// 	strFileChannelRule += ".mef";
// #endif
	if (!ZGetChannelRuleMgr()->ReadXml(GetFileSystem(), strFileChannelRule.c_str()))
	{
		MLog("Error while Read Item Descriptor %s\n", strFileChannelRule.c_str());
	}
	mlog("Init channel rule manager success.\n");
/*
	if (!MGetNPCGroupMgr()->ReadXml(GetFileSystem(), "system/monstergroup.xml"))
	{
		MLog("Error while Read Item Descriptor %s", "system/monstergroup.xml");
	}
	mlog("ZApplication::OnCreate : ZGetNPCGroupMgr()->ReadXml \n");
*/
	// if (!MGetChattingFilter()->Create(GetFileSystem(), "system/abuse.xml"))
	bool bSucceedLoadAbuse = MGetChattingFilter()->LoadFromFile(GetFileSystem(), strFileNameAbuse.c_str());
	if (!bSucceedLoadAbuse || MGetChattingFilter()->GetNumAbuseWords() == 0)
	{
		// 해킹으로 abuse-list 파일자체를 없애거나 내용을 비웠을 경우 실행을 멈추게 하자
		MLog("Error while Read Abuse Filter %s\n", strFileNameAbuse.c_str());
		MessageBox(NULL, ZErrStr(MERR_FIND_INVALIDFILE), ZMsg( MSG_WARNING), MB_OK);	// TODO: 풀스크린에서 메시지 박스는 좀 곤란함;
		return false;
	}
	mlog( "Init abuse manager success.\n" );

	


#ifdef _QUEST_ITEM
	if( !GetQuestItemDescMgr().ReadXml(GetFileSystem(), FILENAME_QUESTITEM_DESC) )
	{
		MLog( "Error while read quest tiem descrition xml file.\n" );
	}
#endif

	mlog("Init chatting filter. success\n");

	if(!m_SkillManager.Create()) {
		MLog("Error while create skill manager\n");
	}

	END_("ETC ..");

#ifndef _BIRDTEST
	etcLoading.UpdateAndDraw(1.f);
#endif

	//CoInitialize(NULL);

//	ZGetInitialLoading()->SetPercentage( 40.0f );
//	ZGetInitialLoading()->Draw( MODE_DEFAULT, 0 , true );
//	loadingProgress.UpdateAndDraw(1.f);

	ZGetEmblemInterface()->Create();

	__EP(2006);

	__EP(2000);

	__SAVEPROFILE("profile_loading.txt");

	if (ZCheckFileHack() == true)
	{
		MLog("File Check Failed\n");
		return false;
	}

	ZSetupDataChecker_Global(&m_GlobalDataChecker);


#ifdef LOCALE_NHNUSA
	GetNHNUSAReport().ReportInitComplete();
#endif


	return true;
}
示例#13
0
int main(int argc, char *argv[])
{
#ifdef __MINGW32__
	SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);

	// Set the timer resolution on Windows
    TIMECAPS tc;
    UINT     wTimerRes;

    if(timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR)
    {
        std::cerr << "FATAL ERROR: Could not determine supported timer resolutions." << std::endl;
        return 1;
    }

    wTimerRes = std::min(std::max((UINT) tc.wPeriodMin, (UINT) TARGET_RESOLUTION), (UINT) tc.wPeriodMax);
    timeBeginPeriod(wTimerRes);
#endif

	// Parse command line options with boost::program_options
	boost::program_options::options_description desc("Available options");
	desc.add_options()
			("help", "show help message")
			("drone", boost::program_options::value<std::string>(), "set which drone to use (ARDrone2 or Bebop, default is ARDrone2)")
            ("script", boost::program_options::value<std::string>(), "load a python script")
            ("script-args", boost::program_options::value<std::vector<std::string>>()->multitoken(), "arguments for the python script")
			("ip-address", boost::program_options::value<std::string>(), "an alternative IP address for the drone (default is 192.168.1.1 for AR.Drone 2.0 and 192.168.42.1 for Bebop)")
			("stream-resolution", boost::program_options::value<std::string>(), "resolution for the live video stream (360P default, can be set to 720P)")
	;

	boost::program_options::variables_map vm;
	boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
	boost::program_options::notify(vm);

	if(vm.count("help"))
	{
	    std::cout << desc << std::endl;
	    return 1;
	}

	drone_type drone_type = BEBOP;
	std::string ip_address = bebop::DEFAULT_IP;
	std::string stream_res = "360P";

	// Detect which drone to use
	if(vm.count("drone"))
	{
		std::string drone_name = vm["drone"].as<std::string>();
		std::transform(drone_name.begin(), drone_name.end(), drone_name.begin(), ::tolower);
		if(drone_name == "ardrone2")
		{
			std::cout << "Using AR.Drone 2.0" << std::endl;
			ip_address = ardrone2::DEFAULT_IP;
			drone_type = ARDRONE2;
		}
		else if(drone_name == "bebop")
		{
			std::cout << "Using Bebop Drone" << std::endl;
			ip_address = bebop::DEFAULT_IP;
			drone_type = BEBOP;
		}
		else
		{
			std::cout << "Drone not supported. Currently only Parrot's AR.Drone 2.0 and Bebop are supported." << std::endl;
		}
	}

	if(vm.count("ip-address"))
	{
		ip_address = vm["ip-address"].as<std::string>();
		std::cout << "Drone IP address manually set to " << ip_address << std::endl;
	}
	else
	{
		std::cout << "Using default Drone IP address ("<< ip_address <<"). Use the --ip-address option to choose a different address." << std::endl;
	}

	if(vm.count("stream-resolution"))
	{
		stream_res = vm["stream-resolution"].as<std::string>();
	}

	std::cout << "Starting AutoFlight...\n";

	Gamepad_init();
	Gamepad_detectDevices();

	AutoFlight af(drone_type, ip_address);

	// TODO: Allow setting stream resolution
	/*
	if(stream_res == "720P")
	{
		af.ardrone2()->setDefaultLiveStreamCodec(ardrone2::config::codec::H264_720P);
		std::cout << "AR.Drone 2.0 live video stream resolution manually set to " << stream_res << std::endl;
	}
	*/

	QApplication gui(argc, argv);

	AFMainWindow w(&af);
	w.show();

    if(vm.count("script"))
    {
        std::string script = vm["script"].as<std::string>();
        std::vector<std::string> args;
        if(vm.count("script-args"))
        {
            args = vm["script-args"].as<std::vector<std::string>>();
        }
        w.launchAutoScriptIDE(script, args);
    }

	gui.exec();

	Gamepad_shutdown();

	//Py_Finalize();

#ifdef __MINGW32__
    timeEndPeriod(wTimerRes);
#endif

	std::cout << "Closing...\n";

	return 0;
}
示例#14
0
void Timer::initializeTimerSystem()
{
    timeBeginPeriod(1);
    InitializeCriticalSection(&WinAPI_GetTimeCS);

}
示例#15
0
int main(int argc,char **argv)
{
  // initialize generator
  InitTexgen();

  // colors
  Pixel black,white;
  black.Init(0,0,0,255);
  white.Init(255,255,255,255);

  timeBeginPeriod(1);
  sInt startTime = timeGetTime();

  for(sInt i=0;i<100;i++)
  {
    // create gradients
    GenTexture gradBW = LinearGradient(0xff000000,0xffffffff);
    GenTexture gradWB = LinearGradient(0xffffffff,0xff000000);
    GenTexture gradWhite = LinearGradient(0xffffffff,0xffffffff);

    // simple noise test texture
    GenTexture noise;
    noise.Init(256,256);
    noise.Noise(gradBW,2,2,6,0.5f,123,GenTexture::NoiseDirect|GenTexture::NoiseBandlimit|GenTexture::NoiseNormalize);

    /*// save test image
    if(!SaveImage(noise,"noise.tga"))
    {
      printf("Couldn't write 'noise.tga'!\n");
      return 1;
    }*/

    // 4 "random voronoi" textures with different minimum distances
    GenTexture voro[4];
    static sInt voroIntens[4] = {     37,     42,     37,     37 };
    static sInt voroCount[4]  = {     90,    132,    240,    255 };
    static sF32 voroDist[4]   = { 0.125f, 0.063f, 0.063f, 0.063f };

    for(sInt i=0;i<4;i++)
    {
      voro[i].Init(256,256);
      RandomVoronoi(voro[i],gradWhite,voroIntens[i],voroCount[i],voroDist[i]);
    }

    // linear combination of them
    LinearInput inputs[4];
    for(sInt i=0;i<4;i++)
    {
      inputs[i].Tex = &voro[i];
      inputs[i].Weight = 1.5f;
      inputs[i].UShift = 0.0f;
      inputs[i].VShift = 0.0f;
      inputs[i].FilterMode = GenTexture::WrapU|GenTexture::WrapV|GenTexture::FilterNearest;
    }

    GenTexture baseTex;
    baseTex.Init(256,256);
    baseTex.LinearCombine(black,0.0f,inputs,4);

    // blur it
    baseTex.Blur(baseTex,0.0074f,0.0074f,1,GenTexture::WrapU|GenTexture::WrapV);

    // add a noise layer
    GenTexture noiseLayer;
    noiseLayer.Init(256,256);
    noiseLayer.Noise(LinearGradient(0xff000000,0xff646464),4,4,5,0.995f,3,GenTexture::NoiseDirect|GenTexture::NoiseNormalize|GenTexture::NoiseBandlimit);

    baseTex.Paste(baseTex,noiseLayer,0.0f,0.0f,1.0f,0.0f,0.0f,1.0f,GenTexture::CombineAdd,0);

    // colorize it
    Colorize(baseTex,0xff747d8e,0xfff1feff);

    // Create transform matrix for grid pattern
    Matrix44 m1,m2,m3;
    MatTranslate(m1,-0.5f,-0.5f,0.0f);
    MatScale(m2,3.0f * sSQRT2F,3.0f * sSQRT2F,1.0f);
    MatMult(m3,m2,m1);
    MatRotateZ(m1,0.125f * sPI2F);
    MatMult(m2,m1,m3);
    MatTranslate(m1,0.5f,0.5f,0.0f);
    MatMult(m3,m1,m2);

    // Grid pattern GlowRect
    GenTexture rect1,rect1x,rect1n;
    rect1.Init(256,256);
    rect1.LinearCombine(black,1.0f,0,0); // black background
    rect1.GlowRect(rect1,gradWB,0.5f,0.5f,0.41f,0.0f,0.0f,0.25f,0.7805f,0.64f);

    rect1x.Init(256,256);
    rect1x.CoordMatrixTransform(rect1,m3,GenTexture::WrapU|GenTexture::WrapV|GenTexture::FilterBilinear);

    // Make a normalmap from it
    rect1n.Init(256,256);
    rect1n.Derive(rect1x,GenTexture::DeriveNormals,2.5f);

    // Apply as bump map
    GenTexture finalTex;
    Pixel amb,diff;

    finalTex.Init(256,256);
    amb.Init(0xff101010);
    diff.Init(0xffffffff);
    finalTex.Bump(baseTex,rect1n,0,0,0.0f,0.0f,0.0f,-2.518f,0.719f,-3.10f,amb,diff,sTRUE);

    // Second grid pattern GlowRect
    GenTexture rect2,rect2x;
    rect2.Init(256,256);
    rect2.LinearCombine(white,1.0f,0,0); // white background
    rect2.GlowRect(rect2,gradBW,0.5f,0.5f,0.36f,0.0f,0.0f,0.20f,0.8805f,0.74f);

    rect2x.Init(256,256);
    rect2x.CoordMatrixTransform(rect2,m3,GenTexture::WrapU|GenTexture::WrapV|GenTexture::FilterBilinear);

    // Multiply it over
    finalTex.Paste(finalTex,rect2x,0.0f,0.0f,1.0f,0.0f,0.0f,1.0f,GenTexture::CombineMultiply,0);
  }

  sInt totalTime = timeGetTime() - startTime;
  timeEndPeriod(1);

  printf("%d ms/tex\n",totalTime / 100);

  /*SaveImage(baseTex,"baseTex.tga");
  SaveImage(finalTex,"final.tga");*/

  return 0;
}
示例#16
0
		inc_prec(){timeBeginPeriod(1);}
示例#17
0
void DoMain (HINSTANCE hInstance)
{
	LONG WinWidth, WinHeight;
	int height, width, x, y;
	RECT cRect;
	TIMECAPS tc;
	DEVMODE displaysettings;

	try
	{
#ifdef _MSC_VER
		_set_new_handler (NewFailure);
#endif

		Args = new DArgs(__argc, __argv);

		// Under XP, get our session ID so we can know when the user changes/locks sessions.
		// Since we need to remain binary compatible with older versions of Windows, we
		// need to extract the ProcessIdToSessionId function from kernel32.dll manually.
		HMODULE kernel = GetModuleHandle ("kernel32.dll");

		if (Args->CheckParm("-stdout"))
		{
			// As a GUI application, we don't normally get a console when we start.
			// If we were run from the shell and are on XP+, we can attach to its
			// console. Otherwise, we can create a new one. If we already have a
			// stdout handle, then we have been redirected and should just use that
			// handle instead of creating a console window.

			StdOut = GetStdHandle(STD_OUTPUT_HANDLE);
			if (StdOut != NULL)
			{
				// It seems that running from a shell always creates a std output
				// for us, even if it doesn't go anywhere. (Running from Explorer
				// does not.) If we can get file information for this handle, it's
				// a file or pipe, so use it. Otherwise, pretend it wasn't there
				// and find a console to use instead.
				BY_HANDLE_FILE_INFORMATION info;
				if (!GetFileInformationByHandle(StdOut, &info))
				{
					StdOut = NULL;
				}
			}
			if (StdOut == NULL)
			{
				// AttachConsole was introduced with Windows XP. (OTOH, since we
				// have to share the console with the shell, I'm not sure if it's
				// a good idea to actually attach to it.)
				typedef BOOL (WINAPI *ac)(DWORD);
				ac attach_console = kernel != NULL ? (ac)GetProcAddress(kernel, "AttachConsole") : NULL;
				if (attach_console != NULL && attach_console(ATTACH_PARENT_PROCESS))
				{
					StdOut = GetStdHandle(STD_OUTPUT_HANDLE);
					DWORD foo; WriteFile(StdOut, "\n", 1, &foo, NULL);
					AttachedStdOut = true;
				}
				if (StdOut == NULL && AllocConsole())
				{
					StdOut = GetStdHandle(STD_OUTPUT_HANDLE);
				}
				FancyStdOut = true;
			}
		}

		// Set the timer to be as accurate as possible
		if (timeGetDevCaps (&tc, sizeof(tc)) != TIMERR_NOERROR)
			TimerPeriod = 1;	// Assume minimum resolution of 1 ms
		else
			TimerPeriod = tc.wPeriodMin;

		timeBeginPeriod (TimerPeriod);

		/*
		killough 1/98:

		This fixes some problems with exit handling
		during abnormal situations.

		The old code called I_Quit() to end program,
		while now I_Quit() is installed as an exit
		handler and exit() is called to exit, either
		normally or abnormally.
		*/

		atexit (call_terms);

		atterm (I_Quit);

		// Figure out what directory the program resides in.
		char *program;

#ifdef _MSC_VER
		if (_get_pgmptr(&program) != 0)
		{
			I_FatalError("Could not determine program location.");
		}
#else
		char progbuff[1024];
		GetModuleFileName(0, progbuff, sizeof(progbuff));
		progbuff[1023] = '\0';
		program = progbuff;
#endif

		progdir = program;
		program = progdir.LockBuffer();
		*(strrchr(program, '\\') + 1) = '\0';
		FixPathSeperator(program);
		progdir.Truncate((long)strlen(program));
		progdir.UnlockBuffer();
/*
		height = GetSystemMetrics (SM_CYFIXEDFRAME) * 2 +
				GetSystemMetrics (SM_CYCAPTION) + 12 * 32;
		width  = GetSystemMetrics (SM_CXFIXEDFRAME) * 2 + 8 * 78;
*/
		width = 512;
		height = 384;

		// Many Windows structures that specify their size do so with the first
		// element. DEVMODE is not one of those structures.
		memset (&displaysettings, 0, sizeof(displaysettings));
		displaysettings.dmSize = sizeof(displaysettings);
		EnumDisplaySettings (NULL, ENUM_CURRENT_SETTINGS, &displaysettings);
		x = (displaysettings.dmPelsWidth - width) / 2;
		y = (displaysettings.dmPelsHeight - height) / 2;

		if (Args->CheckParm ("-0"))
		{
			x = y = 0;
		}

		WNDCLASS WndClass;
		WndClass.style			= 0;
		WndClass.lpfnWndProc	= LConProc;
		WndClass.cbClsExtra		= 0;
		WndClass.cbWndExtra		= 0;
		WndClass.hInstance		= hInstance;
		WndClass.hIcon			= LoadIcon (hInstance, MAKEINTRESOURCE(IDI_ICON1));
		WndClass.hCursor		= LoadCursor (NULL, IDC_ARROW);
		WndClass.hbrBackground	= NULL;
		WndClass.lpszMenuName	= NULL;
		WndClass.lpszClassName	= (LPCTSTR)WinClassName;
		
		/* register this new class with Windows */
		if (!RegisterClass((LPWNDCLASS)&WndClass))
			I_FatalError ("Could not register window class");
		
		/* create window */
		char caption[100];
		mysnprintf(caption, countof(caption), ""GAMESIG" %s "X64, GetVersionString());
		Window = CreateWindowEx(
				WS_EX_APPWINDOW,
				(LPCTSTR)WinClassName,
				(LPCTSTR)caption,
				WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_CLIPCHILDREN,
				x, y, width, height,
				(HWND)   NULL,
				(HMENU)  NULL,
						hInstance,
				NULL);

		if (!Window)
			I_FatalError ("Could not open window");

		if (kernel != NULL)
		{
			typedef BOOL (WINAPI *pts)(DWORD, DWORD *);
			pts pidsid = (pts)GetProcAddress (kernel, "ProcessIdToSessionId");
			if (pidsid != 0)
			{
				if (!pidsid (GetCurrentProcessId(), &SessionID))
				{
					SessionID = 0;
				}
				hwtsapi32 = LoadLibraryA ("wtsapi32.dll");
				if (hwtsapi32 != 0)
				{
					FARPROC reg = GetProcAddress (hwtsapi32, "WTSRegisterSessionNotification");
					if (reg == 0 || !((BOOL(WINAPI *)(HWND, DWORD))reg) (Window, NOTIFY_FOR_THIS_SESSION))
					{
						FreeLibrary (hwtsapi32);
						hwtsapi32 = 0;
					}
					else
					{
						atterm (UnWTS);
					}
				}
			}
		}

		GetClientRect (Window, &cRect);

		WinWidth = cRect.right;
		WinHeight = cRect.bottom;

		CoInitialize (NULL);
		atterm (UnCOM);

		C_InitConsole (((WinWidth / 8) + 2) * 8, (WinHeight / 12) * 8, false);

		I_DetectOS ();
		D_DoomMain ();
	}
	catch (class CNoRunExit &)
	{
		I_ShutdownGraphics();
		if (FancyStdOut && !AttachedStdOut)
		{ // Outputting to a new console window: Wait for a keypress before quitting.
			DWORD bytes;
			HANDLE stdinput = GetStdHandle(STD_INPUT_HANDLE);

			ShowWindow (Window, SW_HIDE);
			WriteFile(StdOut, "Press any key to exit...", 24, &bytes, NULL);
			FlushConsoleInputBuffer(stdinput);
			SetConsoleMode(stdinput, 0);
			ReadConsole(stdinput, &bytes, 1, &bytes, NULL);
		}
		else if (StdOut == NULL)
		{
			ShowErrorPane(NULL);
		}
		exit(0);
	}
	catch (class CDoomError &error)
	{
		I_ShutdownGraphics ();
		RestoreConView ();
		if (error.GetMessage ())
		{
			ShowErrorPane (error.GetMessage());
		}
		exit (-1);
	}
}
示例#18
0
//=============================================================================
// Call repeatedly by the main message loop in WinMain
//=============================================================================
void Game::run(HWND hwnd)
{
    if(graphics == NULL)            // if graphics not initialized
        return;

    // calculate elapsed time of last frame, save in frameTime
    QueryPerformanceCounter(&timeEnd);
    frameTime = (float)(timeEnd.QuadPart - timeStart.QuadPart ) / (float)timerFreq.QuadPart;

    // Power saving code, requires winmm.lib
    // if not enough time has elapsed for desired frame rate
    if (frameTime < MIN_FRAME_TIME) 
    {
        sleepTime = (DWORD)((MIN_FRAME_TIME - frameTime)*1000);
        timeBeginPeriod(1);         // Request 1mS resolution for windows timer
        Sleep(sleepTime);           // release cpu for sleepTime
        timeEndPeriod(1);           // End 1mS timer resolution
        return;
    }

    if (frameTime > 0.0)
        fps = (fps*0.99f) + (0.01f/frameTime);  // average fps
    if (frameTime > MAX_FRAME_TIME) // if frame rate is very slow
        frameTime = MAX_FRAME_TIME; // limit maximum frameTime
    timeStart = timeEnd;

    // update(), ai(), and collisions() are pure virtual functions.
    // These functions must be provided in the class that inherits from Game.
    if (!paused)                    // if not paused
    {
        update();                   // update all game items
        ai();                       // artificial intelligence
        collisions();               // handle collisions
        input->vibrateControllers(frameTime); // handle controller vibration
    }
    renderGame();                   // draw all game items

    //check for console key
    //if (input->wasKeyPressed(CONSOLE_KEY))
    //{
    //    //console->showHide();
    //    paused = console->getVisible(); // pause game when console is visible
    //}
    //consoleCommand();               // process user entered console command

    input->readControllers();       // read state of controllers

    //messageDialog->update();
    //inputDialog->update();

    audio->run();                   // perform periodic sound engine tasks

    // if Alt+Enter toggle fullscreen/window
    if (input->isKeyDown(ALT_KEY) && input->wasKeyPressed(ENTER_KEY))
        setDisplayMode(graphicsNS::TOGGLE); // toggle fullscreen/window

    // if Esc key, set window mode
    if (input->isKeyDown(ESC_KEY))
        setDisplayMode(graphicsNS::WINDOW); // set window mode

    // Clear input
    // Call this after all key checks are done
    input->clear(inputNS::KEYS_PRESSED);
}
示例#19
0
static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter )
{
TickType_t xMinimumWindowsBlockTime;
TIMECAPS xTimeCaps;

	/* Set the timer resolution to the maximum possible. */
	if( timeGetDevCaps( &xTimeCaps, sizeof( xTimeCaps ) ) == MMSYSERR_NOERROR )
	{
		xMinimumWindowsBlockTime = ( TickType_t ) xTimeCaps.wPeriodMin;
		timeBeginPeriod( xTimeCaps.wPeriodMin );

		/* Register an exit handler so the timeBeginPeriod() function can be
		matched with a timeEndPeriod() when the application exits. */
		SetConsoleCtrlHandler( prvEndProcess, TRUE );
	}
	else
	{
		xMinimumWindowsBlockTime = ( TickType_t ) 20;
	}

	/* Just to prevent compiler warnings. */
	( void ) lpParameter;

	for( ;; )
	{
		/* Wait until the timer expires and we can access the simulated interrupt
		variables.  *NOTE* this is not a 'real time' way of generating tick
		events as the next wake time should be relative to the previous wake
		time, not the time that Sleep() is called.  It is done this way to
		prevent overruns in this very non real time simulated/emulated
		environment. */
		if( portTICK_PERIOD_MS < xMinimumWindowsBlockTime )
		{
			Sleep( xMinimumWindowsBlockTime );
		}
		else
		{
			Sleep( portTICK_PERIOD_MS );
		}

		configASSERT( xPortRunning );

		WaitForSingleObject( pvInterruptEventMutex, INFINITE );

		/* The timer has expired, generate the simulated tick event. */
		ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );

		/* The interrupt is now pending - notify the simulated interrupt
		handler thread. */
		if( ulCriticalNesting == 0 )
		{
			SetEvent( pvInterruptEvent );
		}

		/* Give back the mutex so the simulated interrupt handler unblocks
		and can	access the interrupt handler variables. */
		ReleaseMutex( pvInterruptEventMutex );
	}

	#ifdef __GNUC__
		/* Should never reach here - MingW complains if you leave this line out,
		MSVC complains if you put it in. */
		return 0;
	#endif
}
示例#20
0
文件: main.cpp 项目: mxt819/H405
//=============================================================================
//	エントリー関数
//=============================================================================
int APIENTRY WinMain(HINSTANCE _instanceHandle ,HINSTANCE _instanceHandlePrev, LPSTR _cmdLine, int _cmdShow)
{
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

	UNREFERENCED_PARAMETER(_instanceHandlePrev);
	UNREFERENCED_PARAMETER(_cmdLine);

	DWORD execLastTime;
	DWORD LastTimeFPS;
	DWORD currentTime;
	DWORD flameCount;

	WNDCLASSEX wcex =
	{
		sizeof(WNDCLASSEX),
		CS_CLASSDC,
		WndProc,
		0,
		0,
		_instanceHandle,
		NULL,
		LoadCursor(NULL, IDC_ARROW),
		(HBRUSH)(COLOR_WINDOW + 1),
		NULL,
		CLASS_NAME,
		NULL
	};

	HWND windowHandle;
	MSG msg;
	
	//	ウィンドウクラスの登録
	RegisterClassEx(&wcex);

	//	ウィンドウの作成
	windowHandle = CreateWindowEx(0,
								  CLASS_NAME,
								  WINDOW_NAME,
								  WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX & ~WS_THICKFRAME,
								  CW_USEDEFAULT,
								  CW_USEDEFAULT,
								  static_cast<int>(SCREEN_WIDTH + GetSystemMetrics(SM_CXDLGFRAME) * 2),
								  static_cast<int>(SCREEN_HEIGHT + GetSystemMetrics(SM_CXDLGFRAME) * 2 + GetSystemMetrics(SM_CYCAPTION)),
								  NULL,
								  NULL,
								  _instanceHandle,
								  NULL);

	//	フレームカウント初期化
	timeBeginPeriod(1);	//	分解能を設定
	execLastTime = LastTimeFPS = timeGetTime();
	currentTime = flameCount = 0;

	//	ウインドウの表示(初期化処理の後に呼ばないと駄目)
	ShowWindow(windowHandle, _cmdShow);
	UpdateWindow(windowHandle);


#ifndef _DEBUG
	LoadLibraryA("WiiYourself.dll");
#else
	LoadLibraryA("WiiYourself_debug.dll");
#endif



	LPDIRECT3D9 direct3D;	//	Direct3D9用デバイス
	LPDIRECT3DDEVICE9 device;	//	_deviceオブジェクト(描画に必要)
	D3DDISPLAYMODE displayMode;
	D3DPRESENT_PARAMETERS presentParameter;

	//	Direct3Dオブジェクトの作成
	direct3D = Direct3DCreate9(D3D_SDK_VERSION);
	direct3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &displayMode);

	//	デバイスのプレゼンテーションパラメータの設定
	//--------------------------------------------------------------------
	//	ワークをゼロクリア
	ZeroMemory(&presentParameter, sizeof(presentParameter));

	//	バックバッファの数をセット
	presentParameter.BackBufferCount = 1;

	//ゲーム画面サイズ
	presentParameter.BackBufferWidth = static_cast<int>SCREEN_WIDTH;
	presentParameter.BackBufferHeight = static_cast<int>SCREEN_HEIGHT;

	//	バックバッファフォーマットはディスプレイモードに合わせて使う
	presentParameter.BackBufferFormat = displayMode.Format;

	//	映像信号に同期してフリップする
	presentParameter.SwapEffect = D3DSWAPEFFECT_DISCARD;

	//	ウィンドウモード
	presentParameter.Windowed = TRUE;

	//	デプスバッファ(Zバッファ)とステンシルバッファを作成
	presentParameter.EnableAutoDepthStencil = TRUE;

	//	デプスバッファの利用方法
	//	D3DFMT_D16		デプスバッファのみを16bitとして扱う
	//	D3DFMT_D24S8	デプスバッファを24bit ステンシルバッファを8bitとして扱う
	presentParameter.AutoDepthStencilFormat = D3DFMT_D24S8;

	//	ウィンドウモード
	presentParameter.FullScreen_RefreshRateInHz = 0;
	presentParameter.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
	//--------------------------------------------------------------------

	direct3D->CreateDevice(D3DADAPTER_DEFAULT,
		D3DDEVTYPE_HAL,
		windowHandle,
		D3DCREATE_HARDWARE_VERTEXPROCESSING,
		&presentParameter,
		&device);




	CDebug* debug = new CDebug();
	debug->Init(device);

	CKeyboard* keyboard = new CKeyboard();
	keyboard->Init(_instanceHandle, windowHandle);

	CMouse* mouse = new CMouse();
	mouse->Init(_instanceHandle, windowHandle);

	CWiiController* wiiController = new CWiiController();


	//	メッセージループ
	for (;;)
	{
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			if (msg.message == WM_QUIT)
			{
				//	PostQuitMessage()が呼ばれたらループ終了
				break;
			}
			else
			{
				//	メッセージの翻訳とディスパッチ
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}
		else
		{
			currentTime = timeGetTime();
			if ((currentTime - LastTimeFPS) >= 500)
			{
				#ifdef _DEBUG
					countFPS = flameCount * 1000 / (currentTime - LastTimeFPS);
				#endif

				LastTimeFPS = currentTime;
				flameCount = 0;
			}

			if ((currentTime - execLastTime) >= (1000 / 60))
			{
				execLastTime = currentTime ;


				keyboard->Update();
				mouse->Update();
				wiiController->update();


				{
					//	本体
					{
						debug->SetDebug("本体の加速度X [%f]\n", wiiController->getAccelerationX());
						debug->SetDebug("本体の加速度Y [%f]\n", wiiController->getAccelerationY());
						debug->SetDebug("本体の加速度Z [%f]\n", wiiController->getAccelerationZ());

						debug->SetDebug("本体の回転角X [%f]\n", wiiController->getRotX());
						debug->SetDebug("本体の回転角Y [%f]\n", wiiController->getRotY());
						debug->SetDebug("本体の回転角Z [%f]\n", wiiController->getRotZ());

						debug->SetDebug("本体の回転角の変異X [%f]\n", wiiController->getChangeRotX());
						debug->SetDebug("本体の回転角の変異Y [%f]\n", wiiController->getChangeRotY());
						debug->SetDebug("本体の回転角の変異Z [%f]\n", wiiController->getChangeRotZ());

						debug->SetDebug("本体の角速度X [%f]\n", wiiController->getRotSpeedX());
						debug->SetDebug("本体の角速度Y [%f]\n", wiiController->getRotSpeedY());
						debug->SetDebug("本体の角速度Z [%f]\n", wiiController->getRotSpeedZ());
					}

					//	ヌンチャク
					{
						debug->SetDebug("ヌンチャクの加速度X [%f]\n", wiiController->getAccelerationNX());
						debug->SetDebug("ヌンチャクの加速度Y [%f]\n", wiiController->getAccelerationNY());
						debug->SetDebug("ヌンチャクの加速度Z [%f]\n", wiiController->getAccelerationNZ());

						debug->SetDebug("ヌンチャクの回転角X [%f]\n", wiiController->getRotNX());
						debug->SetDebug("ヌンチャクの回転角Y [%f]\n", wiiController->getRotNY());
						debug->SetDebug("ヌンチャクの回転角Z [%f]\n", wiiController->getRotNZ());

						debug->SetDebug("ヌンチャクの位置X [%f]\n", wiiController->getJoystick().x);
						debug->SetDebug("ヌンチャクの位置Y [%f]\n", wiiController->getJoystick().y);
					}

					//	赤外線
					{
						debug->SetDebug("赤外線X [%f]\n", wiiController->getIR().x);
						debug->SetDebug("赤外線Y [%f]\n", wiiController->getIR().y);
					}

					debug->SetDebug("バッテリー残量[%d%]\n", wiiController->battery());

					debug->SetDebug("モーションPlusの接続状態[%d]\n", wiiController->getMotionConnect());

					/*if (wiiController->getTrigger(WC_A))
						wiiController->rumble(true);

					if (wiiController->getTrigger(WC_B))
						wiiController->rumble(false);

					if (wiiController->getTrigger(WC_UP))
						wiiController->rumble((unsigned int)1000);*/

					//	Aボタン
					{
						if (wiiController->getPress(WC_A))
							debug->SetDebug("A [ON]\n");
						else
							debug->SetDebug("A [OFF]\n");
					}

					//	Bボタン
					{
						if (wiiController->getPress(WC_B))
							debug->SetDebug("B [ON]\n");
						else
							debug->SetDebug("B [OFF]\n");
					}

					//	Cボタン
					{
						if (wiiController->getPress(WC_C))
							debug->SetDebug("C [ON]\n");
						else
							debug->SetDebug("C [OFF]\n");
					}

					//	Zボタン
					{
						if (wiiController->getPress(WC_Z))
							debug->SetDebug("Z [ON]\n");
						else
							debug->SetDebug("Z [OFF]\n");
					}

					//	↑ボタン
					{
						if (wiiController->getPress(WC_UP))
							debug->SetDebug("UP [ON]\n");
						else
							debug->SetDebug("UP [OFF]\n");
					}

					//	↓ボタン
					{
						if (wiiController->getPress(WC_DOWN))
							debug->SetDebug("DOWN [ON]\n");
						else
							debug->SetDebug("DOWN [OFF]\n");
					}

					//	←ボタン
					{
						if (wiiController->getPress(WC_LEFT))
							debug->SetDebug("LEFT [ON]\n");
						else
							debug->SetDebug("LEFT [OFF]\n");
					}

					//	→ボタン
					{
						if (wiiController->getPress(WC_RIGHT))
							debug->SetDebug("RIGHT [ON]\n");
						else
							debug->SetDebug("RIGHT [OFF]\n");
					}

					//	-ボタン
					{
						if (wiiController->getPress(WC_MINUS))
							debug->SetDebug("MINUS [ON]\n");
						else
							debug->SetDebug("MINUS [OFF]\n");

						if(wiiController->getTrigger(WC_MINUS))
							wiiController->rotSpeedCalibration();
					}

					//	+ボタン
					{
						if (wiiController->getPress(WC_PLUS))
							debug->SetDebug("PLUS [ON]\n");
						else
							debug->SetDebug("PLUS [OFF]\n");

						if(wiiController->getTrigger(WC_PLUS))
							wiiController->rotReset();
					}

					//	1ボタン
					{
						if (wiiController->getPress(WC_ONE))
							debug->SetDebug("ONE [ON]\n");
						else
							debug->SetDebug("ONE [OFF]\n");
					}

					//	2ボタン
					{
						if (wiiController->getPress(WC_TWO))
							debug->SetDebug("TWO [ON]\n");
						else
							debug->SetDebug("TWO [OFF]\n");
					}

					//	HOMEボタン
					{
						if (wiiController->getPress(WC_HOME))
							debug->SetDebug("HOME [ON]\n");
						else
							debug->SetDebug("HOME [OFF]\n");
					}
				}

				//	バックバッファ&Zバッファのクリア
				device->Clear(0,
					NULL,
					(D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER),
					D3DCOLOR_RGBA(255, 255, 255, 255),
					1.0f,
					0);

				//	Direct3Dによる描画の開始
				if (SUCCEEDED(device->BeginScene()))
				{
					CDebug::Draw();

					//	Direct3Dによる描画の終了
					device->EndScene();
				}

				//	バックバッファとフロントバッファの入れ替える
				device->Present(NULL, NULL, NULL, NULL);

				flameCount++;
			}
		}
	}

	SAFE_DELETE(wiiController);
	SAFE_DELETE(keyboard);
	SAFE_DELETE(mouse);
	SAFE_DELETE(debug);

	//	ウィンドウクラスの登録を解除
	UnregisterClass(CLASS_NAME, wcex.hInstance);

	timeEndPeriod(1);	//	分解能を戻す

	return static_cast<int>(msg.wParam);
}
示例#21
0
// Get current time
void Timer::IncreaseResolution()
{
#ifdef _WIN32
  timeBeginPeriod(1);
#endif
}
示例#22
0
// ----------------------------------------------------------------------------
// Initialize
// ----------------------------------------------------------------------------
void timer_Initialize( ) {
  timer_usingCounter = (QueryPerformanceFrequency((LARGE_INTEGER*)&timer_counterFrequency))? true: false;
  timeBeginPeriod(1);
}
示例#23
0
bool CALL HGE_Impl::System_Initiate()
{
	OSVERSIONINFO	os_ver;
	SYSTEMTIME		tm;
	MEMORYSTATUS	mem_st;
	WNDCLASS		winclass;
	int				width, height;

	// Log system info

	System_Log("HGE Started..\n");

	System_Log("HGE version: %X.%X", HGE_VERSION>>8, HGE_VERSION & 0xFF);
	GetLocalTime(&tm);
	System_Log("Date: %02d.%02d.%d, %02d:%02d:%02d\n", tm.wDay, tm.wMonth, tm.wYear, tm.wHour, tm.wMinute, tm.wSecond);

	System_Log("Application: %s",szWinTitle);
	os_ver.dwOSVersionInfoSize=sizeof(os_ver);
	GetVersionEx(&os_ver);
	System_Log("OS: Windows %ld.%ld.%ld",os_ver.dwMajorVersion,os_ver.dwMinorVersion,os_ver.dwBuildNumber);

	GlobalMemoryStatus(&mem_st);
	System_Log("Memory: %ldK total, %ldK free\n",mem_st.dwTotalPhys/1024L,mem_st.dwAvailPhys/1024L);


	// Register window class
	
	winclass.style = CS_DBLCLKS | CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
	winclass.lpfnWndProc	= WindowProc;
	winclass.cbClsExtra		= 0;
	winclass.cbWndExtra		= 0;
	winclass.hInstance		= hInstance;
	winclass.hCursor		= LoadCursor(NULL, IDC_ARROW);
	winclass.hbrBackground	= (HBRUSH)GetStockObject(BLACK_BRUSH);
	winclass.lpszMenuName	= NULL; 
	winclass.lpszClassName	= WINDOW_CLASS_NAME;
	if(szIcon) winclass.hIcon = LoadIcon(hInstance, szIcon);
	else winclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	
	if (!RegisterClass(&winclass)) {
		_PostError("Can't register window class");
		return false;
	}

	// Create window

	width=nScreenWidth + GetSystemMetrics(SM_CXFIXEDFRAME)*2;
	height=nScreenHeight + GetSystemMetrics(SM_CYFIXEDFRAME)*2 + GetSystemMetrics(SM_CYCAPTION);

	rectW.left=(GetSystemMetrics(SM_CXSCREEN)-width)/2;
	rectW.top=(GetSystemMetrics(SM_CYSCREEN)-height)/2;
	rectW.right=rectW.left+width;
	rectW.bottom=rectW.top+height;
	styleW=WS_POPUP|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX|WS_VISIBLE; //WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX;

	rectFS.left=0;
	rectFS.top=0;
	rectFS.right=nScreenWidth;
	rectFS.bottom=nScreenHeight;
	styleFS=WS_POPUP|WS_VISIBLE; //WS_POPUP

	if(hwndParent)
	{
		rectW.left=0;
		rectW.top=0;
		rectW.right=nScreenWidth;
		rectW.bottom=nScreenHeight;
		styleW=WS_CHILD|WS_VISIBLE; 
		bWindowed=true;
	}

	if(bWindowed)
		hwnd = CreateWindowEx(0, WINDOW_CLASS_NAME, szWinTitle, styleW,
				rectW.left, rectW.top, rectW.right-rectW.left, rectW.bottom-rectW.top,
				hwndParent, NULL, hInstance, NULL);
	else
		hwnd = CreateWindowEx(WS_EX_TOPMOST, WINDOW_CLASS_NAME, szWinTitle, styleFS,
				0, 0, 0, 0,
				NULL, NULL, hInstance, NULL);
	if (!hwnd)
	{
		_PostError("Can't create window");
		return false;
	}

	ShowWindow(hwnd, SW_SHOW);

	// Init subsystems

	timeBeginPeriod(1);
	Random_Seed();
	_InitPowerStatus();
	_InputInit();
	if(!_GfxInit()) { System_Shutdown(); return false; }
	if(!_SoundInit()) { System_Shutdown(); return false; }

	System_Log("Init done.\n");

	fTime=0.0f;
	t0=t0fps=timeGetTime();
	dt=cfps=0;
	nFPS=0;

	// Show splash

#ifdef DEMO

	bool			(*func)();
	bool			(*rfunc)();
	HWND			hwndTmp;

	if(pHGE->bDMO)
	{
		Sleep(200);
		func=(bool(*)())pHGE->System_GetStateFunc(HGE_FRAMEFUNC);
		rfunc=(bool(*)())pHGE->System_GetStateFunc(HGE_RENDERFUNC);
		hwndTmp=hwndParent; hwndParent=0;
		pHGE->System_SetStateFunc(HGE_FRAMEFUNC, DFrame);
		pHGE->System_SetStateFunc(HGE_RENDERFUNC, 0);
		DInit();
		pHGE->System_Start();
		DDone();
		hwndParent=hwndTmp;
		pHGE->System_SetStateFunc(HGE_FRAMEFUNC, func);
		pHGE->System_SetStateFunc(HGE_RENDERFUNC, rfunc);
	}

#endif

	// Done

	return true;
}
JNIEXPORT jboolean JNICALL
Java_com_vladium_utils_timing_HRTimer_timeBeginPeriod (JNIEnv * e, jclass cls, jint ms)
{
	MMRESULT result = timeBeginPeriod(ms);
    return result == TIMERR_NOERROR;
}