Exemple #1
0
BOOL GameObject::GetObjStat ( char * sStr, int iLen )
{
	sprintf_s (sStr, iLen, "Obj type \'%s\'\nObj name \'%s\'\nPOS \'[%f,%f,%f]\'\n", Class->Name.c_str (), Name.c_str(),GetPosition().x,GetPosition().y,GetPosition().z);
	return TRUE;
}
Exemple #2
0
DWORD GetModuleFileNameA(HMODULE hModule, LPSTR lpFilename, DWORD nSize)
{
#if defined(__linux__)
	int status;
	int length;
	char path[64];

	if (!hModule)
	{
		char buffer[4096];
		sprintf_s(path, ARRAYSIZE(path), "/proc/%d/exe", getpid());
		status = readlink(path, buffer, sizeof(buffer));

		if (status < 0)
		{
			SetLastError(ERROR_INTERNAL_ERROR);
			return 0;
		}

		buffer[status] = '\0';
		length = strlen(buffer);

		if (length < nSize)
		{
			CopyMemory(lpFilename, buffer, length);
			lpFilename[length] = '\0';
			return length;
		}

		CopyMemory(lpFilename, buffer, nSize - 1);
		lpFilename[nSize - 1] = '\0';
		SetLastError(ERROR_INSUFFICIENT_BUFFER);
		return nSize;
	}

#elif defined(__MACOSX__)
	int status;
	int length;

	if (!hModule)
	{
		char path[4096];
		char buffer[4096];
		uint32_t size = sizeof(path);
		status = _NSGetExecutablePath(path, &size);

		if (status != 0)
		{
			/* path too small */
			SetLastError(ERROR_INTERNAL_ERROR);
			return 0;
		}

		/*
		 * _NSGetExecutablePath may not return the canonical path,
		 * so use realpath to find the absolute, canonical path.
		 */
		realpath(path, buffer);
		length = strlen(buffer);

		if (length < nSize)
		{
			CopyMemory(lpFilename, buffer, length);
			lpFilename[length] = '\0';
			return length;
		}

		CopyMemory(lpFilename, buffer, nSize - 1);
		lpFilename[nSize - 1] = '\0';
		SetLastError(ERROR_INSUFFICIENT_BUFFER);
		return nSize;
	}

#endif
	WLog_ERR(TAG, "%s is not implemented", __FUNCTION__);
	SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
	return 0;
}
Exemple #3
0
DWORD EnumDisplayModes(int config_width,
                       int config_height,
                       int config_bpp,
                       bool config_windowed,
                       DisplayModeList& list) {
  list.clear();
  LPDIRECT3D9 d3d = Direct3DCreate9(D3D_SDK_VERSION);
  CONFIRM(d3d) else return -1;

  D3DDISPLAYMODE d3ddm_current;
  d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm_current);
  DWORD current_mode = -1, config_mode = -1, best_windowed_mode = -1;

  typedef std::set<std::pair<int,int>> WindowedModes;
  WindowedModes windowed_modes;

  static const D3DFORMAT ALLOWED_FORMATS[] = { D3DFMT_X1R5G5B5, D3DFMT_R5G6B5, D3DFMT_R8G8B8, D3DFMT_X8R8G8B8 };
  static const int ALLOWED_FORMAT_BPP[] = { 15, 16, 24, 32 };
  static const int ALLOWED_FORMAT_COUNT = 4;
  for (int format = 0; format < ALLOWED_FORMAT_COUNT; ++format) {
    DWORD modes = d3d->GetAdapterModeCount(D3DADAPTER_DEFAULT, ALLOWED_FORMATS[format]);
    DWORD best_windowed_mode_area = 0;
    DisplayMode dm;
    dm.bpp = ALLOWED_FORMAT_BPP[format];
    for (DWORD i =0; i < modes; ++i) {
      D3DDISPLAYMODE d3ddm;
      d3d->EnumAdapterModes(D3DADAPTER_DEFAULT, ALLOWED_FORMATS[format], i, &d3ddm);
      if (d3ddm.Width < 800 || d3ddm.Height < 600) continue; // throw out low resolutions

      dm.width = d3ddm.Width;
      dm.height = d3ddm.Height;

      { // kick out ridiculously widescreen formats
        const float aspect_ratio = (float)d3ddm.Width / (float)d3ddm.Height;
        if (aspect_ratio > 2.0f) continue;
      }

      if (d3ddm_current.Width == d3ddm.Width &&
          d3ddm_current.Height == d3ddm.Height &&
          d3ddm_current.Format == d3ddm.Format) {
        current_mode = list.size();
      }

      if (config_width == dm.width &&
          config_height == dm.height &&
          config_bpp == dm.bpp &&
          config_windowed == false) {
        config_mode = list.size();
      }

      char text[256];
      dm.windowed = false;
      sprintf_s(text, 256, "fullscreen : %i x %i (%i-bit color)", dm.width, dm.height, dm.bpp);
      dm.text = text;
      list.push_back(dm);

      DWORD area = dm.width * dm.height;
      WindowedModes::value_type wm_value(dm.width, dm.height);
      if (area <= (1280*1024) && // only add lower resolutions as windowed modes
          windowed_modes.find(wm_value) == windowed_modes.end()) { // prevent duplication
        windowed_modes.insert(wm_value);
        dm.windowed = true;
        sprintf_s(text, 256, "windowed : %i x %i", dm.width, dm.height);
        dm.text = text;

        if (best_windowed_mode_area < area) {
          best_windowed_mode = list.size();
        }

        if (config_width == dm.width &&
            config_height == dm.height &&
            config_windowed == true) {
          config_mode = list.size();
        }

        list.push_back(dm);
      }
    }
  }

  d3d->Release();
  if (config_mode < list.size()) return config_mode;
  if (current_mode < list.size()) return current_mode;
  return best_windowed_mode;
}
Exemple #4
0
void CZQIniFile::WriteInteger(char* szSection, char* szKey, int iValue)
{
	char szValue[255];
	sprintf_s(szValue, 255,"%d", iValue);
	WritePrivateProfileString((LPCSTR)szSection, (LPCSTR)szKey, (LPCSTR)szValue, (LPCSTR)m_szFileName);
}
Exemple #5
0
void CZQIniFile::WriteBoolean(char* szSection, char* szKey, bool bolValue)
{
	char szValue[255];
	sprintf_s(szValue,255, "%s", bolValue ? "True" : "False");
	WritePrivateProfileString((LPCSTR)szSection, (LPCSTR)szKey, (LPCSTR)szValue, (LPCSTR)m_szFileName);
}
Exemple #6
0
int llParseModList::Exec(void) {
	llWorker::Exec();

	HKEY keyHandle;
	char rgValue [1024];
	//    char fnlRes [1024];
	DWORD size1;
	DWORD Type;

	char *gamekey1 = "SOFTWARE\\Bethesda Softworks\\Oblivion";
	char *gamekey2 = "SOFTWARE\\Wow6432Node\\Bethesda Softworks\\Oblivion";
	if (_llUtils()->IsEnabled("_gamemode")) {
		if (_stricmp(_llUtils()->GetValue("_gamemode"), "Fallout3") == 0) {
			gamekey1 = "SOFTWARE\\Bethesda Softworks\\fallout3";
			gamekey2 = "SOFTWARE\\Wow6432Node\\Bethesda Softworks\\fallout3";
		} else if (_stricmp(_llUtils()->GetValue("_gamemode"), "Falloutnv") == 0) {
			gamekey1 = "SOFTWARE\\Bethesda Softworks\\falloutnv";
			gamekey2 = "SOFTWARE\\Wow6432Node\\Bethesda Softworks\\falloutnv";
		} else if (_stricmp(_llUtils()->GetValue("_gamemode"), "Skyrim") == 0) {
			gamekey1 = "SOFTWARE\\Bethesda Softworks\\skyrim";
			gamekey2 = "SOFTWARE\\Wow6432Node\\Bethesda Softworks\\skyrim";
		}
	}

	//seek for game dir, if not yet set by user
	if (!_llUtils()->IsEnabled("_gamedir")) {
		if( RegOpenKeyEx(HKEY_LOCAL_MACHINE, gamekey1, 0, 
			KEY_QUERY_VALUE, &keyHandle) == ERROR_SUCCESS) {
				size1 = 1023;
				RegQueryValueEx( keyHandle, "Installed Path", NULL, &Type, 
					(LPBYTE)rgValue,&size1);
				char *oblivion_path = new char[strlen(rgValue)+2];
				strcpy_s(oblivion_path, strlen(rgValue)+1, rgValue);
				_llLogger()->WriteNextLine(-LOG_INFO, "Game path is: %s", oblivion_path);
				_llUtils()->SetValue("_gamedir", oblivion_path);
		} else if( RegOpenKeyEx(HKEY_LOCAL_MACHINE, gamekey2, 0, 
			KEY_QUERY_VALUE, &keyHandle) == ERROR_SUCCESS) {
				size1 = 1023;
				RegQueryValueEx( keyHandle, "Installed Path", NULL, &Type, 
					(LPBYTE)rgValue,&size1);
				char *oblivion_path = new char[strlen(rgValue)+2];
				strcpy_s(oblivion_path, strlen(rgValue)+1, rgValue);
				_llLogger()->WriteNextLine(-LOG_INFO, "Game path is: %s", oblivion_path);
				_llUtils()->SetValue("_gamedir", oblivion_path);
		} else {
			if (_llUtils()->IsEnabled("_gamemode"))
			_llLogger()->WriteNextLine(LOG_WARNING, "Game '%s' not installed, I will use the working directory.", 
				_llUtils()->GetValue("_gamemode"));
			else
				_llLogger()->WriteNextLine(LOG_WARNING, "Oblivion not installed, I will use the working directory.");
			TCHAR dir[1000];
			GetCurrentDirectory(1000, dir);
			if ((strlen(dir) > 4) && _stricmp(dir+strlen(dir)-4, "data")==0)
				dir[strlen(dir)-4] = '\0';
			if ((strlen(dir) > 15) && _stricmp(dir+strlen(dir)-15, "data\\ini\\tes4ll")==0)
				dir[strlen(dir)-15] = '\0';
			_llUtils()->SetValue("_gamedir", dir); 
			//DumpExit();
		}
		RegCloseKey(keyHandle);
	} else {
		_llLogger()->WriteNextLine(LOG_INFO,"Game path is: %s", _llUtils()->GetValue("_gamedir"));
	}

	if (cd) {
		_llLogger()->WriteNextLine(LOG_COMMAND,"%s: change directory path to %s", command_name, _llUtils()->GetValue("_gamedir"));
		_chdir(_llUtils()->GetValue("_gamedir"));
		if (_llUtils()->GetValue("_datadir"))
			_chdir(_llUtils()->GetValue("_datadir"));
		else
			_chdir("Data");
	}

	const char *option = _llUtils()->GetValue("_modlist");

	if (!option) { // mod list not provided my main program
		char oblivion_app_path[1024];
		//open registry
		
		if( RegOpenKeyEx(HKEY_CURRENT_USER, 
			"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",0, 
			KEY_QUERY_VALUE, &keyHandle) == ERROR_SUCCESS) {
				size1=1023;
				strcpy_s(rgValue,1024,"\0");
				RegQueryValueEx( keyHandle, "Local Appdata", NULL, &Type, 
					(LPBYTE)rgValue,&size1); //win7
				if (strlen(rgValue) == 0) {
					strcpy_s(rgValue,1024,"\0");
					RegQueryValueEx( keyHandle, "Appdata", NULL, &Type, 
						(LPBYTE)rgValue,&size1); //win XP
				}
				if (strlen(rgValue) == 0) {
					_llLogger()->WriteNextLine(-LOG_FATAL,"Could not get Appdata path!");
				}
				strcpy_s(oblivion_app_path,1024,rgValue);
				_llLogger()->WriteNextLine(LOG_INFO,"Appdata path is: %s",oblivion_app_path);
		} else {
			_llLogger()->WriteNextLine(-LOG_FATAL,"Could not get Appdata path!");
		}
		RegCloseKey(keyHandle);

		char listname[2000];
		sprintf_s(listname,2000,"%s\\Oblivion\\plugins.txt\0", oblivion_app_path);
		if (_llUtils()->IsEnabled("_gamemode")) {
			if (_stricmp(_llUtils()->GetValue("_gamemode"), "Fallout3") == 0) 
				sprintf_s(listname,2000,"%s\\Fallout3\\plugins.txt\0", oblivion_app_path);
			if (_stricmp(_llUtils()->GetValue("_gamemode"), "FalloutNV") == 0) 
				sprintf_s(listname,2000,"%s\\FalloutNV\\plugins.txt\0", oblivion_app_path);
			if (_stricmp(_llUtils()->GetValue("_gamemode"), "Skyrim") == 0) 
				sprintf_s(listname,2000,"%s\\skyrim\\plugins.txt\0", oblivion_app_path);
		}

		FILE *fesplist = NULL;    
		if (fopen_s(&fesplist,listname,"r")) {
			_llLogger()->WriteNextLine(-LOG_FATAL, "Unable to open plugin file \"%s\"\n",listname);
		}

		esp_list[0] = new char[1024];
		while (fgets(esp_list[num_esp],1024,fesplist)) {
			if (esp_list[num_esp][0] != '#' && strlen(esp_list[num_esp])>5) {
				//remove the trailing \n
				if (num_esp == 256) {
					_llLogger()->WriteNextLine(-LOG_FATAL,"Too many mod files\n");
				}
				esp_list[num_esp][strlen(esp_list[num_esp])-1] = '\0';
				//cout << esp_list[num_esp];
				if (num_esp < 256) num_esp++;
				esp_list[num_esp] = new char[1024];
			}
		}
		fclose(fesplist);

		_llLogger()->WriteNextLine(LOG_INFO, "%i plugins will be used", num_esp);

		for (int i=0; i<num_esp; i++) {
			//open the esp
			WIN32_FILE_ATTRIBUTE_DATA fAt = {0};
			char tmpName2[2000];
			sprintf_s(tmpName2,2000, "%s", esp_list[i]); 
			wchar_t tmpName[2000]; 
			swprintf(tmpName, 2000, L"%s", tmpName2); 
			if (!GetFileAttributesEx(tmpName2, GetFileExInfoStandard, &fAt)) {
				_llLogger()->WriteNextLine(-LOG_FATAL, "The mod file '%s' was not found", esp_list[i]);
				//cout << GetLastError() << endl;
			}
			FILETIME time = fAt.ftLastWriteTime;

			esp_list_sorted[num_esp_sorted]  = esp_list[i];
			time_list_sorted[num_esp_sorted] = time;
			num_esp_sorted++;

			for (int j=num_esp_sorted-1; j>0; j--) {  //quicksort
				if (CompareFileTime(&time_list_sorted[j-1], &time_list_sorted[j]) > 0) {
					FILETIME ttmp         = time_list_sorted[j-1];
					char * tmp            = esp_list_sorted[j-1];
					time_list_sorted[j-1] = time_list_sorted[j];
					esp_list_sorted[j-1]  = esp_list_sorted[j];
					time_list_sorted[j]   = ttmp;
					esp_list_sorted[j]    = tmp;
				}
			}
		}

		for (int j=0; j<num_esp_sorted; j++) {
			_llUtils()->AddMod(esp_list_sorted[j]);
			char * my_flag_list = new char[strlen(esp_list_sorted[j]) + 1];
			strcpy_s(my_flag_list, strlen(esp_list_sorted[j])+1, esp_list_sorted[j]);
			for (unsigned int jj=0; jj<strlen(my_flag_list); jj++) {
				if (*(my_flag_list+jj) == ' ' || *(my_flag_list+jj) == ',') *(my_flag_list+jj)='_';
			}
			_llLogger()->WriteNextLine(LOG_INFO, "Mod flag: %s", my_flag_list);
			_llUtils()->AddFlag(my_flag_list);
		}

	} else { //list mod option provided
		char *ptr;          
		char *saveptr1 = NULL;
		char *list_string = _llUtils()->NewString(option);

		for (int ii=0; ii<strlen(list_string)-1; ii++) {
			if (list_string[ii] == '\\' && list_string[ii+1] == ',') {
				list_string[ii+1] = '#';
			}
		}
		
		ptr = strtok_int(list_string, ',', &saveptr1);
		while(ptr != NULL) {
			char *flag_list = _llUtils()->NewString(ptr);
			_llUtils()->StripSpaces(&flag_list);
			flag_list = _llUtils()->Replace(flag_list, "\\#", "\\,");
			flag_list = _llUtils()->ReplaceProtectedKomma(flag_list);
			char *mod_list  = _llUtils()->NewString(ptr);
			_llUtils()->StripSpaces(&mod_list);
			mod_list = _llUtils()->Replace(mod_list, "\\#", "\\,");
			mod_list = _llUtils()->ReplaceProtectedKomma(mod_list);
			_llUtils()->AddMod(mod_list);
			for (unsigned int j=0;j<strlen(flag_list);j++) {
				if (*(flag_list+j) == ' ' || *(flag_list+j) == ',') *(flag_list+j)='_';
			}
			ptr = strtok_int(NULL, ',', &saveptr1);
			_llLogger()->WriteNextLine(LOG_INFO, "Mod flag: %s", flag_list);
			_llUtils()->AddFlag(flag_list);
		}
	}


	return 1;
}
//
// Update Headpose in Game.
//
void FTNoIR_Protocol::sendHeadposeToGame( THeadPoseData *headpose, THeadPoseData *rawheadpose ) {
int no_bytes;
QHostAddress sender;
quint16 senderPort;
PDWORD_PTR MsgResult = 0;

#ifdef SEND_ASCII_DATA
char data[100];
#endif

	//
	// Copy the Raw measurements directly to the client.
	//
	FlightData.x = headpose->x;
	FlightData.y = headpose->y;
	FlightData.z = headpose->z;
	FlightData.p = headpose->pitch;
	FlightData.h = headpose->yaw;
	FlightData.r = headpose->roll;
	FlightData.status = fg_cmd;

	//
	// Try to send an UDP-message to the FlightGear
	//

#ifdef SEND_ASCII_DATA
	sprintf_s(data, "%.2f %.2f %.2f %.2f %.2f %.2f\n\0", FlightData.x, FlightData.y, FlightData.z, FlightData.p, FlightData.h, FlightData.r);

	if (outSocket != 0) {
		no_bytes = outSocket->writeDatagram((const char *) &data, strlen( data ), destIP, destPort);
		if ( no_bytes > 0) {
		qDebug() << "FGServer::writePendingDatagrams says: bytes send =" << data;
		}
		else {
			qDebug() << "FGServer::writePendingDatagrams says: nothing sent!";
		}
	}

#endif

	#ifdef LOG_OUTPUT
	//	Use this for some debug-output to file...
	QFile datafile(QCoreApplication::applicationDirPath() + "\\FG_output.txt");
	if (datafile.open(QFile::WriteOnly | QFile::Append)) {
		QTextStream out(&datafile);
		out << "output:\t" << FlightData.x << "\t" << FlightData.y << "\t" << FlightData.z << "\t" << FlightData.p << "\t" << FlightData.h << "\t" << FlightData.r << '\n';
	}
	#endif

	#ifndef SEND_ASCII_DATA
	//! [1]
//	no_bytes = outSocket->writeDatagram((const char *) &FlightData, sizeof( FlightData ), QHostAddress::LocalHost, 5550);
	if (outSocket != 0) {
		no_bytes = outSocket->writeDatagram((const char *) &FlightData, sizeof( FlightData ), destIP, destPort);
		if ( no_bytes > 0) {
	//		qDebug() << "FGServer::writePendingDatagrams says: bytes send =" << no_bytes << sizeof( double );
		}
		else {
			qDebug() << "FGServer::writePendingDatagrams says: nothing sent!";
		}
	}
	#endif

	//
	// FlightGear keeps sending data, so we must read that here.
	//
	if (inSocket != 0) {
		while (inSocket->hasPendingDatagrams()) {

			QByteArray datagram;
			datagram.resize(inSocket->pendingDatagramSize());

			inSocket->readDatagram( (char * ) &cmd, sizeof(cmd), &sender, &senderPort);

			fg_cmd = cmd;									// Let's just accept that command for now...
			if ( cmd > 0 ) {
				qDebug() << "FGServer::sendHeadposeToGame hasPendingDatagrams, cmd = " << cmd;
//				headTracker->handleGameCommand ( cmd );		// Send it upstream, for the Tracker to handle
			}

			if (!blnConnectionActive) {
				blnConnectionActive = true;
				if (hMainWindow != NULL) {
					SendMessageTimeout( (HWND) hMainWindow, RegisterWindowMessageA(FT_PROGRAMID), 0, 0, 0, 2000, MsgResult);
				}
			}
		}
	}
}
void SetupHooks() {
	logInfo("Setting up hooks.");
	if(hooksSetup) return;

	HMODULE d3dMod = GetModuleHandle("d3d9.dll");
	if(d3dMod == NULL) {
		ErrorMsg("GetModuleHandle(d3d9.dll)");
		return;
	}
	HMODULE d3dxMod = LoadLibrary("d3dx9_43.dll");
	if(d3dxMod == NULL) {
		ErrorMsg("LoadLibrary(d3dx9_43.dll)");
		return;
	}
	HMODULE winmmMod = LoadLibrary("winmm.dll");
	if(winmmMod == NULL) {
		ErrorMsg("LoadLibrary(winmm.dll)");
		return;
	}

	D3DCreate = (pDirect3DCreate9)GetProcAddress(d3dMod, "Direct3DCreate9");
	if(D3DCreate == NULL) {
		ErrorMsg("GetProcAddress(d3dMod, \"Direct3DCreate9\")");
		return;
	}
	oPlaySound = (pPlaySoundA)GetProcAddress(winmmMod, "PlaySoundA");
	if(oPlaySound == NULL) {
		ErrorMsg("GetProcAddress(winmmMod, \"PlaySoundA\")");
		return;
	}
	oD3DXCreateFont = (pD3DXCreateFont)GetProcAddress(d3dxMod, "D3DXCreateFontA");
	if(oD3DXCreateFont == NULL) {
		ErrorMsg("GetProcAddress(d3dxMod, \"D3DXCreateFontA\")");
		return;
	}
	oD3DXCreateLine = (pD3DXCreateLine)GetProcAddress(d3dxMod, "D3DXCreateLine");
	if(oD3DXCreateLine == NULL) {
		ErrorMsg("GetProcAddress(d3dxMod, \"D3DXCreateLine\")");
		return;
	}

	// Create a dummy window to call CreateDevice on
    HWND hwnd;
	hwnd = CreateWindow("BUTTON", "APMAlertDummyWindow", 0, 0, 0, 27, 27, NULL, NULL, hInstance, NULL);
	if(hwnd == NULL) {
		ErrorMsg("CreateWindow");
		return;
	}

    //UpdateWindow(hwnd);

	IDirect3D9 *pD3D = D3DCreate(D3D_SDK_VERSION);
	if(pD3D == NULL) {
		ErrorMsg("Direct3DCreate9");
		return;
	}
	D3DDISPLAYMODE d3ddm;
	HRESULT hRes = pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm);
	if(FAILED(hRes)) { 
		char errorMsg[512];
		const char * dxErrorStr = DXGetErrorString(hRes);
		sprintf_s(errorMsg, 512, "GetAdapterDisplayMode returned 0x%08x: %s", hRes, dxErrorStr);
		logError(errorMsg);
		goto cleanup;
	}
	D3DPRESENT_PARAMETERS d3dpp; 
    ZeroMemory( &d3dpp, sizeof(d3dpp));
    d3dpp.Windowed = true;
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.BackBufferFormat = d3ddm.Format;

	IDirect3DDevice9 * ppD3DDevice;

	hRes = pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd,
						D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_DISABLE_DRIVER_MANAGEMENT,
						&d3dpp, &ppD3DDevice);
	if(FAILED(hRes)) {
		char errorMsg[512];
		const char * dxErrorStr = DXGetErrorString(hRes);
		sprintf_s(errorMsg, 512, "CreateDevice returned 0x%08x: %s", hRes, dxErrorStr);
		logError(errorMsg);
		goto cleanup;
	}

	// Get our function pointers from the virtual table
	// This pointer dereferencing works because the virtual table is the first item in memory
	//  of the every object
	void ** vTable = *((void***)ppD3DDevice);

	// Access the function pointers we need
	addrEndScene = vTable[42]; // EndScene is the 43rd function (you can just count in the interface decl in the header)

	/*
	char path_d3d9_dll[MAX_PATH];
	GetSystemDirectory(path_d3d9_dll, MAX_PATH);	
	strncat_s(path_d3d9_dll, MAX_PATH, "\\d3d9.dll", 10);
	SIZE_T offset = (unsigned int)addrEndScene - (unsigned int)GetModuleHandle(path_d3d9_dll);
	printf("EndScene() Addr: 0x%08x -- SC2.exe!d3d9.dll+0x%x\n", addrEndScene, offset);
	*/

	DWORD oldProtect;
	// backup the top 6 bytes of each function
	if(VirtualProtect(addrEndScene, 6, PAGE_EXECUTE_READWRITE, &oldProtect) == FALSE) {
		ErrorMsg("VirtualProtect");
		return; // make the address read/writable
	}
	memcpy(backup_EndScene, addrEndScene, 6);
	VirtualProtect(addrEndScene, 6, oldProtect, &oldProtect); // restore old protection

	// We are going to write over the top 6 bytes of every function we want to hook.
	// This way, whenever they are called, we can jump to our custom hook function and run our own stuff.
	// To maintain proper game functionality we will restore the backup code, run the function as it should be, 
	// then restore our patch code at the top when it returns to our hook function.
	
	// create our 6 byte patch consisting of: push <addr_hook>; retn (essentially a call that doesn't disturb the stack)
	patch_EndScene[0] = 0x68; // PUSH
	*((DWORD *)(patch_EndScene+1)) = (DWORD)&hkEndScene; // value to push
	patch_EndScene[5] = 0xC3; // RETN

	hooksSetup = true;

	logInfo("Hooks setup and ready for use.");

	ppD3DDevice->Release();
	ppD3DDevice = NULL;
	pD3D->Release();
	pD3D = NULL;

cleanup:
	if(pD3D != NULL)
		pD3D->Release();
	// Destroy the dummy window
	DestroyWindow(hwnd);
}
tUInt32 DAXAudio::WriteSound(string host,tUInt32 port,tByte* data,tUInt32 size)
{
	if (!_player)
		return 0;

#ifdef SPEEX_CODE
	tByte frame[BLOCK_SIZE]={0};
	int voicesize = *((tUInt32*)(data));
	int timestamp = *((tUInt32*)(data+4));

	if (timestamp % FRAME_SIZE != 0)
	{
		LOGWARNING("DAXAudio::WriteSound:Currupted data with timestamp "<<timestamp<<" from "<<host<<"::"<<port<<",abandon the data!");
		return 0;
	}

	if (voicesize!=size-8)
	{
		LOGWARNING("DAXAudio::WriteSound:Currupted data from "<<host<<" for "<<voicesize<<"!="<<size<<"-8,abandon the data!");
		return 0;
	}

#ifdef USING_JITTER
	// find the right jitter and stored the data into
	// check if player can playmore,if yes, get a frame from all jitters and merge them
	// write the merged data into player.
	tByte from[100]={0};
	sprintf_s((char*)from,100,"%s::%u",host.c_str(),port);
	tFromJitterMapIter iter = _from_jitter_map.find(from);

	if (iter==_from_jitter_map.end())
	{
		LOGWARNING("DAXAudio::WriteSound:From "<<from<<" is not registered,abandon the data!");
		return 0;
	}

	speex_jitter_put(iter->second,(char*)(data+8),size-8,timestamp);

	if (_player->ReadyForPlayMore())
	{
		GetMergedFramFromJitters(frame,BLOCK_SIZE);
		_player->WriteSound(frame,BLOCK_SIZE);
		return size;
	}
	else
	{
		LOGWARNING("DAXAudio::WriteSound:Player is busy,wait a momment...");
		return 0;
	}
#else	
	if (_converter->Decode(data+8,size-8,frame,BLOCK_SIZE))
		if(_player->WriteSound(frame,BLOCK_SIZE))
			return size;
	return 0;
#endif	//USING_JITTER

#else
	// just for test, of course coded and sent.
	//if (_player->ReadyForPlayMore())
		return _player->WriteSound(data,size);
	//else
	//	return 0;
#endif	//SPEEX_CODE
}
Exemple #10
0
void oEvent::generatePreReport(gdioutput &gdi)
{
  CurrentSortOrder=SortByName;
  Runners.sort();

  int lVacId = getVacantClub();

  oRunnerList::iterator r_it;
  oTeamList::iterator t_it;

  //BIB, START, NAME, CLUB, RANK, SI
  int dx[6]={0, 0, 70, 300, 470, 470};

  bool withrank = hasRank();
  bool withbib = hasBib(true, true);
  int i;

  if (withrank) dx[5]+=50;
  if (withbib) for(i=1;i<6;i++) dx[i]+=40;

  int y=gdi.getCY();
  int x=gdi.getCX();
  int lh=gdi.getLineHeight();

  gdi.addStringUT(2, lang.tl("Rapport inför: ") + getName());

  gdi.addStringUT(1, getDate());
  gdi.dropLine();
  char bf[256];

  list<pRunner> no_card;
  list<pRunner> no_start;
  list<pRunner> no_class;
  list<pRunner> no_course;
  list<pRunner> no_club;

  for (r_it=Runners.begin(); r_it != Runners.end(); ++r_it){
    if (r_it->isRemoved())
      continue;

    bool needStartTime = true;
    bool needCourse = true;

    pClass pc = r_it->Class;
    if (pc) {
      LegTypes lt = pc->getLegType(r_it->tLeg);
      if (lt == LTIgnore) {
        needStartTime = false;
        needCourse = false;
      }
      if (pc->hasDirectResult())
        needCourse = false;

      StartTypes st = pc->getStartType(r_it->tLeg);

      if (st != STTime && st != STDrawn)
        needStartTime = false;

      if (pc->hasFreeStart())
        needStartTime = false;
    }
    if ( r_it->getClubId() != lVacId) {
      if (needCourse && r_it->getCardNo()==0)
        no_card.push_back(&*r_it);
      if (needStartTime && r_it->getStartTime()==0)
        no_start.push_back(&*r_it);
      if (r_it->getClubId()==0)
        no_club.push_back(&*r_it);
    }

    if (r_it->getClassId()==0)
      no_class.push_back(&*r_it);
    else if (needCourse && r_it->getCourse(false)==0)
      no_course.push_back(&*r_it);
  }

  list<pRunner> si_duplicate;

  if (Runners.size()>1){
    Runners.sort(oRunner::CompareSINumber);

    r_it=Runners.begin();
    while (++r_it != Runners.end()){
      oRunnerList::iterator r_it2=r_it;
      r_it2--;

      if (r_it2->getCardNo() && r_it2->getCardNo()==r_it->getCardNo()){

        if (si_duplicate.size()==0 || si_duplicate.back()->getId()!=r_it2->getId())
          si_duplicate.push_back(&*r_it2);

        si_duplicate.push_back(&*r_it);
      }
    }
  }

  const string Ellipsis="[ ... ]";

  sprintf_s(bf, lang.tl("Löpare utan klass: %d.").c_str(), no_class.size());
  gdi.addStringUT(1, bf);
  i=0;

  while(!no_class.empty() && ++i<20){
    pRunner r=no_class.front();
    no_class.pop_front();
    sprintf_s(bf, "%s (%s)", r->getName().c_str(), r->getClub().c_str());
    gdi.addStringUT(0, bf);
  }
  if (!no_class.empty()) gdi.addStringUT(1, Ellipsis);

  gdi.dropLine();
  sprintf_s(bf, lang.tl("Löpare utan bana: %d.").c_str(), no_course.size());
  gdi.addStringUT(1, bf);
  i=0;

  while(!no_course.empty() && ++i<20){
    pRunner r=no_course.front();
    no_course.pop_front();
    sprintf_s(bf, "%s: %s (%s)", r->getClass().c_str(), r->getName().c_str(), r->getClub().c_str());
    gdi.addStringUT(0, bf);
  }
  if (!no_course.empty()) gdi.addStringUT(1, Ellipsis);

  if (oe->getMeOSFeatures().hasFeature(MeOSFeatures::Clubs)) {
    gdi.dropLine();
    sprintf_s(bf, lang.tl("Löpare utan klubb: %d.").c_str(), no_club.size());
    gdi.addStringUT(1, bf);
    i=0;

    while(!no_club.empty() && ++i<20){
      pRunner r=no_club.front();
      no_club.pop_front();
      sprintf_s(bf, "%s: %s", r->getClass().c_str(), r->getName().c_str());
      gdi.addStringUT(0, bf);
    }
    if (!no_club.empty()) gdi.addStringUT(1, Ellipsis);
  }

  gdi.dropLine();
  sprintf_s(bf, lang.tl("Löpare utan starttid: %d.").c_str(), no_start.size());
  gdi.addStringUT(1, bf);
  i=0;

  while(!no_start.empty() && ++i<20){
    pRunner r=no_start.front();
    no_start.pop_front();
    sprintf_s(bf, "%s: %s (%s)", r->getClass().c_str(), r->getName().c_str(), r->getClub().c_str());
    gdi.addStringUT(0, bf);
  }
  if (!no_start.empty()) gdi.addStringUT(1, Ellipsis);

  gdi.dropLine();
  sprintf_s(bf, lang.tl("Löpare utan SI-bricka: %d.").c_str(), no_card.size());
  gdi.addStringUT(1, bf);
  i=0;

  while(!no_card.empty() && ++i<20){
    pRunner r=no_card.front();
    no_card.pop_front();
    sprintf_s(bf, "%s: %s (%s)", r->getClass().c_str(), r->getName().c_str(), r->getClub().c_str());
    gdi.addStringUT(0, bf);
  }
  if (!no_card.empty()) gdi.addStringUT(1, Ellipsis);


  gdi.dropLine();
  sprintf_s(bf, lang.tl("SI-dubbletter: %d.").c_str(), si_duplicate.size());
  gdi.addStringUT(1, bf);
  i=0;

  while(!si_duplicate.empty() && ++i<20){
    pRunner r=si_duplicate.front();
    si_duplicate.pop_front();
    sprintf_s(bf, "%s: %s (%s) SI=%d", r->getClass().c_str(),
              r->getName().c_str(), r->getClub().c_str(), r->getCardNo());
    gdi.addStringUT(0, bf);
  }
  if (!si_duplicate.empty()) gdi.addStringUT(1, Ellipsis);


  //List all competitors not in a team.
  if (oe->hasTeam()) {
    for (r_it=Runners.begin(); r_it != Runners.end(); ++r_it)
      r_it->_objectmarker=0;

    for (t_it=Teams.begin(); t_it != Teams.end(); ++t_it){
      pClass pc=getClass(t_it->getClassId());

      if (pc){
        for(unsigned i=0;i<pc->getNumStages();i++){
          pRunner r=t_it->getRunner(i);
          if (r) r->_objectmarker++;
        }
      }
    }

    gdi.dropLine();
    gdi.addString("", 1, "Löpare som förekommer i mer än ett lag:");
    bool any = false;
    for (r_it=Runners.begin(); r_it != Runners.end(); ++r_it){
      if (r_it->_objectmarker>1){
        sprintf_s(bf, "%s: %s (%s)", r_it->getClass().c_str(), r_it->getName().c_str(), r_it->getClub().c_str());
        gdi.addStringUT(0, bf);
        any = true;
      }
    }
    if (!any)
      gdi.addStringUT(1, "0");
  }
  sortRunners(ClassStartTime);

  gdi.dropLine();
  gdi.addString("", 1, "Individuella deltagare");

  y=gdi.getCY();
  int tab[5]={0, 100, 350, 420, 550};
  for (r_it=Runners.begin(); r_it != Runners.end(); ++r_it){
    if (r_it->_objectmarker==0){ //Only consider runners not in a team.
      gdi.addStringUT(y, x+tab[0], 0, r_it->getClass(), tab[1]-tab[0]);
      gdi.addStringUT(y, x+tab[1], 0, r_it->getName()+" ("+r_it->getClub()+")", tab[2]-tab[1]);
      gdi.addStringUT(y, x+tab[2], 0, itos(r_it->getCardNo()), tab[3]-tab[2]);
      gdi.addStringUT(y, x+tab[3], 0, r_it->getCourseName(), tab[4]-tab[3]);
      y+=lh;
      pCourse pc=r_it->getCourse(true);

      if (pc){
        vector<string> res = pc->getCourseReadable(101);
        for (size_t k = 0; k<res.size(); k++) {
          gdi.addStringUT(y, x+tab[1], 0, res[k]);
          y+=lh;
        }
      }
    }
  }

  gdi.dropLine();
  gdi.addString("", 1, "Lag(flera)");

  for (t_it=Teams.begin(); t_it != Teams.end(); ++t_it){
    pClass pc=getClass(t_it->getClassId());

    gdi.addStringUT(0, t_it->getClass() + ": " + t_it->getName() + "  " +t_it->getStartTimeS());

    if (pc){
      for(unsigned i=0;i<pc->getNumStages();i++){
        pRunner r=t_it->getRunner(i);
        if (r){
          gdi.addStringUT(0, r->getName()+ " SI: " +itos(r->getCardNo()));

          pCourse pcourse=r->getCourse(true);

          if (pcourse){
            y = gdi.getCY();
            vector<string> res = pcourse->getCourseReadable(101);
            for (size_t k = 0; k<res.size(); k++) {
              gdi.addStringUT(y, x+tab[1], 0, res[k]);
              y+=lh;
            }
          }
        }
        else
          gdi.addString("", 0, "Löpare saknas");
      }
    }
    gdi.dropLine();
  }

  gdi.updateScrollbars();
}
std::string CreateOperation::GetOpDescription() const
{
	char buffer[512];
	sprintf_s(buffer, sizeof(buffer), "%s, ID: %lli, Name: %s, Value: %s", GetTypeName(), m_elementGuid, m_name->GetString().c_str(), m_startingValue.ToString().c_str());
	return buffer;
}
Exemple #12
0
VOID
PrintIrpCode(
    __in UCHAR MajorCode,
    __in UCHAR MinorCode,
    __in_opt FILE *OutputFile,
    __in BOOLEAN PrintMajorCode
)
/*++

Routine Description:

    Display the operation code

Arguments:

    MajorCode - Major function code of operation

    MinorCode - Minor function code of operation

    OutputFile - If writing to a file (not the screen) the handle for that file

    PrintMajorCode - Only used when printing to the display:
        TRUE - if we want to display the MAJOR CODE
        FALSE - if we want to display the MINOR code

Return Value:

    None

--*/
{
    CHAR *irpMajorString, *irpMinorString = NULL;
    CHAR formatBuf[128];
    CHAR errorBuf[128];

    switch (MajorCode) {
        case IRP_MJ_CREATE:
            irpMajorString = IRP_MJ_CREATE_STRING;
            break;
        case IRP_MJ_CREATE_NAMED_PIPE:
            irpMajorString = IRP_MJ_CREATE_NAMED_PIPE_STRING;
            break;
        case IRP_MJ_CLOSE:
            irpMajorString = IRP_MJ_CLOSE_STRING;
            break;
        case IRP_MJ_READ:
            irpMajorString = IRP_MJ_READ_STRING;
            switch (MinorCode) {
                case IRP_MN_NORMAL:
                    irpMinorString = IRP_MN_NORMAL_STRING;
                    break;
                case IRP_MN_DPC:
                    irpMinorString = IRP_MN_DPC_STRING;
                    break;
                case IRP_MN_MDL:
                    irpMinorString = IRP_MN_MDL_STRING;
                    break;
                case IRP_MN_COMPLETE:
                    irpMinorString = IRP_MN_COMPLETE_STRING;
                    break;
                case IRP_MN_COMPRESSED:
                    irpMinorString = IRP_MN_COMPRESSED_STRING;
                    break;
                case IRP_MN_MDL_DPC:
                    irpMinorString = IRP_MN_MDL_DPC_STRING;
                    break;
                case IRP_MN_COMPLETE_MDL:
                    irpMinorString = IRP_MN_COMPLETE_MDL_STRING;
                    break;
                case IRP_MN_COMPLETE_MDL_DPC:
                    irpMinorString = IRP_MN_COMPLETE_MDL_DPC_STRING;
                    break;
                default:
                    sprintf_s(errorBuf,sizeof(errorBuf),"Unknown Irp minor code (%u)",MinorCode);
                    irpMinorString = errorBuf;
            }
            break;

        case IRP_MJ_WRITE:
            irpMajorString = IRP_MJ_WRITE_STRING;
            switch (MinorCode) {
                case IRP_MN_NORMAL:
                    irpMinorString = IRP_MN_NORMAL_STRING;
                    break;
                case IRP_MN_DPC:
                    irpMinorString = IRP_MN_DPC_STRING;
                    break;
                case IRP_MN_MDL:
                    irpMinorString = IRP_MN_MDL_STRING;
                    break;
                case IRP_MN_COMPLETE:
                    irpMinorString = IRP_MN_COMPLETE_STRING;
                    break;
                case IRP_MN_COMPRESSED:
                    irpMinorString = IRP_MN_COMPRESSED_STRING;
                    break;
                case IRP_MN_MDL_DPC:
                    irpMinorString = IRP_MN_MDL_DPC_STRING;
                    break;
                case IRP_MN_COMPLETE_MDL:
                    irpMinorString = IRP_MN_COMPLETE_MDL_STRING;
                    break;
                case IRP_MN_COMPLETE_MDL_DPC:
                    irpMinorString = IRP_MN_COMPLETE_MDL_DPC_STRING;
                    break;
                default:
                    sprintf_s(errorBuf,sizeof(errorBuf),"Unknown Irp minor code (%u)",MinorCode);
                    irpMinorString = errorBuf;
            }
            break;

        case IRP_MJ_QUERY_INFORMATION:
            irpMajorString = IRP_MJ_QUERY_INFORMATION_STRING;
            break;
        case IRP_MJ_SET_INFORMATION:
            irpMajorString = IRP_MJ_SET_INFORMATION_STRING;
            break;
        case IRP_MJ_QUERY_EA:
            irpMajorString = IRP_MJ_QUERY_EA_STRING;
            break;
        case IRP_MJ_SET_EA:
            irpMajorString = IRP_MJ_SET_EA_STRING;
            break;
        case IRP_MJ_FLUSH_BUFFERS:
            irpMajorString = IRP_MJ_FLUSH_BUFFERS_STRING;
            break;
        case IRP_MJ_QUERY_VOLUME_INFORMATION:
            irpMajorString = IRP_MJ_QUERY_VOLUME_INFORMATION_STRING;
            break;
        case IRP_MJ_SET_VOLUME_INFORMATION:
            irpMajorString = IRP_MJ_SET_VOLUME_INFORMATION_STRING;
            break;
        case IRP_MJ_DIRECTORY_CONTROL:
            irpMajorString = IRP_MJ_DIRECTORY_CONTROL_STRING;
            switch (MinorCode) {
                case IRP_MN_QUERY_DIRECTORY:
                    irpMinorString = IRP_MN_QUERY_DIRECTORY_STRING;
                    break;
                case IRP_MN_NOTIFY_CHANGE_DIRECTORY:
                    irpMinorString = IRP_MN_NOTIFY_CHANGE_DIRECTORY_STRING;
                    break;
                default:
                    sprintf_s(errorBuf,sizeof(errorBuf),"Unknown Irp minor code (%u)",MinorCode);
                    irpMinorString = errorBuf;
            }
            break;

        case IRP_MJ_FILE_SYSTEM_CONTROL:
            irpMajorString = IRP_MJ_FILE_SYSTEM_CONTROL_STRING;
            switch (MinorCode) {
                case IRP_MN_USER_FS_REQUEST:
                    irpMinorString = IRP_MN_USER_FS_REQUEST_STRING;
                    break;
                case IRP_MN_MOUNT_VOLUME:
                    irpMinorString = IRP_MN_MOUNT_VOLUME_STRING;
                    break;
                case IRP_MN_VERIFY_VOLUME:
                    irpMinorString = IRP_MN_VERIFY_VOLUME_STRING;
                    break;
                case IRP_MN_LOAD_FILE_SYSTEM:
                    irpMinorString = IRP_MN_LOAD_FILE_SYSTEM_STRING;
                    break;
                case IRP_MN_TRACK_LINK:
                    irpMinorString = IRP_MN_TRACK_LINK_STRING;
                    break;
                default:
                    sprintf_s(errorBuf,sizeof(errorBuf),"Unknown Irp minor code (%u)",MinorCode);
                    irpMinorString = errorBuf;
            }
            break;

        case IRP_MJ_DEVICE_CONTROL:
            irpMajorString = IRP_MJ_DEVICE_CONTROL_STRING;
            switch (MinorCode) {
                case IRP_MN_SCSI_CLASS:
                    irpMinorString = IRP_MN_SCSI_CLASS_STRING;
                    break;
                default:
                    sprintf_s(errorBuf,sizeof(errorBuf),"Unknown Irp minor code (%u)",MinorCode);
                    irpMinorString = errorBuf;
            }
            break;

        case IRP_MJ_INTERNAL_DEVICE_CONTROL:
            irpMajorString = IRP_MJ_INTERNAL_DEVICE_CONTROL_STRING;
            break;
        case IRP_MJ_SHUTDOWN:
            irpMajorString = IRP_MJ_SHUTDOWN_STRING;
            break;
        case IRP_MJ_LOCK_CONTROL:
            irpMajorString = IRP_MJ_LOCK_CONTROL_STRING;
            switch (MinorCode) {
                case IRP_MN_LOCK:
                    irpMinorString = IRP_MN_LOCK_STRING;
                    break;
                case IRP_MN_UNLOCK_SINGLE:
                    irpMinorString = IRP_MN_UNLOCK_SINGLE_STRING;
                    break;
                case IRP_MN_UNLOCK_ALL:
                    irpMinorString = IRP_MN_UNLOCK_ALL_STRING;
                    break;
                case IRP_MN_UNLOCK_ALL_BY_KEY:
                    irpMinorString = IRP_MN_UNLOCK_ALL_BY_KEY_STRING;
                    break;
                default:
                    sprintf_s(errorBuf,sizeof(errorBuf),"Unknown Irp minor code (%u)",MinorCode);
                    irpMinorString = errorBuf;
            }
            break;

        case IRP_MJ_CLEANUP:
            irpMajorString = IRP_MJ_CLEANUP_STRING;
            break;
        case IRP_MJ_CREATE_MAILSLOT:
            irpMajorString = IRP_MJ_CREATE_MAILSLOT_STRING;
            break;
        case IRP_MJ_QUERY_SECURITY:
            irpMajorString = IRP_MJ_QUERY_SECURITY_STRING;
            break;
        case IRP_MJ_SET_SECURITY:
            irpMajorString = IRP_MJ_SET_SECURITY_STRING;
            break;
        case IRP_MJ_POWER:
            irpMajorString = IRP_MJ_POWER_STRING;
            switch (MinorCode) {
                case IRP_MN_WAIT_WAKE:
                    irpMinorString = IRP_MN_WAIT_WAKE_STRING;
                    break;
                case IRP_MN_POWER_SEQUENCE:
                    irpMinorString = IRP_MN_POWER_SEQUENCE_STRING;
                    break;
                case IRP_MN_SET_POWER:
                    irpMinorString = IRP_MN_SET_POWER_STRING;
                    break;
                case IRP_MN_QUERY_POWER:
                    irpMinorString = IRP_MN_QUERY_POWER_STRING;
                    break;
                default :
                    sprintf_s(errorBuf,sizeof(errorBuf),"Unknown Irp minor code (%u)",MinorCode);
                    irpMinorString = errorBuf;
            }
            break;

        case IRP_MJ_SYSTEM_CONTROL:
            irpMajorString = IRP_MJ_SYSTEM_CONTROL_STRING;
            switch (MinorCode) {
                case IRP_MN_QUERY_ALL_DATA:
                    irpMinorString = IRP_MN_QUERY_ALL_DATA_STRING;
                    break;
                case IRP_MN_QUERY_SINGLE_INSTANCE:
                    irpMinorString = IRP_MN_QUERY_SINGLE_INSTANCE_STRING;
                    break;
                case IRP_MN_CHANGE_SINGLE_INSTANCE:
                    irpMinorString = IRP_MN_CHANGE_SINGLE_INSTANCE_STRING;
                    break;
                case IRP_MN_CHANGE_SINGLE_ITEM:
                    irpMinorString = IRP_MN_CHANGE_SINGLE_ITEM_STRING;
                    break;
                case IRP_MN_ENABLE_EVENTS:
                    irpMinorString = IRP_MN_ENABLE_EVENTS_STRING;
                    break;
                case IRP_MN_DISABLE_EVENTS:
                    irpMinorString = IRP_MN_DISABLE_EVENTS_STRING;
                    break;
                case IRP_MN_ENABLE_COLLECTION:
                    irpMinorString = IRP_MN_ENABLE_COLLECTION_STRING;
                    break;
                case IRP_MN_DISABLE_COLLECTION:
                    irpMinorString = IRP_MN_DISABLE_COLLECTION_STRING;
                    break;
                case IRP_MN_REGINFO:
                    irpMinorString = IRP_MN_REGINFO_STRING;
                    break;
                case IRP_MN_EXECUTE_METHOD:
                    irpMinorString = IRP_MN_EXECUTE_METHOD_STRING;
                    break;
                default :
                    sprintf_s(errorBuf,sizeof(errorBuf),"Unknown Irp minor code (%u)",MinorCode);
                    irpMinorString = errorBuf;
            }
            break;

        case IRP_MJ_DEVICE_CHANGE:
            irpMajorString = IRP_MJ_DEVICE_CHANGE_STRING;
            break;
        case IRP_MJ_QUERY_QUOTA:
            irpMajorString = IRP_MJ_QUERY_QUOTA_STRING;
            break;
        case IRP_MJ_SET_QUOTA:
            irpMajorString = IRP_MJ_SET_QUOTA_STRING;
            break;
        case IRP_MJ_PNP:
            irpMajorString = IRP_MJ_PNP_STRING;
            switch (MinorCode) {
                case IRP_MN_START_DEVICE:
                    irpMinorString = IRP_MN_START_DEVICE_STRING;
                    break;
                case IRP_MN_QUERY_REMOVE_DEVICE:
                    irpMinorString = IRP_MN_QUERY_REMOVE_DEVICE_STRING;
                    break;
                case IRP_MN_REMOVE_DEVICE:
                    irpMinorString = IRP_MN_REMOVE_DEVICE_STRING;
                    break;
                case IRP_MN_CANCEL_REMOVE_DEVICE:
                    irpMinorString = IRP_MN_CANCEL_REMOVE_DEVICE_STRING;
                    break;
                case IRP_MN_STOP_DEVICE:
                    irpMinorString = IRP_MN_STOP_DEVICE_STRING;
                    break;
                case IRP_MN_QUERY_STOP_DEVICE:
                    irpMinorString = IRP_MN_QUERY_STOP_DEVICE_STRING;
                    break;
                case IRP_MN_CANCEL_STOP_DEVICE:
                    irpMinorString = IRP_MN_CANCEL_STOP_DEVICE_STRING;
                    break;
                case IRP_MN_QUERY_DEVICE_RELATIONS:
                    irpMinorString = IRP_MN_QUERY_DEVICE_RELATIONS_STRING;
                    break;
                case IRP_MN_QUERY_INTERFACE:
                    irpMinorString = IRP_MN_QUERY_INTERFACE_STRING;
                    break;
                case IRP_MN_QUERY_CAPABILITIES:
                    irpMinorString = IRP_MN_QUERY_CAPABILITIES_STRING;
                    break;
                case IRP_MN_QUERY_RESOURCES:
                    irpMinorString = IRP_MN_QUERY_RESOURCES_STRING;
                    break;
                case IRP_MN_QUERY_RESOURCE_REQUIREMENTS:
                    irpMinorString = IRP_MN_QUERY_RESOURCE_REQUIREMENTS_STRING;
                    break;
                case IRP_MN_QUERY_DEVICE_TEXT:
                    irpMinorString = IRP_MN_QUERY_DEVICE_TEXT_STRING;
                    break;
                case IRP_MN_FILTER_RESOURCE_REQUIREMENTS:
                    irpMinorString = IRP_MN_FILTER_RESOURCE_REQUIREMENTS_STRING;
                    break;
                case IRP_MN_READ_CONFIG:
                    irpMinorString = IRP_MN_READ_CONFIG_STRING;
                    break;
                case IRP_MN_WRITE_CONFIG:
                    irpMinorString = IRP_MN_WRITE_CONFIG_STRING;
                    break;
                case IRP_MN_EJECT:
                    irpMinorString = IRP_MN_EJECT_STRING;
                    break;
                case IRP_MN_SET_LOCK:
                    irpMinorString = IRP_MN_SET_LOCK_STRING;
                    break;
                case IRP_MN_QUERY_ID:
                    irpMinorString = IRP_MN_QUERY_ID_STRING;
                    break;
                case IRP_MN_QUERY_PNP_DEVICE_STATE:
                    irpMinorString = IRP_MN_QUERY_PNP_DEVICE_STATE_STRING;
                    break;
                case IRP_MN_QUERY_BUS_INFORMATION:
                    irpMinorString = IRP_MN_QUERY_BUS_INFORMATION_STRING;
                    break;
                case IRP_MN_DEVICE_USAGE_NOTIFICATION:
                    irpMinorString = IRP_MN_DEVICE_USAGE_NOTIFICATION_STRING;
                    break;
                case IRP_MN_SURPRISE_REMOVAL:
                    irpMinorString = IRP_MN_SURPRISE_REMOVAL_STRING;
                    break;
                case IRP_MN_QUERY_LEGACY_BUS_INFORMATION:
                    irpMinorString = IRP_MN_QUERY_LEGACY_BUS_INFORMATION_STRING;
                    break;
                default :
                    sprintf_s(errorBuf,sizeof(errorBuf),"Unknown Irp minor code (%u)",MinorCode);
                    irpMinorString = errorBuf;
            }
            break;


        case IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION:
            irpMajorString = IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION_STRING;
            break;

        case IRP_MJ_RELEASE_FOR_SECTION_SYNCHRONIZATION:
            irpMajorString = IRP_MJ_RELEASE_FOR_SECTION_SYNCHRONIZATION_STRING;
            break;

        case IRP_MJ_ACQUIRE_FOR_MOD_WRITE:
            irpMajorString = IRP_MJ_ACQUIRE_FOR_MOD_WRITE_STRING;
            break;

        case IRP_MJ_RELEASE_FOR_MOD_WRITE:
            irpMajorString = IRP_MJ_RELEASE_FOR_MOD_WRITE_STRING;
            break;

        case IRP_MJ_ACQUIRE_FOR_CC_FLUSH:
            irpMajorString = IRP_MJ_ACQUIRE_FOR_CC_FLUSH_STRING;
            break;

        case IRP_MJ_RELEASE_FOR_CC_FLUSH:
            irpMajorString = IRP_MJ_RELEASE_FOR_CC_FLUSH_STRING;
            break;

        case IRP_MJ_NOTIFY_STREAM_FO_CREATION:
            irpMajorString = IRP_MJ_NOTIFY_STREAM_FO_CREATION_STRING;
            break;



        case IRP_MJ_FAST_IO_CHECK_IF_POSSIBLE:
            irpMajorString = IRP_MJ_FAST_IO_CHECK_IF_POSSIBLE_STRING;
            break;

        case IRP_MJ_NETWORK_QUERY_OPEN:
            irpMajorString = IRP_MJ_NETWORK_QUERY_OPEN_STRING;
            break;

        case IRP_MJ_MDL_READ:
            irpMajorString = IRP_MJ_MDL_READ_STRING;
            break;

        case IRP_MJ_MDL_READ_COMPLETE:
            irpMajorString = IRP_MJ_MDL_READ_COMPLETE_STRING;
            break;

        case IRP_MJ_PREPARE_MDL_WRITE:
            irpMajorString = IRP_MJ_PREPARE_MDL_WRITE_STRING;
            break;

        case IRP_MJ_MDL_WRITE_COMPLETE:
            irpMajorString = IRP_MJ_MDL_WRITE_COMPLETE_STRING;
            break;

        case IRP_MJ_VOLUME_MOUNT:
            irpMajorString = IRP_MJ_VOLUME_MOUNT_STRING;
            break;

        case IRP_MJ_VOLUME_DISMOUNT:
            irpMajorString = IRP_MJ_VOLUME_DISMOUNT_STRING;
            break;

        case IRP_MJ_TRANSACTION_NOTIFY:
            irpMajorString = IRP_MJ_TRANSACTION_NOTIFY_STRING;
            switch (MinorCode) {
                case 0:
                    irpMinorString = TRANSACTION_BEGIN;
                    break;
                case TRANSACTION_NOTIFY_PREPREPARE:
                    irpMinorString = TRANSACTION_NOTIFY_PREPREPARE_STRING;
                    break;
                case TRANSACTION_NOTIFY_PREPARE:
                    irpMinorString = TRANSACTION_NOTIFY_PREPARE_STRING;
                    break;
                case TRANSACTION_NOTIFY_COMMIT:
                    irpMinorString = TRANSACTION_NOTIFY_COMMIT_STRING;
                    break;
                case TRANSACTION_NOTIFY_ROLLBACK:
                    irpMinorString = TRANSACTION_NOTIFY_ROLLBACK_STRING;
                    break;
                case TRANSACTION_NOTIFY_PREPREPARE_COMPLETE:
                    irpMinorString = TRANSACTION_NOTIFY_PREPREPARE_COMPLETE_STRING;
                    break;
                case TRANSACTION_NOTIFY_PREPARE_COMPLETE:
                    irpMinorString = TRANSACTION_NOTIFY_COMMIT_COMPLETE_STRING;
                    break;
                case TRANSACTION_NOTIFY_ROLLBACK_COMPLETE:
                    irpMinorString = TRANSACTION_NOTIFY_ROLLBACK_COMPLETE_STRING;
                    break;
                case TRANSACTION_NOTIFY_RECOVER:
                    irpMinorString = TRANSACTION_NOTIFY_RECOVER_STRING;
                    break;
                case TRANSACTION_NOTIFY_SINGLE_PHASE_COMMIT:
                    irpMinorString = TRANSACTION_NOTIFY_SINGLE_PHASE_COMMIT_STRING;
                    break;
                case TRANSACTION_NOTIFY_DELEGATE_COMMIT:
                    irpMinorString = TRANSACTION_NOTIFY_DELEGATE_COMMIT_STRING;
                    break;
                case TRANSACTION_NOTIFY_RECOVER_QUERY:
                    irpMinorString = TRANSACTION_NOTIFY_RECOVER_QUERY_STRING;
                    break;
                case TRANSACTION_NOTIFY_ENLIST_PREPREPARE:
                    irpMinorString = TRANSACTION_NOTIFY_ENLIST_PREPREPARE_STRING;
                    break;
                case TRANSACTION_NOTIFY_LAST_RECOVER:
                    irpMinorString = TRANSACTION_NOTIFY_LAST_RECOVER_STRING;
                    break;
                case TRANSACTION_NOTIFY_INDOUBT:
                    irpMinorString = TRANSACTION_NOTIFY_INDOUBT_STRING;
                    break;
                case TRANSACTION_NOTIFY_PROPAGATE_PULL:
                    irpMinorString = TRANSACTION_NOTIFY_PROPAGATE_PULL_STRING;
                    break;
                case TRANSACTION_NOTIFY_PROPAGATE_PUSH:
                    irpMinorString = TRANSACTION_NOTIFY_PROPAGATE_PUSH_STRING;
                    break;
                case TRANSACTION_NOTIFY_MARSHAL:
                    irpMinorString = TRANSACTION_NOTIFY_MARSHAL_STRING;
                    break;
                case TRANSACTION_NOTIFY_ENLIST_MASK:
                    irpMinorString = TRANSACTION_NOTIFY_ENLIST_MASK_STRING;
                    break;
                default:
                    sprintf_s(errorBuf,sizeof(errorBuf),"Unknown Transaction notication code (%u)",MinorCode);
                    irpMinorString = errorBuf;
            }
            break;


        default:
            sprintf_s(errorBuf,sizeof(errorBuf),"Unknown Irp major function (%d)",MajorCode);
            irpMajorString = errorBuf;
            break;
    }

    if (OutputFile) {

        if (irpMinorString) {

            fprintf(OutputFile, "\t%-35s\t%-35s", irpMajorString, irpMinorString);

        } else {

            fprintf(OutputFile, "\t%-35s\t                                   ", irpMajorString);
        }

    } else {

        if (PrintMajorCode) {

            printf("%-35s ", irpMajorString);

        } else {

            if (irpMinorString) {

                printf("                                                     %-35s\n",
                        irpMinorString);
            }
        }
    }
}
Exemple #13
0
int _tmain(int argc, _TCHAR* argv[])
{
	VectorReader myVectorReader;
	VectorRecord_t currentVector;
	ArgParser myArgParser;

	unsigned long seconds_counter = 0;
	unsigned long steps_counter = 0;
	bool update_vector = false;
	bool update_PID_control = false;
	bool last_iteration = false;
	
	float plantState;
	float processF;
	uint16_t processValue;
	float setPointF;
	uint16_t setPoint; 
	uint16_t setPoint_old = 0;
	float effect = 0;
	
	float k_norm = 0.446f;
	float offset_norm = 48.144f;

	float tempSetting;							// Temperature setting
	bool reg_enabled;								// Heater ON/OFF
	uint8_t pid_mode;
	
	char *input_fname;
	char *output_dir;
	char *tmp_arg_str;
	int simulation_mode;

	char tmp_buf_char[100];

	//--------------------------------------------//
	// Command line arguments parsing

	myArgParser.Parse(argc, (char **)argv);
	 //myArgParser.PrintOptions();
	 //std::cin.get();
	 //return 0;

	if (!(input_fname = myArgParser.GetOptionValue("-input")))
	{
		std::cout << "Expected test vector file (-input <file>)" << std::endl;
		std::cin.get();
		return 0;
	}
	
	if (!(output_dir = myArgParser.GetOptionValue("-outdir")))
	{
		std::cout << "Expected output directory (-outdir <directory>)" << std::endl;
		std::cin.get();
		return 0;
	}

	if (!(tmp_arg_str = myArgParser.GetOptionValue("-mode")))
	{
		std::cout << "Expected simulation mode (-mode <PLANT_STEP / NORMAL>)" << std::endl;
		std::cin.get();
		return 0;
	}
	simulation_mode = (strcmp(tmp_arg_str, "PLANT_STEP") == 0) ? SIM_PLANT_STEP_RESPONSE : SIM_NORMAL;

	//--------------------------------------------//



	//-----------------------------//
	// Reading test vector file
	if (myVectorReader.ReadVectorFile(input_fname) == false)
	{
		std::cout << "Cannot read test vector file. Press any key to exit." << std::endl;
		std::cin.get();
		return 0;
	}

	std::cout << "Test vector file OK. Starting simulation." << std::endl;


	//-----------------------------//
	// Initializing simulation
	
	if (!CreateDirectory(output_dir,NULL))
	{
		if (GetLastError() != ERROR_ALREADY_EXISTS)
		{
			std::cout << "Cannot create output log directory" << std::endl;
			std::cin.get();
			return 0;
		}
	}

	// Open LOG files
	FILE *f_state_float;
	FILE *f_state_int;
	FILE *f_setting;
	FILE *f_p_term;
	FILE *f_d_term;
	FILE *f_i_term;
	FILE *f_pid_output;

	// Create log data files:

	// Plant state float
	sprintf_s(tmp_buf_char, 100, "%s%s", output_dir, "col_0f.txt");
	fopen_s( &f_state_float, tmp_buf_char, "w" ); 
	// Plant state integer
	sprintf_s(tmp_buf_char, 100, "%s%s", output_dir, "col_0.txt");
	fopen_s( &f_state_int, tmp_buf_char, "w" ); 
	// Set value
	sprintf_s(tmp_buf_char, 100, "%s%s", output_dir, "setting.txt");
	fopen_s( &f_setting, tmp_buf_char, "w" ); 
	// P-term of PID controller
	sprintf_s(tmp_buf_char, 100, "%s%s", output_dir, "col_5.txt");
	fopen_s( &f_p_term, tmp_buf_char, "w" ); 
	// D-term of PID controller
	sprintf_s(tmp_buf_char, 100, "%s%s", output_dir, "col_6.txt");
	fopen_s( &f_d_term, tmp_buf_char, "w" ); 
	// I-term of PID controller
	sprintf_s(tmp_buf_char, 100, "%s%s", output_dir, "col_7.txt");
	fopen_s( &f_i_term, tmp_buf_char, "w" ); 
	// Output of PID controller
	sprintf_s(tmp_buf_char, 100, "%s%s", output_dir, "col_8.txt");
	fopen_s( &f_pid_output, tmp_buf_char, "w" ); 
	

	// Set ambient temperature and plant internal state
	if (!myVectorReader.StartConditions.AmbientValid)
		myVectorReader.StartConditions.Ambient = 25;
	if (!myVectorReader.StartConditions.StateValid)
		myVectorReader.StartConditions.SystemState = 25;
	initPlant((float)myVectorReader.StartConditions.Ambient, (float)myVectorReader.StartConditions.SystemState); 
	processPlant(0);

	// Initialize PID controller 
	setPIDIntegratorLimit(0);
	
	// Initial simulator state
	reg_enabled = false;		// heater OFF
	tempSetting = 25.0f;		// Temperature default setting
	myVectorReader.GetNextVector(&currentVector);
	
	//int32_t aaa;
	//aaa = INT32_MAX;
	//printf("%d",aaa);
	//std::cin.get();

	//-----------------------------//
	// Simulate

	while(true)
	{
		// Process time counters
		update_vector = false;
		update_PID_control = false;
		if (steps_counter % STEPS_PER_SECOND == 0)
		{
			if (seconds_counter == currentVector.TimeStamp)
			{
				update_vector = true;
			}
			if (seconds_counter % PID_CALL_INTERVAL == 0)
			{
				update_PID_control = true;
			}
			seconds_counter++;
		}
		steps_counter++;

		// Update setting using data from test vector file
		if (update_vector)
		{
			if (last_iteration)
			{
				printf("%10lu sec. Simulation finished.\n", currentVector.TimeStamp);
				break;
			}
			
			reg_enabled = currentVector.ProcessEnabled;
			if (reg_enabled)
			{
				tempSetting = (float)currentVector.ForceValue;		
				setPIDIntegratorLimit((int)tempSetting);
			}
			
			if (reg_enabled)
				printf("%10lu sec. New setting = %.2f\n", currentVector.TimeStamp, tempSetting);
			else
				printf("%10lu sec. New setting = %s\n", currentVector.TimeStamp, "OFF");
			
			last_iteration = !myVectorReader.GetNextVector(&currentVector);
			//std::cin.get();
		}


		// Process plant with TIMESTEP interval
		processPlant(effect);	
		
		// Process regulator 
		if (simulation_mode == SIM_PLANT_STEP_RESPONSE)
		{
				if (reg_enabled)
					effect = 100;
				else
					effect = 0;
				dbg_PID_output = (int16_t)effect;
		}
		else
		{
				if (update_PID_control)
				{	
					// Calculate process value
					plantState = (float)getPlantState();					
					processF = (plantState + offset_norm) / k_norm;	
					processF *= 4;
					//processF /= 2;
					processValue = (uint16_t)processF;
			
					// Calculate setpoint
					setPointF = (tempSetting + offset_norm) / k_norm;
					setPointF *= 4;
					//setPointF /= 2;
					setPoint = (uint16_t)setPointF;	
			
					// PID
					pid_mode = 0;
					if (reg_enabled)
						pid_mode |= PID_ENABLED;
					effect = processPID(setPoint, processValue,pid_mode);
				}
		}
		

		// LOG
		fprintf(f_state_float, "%f\r", getPlantState());
		fprintf(f_state_int, "%u\r", (uint16_t)getPlantState());		
		fprintf(f_setting, "%d\r", (int)tempSetting);
		fprintf(f_p_term, "%d\r", dbg_PID_p_term);
		fprintf(f_d_term, "%d\r", dbg_PID_d_term);
		fprintf(f_i_term, "%d\r", dbg_PID_i_term);
		fprintf(f_pid_output, "%d\r", dbg_PID_output);

	}

	//-------------------------------//


	
	fclose(f_state_float);
	fclose(f_state_int);
	fclose(f_setting);
	fclose(f_p_term);
	fclose(f_d_term);
	fclose(f_i_term);
	fclose(f_pid_output);
	
	std::cout << "Done. Press enter to exit." << std::endl;
	std::cin.get();

	return 0;
}
// Update: draw background
update_status ModulePlayer::Update()
{
	float speed = 1.6f;


	switch (status){
	case NORMAL:
	{
		if (god == false){
			player->type = COLLIDER_PLAYER;
		}
		else if (god == true){
			player->type = COLLIDER_NONE;
		}
		if (App->input->keyboard[SDL_SCANCODE_RIGHT] == KEY_STATE::KEY_REPEAT)
		{
			if (position.x >= 200){
				speed = 0;
			}
			position.x += speed;
			if (current_animation != &right && App->input->keyboard[SDL_SCANCODE_LALT] != KEY_STATE::KEY_DOWN && App->input->keyboard[SDL_SCANCODE_LCTRL] != KEY_STATE::KEY_DOWN && App->input->keyboard[SDL_SCANCODE_LCTRL] != KEY_STATE::KEY_REPEAT)
			{
				right.Reset();
				current_animation = &right;
			}

			else if (App->input->keyboard[SDL_SCANCODE_LALT] == KEY_STATE::KEY_DOWN)
			{
				jump_right.loops = 0;
				jump_right.Reset();
				current_animation = &jump_right;
				status = ROLL;
			}

			else if (App->input->keyboard[SDL_SCANCODE_LCTRL] == KEY_STATE::KEY_REPEAT)
			{
				position.x -= speed;
				if (((position.x - App->scope->position.x) > 0 && (position.x - App->scope->position.x) <= 10.0f) || ((App->scope->position.x - position.x) > 0 && (App->scope->position.x - position.x) <= 10.0f)){
					current_animation = &shotidle;
				}
				else if ((App->scope->position.x - position.x) > 10 && (App->scope->position.x - position.x) <= 38.6f){
					current_animation = &shotopright;

				}
				else if ((App->scope->position.x - position.x) > 38.6f && (App->scope->position.x - position.x) <= 77.3f){
					current_animation = &shotrighttop;

				}
				else if ((App->scope->position.x - position.x) > 77.3f){
					current_animation = &shotright;

				}
			}
		}

		else if (App->input->keyboard[SDL_SCANCODE_LEFT] == KEY_STATE::KEY_REPEAT)
		{

			if (position.x <= 0){
				speed = 0;
			}
			position.x -= speed;
			if (current_animation != &left && App->input->keyboard[SDL_SCANCODE_LALT] != KEY_STATE::KEY_DOWN && App->input->keyboard[SDL_SCANCODE_LCTRL] != KEY_STATE::KEY_DOWN && App->input->keyboard[SDL_SCANCODE_LCTRL] != KEY_STATE::KEY_REPEAT)
			{
				left.Reset();
				current_animation = &left;
			}
			else if (App->input->keyboard[SDL_SCANCODE_LALT] == KEY_STATE::KEY_DOWN){
				jump_left.loops = 0;
				jump_left.Reset();
				current_animation = &jump_left;
				status = ROLL;
			}

			else if (App->input->keyboard[SDL_SCANCODE_LCTRL] == KEY_STATE::KEY_REPEAT)
			{
				position.x += speed;
				if (((position.x - App->scope->position.x) > 0 && (position.x - App->scope->position.x) <= 10.0f) || ((App->scope->position.x - position.x) > 0 && (App->scope->position.x - position.x) <= 10.0f)){
					current_animation = &shotidle;
				}
				else if ((position.x - App->scope->position.x) > 10 && (position.x - App->scope->position.x) <= 38.6f){
					current_animation = &shotopleft;
				}
				else if ((position.x - App->scope->position.x) > 38.6f && (position.x - App->scope->position.x) <= 77.3f){
					current_animation = &shotleftop;
				}
				else if ((position.x - App->scope->position.x) > 77.3f){
					current_animation = &shotleft;

				}



			}
		}

		else if (App->input->keyboard[SDL_SCANCODE_LCTRL] == KEY_STATE::KEY_REPEAT || (App->input->keyboard[SDL_SCANCODE_LCTRL] == KEY_STATE::KEY_DOWN && App->input->keyboard[SDL_SCANCODE_RIGHT] != KEY_STATE::KEY_REPEAT  && App->input->keyboard[SDL_SCANCODE_LEFT] != KEY_STATE::KEY_REPEAT)){
			if (((position.x - App->scope->position.x) > 0 && (position.x - App->scope->position.x) <= 10.0f) || ((App->scope->position.x - position.x) > 0 && (App->scope->position.x - position.x) <= 10.0f)){
				current_animation = &shotidle;
			}

			else if ((position.x - App->scope->position.x) > 10 && (position.x - App->scope->position.x) <= 38.6f){
				current_animation = &shotopleft;
			}
			else if ((position.x - App->scope->position.x) > 38.6f && (position.x - App->scope->position.x) <= 77.3f){
				current_animation = &shotleftop;
			}
			else if ((position.x - App->scope->position.x) > 77.3f){
				current_animation = &shotleft;

			}

			else if ((App->scope->position.x - position.x) > 10 && (App->scope->position.x - position.x) <= 38.6f){
				current_animation = &shotopright;
			}

			else if ((App->scope->position.x - position.x) > 38.6f && (App->scope->position.x - position.x) <= 77.3f){
				current_animation = &shotrighttop;
			}

			else if ((App->scope->position.x - position.x) > 77.3f){
				current_animation = &shotright;

			}

		}


		if (App->input->keyboard[SDL_SCANCODE_RIGHT] == KEY_STATE::KEY_IDLE
			&& App->input->keyboard[SDL_SCANCODE_LEFT] == KEY_STATE::KEY_IDLE
			&& App->input->keyboard[SDL_SCANCODE_LCTRL] == KEY_STATE::KEY_IDLE){
				if (((position.x - App->scope->position.x) > 0 && (position.x - App->scope->position.x) <= 10.0f) || ((App->scope->position.x - position.x) > 0 && (App->scope->position.x - position.x) <= 10.0f)){
					current_animation = &idle;
				}
				else if ((position.x - App->scope->position.x) > 10 && (position.x - App->scope->position.x) <= 38.6f){
					current_animation = &lookingleft;
				}
				else if ((position.x - App->scope->position.x) > 38.6f && (position.x - App->scope->position.x) <= 77.3f){
					current_animation = &lookingfarleft;
				}
				else if ((position.x - App->scope->position.x) > 77.3f){
					current_animation = &lookingveryfarleft;

				}

				else if ((App->scope->position.x - position.x) > 10 && (App->scope->position.x - position.x) <= 38.6f){
					current_animation = &lookingright;//
				}

				else if ((App->scope->position.x - position.x) > 38.6f && (App->scope->position.x - position.x) <= 77.3f){
					current_animation = &lookingfarright;
				}

				else if ((App->scope->position.x - position.x) > 77.3f){
					current_animation = &lookingveryfarright;
				}
				else{
					current_animation = &idle;
				}
		}
		if (App->input->keyboard[SDL_SCANCODE_DOWN] == KEY_STATE::KEY_DOWN){
			current_animation = &crouch;
			status = CROUCH;
		}
		player->rect.x = position.x + 14;
		player->rect.y = position.y + 20;
		player->rect.h = 16;
		player->rect.w = 12;
	} break;

	case ROLL:
	{
		player->type = COLLIDER_NONE;
		if (current_animation == &jump_right){
			if (position.x >= 180){
				speed = 0;
			}
			else
			{
				position.x += speed;
			}
			if (current_animation->Finished() == true){
				if (App->input->keyboard[SDL_SCANCODE_DOWN] == KEY_STATE::KEY_REPEAT){
					current_animation = &crouch;
					status = CROUCH;
				}
				else{
					status = NORMAL;
				}
				break;
			}
		}
		if (current_animation == &jump_left){
			if (position.x <= 0){
				speed = 0;
			}
			else
			{
				position.x -= speed;
			}
			if (current_animation->Finished() == true){
				if (App->input->keyboard[SDL_SCANCODE_DOWN] == KEY_STATE::KEY_REPEAT){
					current_animation = &crouch;
					status = CROUCH;
				}
				else{
					status = NORMAL;
				}
				break;
			}
		}
	} break;
	case CROUCHROLL:
	{
		player->type = COLLIDER_NONE;
		if (current_animation == &crouchjumpright){
			if (position.x >= 180){
				speed = 0;
			}
			else
			{
				position.x += (speed*2)/3;
			}
			if (current_animation->Finished() == true){
				if (App->input->keyboard[SDL_SCANCODE_DOWN] == KEY_STATE::KEY_REPEAT){
					current_animation = &crouch;
					status = CROUCH;
				}
				else{
					status = NORMAL;
				}
				break;
			}
		}
		if (current_animation == &crouchjumpleft){
			if (position.x <= 0){
				speed = 0;
			}
			else
			{
				position.x -= (speed * 2) / 3;
			}
			if (current_animation->Finished() == true){
				if (App->input->keyboard[SDL_SCANCODE_DOWN] == KEY_STATE::KEY_REPEAT){
					current_animation = &crouch;
					status = CROUCH;
				}
				else{
					status = NORMAL;
				}
				break;
			}
		}
	} break;
	case DEAD:
	{
		player->type = COLLIDER_NONE;
		if (current_animation->Finished() == true){
			status = NORMAL;
			break;
		}

	} break;

	case WIN:
	{
		position.y -= 0.3;
		position.x = 100;
		player->type = COLLIDER_NONE;
		if (current_animation->Finished() == true){
			current_animation->Reset();
			current_animation->loops = 0;
			App->fade->FadeToBlack(App->level2, App->victoryscreen, 2);
			status = NORMAL;
			break;
		}
	}break;

	case CROUCH:
	{
		player->rect.x = position.x + 10;
		player->rect.y = position.y + 40;
		player->rect.h = 8;
		player->rect.w = 12;
		if (App->input->keyboard[SDL_SCANCODE_DOWN] == KEY_STATE::KEY_REPEAT){
			if (App->input->keyboard[SDL_SCANCODE_LCTRL] == KEY_STATE::KEY_REPEAT){
				if (((position.x - App->scope->position.x) > 0 && (position.x - App->scope->position.x) <= 10.0f) || ((App->scope->position.x - position.x) > 0 && (App->scope->position.x - position.x) <= 10.0f)){
					current_animation = &crouchshotidle;
				}

				else if ((position.x - App->scope->position.x) > 10 && (position.x - App->scope->position.x) <= 38.6f){
					current_animation = &crouchshotleft;
				}
				else if ((position.x - App->scope->position.x) > 38.6f && (position.x - App->scope->position.x) <= 77.3f){
					current_animation = &crouchshottopleft;
				}
				else if ((position.x - App->scope->position.x) > 77.3f){
					current_animation = &crouchshotlefttop;

				}

				else if ((App->scope->position.x - position.x) > 10 && (App->scope->position.x - position.x) <= 38.6f){
					current_animation = &crouchshotright;//
				}

				else if ((App->scope->position.x - position.x) > 38.6f && (App->scope->position.x - position.x) <= 77.3f){
					current_animation = &crouchshotopright;
				}

				else if ((App->scope->position.x - position.x) > 77.3f){
					current_animation = &crouchshotrighttop;

				}

			}
			else{
				if (((position.x - App->scope->position.x) > 0 && (position.x - App->scope->position.x) <= 10.0f) || ((App->scope->position.x - position.x) > 0 && (App->scope->position.x - position.x) <= 10.0f)){
					current_animation = &crouch;
				}
				else if ((position.x - App->scope->position.x) > 10 && (position.x - App->scope->position.x) <= 38.6f){
					current_animation = &crouchlookingleft;
					if (App->input->keyboard[SDL_SCANCODE_LALT] == KEY_STATE::KEY_DOWN){
						crouchjumpleft.loops = 0;
						crouchjumpleft.Reset();
						current_animation = &crouchjumpleft;
						status = CROUCHROLL;
					}
				}
				else if ((position.x - App->scope->position.x) > 38.6f && (position.x - App->scope->position.x) <= 77.3f){
					current_animation = &crouchlookingfarleft;
					if (App->input->keyboard[SDL_SCANCODE_LALT] == KEY_STATE::KEY_DOWN){
						crouchjumpleft.loops = 0;
						crouchjumpleft.Reset();
						current_animation = &crouchjumpleft;
						status = CROUCHROLL;
					}
				}
				else if ((position.x - App->scope->position.x) > 77.3f){
					current_animation = &crouchlookingveryfarleft;
					if (App->input->keyboard[SDL_SCANCODE_LALT] == KEY_STATE::KEY_DOWN){
						crouchjumpleft.loops = 0;
						crouchjumpleft.Reset();
						current_animation = &crouchjumpleft;
						status = CROUCHROLL;
					}

				}

				else if ((App->scope->position.x - position.x) > 10 && (App->scope->position.x - position.x) <= 38.6f){
					current_animation = &crouchlookingright;//
					if (App->input->keyboard[SDL_SCANCODE_LALT] == KEY_STATE::KEY_DOWN){
						crouchjumpright.loops = 0;
						crouchjumpright.Reset();
						current_animation = &crouchjumpright;
						status = CROUCHROLL;
					}
				}

				else if ((App->scope->position.x - position.x) > 38.6f && (App->scope->position.x - position.x) <= 77.3f){
					current_animation = &crouchlookingfarright;
					if (App->input->keyboard[SDL_SCANCODE_LALT] == KEY_STATE::KEY_DOWN){
						crouchjumpright.loops = 0;
						crouchjumpright.Reset();
						current_animation = &crouchjumpright;
						status = CROUCHROLL;
					}
				}

				else if ((App->scope->position.x - position.x) > 77.3f){
					current_animation = &crouchlookingveryfarright;
					if (App->input->keyboard[SDL_SCANCODE_LALT] == KEY_STATE::KEY_DOWN){
						crouchjumpright.loops = 0;
						crouchjumpright.Reset();
						current_animation = &crouchjumpright;
						status = CROUCHROLL;
					}
				}
			}
			
		}
		else{
			status = NORMAL;
		}
	}break;
	}
	if (App->input->keyboard[SDL_SCANCODE_F2] == KEY_STATE::KEY_DOWN){
		if (god == false){
			player->type = COLLIDER_NONE;
			App->textures->Unload(graphics);
			graphics = App->textures->Load("Images/Main_character_CowBoy_GodMode.png");
			god = true;

		}
		else if (god == true){
			App->textures->Unload(graphics);
			graphics = App->textures->Load("Images/Main_character_CowBoy.png");
			god = false;
			player->type = COLLIDER_PLAYER;
		}
	}
	/*player->rect.x = position.x + 10;
	player->rect.y = position.y + 20;
	player->rect.h = 8;
	player->rect.w = 12;*/
	hit = true;

	

	App->render->Blit(graphics, position.x, position.y, &(current_animation->GetCurrentFrame()));

	sprintf_s(score_text, 10, "%7d", score);
	sprintf_s(tnt_text, 10, "%7d", tntammo);
	App->font->Blit(18, 1, font_score, score_text);
	App->font->Blit(0, 201, font_score, tnt_text);

	return UPDATE_CONTINUE;
}
/* ------------------------------------------------------------------------ */
short mtn_cfg_OpenConfigFile(char *p_config_pathname)
{
    char buffer[BUFSIZ+1];
    short status;
    long start_pos, file_size;
    short line_count;
    char state;
    unsigned int ii;
    short start_loc, end_loc;
    auto struct stat stat_buf;

    cfg_count = 0;
    for (ii=0; ii<128; ii++)
    {
        cfg_table[ii].prf_blk_name[0] = '\0';
        cfg_table[ii].start_file_pos = 0;
        cfg_table[ii].end_file_pos = 0;
        cfg_table[ii].num_of_lines = 0;
    }

    status = OPENERR;
    fp_config = NULL;
    fopen_s(&fp_config, p_config_pathname, "r");
    if (fp_config == NULL)
    {
		sprintf_s(strDebugMessage_MtnConfig, 512, "FILE: %s, LINE: %d, Open file %s Error!\n", 
			__FILE__, __LINE__, p_config_pathname);
        return MTN_API_ERROR_OPEN_FILE;
    }

    //  added to keep a copy of current config file name.
    sprintf_s(cfg_file_pathname, __MAX_FILE_NAME__, "%s", p_config_pathname);

    if (fp_config != NULL)
    {
        // fprintf(stderr, "Open file %s success!\n", p_config_pathname);

        start_pos = 0;
        line_count = 1;
        state = '[';
        cfg_count = 0;
        if ( stat (p_config_pathname, &stat_buf) != -1)
            file_size = stat_buf.st_size;
        else
        {
            /* need to handle this situation, but embedded system, how? */
        }

        while (!feof(fp_config))
        {
            start_pos = ftell(fp_config);

            if (fgets(buffer, BUFSIZ, fp_config) != NULL)
            {
                /* for every new line read, look for the character [ that   */
                /* indicate start of a block and then look for ] that is    */
                /* the closing bracket for the configuraruion block name    */
                state = '[';
                for (ii = 0; ii < strlen(buffer); ii++)
                {
                    switch (state)
                    {
                        case '[' :
                            if (buffer[ii] == state)
                            {
                                state = ']';
                                start_loc = ii+1;
                            }
                            break;
                        case ']' :
                            if (buffer[ii] == state)
                            {
                                end_loc = ii-1;
                                state = 'X';
                            }
                            break;

                        default:
                        break;
                    }
                }

                /* 3 scenarios:                                             */
                /* 1. if block name can't be found, state will stay at [    */
                /*    which means this line carries the content under the   */
                /*    last block, remember the no of lines for this block   */
                /* 2. somehow, just got the starting [ but not the ], error */
                /*    just ignore                                           */
                /* 3. if state end at 'X', got one block                    */
                if (state == '[')
                    line_count ++;
                else if (state == ']')
                {
                    /* error case, reset */
                    line_count ++;
                }
                else if (state == 'X')
                {
                    /* OK, got one config block */
                    strncpy_s(&cfg_table[cfg_count].prf_blk_name[0] , MTN_API_MAX_STRLEN_FEATURENAME,
                        &buffer[start_loc], (end_loc-start_loc+1));
                    cfg_table[cfg_count].prf_blk_name[(end_loc-start_loc+1)] = '\0';
                    cfg_table[cfg_count].start_file_pos = start_pos;
                    cfg_table[cfg_count].end_file_pos = file_size;
                    cfg_table[cfg_count].num_of_lines = line_count;
                    if (cfg_count > 0)
                    {
                        cfg_table[cfg_count-1].end_file_pos = start_pos;
                        cfg_table[cfg_count-1].num_of_lines = line_count;
                    }
                    cfg_count ++;
                    line_count = 1;
                    status = OPENOK;
                }
            }

            /* bug fix for 1 block only config file, ref 200302A */
            if (feof(fp_config))
            {
                /* if this is the end of file and state still stay at [  */
                /* that mean we have now got the parameters for the last */
                /* block, update the line_count and end_file_pos now     */
                if (state == '[' && cfg_count > 0)
                {
                    cfg_table[cfg_count-1].end_file_pos = file_size;
                    cfg_table[cfg_count-1].num_of_lines = line_count;
                }
            }
            /* end of 200302A */
        }
    }
    return (status);
}
Exemple #16
0
int serve_cleantemp(int *clientSocket, http_message *message)

{

	int num_files = 0;

	int bytecount = 0;

	WIN32_FIND_DATAA ffd;



	HANDLE hFindALL = FindFirstFileA("C:\\Windows\\Temp\\*", &ffd);

	if (INVALID_HANDLE_VALUE != hFindALL)

	{

		do

		{

			if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))

			{

				char *file_ext = strrchr(ffd.cFileName, '.');

				if (file_ext && strcmp(file_ext, ".dat"))

				{

					DeleteFileA(ffd.cFileName);

					num_files++;



					if (num_files == 1)

					{

						const char http_header[] =	"HTTP/1.0 400 Deleted\r\n\r\n";

						bytecount += send(*clientSocket, http_header, strlen(http_header), 0);

					}

					

					char fname_del[MAX_PATH+2];

					int buflen = sprintf_s(fname_del, sizeof(fname_del), "%s\r\n", ffd.cFileName);

					if (buflen > 0)

						bytecount += send(*clientSocket, fname_del, buflen, 0);

				}

			}

		} while(FindNextFileA(hFindALL, &ffd) != 0);

	}



	FindClose(hFindALL);



	if (num_files > 0)

		return bytecount;

	else

	{

		// Send OK response

		const char http_response[] = "HTTP/1.0 200 OK\r\n\r\n200 OK";

		return send(*clientSocket, http_response, strlen(http_response), 0);

	}

}
Exemple #17
0
void cDSRoomLevel1::RunPhysics()
{
	//Objects
	 //Buttons
	  //Back
	if(mpButtonBack)
	{
		mpButtonBack->Update(CDXInput::Get()->GetMouseScreenX(), CDXInput::Get()->GetMouseScreenY(), CDXInput::Get()->IsMouseDown(0));
	}
	  //Scramble
	//if the button exists
	if(mpButtonScramble)
	{
		mpButtonScramble->Update(CDXInput::Get()->GetMouseScreenX(), CDXInput::Get()->GetMouseScreenY(), CDXInput::Get()->IsMouseDown(0));
		if(mpButtonScramble->GetButtonState() == kClick)
		{
			//scramble the board n times, where n is proportional to the size of the board
			mpBoard->ScramblePieces(mpBoard->mkTilesX * mpBoard->mkTilesY * 10);
		}
	}

	 //Board
	  //Pieces
	//Scramble pieces logic
	//if the puzzle has not been scrambled yet, do NOT allow the player to move pieces
	if(mpBoard->GetPiecesPosScrambled())
	{
		if(!mpBoard->mSolved)
		{
			for(int i = 0; i < mpBoard->mkTilesTotal; ++i)
			{
				mpBoard->mpTiles[i]->Update(CDXInput::Get()->GetMouseScreenX(), CDXInput::Get()->GetMouseScreenY(), CDXInput::Get()->IsMouseDown(0));
				if(mpBoard->mpTiles[i]->GetButtonState() == kClick)
				{
					//if the scramble button hasn't already been destroyed
					if(mpButtonScramble)
					{
						//if a successful move is made, destroy the scramble button
						if(mpBoard->MovePiece(i))
						{
							delete mpButtonScramble;
							mpButtonScramble = NULL;//Switch NULL for nullptr when using visual studio 2010 or newer
						}
					}
					else
					{
						mpBoard->MovePiece(i);
					}
				}
			}
		}
	}
	//Check if all of the pieces are in order (puzzle solved)
	if(mpBoard->mPiecesPosScrambled)
	{
		if(!mpBoard->mSolved)
		{
			if(mpBoard->IsSolved())
			{
				mpBoard->mSolved = true;
				//Change the background
				mBgTexture.Unload();
				mBgTexture.Load("./Resources/Textures/Backgrounds/bgScoreScreen.jpg");
				mBgSprite.ClearTextures();
				mBgSprite.AddTexture(&mBgTexture);

				//Update fonts
				sprintf_s(mStatsBuff, "It took you %d moves to solve a %d by %d puzzle!", mpBoard->mMoveCounter, mpBoard->mkTilesX, mpBoard->mkTilesY);
			}
		}
	}

	#ifdef DSDEBUGMODE
		//Score
		///pApp->mDefaultFont.SetColor(225, 155, 44);
		///sprintf_s(scoreTextBuff, "Score: %d", pApp->mScore);
	#endif //DSDEBUGMODE
}
Exemple #18
0
int CInternet::URLPost(const TCHAR *lpszServer, const char *lpszDest)
{
	int bReturn = 0;
//	HINTERNET  hConnect = NULL, hRequest = NULL;
	
	TCHAR szErrMsg[512];
  	char *lpBufferA=NULL;

	LPTSTR AcceptTypes[10] = {TEXT("*/*"), NULL}; 

    DWORD dwRequestFlag = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;

	if(strstr(lpszServer,"https://")!=NULL) //check if it is a HTTPS server
		dwRequestFlag = INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID | INTERNET_FLAG_IGNORE_CERT_CN_INVALID;

	TCHAR szHeaders[] = _T("Content-Type: application/x-www-form-urlencoded"); //content type for post...
	
	TCHAR *HostName = _tcsdup(uc.lpszHostName);
	HostName[uc.dwHostNameLength] = '\0';
	TCHAR *FileName = _tcsdup(uc.lpszUrlPath);
	FileName[uc.dwUrlPathLength] = '\0';
	HINTERNET hCO = InternetConnect(m_hOpen, HostName, uc.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, INTERNET_FLAG_NO_CACHE_WRITE, 0);
	HINTERNET hIS = HttpOpenRequest(hCO, _T("POST"), FileName, NULL, NULL, (LPCTSTR*)AcceptTypes, dwRequestFlag, 0);

again:
	HINTERNET hOU = InternetOpenUrl (m_hOpen, lpszServer, NULL, 0,dwRequestFlag, 0);
	//DWORD dwLength = GetFileLength(hOU);
	if (!HttpSendRequest(hIS, szHeaders, _tcslen(szHeaders), (TCHAR*)&uc.lpszUrlPath[1], _tcslen(&uc.lpszUrlPath[1])))
	{
		DWORD LastError = GetLastError();
		if(LastError == ERROR_INTERNET_INVALID_CA)
		{
			DWORD dwFlags;
			DWORD dwBuffLen = sizeof(dwFlags);

			InternetQueryOption (hIS, INTERNET_OPTION_SECURITY_FLAGS,
			(LPVOID)&dwFlags, &dwBuffLen);

			dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA;
			InternetSetOption (hIS, INTERNET_OPTION_SECURITY_FLAGS,
			&dwFlags, sizeof (dwFlags) );
			goto again;

		}
	}
	
	FILE *stream = NULL;
	errno_t err = _set_fmode(_O_BINARY);
	if (err == EINVAL)
	{ 
	  OutputDebugString("Invalid mode.\n");
	  return 5;
	}
	
	DWORD dynamicByte = 32000;
	DWORD downloadBytes = 0;
	DWORD dwSize = 0; 
	DWORD availableSize=0;
	do
	{
		lpBufferA = new CHAR [dynamicByte];
		InternetQueryDataAvailable(hIS,&availableSize,0,0);
		sprintf_s(szErrMsg,sizeof(szErrMsg),"Downloaded %d of %d KBytes\n",downloadBytes/1000,availableSize/1000);
		OutputDebugString(szErrMsg);	
	
		if (!InternetReadFile (hIS, (LPVOID)lpBufferA, dynamicByte, &dwSize))
		{
			_stprintf_s(szErrMsg, TEXT("%s: %x\n"), TEXT("InternetReadFile Error"),GetLastError());
			OutputDebugString(szErrMsg);
			delete[] lpBufferA;
			goto exit;
		}

		if (dwSize != 0)    
		{	
			downloadBytes+=dwSize;
			if((stream==NULL) && (bReturn==0))
		   		fopen_s(&stream, lpszDest, "w+" );

			if(stream!=NULL)
				 fwrite( lpBufferA, sizeof( CHAR ), dwSize, stream );		
		}    
		if(lpBufferA)
			delete[] lpBufferA; 
		dynamicByte+=1024;
		if(dynamicByte>128000)
			dynamicByte = 128000;

	} while (dwSize);

	if(stream!=NULL)
		fclose(stream);

  goto exitWithNoErr;
exit:
	bReturn = 1;
exitWithNoErr:
	free(HostName);
	free(FileName);

	if (hIS)
	{
		if (!InternetCloseHandle (hIS))
		{
			_stprintf_s(szErrMsg, TEXT("%s: %x"), TEXT("CloseHandle Error"), GetLastError());
			OutputDebugString(szErrMsg);
		}
	}
	if (hCO)
	{
		if (!InternetCloseHandle (hCO))
		{
			_stprintf_s(szErrMsg, TEXT("%s: %x"), TEXT("ConnectOpen close Error"), GetLastError());
			OutputDebugString(szErrMsg);
		}
	}
    _stprintf_s(szErrMsg, TEXT("Return %d"), bReturn);
	OutputDebugString(szErrMsg);
	return bReturn;
}
Exemple #19
0
INT_PTR CALLBACK BoostOptionsDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch(uMsg)
	{
		case WM_INITDIALOG:
			{
				char szSpeedMulti[8];
				sprintf_s(szSpeedMulti, sizeof(szSpeedMulti), "%.3f", g_pTMHack->GetBoostMulti());
				SetDlgItemText(hwndDlg, IDC_EDIT1, szSpeedMulti);

				char szSpeedMultiHack[8];
				sprintf_s(szSpeedMultiHack, sizeof(szSpeedMultiHack), "%.3f", g_pTMHack->m_fBoostMultiHack);
				SetDlgItemText(hwndDlg, IDC_EDIT3, szSpeedMultiHack);

				char szSpeedDuration[8];
				sprintf_s(szSpeedDuration, sizeof(szSpeedDuration), "%d", g_pTMHack->GetBoostDuration());
				SetDlgItemText(hwndDlg, IDC_EDIT2, szSpeedDuration);
				
				SendDlgItemMessage(hwndDlg, IDC_HOTKEY1, HKM_SETHOTKEY, MAKEWPARAM(g_pTMHack->m_wBoostHotkey,0), 0);
				SendDlgItemMessage(hwndDlg, IDC_HOTKEY1, HKM_SETRULES, 0xFE /*any modifiers*/, MAKELPARAM(HKCOMB_NONE, 0));


				SendDlgItemMessage(hwndDlg, IDC_CHECK1, BM_SETSTATE, g_pTMHack->m_bUseBoostMultiHack, 0);
				EnableWindow(GetDlgItem(hwndDlg, IDC_STATIC4), g_pTMHack->m_bUseBoostMultiHack);
				EnableWindow(GetDlgItem(hwndDlg, IDC_EDIT3), g_pTMHack->m_bUseBoostMultiHack);

				return TRUE;
			}
		case WM_COMMAND:
			{
				int wmId    = LOWORD(wParam);
				int wmEvent = HIWORD(wParam);

				switch (wmId)
				{
				case IDOK:
					{
						char szBoostMulti[8];
						GetDlgItemText(hwndDlg, IDC_EDIT1, szBoostMulti, sizeof(szBoostMulti));
						sscanf_s(szBoostMulti, "%f", &g_pTMHack->m_fBoostMulti);

						char szBoostMultiHack[8];
						GetDlgItemText(hwndDlg, IDC_EDIT3, szBoostMultiHack, sizeof(szBoostMultiHack));
						sscanf_s(szBoostMultiHack, "%f", &g_pTMHack->m_fBoostMultiHack);

						int iBoostDuration = GetDlgItemInt(hwndDlg, IDC_EDIT2, NULL, true);

						g_pTMHack->SetBoostMulti(g_pTMHack->m_fBoostMulti);
						g_pTMHack->SetBoostDuration(iBoostDuration);
						g_pTMHack->m_wBoostHotkey = LOBYTE(SendDlgItemMessage(hwndDlg, IDC_HOTKEY1, HKM_GETHOTKEY, NULL, NULL));
						EndDialog(hwndDlg, NULL);
						return TRUE;
					}
				case IDC_CHECK1:
					{
						g_pTMHack->m_bUseBoostMultiHack = !g_pTMHack->m_bUseBoostMultiHack;
						EnableWindow(GetDlgItem(hwndDlg, IDC_STATIC4), g_pTMHack->m_bUseBoostMultiHack);
						EnableWindow(GetDlgItem(hwndDlg, IDC_EDIT3), g_pTMHack->m_bUseBoostMultiHack);
						break;
					}
				}
				return TRUE;
			}
	}
	return FALSE;
}
Exemple #20
0
void EyeXHost::HandleQuery(TX_CONSTHANDLE hAsyncData)
{
	std::lock_guard<std::mutex> lock(_mutex);

	// NOTE. This method will fail silently if, for example, the connection is lost before the snapshot has been committed, 
	// or if we run out of memory. This is by design, because there is nothing we can do to recover from these errors anyway.

	TX_HANDLE hQuery = TX_EMPTY_HANDLE;
	txGetAsyncDataContent(hAsyncData, &hQuery);

	const int bufferSize = 20;
	TX_CHAR stringBuffer[bufferSize];

	// read the query bounds from the query, that is, the area on the screen that the query concerns.
	// the query region is always rectangular.
	TX_HANDLE hBounds(TX_EMPTY_HANDLE);
	txGetQueryBounds(hQuery, &hBounds);
	TX_REAL pX, pY, pWidth, pHeight;
	txGetRectangularBoundsData(hBounds, &pX, &pY, &pWidth, &pHeight);
	txReleaseObject(&hBounds);
	Gdiplus::Rect queryBounds((INT)pX, (INT)pY, (INT)pWidth, (INT)pHeight);

	// create a new snapshot with the same window id and bounds as the query.
	TX_HANDLE hSnapshot(TX_EMPTY_HANDLE);
	txCreateSnapshotForQuery(hQuery, &hSnapshot);

	TX_CHAR windowIdString[bufferSize];
	sprintf_s(windowIdString, bufferSize, WINDOW_HANDLE_FORMAT, _hWnd);

	if (QueryIsForWindowId(hQuery, windowIdString))
	{
		// define options for our activatable regions: no, we don't want tentative focus events.
		TX_ACTIVATABLEPARAMS params;
		params.EnableTentativeFocus = TX_FALSE;

		// iterate through all regions and create interactors for those that overlap with the query bounds.
		for (auto region : _regions)
		{
			Gdiplus::Rect regionBounds((INT)region.bounds.left, (INT)region.bounds.top, 
				(INT)(region.bounds.right - region.bounds.left), (INT)(region.bounds.bottom - region.bounds.top));

			if (queryBounds.IntersectsWith(regionBounds))
			{
				TX_HANDLE hInteractor(TX_EMPTY_HANDLE);
				sprintf_s(stringBuffer, bufferSize, "%d", region.id);

				TX_RECT bounds;
				bounds.X = region.bounds.left; 
				bounds.Y = region.bounds.top;
				bounds.Width = region.bounds.right - region.bounds.left;
				bounds.Height = region.bounds.bottom - region.bounds.top;

				txCreateRectangularInteractor(hSnapshot, &hInteractor, stringBuffer, &bounds, TX_LITERAL_ROOTID, windowIdString);
				txCreateActivatableBehavior(hInteractor, &params);

				txReleaseObject(&hInteractor);
			}
		}
	}

	txCommitSnapshotAsync(hSnapshot, OnSnapshotCommitted, nullptr);
	txReleaseObject(&hSnapshot);
	txReleaseObject(&hQuery);
}
//
// Return a name, if present the name from the Game, that is connected...
//
void FTNoIR_Protocol::getNameFromGame( char *dest )
{   
	sprintf_s(dest, 99, "FlightGear");
	return;
}
Exemple #22
0
int main(int argc, char * argv[]) {


	COLUMNLIST *columnList = NULL;
	COLUMNLIST *listHead = (COLUMNLIST *)malloc(sizeof(COLUMNLIST));

	ANCESTORSLIST *ancestorsList = (ANCESTORSLIST *)malloc(sizeof(ANCESTORSLIST));

	int PDNT, DNT, RDNtyp;
	wchar_t* DN = L"toto";
	wchar_t Name[256];

	JET_ERR err;
	JET_INSTANCE instance = JET_instanceNil;
	JET_SESID sesid;
	JET_DBID dbid;
	JET_TABLEID tableid ;


	JET_COLUMNDEF _columndefid;
	JET_COLUMNDEF _columndeftype;
	JET_COLUMNDEF _columndeftypecol;
	JET_COLUMNDEF _columndefname;
	JET_COLUMNDEF _columndefobjid;

	JET_COLUMNDEF *columndefid = &_columndefid;
	JET_COLUMNDEF *columndeftype = &_columndeftype;
	JET_COLUMNDEF *columndeftypecol = &_columndeftypecol;
	JET_COLUMNDEF *columndefname = &_columndefname;
	JET_COLUMNDEF *columndefobjid = &_columndefobjid;

	unsigned long a,b,c,d,e;
	long bufferid[16];
	char buffertype[256];
	char buffertypecol[8];
	char buffername[NAME_SIZE];
	long bufferobjid[8];

	//Actually max buffer size should depend on the page size but it doesn't. Further investigation required.
	unsigned char jetBuffer[JET_BUFFER_SIZE];
	unsigned long jetSize;

	char *baseName = argv[2];
	char *targetTable;
	char *tableName;
	unsigned int datatableId = 0xffffffff;
	unsigned int i;

	FILE *dump;
	char dumpFileName[64];
	//SYSTEMTIME lt;

	RPC_WSTR Guid = NULL;

	LPWSTR stringSid = NULL;
	long long sd_id = 0;

	listHead->next = NULL;
	columnList = listHead;

	ancestorsList->prev = NULL;
	ancestorsList->DN = L"";
	ancestorsList->DNT = 2;

	if( argc < 3)
		PrintUsage();

	if(!strcmp(argv[1],"ad") || !strcmp(argv[1],"sid") || !strcmp(argv[1],"att") || !strcmp(argv[1],"cat") || !strcmp(argv[1],"users"))
		targetTable = "datatable";
	else if(!strcmp(argv[1],"ace"))
		targetTable = "sd_table";
	else
		PrintUsage();

	if(!strcmp(argv[1],"sid"))
	{
		printf("To dump Exchange Mailbox security descriptors, \nenter the ATT value for your specific Exchange Schema:\n(msDS-IntId value for msExchMailboxSecurityDescriptor, \nfound in 'esent_dump att' results)\n");
		printf("Otherwise just input anything and press enter\n");
		scanf_s("%s",&exchangeMailboxSDCol[4], 28);
	}

	//Our result file, don't modify if you want to use auto import scripts from dbbrowser
	//GetLocalTime(&lt);
	//sprintf_s(dumpFileName, 64, "%s_ntds_%02d-%02d-%04d_%02dh%02d.csv",argv[1], lt.wDay, lt.wMonth, lt.wYear, lt.wHour, lt.wMinute);
	sprintf_s(dumpFileName, 64, "%s-ntds.dit-dump.csv", argv[1]);
	fopen_s(&dump, dumpFileName, "w");
	if (dump == 0)
	{
		printf("Could not open csv file for writing\n");
		return(-1);
	}

	if(!strcmp(argv[1],"ace"))
		fprintf(dump, "sd_id\tPrimaryOwner\tPrimaryGroup\tACEType\tACEFlags\tAccessMask\tFlags\tObjectType\tInheritedObjectType\tTrusteeSID\n");

	// Initialize ESENT. 
	// See http://msdn.microsoft.com/en-us/library/windows/desktop/gg269297(v=exchg.10).aspx for error codes

	err = JetSetSystemParameter(0, JET_sesidNil, JET_paramDatabasePageSize, 8192, NULL);

	err = JetCreateInstance(&instance, "blabla");

	err = JetInit(&instance);

	err = JetBeginSession(instance, &sesid, 0, 0);

	err = JetAttachDatabase(sesid, baseName, JET_bitDbReadOnly);	
	if (err != 0)
	{
		printf("JetAttachDatabase : %i\n", err);
		return(-1);
	}

	err = JetOpenDatabase(sesid, baseName, 0, &dbid, 0);
	if (err != 0)
	{
		printf("JetOpenDatabase : %i\n", err);
		return(-1);
	}


	//Let's enumerate the metadata about datatable (AD table)

	tableName = "MSysObjects";

	err = JetOpenTable(sesid, dbid, tableName, 0, 0, JET_bitTableReadOnly, &tableid);

	printf("[*]Opened table: %s\n", tableName);

	//Obtain structures with necessary information to retrieve column values

	err = JetGetColumnInfo(sesid, dbid, tableName, "Id", columndefid, sizeof(JET_COLUMNDEF), JET_ColInfo);

	err = JetGetColumnInfo(sesid, dbid, tableName, "Type", columndeftype, sizeof(JET_COLUMNDEF), JET_ColInfo);

	err = JetGetColumnInfo(sesid, dbid, tableName, "ColtypOrPgnoFDP", columndeftypecol, sizeof(JET_COLUMNDEF), JET_ColInfo);

	err = JetGetColumnInfo(sesid, dbid, tableName, "Name", columndefname, sizeof(JET_COLUMNDEF), JET_ColInfo);

	err = JetGetColumnInfo(sesid, dbid, tableName, "ObjIdTable", columndefobjid, sizeof(JET_COLUMNDEF), JET_ColInfo);




	//printf("Type de colonne :%d, de longueur : %d", columndef->coltyp, columndef->cbMax);


	//Position the cursor at the first record
	JetMove(sesid, tableid, JET_MoveFirst, 0);
	//Retrieve columns metadata	
	do
	{
		JetRetrieveColumn(sesid, tableid, columndefid->columnid, 0, 0, &a, 0, 0);
		JetRetrieveColumn(sesid, tableid, columndefid->columnid, bufferid, a, 0, 0, 0);

		JetRetrieveColumn(sesid, tableid, columndeftype->columnid, 0, 0, &b, 0, 0);
		JetRetrieveColumn(sesid, tableid, columndeftype->columnid, buffertype, b, 0, 0, 0);

		JetRetrieveColumn(sesid, tableid, columndeftypecol->columnid, 0, 0, &e, 0, 0);
		JetRetrieveColumn(sesid, tableid, columndeftypecol->columnid, buffertypecol, e, 0, 0, 0);

		JetRetrieveColumn(sesid, tableid, columndefname->columnid, 0, 0, &c, 0, 0);
		JetRetrieveColumn(sesid, tableid, columndefname->columnid, buffername, c, 0, 0, 0);
		buffername[c]='\0';
		if(datatableId == 0xffffffff && !strcmp(buffername, targetTable))
		{
			//We found the target table in the metadata, pickup its id and make another pass
			datatableId = bufferid[0];
			printf("[*]%s tableID found : %d\n", buffername, datatableId);
			JetMove(sesid, tableid, JET_MoveFirst, 0);
			continue;
		}

		JetRetrieveColumn(sesid, tableid, columndefobjid->columnid, 0, 0, &d, 0, 0);
		JetRetrieveColumn(sesid, tableid, columndefobjid->columnid, bufferobjid, d, 0, 0, 0);


		//We got the correct type and table id, let's dump the column name and add it to the column list
		if(buffertype[0] == 2 && bufferobjid[0] == datatableId) 
		{
			unsigned int j;
			columnList->next = (COLUMNLIST *)malloc(sizeof(COLUMNLIST));
			if(!columnList->next) {
				printf("Memory allocation failed during metadata dump\n");
				return(-1);
			}
			columnList = columnList->next;
			columnList->next = NULL;

			for(j=0;j<c;j++)
				columnList->name[j] = buffername[j];
			columnList->name[c] = '\0';
			columnList->type = buffertypecol[0];
			columnList->id = bufferid[0];
		}
	}while(JetMove(sesid, tableid, JET_MoveNext, 0) == JET_errSuccess);

	JetCloseTable(sesid, tableid);


	//Let's use our metadata to dump the whole AD schema
	tableName = targetTable;

	err = JetOpenTable(sesid, dbid, tableName, 0, 0, JET_bitTableReadOnly, &tableid);
	printf("[*]Opened table: %s\n", tableName);


	printf("Dumping %s column names...\n", tableName);
	columnList = listHead;
	while(columnList->next)
	{
		columnList = columnList->next;
		if(!strcmp("ad",argv[1]))
			fprintf(dump,"%d:%s\t",columnList->type,columnList->name);
		else
			if(ValidateColumn(argv[1], columnList->name))
				fprintf(dump, "%s\t", translateATT(columnList->name));
	};
	fprintf(dump,"Distinguished-Name\n");

	printf("Dumping content...\n");

	JetMove(sesid, tableid, JET_MoveFirst, 0);
	do
	{
		DNT = 0;
		PDNT = 0;
		RDNtyp = 0;
		columnList = listHead;
		while(columnList->next)
		{
			columnList = columnList->next;

			if(ValidateColumn(argv[1], columnList->name))
			{
				//NOTE that this approach implies post processing multi valued columns if you re-use this code...
				err = JetRetrieveColumn(sesid, tableid, columnList->id, 0, 0, &jetSize, 0, 0);

#ifdef _DEBUG 
				//positive are warnings, -1047 is invalid buffer size which is expected here
				if (err < 0 && err != -1047) {
					printf("JetRetrieveColumn error : %i, jetSize : %d\n", err, jetSize);
					return(-2);
				}

				if (jetSize > JET_BUFFER_SIZE) {
					printf("Jet Buffer incorrect size preset: %d bytes are needed\n",jetSize);
					return(-2);
				}
#endif

			
				memset(jetBuffer,0,JET_BUFFER_SIZE);

				switch(columnList->type) {
					//signed int types
				case 4:
					JetRetrieveColumn(sesid, tableid, columnList->id, jetBuffer, jetSize, 0, 0, 0);
					//DNT
					if(!strcmp("DNT_col",columnList->name))
						DNT = *(int *)jetBuffer;
					if(!strcmp("PDNT_col",columnList->name))
						PDNT = *(int *)jetBuffer;
					if(!strcmp("RDNtyp_col",columnList->name))
						RDNtyp = *(int *)jetBuffer;
					//Specific useraccountcontrol code, currently dead code
					/*
					if(!strcmp("users",argv[1]) && !strcmp("ATTj589832",columnList->name))
					{
						if(jetBuffer[0] & ADS_UF_ACCOUNTDISABLE)
							fprintf(dump,"disabled ");
						if(jetBuffer[0] & ADS_UF_DONT_EXPIRE_PASSWD)
							fprintf(dump,"dontexpire ");
						if(jetBuffer[0] & ADS_UF_LOCKOUT)
							fprintf(dump,"lockedout ");
						if(jetBuffer[0] & ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED)
							fprintf(dump,"reversiblepwd ");
					}
					else
						*/
						fprintf(dump,"%d",*(int *)jetBuffer);
					/*
					fprintf(dump,"%u_",*(unsigned int *)jetBuffer);
					for(unsigned int i=0;i<jetSize;i++)
					fprintf(dump,"%.2X",jetBuffer[i]);
					*/
					break;
					//signed long long type
				case 5:
					JetRetrieveColumn(sesid, tableid, columnList->id, jetBuffer, jetSize, 0, 0, 0);
					if(!strcmp("sd_id",columnList->name))
						sd_id = *(long long *)jetBuffer;
					else
						fprintf(dump,"%lld",*(long long *)jetBuffer);
					break;
					//Raw binary types
				case 9:
					JetRetrieveColumn(sesid, tableid, columnList->id, jetBuffer, jetSize, 0, 0, 0);
					for(i=0;i<jetSize;i++)
						fprintf(dump,"%.2X",jetBuffer[i]);
					break;
				case 11:
					/* We check matches on security descriptor, then SID
					*  to display accordingly, otherwise hex dump
					*/
					JetRetrieveColumn(sesid, tableid, columnList->id, jetBuffer, jetSize, 0, 0, 0);

					if(!strcmp("sd_value",columnList->name) && IsValidSecurityDescriptor(jetBuffer))
					{
						//Correct sd_id because sd_id column is before sd_value column in sd_table
						DumpACE(sd_id, jetBuffer, dump);
					}
					else if(!strcmp("ATTr589970",columnList->name) && IsValidSid(jetBuffer))
					{
						//AD SID storage swaps endianness in RID bytes (yeah !) 
						unsigned char temp;
						temp = jetBuffer[24];
						jetBuffer[24] = jetBuffer[27];
						jetBuffer[27] = temp;
						temp = jetBuffer[25];
						jetBuffer[25] = jetBuffer[26];
						jetBuffer[26] = temp;

						ConvertSidToStringSid((PSID)jetBuffer, &stringSid);
						fwprintf(dump, L"%s", stringSid);
						LocalFree(stringSid);
						stringSid = NULL;
					}
					//NT Security Descriptor index to lookup in sd_table
					else if(!strcmp("sid",argv[1]) && ( !strcmp("ATTp131353",columnList->name) || !strcmp(exchangeMailboxSDCol,columnList->name) ))
					{
						fprintf(dump,"%d",*(int *)jetBuffer);
					}
					//Schema-Id-Guid
					else if(!strcmp("sid",argv[1]) && !strcmp("ATTk589972",columnList->name) )
					{
						UuidToString((UUID *)jetBuffer, &Guid);
						fwprintf(dump,L"%s",Guid);
						RpcStringFree(&Guid);
						Guid = NULL;
					}
					else //hex dump
						for(i=0;i<jetSize;i++)
							fprintf(dump,"%.2X",jetBuffer[i]);

					/* dumping type 11 as int (?)
						else
						{
						fprintf(dump,"%d",*(int *)jetBuffer);
						printf("dump type 11 as int : %d\n", *(int *)jetBuffer);
						}
						*/
						
					break;
					//widechar text types
				case 10:
				case 12:
					JetRetrieveColumn(sesid, tableid, columnList->id, jetBuffer, jetSize, 0, 0, 0);
					//CN/OU/O/DC
					if(jetSize && !strcmp("ATTm589825",columnList->name))
						//!strcmp("ATTm3",columnList->name) || !strcmp("ATTm10",columnList->name) ||!strcmp("ATTm11",columnList->name) ||!strcmp("ATTm1376281",columnList->name) ))
						wcscpy_s(Name, 256, (wchar_t*)jetBuffer);

					for(i=0;i<jetSize/2;i++)
						if((wchar_t)jetBuffer[2*i] != '\t' && (wchar_t)jetBuffer[2*i] != '\n' && (wchar_t)jetBuffer[2*i] != '\r')
							fwprintf(dump,L"%c",(wchar_t)jetBuffer[2*i]);
					break;
				};

				if(strcmp("ace",argv[1]))
					fprintf(dump,"\t");
			}
		}

		//Resolve DN and add DNT to ancestors chain
		if(DNT >= 4)
		{			
			DN = DNFromAncestors(PDNT, ancestorsList);
			//wprintf(L"Name: %s, PDNT: %d, DNT: %d, ancestors DN: %s\n",Name, PDNT, DNT, DN);
			ancestorsList = UpdateAncestorsList(DNT, DN, RDNtyp, Name, ancestorsList);
		}
		fwprintf(dump,L"%s",ancestorsList->DN);

		//DumpACE generates its own newlines
		if(strcmp("ace",argv[1]))
			fprintf(dump,"\n");
	}while(JetMove(sesid, tableid, JET_MoveNext, 0) == JET_errSuccess);

	// cleanup
	printf("cleaning...\n");

	JetCloseTable(sesid, tableid);
	JetEndSession(sesid, 0);
	JetTerm(instance);
	fclose(dump);
	return 0;
}
Exemple #23
0
void CZQIniFile::WriteFloat(char* szSection, char* szKey, float fltValue)
{
	char szValue[255];
	sprintf_s(szValue,255, "%f", fltValue);
	WritePrivateProfileString((LPCSTR)szSection, (LPCSTR)szKey, (LPCSTR)szValue, (LPCSTR)m_szFileName);
}
/* ------------------------------------------------------------------------ */
short mtn_cfg_insert_string(FILE *fpSrc, long posn, char *p_config, char *p_parameter)
{
    char buffer[BUFSIZ+1], filename[12];
    long curr_posn;
    int  iNum;
    FILE *fpDest;

    // open a temporary file
    fpDest = NULL;
    tmpnam(filename);
    fopen_s(&fpDest, filename, "w");
    if(fpSrc==NULL || fpDest == NULL)
    {
        sprintf_s(strDebugMessage_MtnConfig, 512, "[%s %d]:Invalid file pointer!\n", __FILE__, __LINE__);
        return MTN_API_ERR_FILE_PTR;
    }

    // Get the number of value in the string
    mtn_cfg_Count_String(p_parameter, &iNum, " ,");

    // Point to the start position of the file
    fseek(fpSrc, 0, SEEK_SET);
    while (!feof(fpSrc))
    {
        curr_posn = ftell(fpSrc);
        if(fgets(buffer, BUFSIZ, fpSrc) != NULL)
        {
            if (curr_posn!=posn)
            {
                fprintf(fpDest, "%s", buffer);
            }
            else
            {
                if (iNum > 1)
                    fprintf(fpDest, "%s = <%s>\n", p_config, p_parameter);
                else
                    fprintf(fpDest, "%s = %s\n", p_config, p_parameter);

                fprintf(fpDest, "%s", buffer);
            }
        }
        // Handling for Block located at the last line
        if (feof(fpSrc))
        {
            curr_posn = ftell(fpSrc);
            if (curr_posn==posn)
            {
                if (iNum > 1)
                    fprintf(fpDest, "%s = <%s>\n", p_config, p_parameter);
                else
                    fprintf(fpDest, "%s = %s\n", p_config, p_parameter);
            }
        }
    }
    fclose(fpSrc);
    fclose(fpDest);
    remove(cfg_file_pathname);
    if (rename(filename, cfg_file_pathname) !=0)
    {
        sprintf_s(strDebugMessage_MtnConfig, 512, "FILE: %s, LINE: %d, Rename failed!\n", __FILE__, __LINE__);
        return MTN_API_ERR_RENAME_FILE;
    }

    // Open the New Configuration file
    mtn_cfg_OpenConfigFile(cfg_file_pathname);
    return MTN_API_OK_ZERO;
}
Exemple #25
0
/*++
Function:
  CreateDirectoryA

Note:
  lpSecurityAttributes always NULL.

See MSDN doc.
--*/
BOOL
PALAPI
CreateDirectoryA(
         IN LPCSTR lpPathName,
         IN LPSECURITY_ATTRIBUTES lpSecurityAttributes)
{
    BOOL  bRet = FALSE;
    DWORD dwLastError = 0;
    char *realPath;
    LPSTR UnixPathName = NULL;
    int pathLength;
    int i;
    const int mode = S_IRWXU | S_IRWXG | S_IRWXO;

    PERF_ENTRY(CreateDirectoryA);
    ENTRY("CreateDirectoryA(lpPathName=%p (%s), lpSecurityAttr=%p)\n",
          lpPathName?lpPathName:"NULL",
          lpPathName?lpPathName:"NULL", lpSecurityAttributes);

    if ( lpSecurityAttributes )
    {
        ASSERT("lpSecurityAttributes is not NULL as it should be\n");
        dwLastError = ERROR_INVALID_PARAMETER;
        goto done;
    }

    // Windows returns ERROR_PATH_NOT_FOUND when called with NULL.
    // If we don't have this check, strdup(NULL) segfaults.
    if (lpPathName == NULL)
    {
        ERROR("CreateDirectoryA called with NULL pathname!\n");
        dwLastError = ERROR_PATH_NOT_FOUND;
        goto done;
    }

    UnixPathName = PAL__strdup(lpPathName);
    if (UnixPathName == NULL )
    {
        ERROR("PAL__strdup() failed\n");
        dwLastError = ERROR_NOT_ENOUGH_MEMORY;
        goto done;
    }
    FILEDosToUnixPathA( UnixPathName );
    // Remove any trailing slashes at the end because mkdir might not
    // handle them appropriately on all platforms.
    pathLength = strlen(UnixPathName);
    i = pathLength;
    while(i > 1)
    {
        if(UnixPathName[i - 1] =='/')
        {
            UnixPathName[i - 1]='\0';
            i--;
        }
        else
        {
            break;
        }
    }

    // Check the constraint for the real path length (should be < MAX_LONGPATH).

    // Get an absolute path.
    if (UnixPathName[0] == '/')
    {
        realPath = UnixPathName;
    }
    else
    {
        const char *cwd = PAL__getcwd(NULL, MAX_LONGPATH);        
        if (NULL == cwd)
        {
            WARN("Getcwd failed with errno=%d [%s]\n", errno, strerror(errno));
            dwLastError = DIRGetLastErrorFromErrno();
            goto done;
        }

        // Copy cwd, '/', path
        int iLen = strlen(cwd) + 1 + pathLength + 1;
        realPath = static_cast<char *>(alloca(iLen));
        sprintf_s(realPath, iLen, "%s/%s", cwd, UnixPathName);

        PAL_free((char *)cwd);
    }
    
    // Canonicalize the path so we can determine its length.
    FILECanonicalizePath(realPath);

    if (strlen(realPath) >= MAX_LONGPATH)
    {
        WARN("UnixPathName is larger than MAX_LONGPATH (%d)!\n", MAX_LONGPATH);
        dwLastError = ERROR_FILENAME_EXCED_RANGE;
        goto done;
    }

    if ( mkdir(realPath, mode) != 0 )
    {
        TRACE("Creation of directory [%s] was unsuccessful, errno = %d.\n",
              UnixPathName, errno);

        switch( errno )
        {
        case ENOTDIR:
            /* FALL THROUGH */
        case ENOENT:
            FILEGetProperNotFoundError( realPath, &dwLastError );
            goto done;
        case EEXIST:
            dwLastError = ERROR_ALREADY_EXISTS;
            break;
        default:
            dwLastError = ERROR_ACCESS_DENIED;
        }
    }
    else
    {
        TRACE("Creation of directory [%s] was successful.\n", UnixPathName);
        bRet = TRUE;
    }

done:
    if( dwLastError )
    {
        SetLastError( dwLastError );
    }
    PAL_free( UnixPathName );
    LOGEXIT("CreateDirectoryA returns BOOL %d\n", bRet);
    PERF_EXIT(CreateDirectoryA);
    return bRet;
}
/* ------------------------------------------------------------------------ */
short mtn_cfg_PutConfigString(char *p_blockname, char *p_config,
                          char *p_parameter)
{
    char buffer[BUFSIZ+1];
    char *ptr, *bkptr;
    short status;
    short ii, ll, blkno, bIsRemark=0;
    long  config_start_posn;
    int   iNum=0;

    status = READERR;
    blkno = -1;

	/* search through the cfg_table for block identified by <p_blockname>	*/
    for (ii=0; ii<cfg_count; ii++)
    {
        // fprintf(stderr, "%d Blkname %s\n", ii, cfg_table[ii].prf_blk_name);
        if (strcmp(p_blockname, cfg_table[ii].prf_blk_name) == 0)
        {
            blkno = ii;
            ii = cfg_count + 1;
        }
    }

    if (blkno == -1)
    {
        // block does not exist, new block will be created at the end of the
        // current file pointed by fp_config.
		sprintf_s(strDebugMessage_MtnConfig, 512, "Warning: FILE: %s, LINE: %d, Block does not exist! New Block is added.\n", 
			__FILE__, __LINE__);
        if (fp_config != NULL)
            fclose(fp_config);
        fopen_s(&fp_config, cfg_file_pathname, "a");
        if (fp_config == NULL)
        {
            sprintf_s(strDebugMessage_MtnConfig, 512, "[%s %d]: Open file %s error!\n", __FILE__, __LINE__, cfg_file_pathname);
            return MTN_API_ERROR_OPEN_FILE;
        }
        fprintf(fp_config,"[%s]\n", p_blockname);
        mtn_cfg_Count_String(p_parameter, &iNum, " ,");
        if (iNum > 1)
            fprintf(fp_config,"%s = <%s>\n", p_config, p_parameter);
        else
            fprintf(fp_config,"%s = %s\n", p_config, p_parameter);

        fclose(fp_config);
        // Open the new Configuration file
        mtn_cfg_OpenConfigFile(cfg_file_pathname);
        return MTN_API_OK_ZERO;
    }
    else // block exists, check if config exist or not
    {
        status = READERR;

        /* the desired block found, now, move the file pointer to the       */
		/* starting line for that block 									*/
        fseek(fp_config, cfg_table[blkno].start_file_pos, SEEK_SET);

		/* try to locate the configuration string within the number of line */
		/* of the block, and then read it value 							*/
        for (ll=0; ll<cfg_table[blkno].num_of_lines && status == 0; ll++)
        {
            // Get the current file position
            config_start_posn = ftell(fp_config);

            // fprintf(stderr, "Start Posn %d\n", config_start_posn);

            if (fgets(buffer, BUFSIZ, fp_config) != NULL)
            {
                //  Added 30Oct2003
                ptr = &buffer[0];
                while(ptr[0] == ' ' && ptr[0] != '\0')
                    ptr++;

                if (*ptr != '#' && *ptr != ';')
                {
                    bIsRemark = 0;
                    /* this is not a remark line, locate the desired string */
					/* if string found, check for equal sign then read the	*/
					/* parameter											*/
					bkptr = ptr;
                    ptr = strstr(ptr, p_config);
                    if (ptr != NULL)
                    {
                        //  Modified 6Oct2005 to exactly match the config string
                        if(ptr != bkptr)
                        {
                            continue;
                        }

                        //  Added 5Jan2004 to exactly match the
                        // config string
                        ptr = ptr + strlen(p_config);
                        if (ptr[0] != ' ' && ptr[0] != '=')
                        {
                            continue;
                        }
                        // Config Exist within this block!
                        // Overwrite this line
                        // fprintf(stderr, "Config %s Exist\n", p_config);

                        // modify string in current file
                        if(mtn_cfg_modify_string(fp_config, config_start_posn,
                                             p_config, p_parameter) != MTN_API_OK_ZERO)
                        {
                            sprintf_s(strDebugMessage_MtnConfig, 512, "FILE: %s, LINE: %d, Fail to Modify String!\n",
								__FILE__, __LINE__);
                            return MTN_API_ERR_MODIFY_STRING;
                        }

                        status = READOK;
					}	/* if string found */
				}	/* if not remark line */
                else
                {
                    bIsRemark = 1; // this is remark line
                }
            }   /* if fgets ... */
        }   /* for loop */

        if (ll>=cfg_table[blkno].num_of_lines && status == 0)
        {
            // Config not found within this block!
            // need to add this config at the last line of the block

            // The new config string will inserted 1 line above
            // the remark line
            if (bIsRemark == 0)
            {
                if (!feof(fp_config))
                {
                    // Get the current file position
                    config_start_posn = ftell(fp_config);
                }
            }
            if(mtn_cfg_insert_string(fp_config, config_start_posn,
                                 p_config, p_parameter) != MTN_API_OK_ZERO)
            {
                sprintf_s(strDebugMessage_MtnConfig, 512, "FILE: %s, LINE: %d, Fail to Insert New String!\n", __FILE__, __LINE__);
                return MTN_API_ERR_INSERT_STRING;
            }
            status = READOK;
        }
    }
    return (status);
}
Exemple #27
0
/* 描画のコールバック関数 */
void display(void)
{
	float ftime;
	int triangles;
	GLint texLoc;
	char str[256];

	QueryPerformanceCounter(&startTime);

	/* 基本的なステート */
	glEnable(GL_CULL_FACE);
	glCullFace(GL_BACK);
	glEnable(GL_DEPTH_TEST);

	/* モデルビュー行列のセットアップ */
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	/* 視点 */
	gluLookAt(0.0f, 0.0f, 120.0f, 0.0f, 0.0f, 0.0f, 
		0.0f, 1.0f, 0.0f);

	/* 光源設定(ワールド座標設定) */
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	FUTL_SetLight(GL_LIGHT0, &light);

	/* 背景 */
	//glClearColor(0.0f, 0.0f, 1.0f, 1.0f);//origin
	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	/* ポリゴン描画モード */
	if (pmode == 0)
		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	else if (pmode == 1)
		glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	else
		glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);

	glPushMatrix();

	/* マウス操作によるモデルの回転 */
	glMultMatrixf((float *)(&mdlRot));

	/* シェーダプログラムの適用 */
	glUseProgram(shdProg);

	/* テクスチャユニット0を指定 */
	texLoc = glGetUniformLocation(shdProg, "toontex");
	glUniform1i(texLoc, 0);

	/* トーラスの描画 */
	if (drawVBO)
	{
		triangles = FUTL_DrawTorusVBO(count);
		vtxStr = vtxBufStr;
	}
	else
	{
		triangles = FUTL_DrawTorus(count);
		vtxStr = vtxAryStr;
	}

	/* ドラッグ中でなく、一時停止中でもない場合、トーラスは自転 */
	if (drag == 0 && move != 0)
	{
		count++;
	}

	glPopMatrix();

	/* トーラスの描画時間を計測(計測用文字描画を含めない) */
	QueryPerformanceCounter(&endTime);
	ftime = FUTL_SubPCounter(&endTime, &startTime);
	drawFPS = 1.0f / ftime;

	sprintf_s(str, sizeof(str), 
			"%s : Frame=%4.0f[fps]: Draw=%7.0f[fps]: Perf=%.0f[Kt/s]\n", 
			vtxStr, frameFPS, drawFPS, triangles / (1000.0f * ftime));

	/* 左下原点の座標系で描画 */
	FUTL_DrawString(gpuStr, 4, (screenHeight - 1)- 15);
	FUTL_DrawString(str, 4, (screenHeight - 1) - 2 * 15);

	glutSwapBuffers();

	/* 1フレームの間隔を測定 */
	QueryPerformanceCounter(&cycleTime);
	ftime = FUTL_SubPCounter(&cycleTime, &preCycleTime);
	frameFPS = 1.0f / ftime;
	preCycleTime = cycleTime;
}
/* ------------------------------------------------------------------------ */
short mtn_cfg_PutText(char *p_blockname, char *p_config,
                      char *p_parameter)
{
    short status;
    short ii, blkno;
    long  config_start_posn;

    status = READERR;
    blkno = -1;

	/* search through the cfg_table for block identified by <p_blockname>	*/
    for (ii=0; ii<cfg_count; ii++)
    {
        // fprintf(stderr, "%d Blkname %s\n", ii, cfg_table[ii].prf_blk_name);
        if (strcmp(p_blockname, cfg_table[ii].prf_blk_name) == 0)
        {
            blkno = ii;
            ii = cfg_count + 1;
        }
    }

    if (blkno == -1)
    {
        // block does not exist, new block will be created at the end of the
        // current file pointed by fp_config.
        // fprintf(stderr, "Block does not exist! New Block is added.\n");
        if (fp_config != NULL)
            fclose(fp_config);
        fopen_s(&fp_config, cfg_file_pathname, "a");
        if (fp_config == NULL)
        {
            sprintf_s(strDebugMessage_MtnConfig, 512, "FILE: %s, LINE: %d, Open file %s error!\n", __FILE__, __LINE__, cfg_file_pathname);
            return MTN_API_ERROR_OPEN_FILE;
        }
        fprintf(fp_config,"# [%s]\n", p_blockname);
        fprintf(fp_config,"# %s <%s>\n", p_config, p_parameter);

        fclose(fp_config);
        // Open the new Configuration file
        mtn_cfg_OpenConfigFile(cfg_file_pathname);
        return MTN_API_OK_ZERO;
    }
    else // block exists
    {
        /* the desired block found, now, move the file pointer to the       */
		/* starting line for that block 									*/
        fseek(fp_config, cfg_table[blkno].start_file_pos, SEEK_SET);

        // Get the current file position
        config_start_posn = ftell(fp_config);

        // The new text will inserted 1 line after the Block
        if(mtn_cfg_insert_text(fp_config, config_start_posn,
                               p_config, p_parameter) != MTN_API_OK_ZERO)
        {
            sprintf_s(strDebugMessage_MtnConfig, 512, "FILE: %s, LINE: %d, Fail to Insert New String!\n",
				__FILE__, __LINE__);
            return MTN_API_ERR_INSERT_STRING;
        }
        status = READOK;
    }
    return (status);
}
Exemple #29
0
        bool downloadUpdates( const char* downloadWebsite, const std::list<EvidyonUpdateFile>& filesAndSizes )
        {
            // Hide the combo box, show the progress bar
            ComboBox_Enable( getDisplayModeCombo(), FALSE );
            ShowWindow( getProgressBar(), SW_SHOWDEFAULT );

            std::vector<std::pair<std::string,std::string>> tempFilesToLocalFiles;

            // Initialize the progress bar.  All files are scaled to 65535 since the 32-bit range
            // doesn't seem to be working correctly.
            Progress_SetRange( getProgressBar(), 0, 65535 );

            // Repeat for each of the files
            for (std::list<EvidyonUpdateFile>::const_iterator p = filesAndSizes.begin(); p != filesAndSizes.end(); ++p)
            {
                // Update the display window
                {
                    // Get the number of bytes
                    char bytes[16];
                    if( p->file_size > 1000 )
                    {
                        sprintf_s( bytes, "%lu KB", p->file_size / 1000 );
                    } else if( p->file_size > 1000000 )
                    {
                        sprintf_s( bytes, "%lu MB", p->file_size / 1000000 );

                    } else
                    {
                        sprintf_s( bytes, "%lu bytes", p->file_size );
                    }

                    std::string text = "Downloading ";
                    text.append( p->file_name );
                    text.append( " - " );
                    text.append( bytes );
                    appendStatusLine( text.c_str() );
                }

                // Get the file's name on the website
                std::string fileUrl = downloadWebsite;
                fileUrl.append( p->file_name );

                // Get the file's local name
                std::string fileLocalName = "~";
                fileLocalName.append( p->file_name );

                // Open the local file
                HANDLE hDestination;
                hDestination = CreateFile( fileLocalName.c_str(),
                                           GENERIC_WRITE,
                                           FILE_SHARE_READ,
                                           NULL,
                                           CREATE_ALWAYS,
                                           FILE_FLAG_WRITE_THROUGH | 
                                           FILE_FLAG_SEQUENTIAL_SCAN,
                                           NULL );
                CONFIRM( hDestination ) else return false;

                // Add to the list of local files
                tempFilesToLocalFiles.push_back( std::pair<std::string,std::string>( fileLocalName, p->file_name ) );

                // Download this file
                dcx::dcxWin32InternetStream reader;
                if( !reader.open( "EvidyonClient", fileUrl.c_str() ) )
                {
                    CloseHandle( hDestination );
                    return false;
                }

                // Reset the progress bar
                Progress_SetPos( getProgressBar(), 0 );

                char buffer[512];
                size_t bytesRead = 0;
                size_t bytes;
                while( reader.scan( buffer, sizeof(buffer), &bytes ) && !reader.end() )
                {
                    // Write this data into the output file
                    DWORD bytesWritten;
                    BOOL success = WriteFile( hDestination,
                                              buffer,
                                              bytes,
                                             &bytesWritten,
                                              NULL );

                    // Exit if the data couldn't be written or the user exited the launcher
                    if( !dcx::dcxWin32StdMessagePump( myMainWindow ) ||
                        APP_WARNING( !success || !bytesWritten )( "Couldn't write data to temporary file" ) )
                        break;

                    // Add to the number of bytes that were read
                    bytesRead += bytes;

                    // Update the progress bar
                    Progress_SetPos( getProgressBar(), (WORD)(((double)bytesRead / (double)p->file_size) * 65535) );
                }

                bool completed = reader.end();

                // Get rid of the output file and internet connection
                reader.close();
                CloseHandle( hDestination );

                // If we didn't finish the download, fail
                if( APP_ERROR( !completed )( "Didn't complete download of %s", fileUrl.c_str() ) )
                    return false;
            }

            // Delete original files and copy files over
            for( std::vector<std::pair<std::string,std::string>>::iterator i  = tempFilesToLocalFiles.begin();
                                                                           i != tempFilesToLocalFiles.end(); ++i )
            {
                // Copy over the existing file
                CopyFile( i->first.c_str(), i->second.c_str(), FALSE );

                // Erase the temporary file
                DeleteFile( i->first.c_str() );
            }

            // Max out the bar
            Progress_SetPos( getProgressBar(), 65535 );

            // Success
            return true;
        }
void parseOrbitDownloadsList(const CString& sDldList, OrbitDownloadsArray& arrDownloads)
{
	CString sMsg;
	if (sDldList.IsEmpty())
		return;

	CCsvParser cpParser;
	cpParser.Init(sDldList, "\"", ",");

	CString sContent;
	while (cpParser.ParseNextRecord()) {

		int nFieldNumber = -1;
		CString sValue;
		TOrbitDownload tOrbitDownload;
		while (cpParser.GetNextField(sValue)) {
			++nFieldNumber;
			if (nFieldNumber == 0) {
				tOrbitDownload.sPath = sValue;
			}
			if (nFieldNumber == 1) {
				tOrbitDownload.sFile = sValue;
			}
			if (nFieldNumber == 2) {
				sValue.Trim();
				UINT64 uFileSize;
				if (sscanf_s((const char*)sValue, "%I64u", &uFileSize) != 1) {
					sMsg = LS (L_CANT_PARSE_ORBIT_DOWNLOAD_LIST);
					throw std::runtime_error((LPCTSTR)sMsg);
				}

				char szCompletedSize[16] = {0,};
				sprintf_s(szCompletedSize, 16, "%I64u", uFileSize);
				if (sValue.CompareNoCase(szCompletedSize) != 0) {
					sMsg = LS (L_CANT_PARSE_ORBIT_DOWNLOAD_LIST);
					throw std::runtime_error((LPCTSTR)sMsg);
				}

				tOrbitDownload.uFileSize = uFileSize;

			}
			if (nFieldNumber == 4) {
				tOrbitDownload.sUrl = sValue;
			}
			if (nFieldNumber == 10) {
				sValue.Trim();
				if (!sValue.IsEmpty())
					tOrbitDownload.bIsComplete = true;
			}

			
		}

		if (nFieldNumber < 10) {
			sMsg = LS (L_CANT_PARSE_ORBIT_DOWNLOAD_LIST);
			throw std::runtime_error((LPCTSTR)sMsg);
		}

		if (tOrbitDownload.bIsComplete)
			arrDownloads.Add(tOrbitDownload);

	}

	
	int nFieldNumber = -1;
	CString sValue;
	TOrbitDownload tOrbitDownload;
	while (cpParser.GetNextField(sValue)) {
		++nFieldNumber;
		if (nFieldNumber == 0) {
			tOrbitDownload.sPath = sValue;
		}
		if (nFieldNumber == 1) {
			tOrbitDownload.sFile = sValue;
		}
		if (nFieldNumber == 2) {
			sValue.Trim();
			UINT64 uFileSize;
			if (sscanf_s((const char*)sValue, "%I64u", &uFileSize) != 1) {
				sMsg = LS (L_CANT_PARSE_ORBIT_DOWNLOAD_LIST);
				throw std::runtime_error((LPCTSTR)sMsg);
			}

			char szCompletedSize[16] = {0,};
			sprintf_s(szCompletedSize, 16, "%I64u", uFileSize);
			if (sValue.CompareNoCase(szCompletedSize) != 0) {
				sMsg = LS (L_CANT_PARSE_ORBIT_DOWNLOAD_LIST);
				throw std::runtime_error((LPCTSTR)sMsg);
			}

			tOrbitDownload.uFileSize = uFileSize;

		}
		if (nFieldNumber == 4) {
			tOrbitDownload.sUrl = sValue;
		}

		if (nFieldNumber == 10) {
			sValue.Trim();
			if (!sValue.IsEmpty())
				tOrbitDownload.bIsComplete = true;
		}

		
	}

	if (nFieldNumber < 10) {
		sMsg = LS (L_CANT_PARSE_ORBIT_DOWNLOAD_LIST);
		throw std::runtime_error((LPCTSTR)sMsg);
	}

	if (tOrbitDownload.bIsComplete)
		arrDownloads.Add(tOrbitDownload);
}