コード例 #1
0
void DXRenderer::InitializeDX(int _screenWidth, int _screenHeight, bool _vsync, HWND _hwnd, bool _fullScreen, float _screenDepth, float _screenNear)
{
	HRESULT result;
	IDXGIFactory* factory;
	IDXGIAdapter* adapter;
	IDXGIOutput* adapterOutput;
	unsigned int numModes, i, numerator = 60, denominator = 1, stringLength;
	DXGI_MODE_DESC* displayModeList;
	DXGI_ADAPTER_DESC adapterDesc;
	int error;
	DXGI_SWAP_CHAIN_DESC swapChainDesc;
	ID3D11Texture2D* backBufferPtr;
	D3D11_TEXTURE2D_DESC depthBufferDesc;
	D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
	D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
	D3D11_RASTERIZER_DESC rasterDesc;
	D3D11_VIEWPORT viewport;
	float fieldOfView, screenAspect;

	m_fScreenDepth = _screenDepth;
	m_fScreenNear = _screenNear;

	// Store the vsync setting.
	m_bVSyncEnabled = _vsync;

	// Create a DirectX graphics interface factory.
	result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
	if (FAILED(result))
	{
		//return false;
		std::cout << "Error creating DXGIFactory" << std::endl;
	}

	// Use the factory to create an adapter for the primary graphics interface (video card).
	result = factory->EnumAdapters(0, &adapter);
	if (FAILED(result))
	{
		//return false;
	}

	// Enumerate the primary adapter output (monitor).
	result = adapter->EnumOutputs(0, &adapterOutput);
	if (FAILED(result))
	{
		//return false;
	}

	// Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	if (FAILED(result))
	{
		//return false;
	}

	// Create a list to hold all the possible display modes for this monitor/video card combination.
	displayModeList = new DXGI_MODE_DESC[numModes];
	if (!displayModeList)
	{
		//return false;
	}

	// Now fill the display mode list structures.
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	if (FAILED(result))
	{
		//return false;
	}

	// Now go through all the display modes and find the one that matches the screen width and height.
	// When a match is found store the numerator and denominator of the refresh rate for that monitor.
	for (i = 0; i<numModes; i++)
	{
		if (displayModeList[i].Width == (unsigned int)_screenWidth)
		{
			if (displayModeList[i].Height == (unsigned int)_screenHeight)
			{
				numerator = displayModeList[i].RefreshRate.Numerator;
				denominator = displayModeList[i].RefreshRate.Denominator;
			}
		}
	}

	// Get the adapter (video card) description.
	result = adapter->GetDesc(&adapterDesc);
	if (FAILED(result))
	{
		//return false;
	}

	// Store the dedicated video card memory in megabytes.
	m_iVideoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);


	// Convert the name of the video card to a character array and store it.
	error = wcstombs_s(&stringLength, m_sVideoCardDescription, 128, adapterDesc.Description, 128);
	if (error != 0)
	{
		//return false;
	}
	std::cout << "Video Card: " << m_sVideoCardDescription << std::endl;

	//Ora si possono liberare tutti gli oggetti e strutture create per ottenere le informazioni sulla scheda video e refresh rate

	// Release the display mode list.
	delete[] displayModeList;
	displayModeList = 0;

	// Release the adapter output.
	adapterOutput->Release();
	adapterOutput = 0;

	// Release the adapter.
	adapter->Release();
	adapter = 0;

	// Release the factory.
	factory->Release();
	factory = 0;

	//Ora inizializziamo DirectX!

	//Initialize the swap chain description.
	ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

	// Set to a single back buffer.
	swapChainDesc.BufferCount = 1;

	// Set the width and height of the back buffer.
	swapChainDesc.BufferDesc.Width = _screenWidth;
	swapChainDesc.BufferDesc.Height = _screenHeight;

	// Set regular 32-bit surface for the back buffer.
	swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

	// Set the refresh rate of the back buffer.
	if (m_bVSyncEnabled)
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
	}
	else
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
	}

	// Set the usage of the back buffer.
	swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

	// Set the handle for the window to render to.
	swapChainDesc.OutputWindow = _hwnd;

	// Turn multisampling off.
	swapChainDesc.SampleDesc.Count = 1;
	swapChainDesc.SampleDesc.Quality = 0;

	// Set to full screen or windowed mode.
	if (_fullScreen)
	{
		swapChainDesc.Windowed = false;
	}
	else
	{
		swapChainDesc.Windowed = true;
	}

	//Proviamo senza questa roba avanzata

	// Set the scan line ordering and scaling to unspecified.
	swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	// Discard the back buffer contents after presenting.
	swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

	// Don't set the advanced flags.
	swapChainDesc.Flags = 0;



	D3D_FEATURE_LEVEL featureLevel[] =
	{
		// TODO: Modify for supported Direct3D feature levels (see code below related to 11.1 fallback handling)
		D3D_FEATURE_LEVEL_11_1,
		D3D_FEATURE_LEVEL_11_0,
		D3D_FEATURE_LEVEL_10_1,
		D3D_FEATURE_LEVEL_10_0,
		D3D_FEATURE_LEVEL_9_3,
		D3D_FEATURE_LEVEL_9_2,
		D3D_FEATURE_LEVEL_9_1,
	};

	D3D_DRIVER_TYPE driverTypes[] =
	{
		D3D_DRIVER_TYPE_HARDWARE,
		D3D_DRIVER_TYPE_REFERENCE,
		D3D_DRIVER_TYPE_SOFTWARE,
	};

	UINT numDriverTypes = sizeof(driverTypes) / sizeof(driverTypes[0]);

	D3D_DRIVER_TYPE g_driverType;

	for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; ++driverTypeIndex)
	{
		// Prova ad inizializzare per i tipi di driver definiti
		g_driverType = driverTypes[driverTypeIndex];

		//result = D3D11CreateDevice(nullptr, g_driverType, nullptr, 0, nullptr, 0, D3D11_SDK_VERSION, &m_device, nullptr, &m_deviceContext);

		result = D3D11CreateDeviceAndSwapChain(nullptr, g_driverType, nullptr, 0, nullptr, 0,
			D3D11_SDK_VERSION, &swapChainDesc, &m_dSwapChain, &m_dDevice, nullptr, &m_dDeviceContext);

		// Appena funziona esci
		if (SUCCEEDED(result))
			break;
	}

	if (FAILED(result))
	{
		//return false;
		std::cout << "Error creating SwapChain" << std::endl;
	}
	else std::cout << "DirectX SwapChain created successfully." << std::endl;

	//D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;

	//Creiamo la swapchain, il device e il device context!!
	/*
	result = D3D11CreateDeviceAndSwapChain(
	NULL,
	D3D_DRIVER_TYPE_HARDWARE,
	NULL,
	0,
	featureLevel,
	1,
	D3D11_SDK_VERSION,
	&swapChainDesc,
	&m_swapChain,
	&m_device,
	NULL,
	&m_deviceContext);

	if (FAILED(result))
	{
	return false;
	}
	*/
	// Get the pointer to the back buffer.
	result = m_dSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
	if (FAILED(result))
	{
		//return false;
		std::cout << "Error creating backbuffer" << std::endl;
	}

	// Create the render target view with the back buffer pointer.
	result = m_dDevice->CreateRenderTargetView(backBufferPtr, NULL, &m_dRenderTargetView);
	if (FAILED(result))
	{
		//return false;
		std::cout << "Error creating Render Target View" << std::endl;
	}

	// Release pointer to the back buffer as we no longer need it.
	backBufferPtr->Release();
	backBufferPtr = nullptr;


	// Initialize the description of the depth buffer.
	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

	// Set up the description of the depth buffer.
	depthBufferDesc.Width = _screenWidth;
	depthBufferDesc.Height = _screenHeight;
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 1;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;

	// Create the texture for the depth buffer using the filled out description.
	result = m_dDevice->CreateTexture2D(&depthBufferDesc, NULL, &m_dDepthStencilBuffer);
	if (FAILED(result))
	{
		//return false;
	}

	// Initialize the description of the stencil state.
	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

	// Set up the description of the stencil state.
	depthStencilDesc.DepthEnable = true;
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0xFF;

	// Stencil operations if pixel is front-facing.
	depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Stencil operations if pixel is back-facing.
	depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Create the depth stencil state.
	result = m_dDevice->CreateDepthStencilState(&depthStencilDesc, &m_dDepthStencilState);
	if (FAILED(result))
	{
		//return false;
		std::cout << "Error creating Depth Stencil State" << std::endl;
	}

	// Set the depth stencil state.
	m_dDeviceContext->OMSetDepthStencilState(m_dDepthStencilState, 1);

	// Initailze the depth stencil view.
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

	// Set up the depth stencil view description.
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	// Create the depth stencil view.
	result = m_dDevice->CreateDepthStencilView(m_dDepthStencilBuffer, &depthStencilViewDesc, &m_dDepthStencilView);
	if (FAILED(result))
	{
		//return false;
		std::cout << "Error creating Depth Stencil View" << std::endl;
	}

	// Bind the render target view and depth stencil buffer to the output render pipeline.
	m_dDeviceContext->OMSetRenderTargets(1, &m_dRenderTargetView, m_dDepthStencilView);

	// Setup the raster description which will determine how and what polygons will be drawn.
	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_BACK;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = true;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	// Create the rasterizer state from the description we just filled out.
	result = m_dDevice->CreateRasterizerState(&rasterDesc, &m_dRasterState);
	if (FAILED(result))
	{
		//return false;
	}

	// Now set the rasterizer state.
	m_dDeviceContext->RSSetState(m_dRasterState);

	// Setup the viewport for rendering.
	viewport.Width = (float)_screenWidth;
	viewport.Height = (float)_screenHeight;
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.TopLeftX = 0.0f;
	viewport.TopLeftY = 0.0f;

	// Create the viewport.
	m_dDeviceContext->RSSetViewports(1, &viewport);

	// Setup the projection matrix.
	fieldOfView = (float)DirectX::XM_PI / 4.0f;
	screenAspect = (float)_screenWidth / (float)_screenHeight;

	//Create constant buffer for the vertex shader
	D3D11_BUFFER_DESC cbDesc;
	ZeroMemory(&cbDesc, sizeof(D3D11_BUFFER_DESC));

	cbDesc.Usage = D3D11_USAGE_DEFAULT;
	cbDesc.ByteWidth = sizeof(GFX::ConstantObject);
	cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	cbDesc.CPUAccessFlags = 0;
	cbDesc.MiscFlags = 0;

	D3D11_SAMPLER_DESC sampDesc;
	ZeroMemory(&sampDesc, sizeof(sampDesc));
	sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
	sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
	sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
	sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
	sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
	sampDesc.MinLOD = 0;
	sampDesc.MaxLOD = D3D11_FLOAT32_MAX;

	m_dDevice->CreateSamplerState(&sampDesc, &m_dSamplerState);


	m_dDevice->CreateBuffer(&cbDesc, NULL, &m_bConstObj);

	m_dDeviceContext->VSSetConstantBuffers(0, 1, &m_bConstObj);

	std::cout << "DirectX initialized successfully." << std::endl;
}
コード例 #2
0
/* 
	Populate the imFileInfoRec8 structure describing this file instance
	to Premiere.  Check file validity, allocate any private instance data 
	to share between different calls.
*/
prMALError 
SDKGetInfo8(
	imStdParms			*stdParms, 
	imFileAccessRec8	*fileAccessInfo, 
	imFileInfoRec8		*fileInfo)
{
	prMALError					result				= malNoError;
	PrivateDataH pdH = reinterpret_cast<PrivateDataH>(fileInfo->privatedata); 

	stdParms->piSuites->memFuncs->lockHandle(reinterpret_cast<char**>(pdH)); //Lock private data

	(*pdH)->flacErrorCode = 0;
	(*pdH)->flacDecoder = 0;

	char filepathASCII[255];
	int stringLength = (int)wcslen(reinterpret_cast<const wchar_t*>(fileAccessInfo->filepath));
	wcstombs_s(	NULL, reinterpret_cast<char*>(filepathASCII), sizeof (filepathASCII), fileAccessInfo->filepath, stringLength);

	FLAC__bool ok = true;
    FLAC__StreamDecoderInitStatus init_status;
	if(((*pdH)->flacDecoder = FLAC__stream_decoder_new()) == NULL)
	{
		(*pdH)->flacErrorCode = 1;
	}

	FLAC__stream_decoder_set_md5_checking((*pdH)->flacDecoder, true);

	init_status = FLAC__stream_decoder_init_file((*pdH)->flacDecoder, filepathASCII, write_callback, NULL, error_callback, pdH);
	if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK )
	{
		return imBadFile; //Error, bail out
	}
	FLAC__stream_decoder_process_until_end_of_metadata((*pdH)->flacDecoder);
	FLAC__stream_decoder_process_single((*pdH)->flacDecoder);

	(*pdH)->audioChannels = FLAC__stream_decoder_get_channels((*pdH)->flacDecoder);
	(*pdH)->audioNumberOfSamples = FLAC__stream_decoder_get_total_samples((*pdH)->flacDecoder);
	(*pdH)->audioNumberOfSamplesPerSecond = FLAC__stream_decoder_get_sample_rate((*pdH)->flacDecoder);
	(*pdH)->audioBytesPerSample = FLAC__stream_decoder_get_bits_per_sample((*pdH)->flacDecoder) / 8;
	(*pdH)->audioPosition = 0;

	//Fill out the general file info
	fileInfo->accessModes						= kSeparateSequentialAudio;
	fileInfo->hasDataRate						= kPrFalse;	
	fileInfo->hasVideo							= kPrFalse;
	fileInfo->hasAudio							= kPrTrue;
	fileInfo->alwaysUnquiet						= 0;
	fileInfo->highMemUsage						= 0;
	fileInfo->audInfo.numChannels				= (*pdH)->audioChannels;
	fileInfo->audInfo.sampleRate				= (float)(*pdH)->audioNumberOfSamplesPerSecond;
	fileInfo->audDuration						= (*pdH)->audioNumberOfSamples;

	if((*pdH)->audioBytesPerSample == 1)
	{
		fileInfo->audInfo.sampleType = kPrAudioSampleType_8BitInt;
	}
	else if((*pdH)->audioBytesPerSample == 2)
	{
		fileInfo->audInfo.sampleType = kPrAudioSampleType_16BitInt;
	}
	else if((*pdH)->audioBytesPerSample == 3)
	{
		fileInfo->audInfo.sampleType = kPrAudioSampleType_24BitInt;
	}
	else if((*pdH)->audioBytesPerSample == 4)
	{
		fileInfo->audInfo.sampleType = kPrAudioSampleType_32BitInt;
	}
	else
	{
		fileInfo->audInfo.sampleType = kPrAudioSampleType_Other;
	}

	(*pdH)->suiteBasic = stdParms->piSuites->utilFuncs->getSPBasicSuite(); //Allocate an audio suite
	if ((*pdH)->suiteBasic)
	{
		(*pdH)->suiteBasic->AcquireSuite (kPrSDKAudioSuite, kPrSDKAudioSuiteVersion, (const void**)&(*pdH)->suiteAudio);
	}

	stdParms->piSuites->memFuncs->unlockHandle(reinterpret_cast<char**>(pdH)); //Unlock private data

	return result;
}
コード例 #3
0
ファイル: War3Key.cpp プロジェクト: frostzhenya/War3Key
BOOL CWar3KeyApp::InitInstance()
{
	// 如果一个运行在 Windows XP 上的应用程序清单指定要
	// 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式,
	//则需要 InitCommonControlsEx()。否则,将无法创建窗口。
	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);
	// 将它设置为包括所有要在应用程序中使用的
	// 公共控件类。
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	CWinApp::InitInstance();

	AfxEnableControlContainer();

	// 标准初始化
	// 如果未使用这些功能并希望减小
	// 最终可执行文件的大小,则应移除下列
	// 不需要的特定初始化例程
	// 更改用于存储设置的注册表项
	// TODO: 应适当修改该字符串,
	// 例如修改为公司或组织名
	SetRegistryKey(_T("应用程序向导生成的本地应用程序"));

	HANDLE hMapping;
	hMapping = OpenFileMapping(FILE_MAP_ALL_ACCESS,true,_T("War3KeyMappingShared"));
	if (!hMapping)
		hMapping = CreateFileMapping((HANDLE)0xFFFFFFFF,NULL,PAGE_READWRITE,0,sizeof(KeyMappingInformation),_T("War3KeyMappingShared"));
	KeyMappingInformation *lpMapping = (KeyMappingInformation*)MapViewOfFile(hMapping,FILE_MAP_WRITE,0,0,0);
	if(!lpMapping) {
		MessageBox(0,_T("OpenFileMapping failed"),_T("Error"),0);
		return FALSE;
	}
	memset(lpMapping,0,sizeof(KeyMappingInformation));

    
	int i;
	XMLNode xMainNode;
	FILE *f;
	CWar3KeyDlg dlg;

	f = fopen("config.xml","rt");
	if(f==NULL) {
		f = fopen("config.xml","wt");
		fwrite("<?War3 KeyMapper Configuration?>",strlen("<?War3 KeyMapper Configuration?>"),1,f);
	}
	fclose(f);
	xMainNode = XMLNode::openFileHelper(_T("config.xml"));
		
	InitializeCriticalSection(&(lpMapping->CriticalSection));

	for (int i=0;i<xMainNode.nChildNode();i++) {
	
		lpMapping->OriginalKey[i] = _wtoi(xMainNode.getChildNode(i).getAttribute(_T("OriginalKey")));
		lpMapping->MappedKey[i] = _wtoi(xMainNode.getChildNode(i).getAttribute(_T("MappedKey")));
		lpMapping->nMappingCount++;
	}
	
	m_pMainWnd = &dlg;
	dlg.lpMapping = lpMapping;
	INT_PTR nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		// TODO: 在此处放置处理何时用“确定”来关闭
		//  对话框的代码
	}
	Unhook();

    xMainNode=XMLNode::createXMLTopNode(_T("War3 KeyMapper Configuration"),TRUE);
	XMLNode xNode;
	wchar_t txt[256];
	for (i=0;i<lpMapping->nMappingCount;i++) {
		_itow(i,txt,10);
		xNode=xMainNode.addChild(txt);

		_itow(lpMapping->OriginalKey[i],txt,10);
		xNode.addAttribute(_T("OriginalKey"),txt);
		_itow(lpMapping->MappedKey[i],txt,10);
		xNode.addAttribute(_T("MappedKey"),txt);
	}

    wchar_t *t=xMainNode.createXMLString(TRUE);
    size_t converted,origsize = wcslen(t) + 1;
    char* buffer = (char *)malloc(origsize);
    wcstombs_s(&converted,buffer, origsize, t, _TRUNCATE);

	f = fopen("config.xml","wt");
	fwrite(buffer,converted-1,1,f);
	fclose(f);
	free(buffer);
    free(t);

	DeleteCriticalSection(&(lpMapping->CriticalSection));
	UnmapViewOfFile(lpMapping);
	CloseHandle(hMapping);

	// 由于对话框已关闭,所以将返回 FALSE 以便退出应用程序,
	//  而不是启动应用程序的消息泵。
	return FALSE;
}
コード例 #4
0
ファイル: encryptor.cpp プロジェクト: msatoh/photoencryptor
LRESULT CALLBACK EncProc(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp){
	PAINTSTRUCT ps;
	static HWND hButton;
	HDC hdc, hMdc;
	TCHAR buf[256];
	static int flag = 0;
	static WCHAR chr[MAXLENGTH + MAX_PATH];
	char filename[MAXLENGTH + MAX_PATH], outfilename[MAXLENGTH + MAX_PATH] = { '\0' };
	static BITMAP bm;
	static OPENFILENAME ofn = { 0 };
	static TCHAR strFile[MAX_PATH], strCustom[256] = TEXT("Before files\0*.*\0\0");
	static HBITMAP hBitmap;

	switch (msg){
	case WM_CREATE:
		ofn.lStructSize = sizeof(OPENFILENAME);
		ofn.hwndOwner = hWnd;
		ofn.lpstrFilter = TEXT("Bitmap files {*.bmp}\0*.bmp\0")
			/*TEXT("他のファイルも同様の形式で")*/;
		ofn.lpstrCustomFilter = strCustom;
		ofn.nMaxCustFilter = 256;
		ofn.nFilterIndex = 0;
		ofn.lpstrFile = strFile;
		ofn.nMaxFile = MAX_PATH;
		ofn.Flags = OFN_FILEMUSTEXIST;
		GetOpenFileName(&ofn);

		// プッシュボタンを作成する
		hButton = CreateWindow(
			_T("BUTTON"),                            // ウィンドウクラス名
			_T("GO"),                             // キャプション
			WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,   // スタイル指定
			bm.bmWidth + 20, 200,                                // 座標
			60, 40,                                  // サイズ
			hWnd,                                    // 親ウィンドウのハンドル
			(HMENU)BUTTON_ID,                        // メニューハンドル
			((LPCREATESTRUCT)lp)->hInstance,                                   // インスタンスハンドル
			NULL                                     // その他の作成データ
			);
		break;
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);     // 描画処理を開始します。
		SetBkMode(hdc, TRANSPARENT);    // 背景を透過モードにします
		if (flag==0){
			hBitmap = (HBITMAP)LoadImage(NULL, (LPCWSTR)ofn.lpstrFile, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
			//エラー処理
			if (hBitmap == NULL){
				MessageBox(hWnd, TEXT("FailedToOpenFile"), TEXT("はい..."), MB_OK);
				PostMessage(hWnd, WM_CLOSE, 0, 0);
				EndPaint(hWnd, &ps);
				break;
			}
			hMdc = CreateCompatibleDC(hdc);
			SelectObject(hMdc, hBitmap);
			GetObject(hBitmap, sizeof(BITMAP), &bm);
			BitBlt(hdc, 5, 5, bm.bmWidth, bm.bmHeight, hMdc, 0, 0, SRCCOPY);
		}
		else{
			//ひらいた画像ファイルを表示
			hBitmap = (HBITMAP)LoadImage(NULL, (LPCWSTR)chr, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
			if (hBitmap == NULL){
				MessageBox(hWnd, TEXT("FailedToOpenFileofOutput"), TEXT("はい..."), MB_OK);
				PostMessage(hWnd, WM_CLOSE, 0, 0);
				EndPaint(hWnd, &ps);
				break;
			}
			hMdc = CreateCompatibleDC(hdc);
			SelectObject(hMdc, hBitmap);
			if (!BitBlt(hdc, bm.bmWidth + 100, 5, bm.bmWidth, bm.bmHeight, hMdc, 0, 0, SRCCOPY))
				MessageBox(hWnd, TEXT("FailedTobitbltofoutput"), TEXT("はい..."), MB_OK);
		}
		MoveWindow(
			hButton,      // ウィンドウのハンドル
			bm.bmWidth + 25,          // 横方向の位置
			200,          // 縦方向の位置
			60,     // 幅
			40,    // 高さ
			false   // 再描画オプション
			);
	/*	DeleteDC(hMdc);
		DeleteObject(hBitmap);
		EndPaint(hWnd, &ps);*/
		break;
	case WM_COMMAND:
		GetClassName(hWnd, buf, 255);
		switch (LOWORD(wp)){
		case BUTTON_ID:
			setlocale(LC_ALL, "japanese");
			//ひらいた画像ファイルを表示
			wcstombs_s(0, filename, MAXLENGTH + MAX_PATH, ofn.lpstrFile, _TRUNCATE);
			if (!Encryption(filename)){
				MessageBox(hWnd, TEXT("4545"), TEXT("変換に失敗した..."), MB_OK);
				return -1;
			}
			else{
				wcscpy(chr,ofn.lpstrFile);
				wcscat(chr,_T("_conv.bmp"));
				++flag; //ここでスイッチを切れ変える。
				flag &= 1;
				InvalidateRect(
					hWnd,           // ウィンドウのハンドル
					NULL,  // 長方形の座標
					false          // 消去するかどうかの状態
					);
			}
			break;
		default:
			return (DefWindowProc(hWnd, msg, wp, lp));
		}
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return (DefWindowProc(hWnd, msg, wp, lp));
	}
	return 0;
}
コード例 #5
0
ファイル: ch.cpp プロジェクト: EdwardBetts/spidernode
HRESULT CreateLibraryByteCodeHeader(LPCOLESTR fileContents, BYTE * contentsRaw, DWORD lengthBytes, LPCWSTR bcFullPath, LPCWSTR libraryNameWide)
{
    HRESULT hr = S_OK;
    HANDLE bcFileHandle = nullptr;
    BYTE *bcBuffer = nullptr;
    DWORD bcBufferSize = 0;
    IfFailGo(GetSerializedBuffer(fileContents, &bcBuffer, &bcBufferSize));

    bcFileHandle = CreateFile(bcFullPath, GENERIC_WRITE, FILE_SHARE_DELETE, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
    if (bcFileHandle == INVALID_HANDLE_VALUE)
    {
        IfFailGo(E_FAIL);
    }

    DWORD written;

    // For validating the header file against the library file
    auto outputStr =
        "//-------------------------------------------------------------------------------------------------------\r\n"
        "// Copyright (C) Microsoft. All rights reserved.\r\n"
        "// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\r\n"
        "//-------------------------------------------------------------------------------------------------------\r\n"
        "#if 0\r\n";
    IfFalseGo(WriteFile(bcFileHandle, outputStr, (DWORD)strlen(outputStr), &written, nullptr));
    IfFalseGo(WriteFile(bcFileHandle, contentsRaw, lengthBytes, &written, nullptr));
    if (lengthBytes < 2 || contentsRaw[lengthBytes - 2] != '\r' || contentsRaw[lengthBytes - 1] != '\n')
    {
        outputStr = "\r\n#endif\r\n";
    }
    else
    {
        outputStr = "#endif\r\n";
    }
    IfFalseGo(WriteFile(bcFileHandle, outputStr, (DWORD)strlen(outputStr), &written, nullptr));

    // Write out the bytecode
    outputStr = "namespace Js\r\n{\r\n    const char Library_Bytecode_";
    IfFalseGo(WriteFile(bcFileHandle, outputStr, (DWORD)strlen(outputStr), &written, nullptr));
    size_t convertedChars;
    char libraryNameNarrow[MAX_PATH + 1];
    IfFalseGo((wcstombs_s(&convertedChars, libraryNameNarrow, libraryNameWide, _TRUNCATE) == 0));
    IfFalseGo(WriteFile(bcFileHandle, libraryNameNarrow, (DWORD)strlen(libraryNameNarrow), &written, nullptr));
    outputStr = "[] = {\r\n/* 00000000 */";
    IfFalseGo(WriteFile(bcFileHandle, outputStr, (DWORD)strlen(outputStr), &written, nullptr));

    for (unsigned int i = 0; i < bcBufferSize; i++)
    {
        char scratch[6];
        auto scratchLen = sizeof(scratch);
        int num = _snprintf_s(scratch, scratchLen, " 0x%02X", bcBuffer[i]);
        Assert(num == 5);
        IfFalseGo(WriteFile(bcFileHandle, scratch, (DWORD)(scratchLen - 1), &written, nullptr));

        // Add a comma and a space if this is not the last item
        if (i < bcBufferSize - 1)
        {
            char commaSpace[2];
            _snprintf_s(commaSpace, sizeof(commaSpace), ",");  // close quote, new line, offset and open quote
            IfFalseGo(WriteFile(bcFileHandle, commaSpace, (DWORD)strlen(commaSpace), &written, nullptr));
        }

        // Add a line break every 16 scratches, primarily so the compiler doesn't complain about the string being too long.
        // Also, won't add for the last scratch
        if (i % 16 == 15 && i < bcBufferSize - 1)
        {
            char offset[17];
            _snprintf_s(offset, sizeof(offset), "\r\n/* %08X */", i + 1);  // close quote, new line, offset and open quote
            IfFalseGo(WriteFile(bcFileHandle, offset, (DWORD)strlen(offset), &written, nullptr));
        }
    }
    outputStr = "};\r\n\r\n";
    IfFalseGo(WriteFile(bcFileHandle, outputStr, (DWORD)strlen(outputStr), &written, nullptr));

    outputStr = "}\r\n";
    IfFalseGo(WriteFile(bcFileHandle, outputStr, (DWORD)strlen(outputStr), &written, nullptr));

Error:
    if (bcFileHandle != nullptr)
    {
        CloseHandle(bcFileHandle);
    }
    if (bcBuffer != nullptr)
    {
        delete[] bcBuffer;
    }

    return hr;
}
コード例 #6
0
ファイル: hsflowd.c プロジェクト: Chansie/host-sflow
void ServiceMain(int argc, char** argv) 
{ 
	ServiceStatus.dwServiceType        = SERVICE_WIN32; 
	ServiceStatus.dwCurrentState       = SERVICE_START_PENDING; 
	ServiceStatus.dwControlsAccepted   = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
	ServiceStatus.dwWin32ExitCode      = 0; 
	ServiceStatus.dwServiceSpecificExitCode = 0; 
	ServiceStatus.dwCheckPoint         = 0;
	ServiceStatus.dwWaitHint           = 0;
	if (isService) {
		hStatus = RegisterServiceCtrlHandler(HSP_SERVICE_NAME, 
											 (LPHANDLER_FUNCTION)ControlHandler); 

		if (hStatus == 0) 
		{ 
			return; 
		}
	}
	// Test for only one instance is running
	HANDLE mutex = CreateMutex(NULL, TRUE, instanceMutexName);
	DWORD err = GetLastError();
	if (mutex != NULL && err == ERROR_ALREADY_EXISTS ||
		mutex == NULL && err == ERROR_ACCESS_DENIED) {
			// Mutex found, so another instance is running
		if (hStatus != 0) {
			ServiceStatus.dwCurrentState = SERVICE_STOPPED;
			ServiceStatus.dwWin32ExitCode = ERROR_SINGLE_INSTANCE_APP;
			SetServiceStatus(hStatus, &ServiceStatus);
		} else {
			myLog(LOG_ERR, "%s.ServiceMain: only one instance can run, existing instance found", HSP_SERVICE_NAME);
		}
		return;
	} else {
		ServiceStatus.dwCurrentState = SERVICE_RUNNING; 
		if (hStatus != 0) {
			// We are the first instance, report the running status to SCM. 
			SetServiceStatus (hStatus, &ServiceStatus);
		}
	}
	wchar_t programDataDir[MAX_PATH];
	if (!initialiseProgramDataDir(programDataDir, MAX_PATH)) {
		*programDataDir = NULL;
	}
	char mbcLogFilename[MAX_PATH];
	if (isService && *programDataDir != NULL) {
		//set the log file name to the default.
		size_t dirLen = 0;
		if (0 == wcstombs_s(&dirLen, mbcLogFilename, MAX_PATH, programDataDir, wcslen(programDataDir))) {
			PathAppend(mbcLogFilename, HSP_DEFAULT_LOGFILE);
			logFilename = mbcLogFilename;
		} else {
			logFilename = NULL;
		}
	}
	if (logFilename != NULL) {
        // Logging on
     	errno_t error = fopen_s(&logFile, logFilename, "wt");
        if (error != 0) {
			logFile = stderr;
			myLog(LOG_ERR, "%s.ServiceMain: could not open log file %s: error %d\n", HSP_SERVICE_NAME, logFilename, error);
        }
		logFilename = NULL;
    }
	myLog(debug, "-------------Starting %s %s--------------", HSP_SERVICE_NAME, HSP_VERSION);
	fflush(logFile);

	HRESULT initComHr = initCom();
	if (FAILED(initComHr)) {
		myLog(LOG_ERR, "%s.ServiceMain: cannot initialize COM for WMI error=0x%x", HSP_SERVICE_NAME, initComHr);
		if (hStatus != 0) {
			ServiceStatus.dwCurrentState = SERVICE_STOPPED;
			ServiceStatus.dwWin32ExitCode = ERROR_APP_INIT_FAILURE;
			SetServiceStatus(hStatus, &ServiceStatus);
		}
		return;
	}

	HSP sp = { 0 };
	sp.DNSSD_startDelay = HSP_DEFAULT_DNSSD_STARTDELAY;
	sp.DNSSD_retryDelay = HSP_DEFAULT_DNSSD_RETRYDELAY;
	// look up host-id fields at startup only (hostname
	// may change dynamically so will have to revisit this $$$)
	sp.host_hid.hostname.str = (char *)my_calloc(SFL_MAX_HOSTNAME_CHARS+1);
	sp.host_hid.os_release.str = (char *)my_calloc(SFL_MAX_OSRELEASE_CHARS+1);
	readHidCounters(&sp, &sp.host_hid);
	
	sp.nio_polling_secs = HSP_NIO_POLLING_SECS_32BIT;

	readInterfaces(&sp, TRUE);
	if (!readConfig(&sp)) {
		myLog(LOG_ERR, "%s.ServiceMain: invalid configuration", HSP_SERVICE_NAME);
		if (hStatus != 0) {
			ServiceStatus.dwCurrentState = SERVICE_STOPPED;
			ServiceStatus.dwWin32ExitCode = ERROR_INVALID_PARAMETER;
			SetServiceStatus(hStatus, &ServiceStatus);
		}
		return;
	}
	sp.hyperV = testForHyperv();
	if (sp.hyperV) {
		myLog(debug, "%s.ServiceMain Hyper-V services are running", HSP_SERVICE_NAME);
		if (programDataDir == NULL || !initialiseProgramDataFiles(&sp, programDataDir)) {
			myLog(LOG_ERR, "%s.ServiceMain: cannot initialise switch port and VM state files", HSP_SERVICE_NAME);
			if (hStatus != 0) {
				ServiceStatus.dwCurrentState = SERVICE_STOPPED;
				ServiceStatus.dwWin32ExitCode = ERROR_FILE_NOT_FOUND;
				SetServiceStatus(hStatus, &ServiceStatus);
			}
			return;
		}
		readGuidStore(sp.f_vmStore, sp.vmStoreFile, &sp.vmStore, &sp.maxDsIndex);
		readGuidStore(sp.f_portStore, sp.portStoreFile, &sp.portStore, &sp.maxIfIndex);
	}
	
	if (sp.DNSSD) {
		//start the DNS thread and loop waiting until we have the config from DNSSD
		HANDLE dnsSDThread;
		unsigned threadID;
		dnsSDThread = (HANDLE)_beginthreadex(NULL, 0, &runDNSSD, &sp, 0, &threadID);
		BOOL gotConfig = FALSE;
		while (!gotConfig) {
			HSPSFlowSettings *settings = sp.sFlow->sFlowSettings;
			if (newerSettingsAvailable(settings)) {
				HSPSFlowSettings *newSettings = newSFlowSettings();
				if (readSFlowSettings(newSettings)) {
					//we have the config now
					gotConfig = TRUE;
					if (settings != NULL) {
						freeSFlowSettings(settings);
					}
					sp.sFlow->sFlowSettings = newSettings;
					myLog(debug, "%s.ServiceMain: DNS-SD enabled. Initial sFlow settings from registry currentconfig",
						HSP_SERVICE_NAME);
				} else {
					freeSFlowSettings(newSettings);
					myLog(LOG_ERR, "%s.ServiceMain: invalid DNS-SD discovered sFlow settings", HSP_SERVICE_NAME);
					if (hStatus != 0) {
						ServiceStatus.dwCurrentState = SERVICE_STOPPED;
						ServiceStatus.dwWin32ExitCode = ERROR_INVALID_PARAMETER;
						SetServiceStatus(hStatus, &ServiceStatus);
					}
					return;
				}
			} else {
				Sleep(sp.DNSSD_startDelay*1000);
			}
		}
	} else { // read the manual config
		HSPSFlowSettings *newSettings = newSFlowSettings();
		if (readSFlowSettings(newSettings)) {
			sp.sFlow->sFlowSettings = newSettings;
		} else {
			myLog(LOG_ERR, "%s.ServiceMain: invalid sFlow configuration in registry", HSP_SERVICE_NAME);
			if (hStatus != 0) {
				ServiceStatus.dwCurrentState = SERVICE_STOPPED;
				ServiceStatus.dwWin32ExitCode = ERROR_INVALID_PARAMETER;
				SetServiceStatus(hStatus, &ServiceStatus);
			}
			return;
		}
	}
	openFilter(&sp); //try to initialise the sFlow filter for sampling
	initAgent(&sp);
	logSFlowSettings(sp.sFlow);


	// initialize the clock so we can detect second boundaries
	sp.clk = time(NULL);
 
    // main loop
	BOOL dataAvailable = true;
	uint32_t currReadNum = 0;
	while (ServiceStatus.dwCurrentState == SERVICE_RUNNING && dataAvailable)
	{
		// check for second boundaries and generate ticks for the sFlow library
		time_t now = time(NULL);
		if ((now < sp.clk) || (now - sp.clk) > HSP_MAX_TICKS) {
			// avoid a busy-loop of ticks if time jumps
			myLog(LOG_INFO, "%s.ServiceMain: time jump detected", HSP_SERVICE_NAME);
			sp.clk = now - 1;
		}
		while (sp.clk < now) { //only happens on second boundary
			//start critical
			if (sp.sFlow->sFlowSettings) {
				if (sp.clk%5 == 0 && newerSettingsAvailable(sp.sFlow->sFlowSettings)) {
					//get the new config
					HSPSFlowSettings *newSettings = newSFlowSettings();
					if (readSFlowSettings(newSettings)) {
						//we have the config now
						BOOL pollingChanged = sp.sFlow->sFlowSettings->pollingInterval !=  newSettings->pollingInterval;
						BOOL samplingChanged = sp.sFlow->sFlowSettings->samplingRate !=  newSettings->samplingRate;
						freeSFlowSettings(sp.sFlow->sFlowSettings);
						sp.sFlow->sFlowSettings = newSettings;
						myLog(debug, "%s.ServiceMain: updated configuration settings", HSP_SERVICE_NAME);
						logSFlowSettings(sp.sFlow);
						if (pollingChanged) {
							for (SFLPoller *poller = sp.sFlow->agent->pollers;
								poller; poller = poller->nxt) {
								sfl_poller_set_sFlowCpInterval(poller, sp.sFlow->sFlowSettings->pollingInterval);
							}
						}
						if (samplingChanged && HSP_FILTER_ACTIVE(sp.filter)) {
							setFilterSamplingParams(&sp);
						}
					} else {
						freeSFlowSettings(newSettings);
					}
				}
				tick(&sp);
			}
			//end critical
			sp.clk++;
		}
		DWORD result;
		//process a queued counter poller
		processQueuedPoller(&sp);
		//timeout is set so that we loop around checking for ticks and samples
		//several times/s.
		//calculate timeout 200 if the counter poller queue is empty, 0 otherwise
		DWORD timeout = sp.pollerQHead == NULL ? HSP_TIMEOUT : 0;
		if (HSP_FILTER_ACTIVE(sp.filter)) {
			result = WaitForSingleObject(sp.filter.overlaps[currReadNum].hEvent, 
										 timeout);
			if (result == WAIT_OBJECT_0) {
				dataAvailable = sp.filter.overlaps[currReadNum].Internal == ERROR_SUCCESS;
				if (dataAvailable && sp.filter.overlaps[currReadNum].InternalHigh > 0) {
					//process the sample info in sp.filter.buffers[currReadNum]
					readPackets(&sp, sp.filter.buffers[currReadNum]);
				}
				// Re-queue this read
				queueRead(sp.filter.dev,
					      sp.filter.buffers[currReadNum], 
					      sizeof(sp.filter.buffers[currReadNum]), 
						  &sp.filter.overlaps[currReadNum]);
				//set the next buffer to read
				currReadNum = (currReadNum+1)%numConcurrentReads;
			}
		} else {
			Sleep(timeout);
		}
	}
    return; 
}
コード例 #7
0
ファイル: DrawDlg.Cpp プロジェクト: nizihabi/sdk71examples
DWORD ReceiveUpdates(CDisdrawDlg *pDrawDlg)
{
   	//
	// Prepare the message properties to receive.
	//
	DWORD cProps = 0;
	MQMSGPROPS    propsMessage;
	MQPROPVARIANT aPropVar[2];
	MSGPROPID     aPropId[2];

	WCHAR wcsBody[MAX_MSG_BODY_LEN+1];
	aPropId[cProps]				= PROPID_M_BODY;
	aPropVar[cProps].vt			= VT_UI1 | VT_VECTOR;
	aPropVar[cProps].caub.cElems = sizeof(wcsBody);
	aPropVar[cProps].caub.pElems = (UCHAR *)wcsBody;
	cProps++;

    aPropId[cProps]				= PROPID_M_BODY_SIZE;
	aPropVar[cProps].vt			= VT_UI4;
	cProps++;

	propsMessage.cProp    = cProps;
	propsMessage.aPropID  = aPropId;
	propsMessage.aPropVar = aPropVar;
	propsMessage.aStatus  = NULL;


    //
    // Keep receiving updates sent to the incoming queue.
    //
    HRESULT hr;
    LINE line;
	char mbsBody[MAX_MSG_BODY_LEN + 1];

    while (TRUE)
    {
        //
        // Synchronously receive a message from the incoming queue.
        //
        hr = MQReceiveMessage(pDrawDlg->m_hqIncoming, INFINITE, 
                              MQ_ACTION_RECEIVE, &propsMessage, 
							  NULL, NULL, NULL, NULL);

		//
		// Determine if the message contains a keystroke or a line.
		//
        if (!FAILED(hr))
        {
			//
			// Convert the body to a multibyte null-terminated string. 
			//
            UINT uNumChars = aPropVar[1].ulVal/sizeof(WCHAR);
            size_t nResultedStringLength=0;
            wcstombs_s(
                &nResultedStringLength,
                mbsBody, 
                sizeof(mbsBody),
                wcsBody, 
                uNumChars
                );

			//
			// Add the keystroke to the drawing.
			//
			if (uNumChars == 1)
            {
				pDrawDlg->m_drawScribble.AddKeystroke(mbsBody);
            }
			
			//
			// Add the line received to the drawing.
			//
			else
			{
                		sscanf_s(mbsBody, "%07ld%07ld%07ld%07ld", 
					   &line.ptStart.x, &line.ptStart.y, 
					   &line.ptEnd.x, &line.ptEnd.y);
				pDrawDlg->m_drawScribble.AddLine(line);
			}
        }
    }


    return 0;
}
コード例 #8
0
bool D3DManager::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, 
                          float screenDepth, float screenNear) {
    HRESULT result;
    IDXGIFactory* factory;
    IDXGIAdapter* adapter;
    IDXGIOutput* adapterOutput;
    unsigned int numModes, i, numerator, denominator, stringLength;
    DXGI_MODE_DESC* displayModeList;
    DXGI_ADAPTER_DESC adapterDesc;
    int error;
    DXGI_SWAP_CHAIN_DESC swapChainDesc;
    D3D_FEATURE_LEVEL featureLevel;
    ID3D11Texture2D* backBufferPtr;
    D3D11_TEXTURE2D_DESC depthBufferDesc;
    D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
    D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
    D3D11_RASTERIZER_DESC rasterDesc;
    D3D11_VIEWPORT viewport;
    float fieldOfView, screenAspect;
    D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
    D3D11_BLEND_DESC blendStateDescription;
	std::vector<IDXGIAdapter*> vAdapters;
	int largestAdapter = 0;
	int videoCardMemory;

    // Store our screen width and height
    m_ScreenWidth = screenWidth;
    m_ScreenHeight = screenHeight;

    // Store the vsync setting.
    m_vsync_enabled = vsync;

    // Create a DirectX graphics interface factory.
    result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create a DXGI factory.");
        return false;
    }

	// Loop through each adapter on the computer
	for(UINT i = 0; factory->EnumAdapters(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i)
	{
		// Store the adapter
		vAdapters.push_back(adapter);

		// Get the adapter (video card) description.
		result = adapter->GetDesc(&adapterDesc);
		if(FAILED(result))
		{
			log_sxerror("D3DManager", "Failed to get the video card description.");
			return false;
		}

		// Store the dedicated video card memory in megabytes.
		videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

		// If the memory is larger than our current memory, save this index
		if(videoCardMemory > m_videoCardMemory) {
			m_videoCardMemory = videoCardMemory;
			largestAdapter = i;

			// Convert the name of the video card to a character array and store it.
			error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128);
			if(error != 0)
			{
				log_sxerror("D3DManager", "Failed to get the name of the graphics card.");
				return false;
			}
		}
	}

    // Enumerate the primary adapter output (monitor).
	result = vAdapters.at(0)->EnumOutputs(0, &adapterOutput);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to grab the monitor.");
        return false;
    }

    // Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
    result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to get a list of display modes.");
        return false;
    }

    // Create a list to hold all the possible display modes for this monitor/video card combination.
    displayModeList = new DXGI_MODE_DESC[numModes];
    if(!displayModeList)
    {
		log_sxerror("D3DManager", "Failed to create a display mode list for the monitor/gfx card combo.");
        return false;
    }

    // Now fill the display mode list structures.
    result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to fill the display mode list structures.");
        return false;
    }

    // Now go through all the display modes and find the one that matches the screen width and height.
    // When a match is found store the numerator and denominator of the refresh rate for that monitor.
    for(i=0; i<numModes; i++)
    {
            if(displayModeList[i].Width == (unsigned int)screenWidth)
            {
                    if(displayModeList[i].Height == (unsigned int)screenHeight)
                    {
                            numerator = displayModeList[i].RefreshRate.Numerator;
                            denominator = displayModeList[i].RefreshRate.Denominator;
                    }
            }
    }

    // Release the display mode list.
    delete [] displayModeList;
    displayModeList = 0;

    // Release the adapter output.
    adapterOutput->Release();
    adapterOutput = 0;

    // Release the factory.
    factory->Release();
    factory = 0;

    // Initialize the swap chain description.
    ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

    // Set to a single back buffer.
    swapChainDesc.BufferCount = 1;

    // Set the width and height of the back buffer.
    swapChainDesc.BufferDesc.Width = screenWidth;
    swapChainDesc.BufferDesc.Height = screenHeight;

    // Set regular 32-bit surface for the back buffer.
    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

    // Set the refresh rate of the back buffer.
    if(m_vsync_enabled)
    {
		swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;//numerator;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;//denominator;
    }
    else
    {
        swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
        swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
    }

    // Set the usage of the back buffer.
    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

    // Set the handle for the window to render to.
    swapChainDesc.OutputWindow = hwnd;

    // Turn multisampling off.
    swapChainDesc.SampleDesc.Count = 1;
    swapChainDesc.SampleDesc.Quality = 0;

    // Set to full screen or windowed mode.
    if(fullscreen)
    {
        swapChainDesc.Windowed = false;
    }
    else
    {
        swapChainDesc.Windowed = true;
    }

    // Set the scan line ordering and scaling to unspecified.
    swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
    swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

    // Discard the back buffer contents after presenting.
    swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	//swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_SEQUENTIAL;

    // Don't set the advanced flags.
    swapChainDesc.Flags = 0;

    // Grab the highest feature level
	result = D3D11CreateDevice(vAdapters.at(largestAdapter), D3D_DRIVER_TYPE_UNKNOWN, NULL, 0, NULL, 0,
                       D3D11_SDK_VERSION, NULL, &featureLevel, NULL );
	if(FAILED(result))
	{
		log_sxerror("D3DManager", "Failed to retrieve the featurelevel.");
		ErrorDescription(result);

		// Try to use the default adapter
		largestAdapter = 0;

		result = D3D11CreateDevice(vAdapters.at(largestAdapter), D3D_DRIVER_TYPE_UNKNOWN, NULL, 0, NULL, 0,
                       D3D11_SDK_VERSION, NULL, &featureLevel, NULL );
		if(FAILED(result))
		{
			log_sxerror("D3DManager", "Failed to retrieve the featurelevel the second time.");
			ErrorDescription(result);
			return false;
		}
	}

    
#ifdef _DEBUG
	// Create the swap chain, Direct3D device, and Direct3D device context.
	result = D3D11CreateDeviceAndSwapChain(vAdapters.at(largestAdapter), D3D_DRIVER_TYPE_UNKNOWN, NULL, D3D11_CREATE_DEVICE_DEBUG | D3D11_CREATE_DEVICE_BGRA_SUPPORT , &featureLevel, 1, 
                                            D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the Direct3D device, context, and swap chain.");
        return false;
    }

	result = m_device->QueryInterface((IID)IID_ID3D11Debug, (void**)&m_Debug);
	if(FAILED(result))
	{
		log_sxerror("D3DManager", "Failed to create a debugging interface for the device. Debugging may not work");
	} else {
		result = m_Debug->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
		if(FAILED(result)) {
			log_sxerror("D3DManager", "Failed to enable detailed object reporting.");
		}	
	}

#else
	// Create the swap chain, Direct3D device, and Direct3D device context.
	result = D3D11CreateDeviceAndSwapChain(vAdapters.at(largestAdapter), D3D_DRIVER_TYPE_UNKNOWN, NULL, D3D11_CREATE_DEVICE_BGRA_SUPPORT , &featureLevel, 1, 
                                            D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the Direct3D device, context, and swap chain.");
        return false;
    }

#endif

	// Release each adapter.
	for(auto it = vAdapters.begin(); it != vAdapters.end(); ++it)
	{
		(*it)->Release();
		(*it) = 0;
	}

    // Get the pointer to the back buffer.
    result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to get a pointer to the back buffer.");
        return false;
    }

    // Create the render target view with the back buffer pointer.
    result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the render target view.");
        return false;
    }

    // Release pointer to the back buffer as we no longer need it.
    backBufferPtr->Release();
    backBufferPtr = 0;

    // Initialize the description of the depth buffer.
    ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

    // Set up the description of the depth buffer.
    depthBufferDesc.Width = screenWidth;
    depthBufferDesc.Height = screenHeight;
    depthBufferDesc.MipLevels = 1;
    depthBufferDesc.ArraySize = 1;
    depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthBufferDesc.SampleDesc.Count = 1;
    depthBufferDesc.SampleDesc.Quality = 0;
    depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    depthBufferDesc.CPUAccessFlags = 0;
    depthBufferDesc.MiscFlags = 0;

    // Create the texture for the depth buffer using the filled out description.
    result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the depth buffer.");
        return false;
    }

    // Initialize the description of the stencil state.
    ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

    // Set up the description of the stencil state.
    depthStencilDesc.DepthEnable = true;
    depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

    depthStencilDesc.StencilEnable = true;
    depthStencilDesc.StencilReadMask = 0xFF;
    depthStencilDesc.StencilWriteMask = 0xFF;

    // Stencil operations if pixel is front-facing.
    depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
    depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

    // Stencil operations if pixel is back-facing.
    depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
    depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

    // Create the depth stencil state.
    result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the depth stencil state.");
        return false;
    }

    // Set the depth stencil state.
    m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);

    // Initailze the depth stencil view.
    ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

    // Set up the depth stencil view description.
    depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    depthStencilViewDesc.Texture2D.MipSlice = 0;

    // Create the depth stencil view.
    result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the depth stencil view.");
        return false;
    }

    // Bind the render target view and depth stencil buffer to the output render pipeline.
    m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);

    // Setup the raster description which will determine how and what polygons will be drawn.
    rasterDesc.AntialiasedLineEnable = false;
    rasterDesc.CullMode = D3D11_CULL_BACK;
    rasterDesc.DepthBias = 0;
    rasterDesc.DepthBiasClamp = 0.0f;
    rasterDesc.DepthClipEnable = true;
    rasterDesc.FillMode = D3D11_FILL_SOLID;
    rasterDesc.FrontCounterClockwise = false;
    rasterDesc.MultisampleEnable = false;
    rasterDesc.ScissorEnable = false;
    rasterDesc.SlopeScaledDepthBias = 0.0f;

    // Create the rasterizer state from the description we just filled out.
    result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the rasterizer state.");
        return false;
    }

    // Now set the rasterizer state.
    m_deviceContext->RSSetState(m_rasterState);

    // Setup the viewport for rendering.
    viewport.Width = (float)screenWidth;
    viewport.Height = (float)screenHeight;
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;
    viewport.TopLeftX = 0.0f;
    viewport.TopLeftY = 0.0f;

    // Create the viewport.
    m_deviceContext->RSSetViewports(1, &viewport);

    // Setup the projection matrix.
	fieldOfView = (float)XM_PI / 4.0f;
	assert(screenWidth != 0);
	assert(screenHeight != 0);
    screenAspect = (float)screenWidth / (float)screenHeight;

    // Create the projection matrix for 3D rendering.
	XMStoreFloat4x4(&m_projectionMatrix, XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth));

    // Initialize the world and view matrix to the identity matrix.
    XMStoreFloat4x4(&m_worldMatrix, XMMatrixIdentity());
	XMStoreFloat4x4(&m_viewMatrix, XMMatrixIdentity());

    // Create an orthographic projection matrix for 2D rendering.
    XMStoreFloat4x4(&m_orthoMatrix, XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth));

    // Clear the second depth stencil state before setting the parameters.
    ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));

    // Now create a second depth stencil state which turns off the Z buffer for 2D rendering.  The only difference is 
    // that DepthEnable is set to false, all other parameters are the same as the other depth stencil state.
    depthDisabledStencilDesc.DepthEnable = false;
    depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
    depthDisabledStencilDesc.StencilEnable = true;
    depthDisabledStencilDesc.StencilReadMask = 0xFF;
    depthDisabledStencilDesc.StencilWriteMask = 0xFF;
    depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
    depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
    depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
    depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

    // Create the state using the device.
    result = m_device->CreateDepthStencilState(&depthDisabledStencilDesc, &m_depthDisabledStencilState);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the depth disabled stencil state.");
        return false;
    }

    // Clear the blend state description.
    ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC));

    // Create an alpha enabled blend state description.

    blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
    blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
    blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
	blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
    blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO;
    blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
    blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
    blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f;

	//blendStateDescription.RenderTarget[0].BlendEnable            = true;
    //blendStateDescription.RenderTarget[0].SrcBlend               = D3D11_BLEND_SRC_COLOR; // This one f***s by adding white
    //blendStateDescription.RenderTarget[0].DestBlend              = D3D11_BLEND_DEST_COLOR; // This one produces fail whale, dusky background, lite trees
    //blendStateDescription.RenderTarget[0].BlendOp                = D3D11_BLEND_OP_ADD;
    //blendStateDescription.RenderTarget[0].SrcBlendAlpha          = D3D11_BLEND_SRC_ALPHA;
    //blendStateDescription.RenderTarget[0].DestBlendAlpha         = D3D11_BLEND_DEST_ALPHA;
    //blendStateDescription.RenderTarget[0].BlendOpAlpha           = D3D11_BLEND_OP_ADD;
    //blendStateDescription.RenderTarget[0].RenderTargetWriteMask  = 7;

    // Create the blend state using the description.
    result = m_device->CreateBlendState(&blendStateDescription, &m_alphaEnableBlendingState);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the alpha blending state.");
        return false;
    }

    // Modify the description to create an alpha disabled blend state description.
    blendStateDescription.RenderTarget[0].BlendEnable = FALSE;

    // Create the blend state using the description.
    result = m_device->CreateBlendState(&blendStateDescription, &m_alphaDisableBlendingState);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the alpha disabled blending state.");
        return false;
    }

    return true;
}
コード例 #9
0
ファイル: rendercore.cpp プロジェクト: bitkid83/TinyCap
bool RenderCore::Init(int screenWidth, int screenHeight, HWND hWnd)
{
	HRESULT hr;
		
	IDXGIAdapter1 *adapter;
	IDXGIOutput *adapterOutput;
	IDXGIOutput1 *adapterOutput1;

	DXGI_ADAPTER_DESC adapterDesc;	
	DXGI_MODE_DESC *displayModeList;
	DXGI_SWAP_CHAIN_DESC swapChainDesc;

	ID3D11Texture2D *pBackBuffer;

	D3D11_TEXTURE2D_DESC depthBufferDesc;
	D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
	D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
	D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
	D3D11_RASTERIZER_DESC rasterDesc;	

	uint32_t numModes, fpsNumerator, fpsDenominator;
	size_t stringLength;
	int error;
	float fov, aspect;
		
	if (!EnumerateDisplayAdapters(&g_DXGIAdapters)) {
		return false;
	}
	adapter = g_DXGIAdapters.at(0);

	hr = adapter->EnumOutputs(0, &adapterOutput);
	if (FAILED(hr)) {
		return false;
	}
	
	// desktop duplication stuff
	hr = adapterOutput->QueryInterface(&adapterOutput1);
	
	hr = adapterOutput1->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, nullptr);
	if (FAILED(hr)) {
		return false;
	}

	displayModeList = new DXGI_MODE_DESC[numModes];
	if (!displayModeList) {
		return false;
	}

	hr = adapterOutput1->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	if (FAILED(hr)) {
		return false;
	}
	
	for (UINT i = 0; i < numModes; i++) {
		if (displayModeList[i].Width == (unsigned int)screenWidth) {
			if (displayModeList[i].Height == (unsigned int)screenHeight) {
				fpsNumerator = displayModeList[i].RefreshRate.Numerator;
				fpsDenominator = displayModeList[i].RefreshRate.Denominator;
			}
		}
	}

	hr = adapter->GetDesc(&adapterDesc);
	if (FAILED(hr)) {
		return false;
	}
		
	// retrieve video adapter memory and name
	m_VideoMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);	
	
	error = wcstombs_s(&stringLength, m_VideoCardDesc, 128, adapterDesc.Description, 128);
	
	if (error != 0) {
		return false;
	}
	DebugOut("Found graphics adapter: %s (%dMB VRAM)\n", m_VideoCardDesc, m_VideoMemory);

	delete[] displayModeList;
	displayModeList = nullptr;

	adapterOutput->Release();
	adapter->Release();
	
	// set single back buffer
	ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
	swapChainDesc.BufferCount = 1;
	swapChainDesc.BufferDesc.Width = screenWidth;
	swapChainDesc.BufferDesc.Height = screenHeight;
	swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
	swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
	swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	swapChainDesc.OutputWindow = hWnd;
	swapChainDesc.SampleDesc.Count = 1;
	swapChainDesc.SampleDesc.Quality = 0;
	swapChainDesc.Windowed = true;
	//swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	//swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
	//swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	//swapChainDesc.Flags = 0;

	// create swap chain, direct3d device, and d3d context	
	uint32_t deviceFlags = 0;
#define D3D_DEVICE_DEBUG
#ifdef D3D_DEVICE_DEBUG
	deviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

	D3D_FEATURE_LEVEL featureLevels[] = {
		D3D_FEATURE_LEVEL_11_1,
		D3D_FEATURE_LEVEL_11_0,
		D3D_FEATURE_LEVEL_10_1,
		D3D_FEATURE_LEVEL_10_0,
	};
	uint32_t numFeatureLevels = ARRAYSIZE(featureLevels);

	hr = D3D11CreateDeviceAndSwapChain(		nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, deviceFlags, featureLevels, numFeatureLevels,
											D3D11_SDK_VERSION, &swapChainDesc, &m_SwapChain, &m_d3d11Device, nullptr, &m_d3d11DeviceContext);
	if (FAILED(hr)) { 
		DebugOut("D3D11CreateDeviceAndSwapChain failed!\n");
		return false;
	}

	// enable multithreaded device context protection
	ID3D10Multithread *contextMT = nullptr;
	m_d3d11DeviceContext->QueryInterface(&contextMT);

	if (contextMT) {
		contextMT->SetMultithreadProtected(true);
		contextMT->Release();
	}
	else {
		DebugOut("Fatal error! ID3D10Multithread::SetMultithreadProtected for D3D11 device context failed!\n");
		return false;
	}

	// get pointer to the back buffer
	hr = m_SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID *)&pBackBuffer);
	if (FAILED(hr)) {
		DebugOut("IDXGISwapChain::GetBuffer failed!\n");
		return false;
	}

	// create render target view from back buffer
	hr = m_d3d11Device->CreateRenderTargetView(pBackBuffer, nullptr, &m_d3d11RenderTargetView);
	if (FAILED(hr)) {
		DebugOut("ID3D11Device::CreateRenderTargetView failed!\n");
		return false;
	}
	pBackBuffer->Release();

	// set up depth buffer description
	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));		
	depthBufferDesc.Width = screenWidth;
	depthBufferDesc.Height = screenHeight;
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 1;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;

	// create texture for depth buffer
	hr = m_d3d11Device->CreateTexture2D(&depthBufferDesc, nullptr, &m_d3d11DepthStencilBuffer);
	if (FAILED(hr)) {
		DebugOut("ID3D11Device::CreateTexture2D failed! Could not create texture for depth buffer.\n");
		return false;
	}

	// set up description of stencil state
	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));	
	depthStencilDesc.DepthEnable = true; // z-buffer enabled
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0xFF;

	// Stencil operations if pixel is front-facing.
	depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Stencil operations if pixel is back-facing.
	depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// create depth stencil state
	hr = m_d3d11Device->CreateDepthStencilState(&depthStencilDesc, &m_d3d11DepthStencilState);
	if (FAILED(hr)) {
		DebugOut("ID3D11Device::CreateDepthStencilState failed!\n");
		return false;
	}

	// Now create a second depth stencil state which turns off the Z buffer for 2D rendering.  The only difference is 
	// that DepthEnable is set to false, all other parameters are the same as the other depth stencil state.
	depthDisabledStencilDesc.DepthEnable = false;
	depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
	depthDisabledStencilDesc.StencilEnable = true;
	depthDisabledStencilDesc.StencilReadMask = 0xFF;
	depthDisabledStencilDesc.StencilWriteMask = 0xFF;
	depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
	depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Create the state using the device.
	hr = m_d3d11Device->CreateDepthStencilState(&depthDisabledStencilDesc, &m_d3d11DepthStencilDisabledState);
	if (FAILED(hr))
	{
		return false;
	}

	// disable the Z-Buffer
	ZBufferState(0);

	// set up depth stencil view description
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));	
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	// create depth stencil view
	hr = m_d3d11Device->CreateDepthStencilView(m_d3d11DepthStencilBuffer, &depthStencilViewDesc, &m_d3d11DepthStencilView);
	if (FAILED(hr)) {
		DebugOut("ID3D11Device::CreateDepthStencilView failed!\n");
		return false;
	}

	// bind render target view and depth stencil buffer to the output render pipeline
	m_d3d11DeviceContext->OMSetRenderTargets(1, &m_d3d11RenderTargetView, m_d3d11DepthStencilView);

	// set up rasterizer description	
	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_NONE;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = false;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	// create the rasterizer
	hr = m_d3d11Device->CreateRasterizerState(&rasterDesc, &m_d3d11RasterState);
	if (FAILED(hr)) {
		DebugOut("ID3D11Device::CreateRasterizerState failed!");
		return false;
	}
	
	m_d3d11DeviceContext->RSSetState(m_d3d11RasterState);

	// set up viewport for rendering
	D3D11_VIEWPORT viewport;
	viewport.Width = (float)screenWidth;
	viewport.Height = (float)screenHeight;
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.TopLeftX = 0.0f;
	viewport.TopLeftY = 0.0f;

	// create the viewport
	m_d3d11DeviceContext->RSSetViewports(1, &viewport);
		
	fov = (float)PI / 4.0f;
	aspect = (float)screenWidth / (float)screenHeight;
		
	m_ProjectionMatrix = DirectX::XMMatrixPerspectiveFovLH(fov, aspect, SCREEN_NEAR, SCREEN_DEPTH);
	m_WorldMatrix = DirectX::XMMatrixIdentity();
	m_OrthoMatrix = DirectX::XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, SCREEN_NEAR, SCREEN_DEPTH);

	// Scene is a textured quad to draw on
	g_Scene = new Scene(GetDevice(), GetDeviceContext(), screenWidth, screenHeight);
	//g_Scene2 = new Scene(GetDevice(), GetDeviceContext(), screenWidth, screenHeight);	

	// new DXGI Desktop Duplication object
	g_DesktopDuplication = new DXGIDuplication();
	if (!g_DesktopDuplication->Init(0, 0, &g_DXGIAdapters, GetDevice())) { DebugOut("Failed to init DXGI Desktop Duplication API!\n"); return false; }
	
	//g_DesktopDuplication2 = new DXGIDuplication();
	//if (!g_DesktopDuplication2->Init(0, 1, &g_DXGIAdapters, GetDevice())) { DebugOut("Failed to init DXGI Desktop Duplication API for Adapter 1/Output 2!\n"); return false; }

	// initialize Media Foundation
	g_MFEncoder = new MF_H264_Encoder(m_d3d11Device, m_d3d11DeviceContext);
	if (!g_MFEncoder->Init()) { DebugOut("Failed to init Media Foundation H.264 Encoder!\n"); return false; }

	return true;
};
コード例 #10
0
bool DXManager::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen)
{
	HRESULT result;
	IDXGIFactory* factory;
	IDXGIAdapter* adapter;
	IDXGIOutput* adapterOutput;
	unsigned int numModes, numerator = 0, denominator = 0, stringLength;
	DXGI_MODE_DESC* displayModeList;
	DXGI_ADAPTER_DESC adapterDesc;
	int error;
	ID3D11Texture2D* backBufferPtr;

	//store vsync setting
	m_vsync_enabled = vsync;

	//Create a DirectX graphic interface factory
	result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
	if(FAILED(result))
	{
		return false;
	}

	//Use the factory to create an adapter for the primary graphics interface
	result = factory->EnumAdapters(0, &adapter);
	if(FAILED(result))
	{
		return false;
	}

	//Enumerate the primary adapter output
	result = adapter->EnumOutputs(0, &adapterOutput);
	if(FAILED(result))
	{
		return false;
	}

	//Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	if(FAILED(result))
	{
		return false;
	}

	//Create a list to hold all the possible modes for this monitor/video card combination
	displayModeList = new DXGI_MODE_DESC[numModes];

	//Fill the display mode list
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	if(FAILED(result))
	{
		return false;
	}

	for(int i = 0; i < (int)numModes; ++i)
	{
		if(displayModeList[i].Width == (unsigned int)screenWidth)
		{
			if(displayModeList[i].Height == (unsigned int)screenHeight)
			{
				numerator = displayModeList[i].RefreshRate.Numerator;
				denominator = displayModeList[i].RefreshRate.Denominator;
			}
		}
	}

	if(numerator == 0 && denominator == 0)
	{
		return false;
	}

	//Get the adapter description
	result = adapter->GetDesc(&adapterDesc);
	if(FAILED(result))
	{
		return false;
	}

	//Store the video card memory in megabytes
	m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

	//Convert the name of the video card to a character array
	error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128);
	if(error != 0)
	{
		return false;
	}

	//release memory
	delete [] displayModeList;
	displayModeList = 0;

	adapterOutput->Release();
	adapterOutput = 0;

	adapter->Release();
	adapter = 0;

	factory->Release();
	factory = 0;

	if(!InitializeSwapChain(hwnd, fullscreen, screenWidth, screenHeight, numerator, denominator))
	{
		return false;
	}

	//Get the pointer to the back buffer
	result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
	if(FAILED(result))
	{
		return false;
	}

	//create the render target view
	result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView);
	if(FAILED(result))
	{
		return false;
	}

	//release back buffer
	backBufferPtr->Release();
	backBufferPtr = 0;

	if(!InitializeDepthBuffer(screenWidth, screenHeight))
	{
		return false;
	}

	if(!InitializeDepthStencilBuffer())
	{
		return false;
	}

	if(!InitializeStencilView())
	{
		return false;
	}

	//bind the render target view and depth stencil buffer to the output render pipeline
	m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);

	if(!InitializeRasterizerState())
	{
		return false;
	}

	InitializeViewport(screenWidth, screenHeight);

	if(!InitializeAlphaBlending())
	{
		return false;
	}

	if(!InitializeZBuffer())
	{
		return false;
	}

	return true;
}
コード例 #11
0
bool D3DClass::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, 
			  float screenDepth, float screenNear)
{
	HRESULT result;
	IDXGIFactory* factory;
	IDXGIAdapter* adapter;
	IDXGIOutput* adapterOutput;
	unsigned int numModes, i, numerator, denominator, stringLength;
	DXGI_MODE_DESC* displayModeList;
	DXGI_ADAPTER_DESC adapterDesc;
	int error;
	DXGI_SWAP_CHAIN_DESC swapChainDesc;
	D3D_FEATURE_LEVEL featureLevel;
	ID3D11Texture2D* backBufferPtr;
	D3D11_TEXTURE2D_DESC depthBufferDesc;
	D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
	D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
	D3D11_RASTERIZER_DESC rasterDesc;
	D3D11_VIEWPORT viewport;
	float fieldOfView, screenAspect;


	// Store the vsync setting.
	m_vsync_enabled = vsync;

	// Create a DX graphics interface factory
	result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
	if (FAILED(result))
	{
		return false;
	}

	// Adapter for the primary graphics interface (video card)
	result = factory->EnumAdapters(0, &adapter);
	if (FAILED(result))
	{
		return false;
	}

	// primary adapter output = monitor
	result = adapter->EnumOutputs(0, &adapterOutput);
	if (FAILED(result))
	{
		return false;
	}

	// Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	if (FAILED(result))
	{
		return false;
	}

	// Create a list to hold all the possible display modes for this monitor/video card combination.
	displayModeList = new DXGI_MODE_DESC[numModes];
	if(!displayModeList)
	{
		return false;
	}

	// Now fill the display mode list structures.
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	if(FAILED(result))
	{
		return false;
	}

	// Now go through all the display modes and find the one that matches the screen width and height.
	// When a match is found store the numerator and denominator of the refresh rate for that monitor.
	for(i=0; i<numModes; i++)
	{
		if(displayModeList[i].Width == (unsigned int)screenWidth)
		{
			if(displayModeList[i].Height == (unsigned int)screenHeight)
			{
				numerator = displayModeList[i].RefreshRate.Numerator;
				denominator = displayModeList[i].RefreshRate.Denominator;
			}
		}
	}

	// Get the adapter (video card) description.
	result = adapter->GetDesc(&adapterDesc);
	if(FAILED(result))
	{
		return false;
	}

	m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

	error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128);
	if (error != 0)
	{
		return false;
	}

	// Release the display mode list.
	delete[] displayModeList;
	displayModeList = 0;

	adapterOutput->Release();
	adapterOutput = 0;

	adapter->Release();
	adapter = 0;

	factory->Release();
	factory = 0;

	ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

	swapChainDesc.BufferCount = 1;

	swapChainDesc.BufferDesc.Width = screenWidth;
	swapChainDesc.BufferDesc.Height = screenHeight;

	swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

	if (m_vsync_enabled)
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
	}
	else
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
	}

	swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	swapChainDesc.OutputWindow = hwnd;
	//multisampling off
	swapChainDesc.SampleDesc.Count = 1;
	swapChainDesc.SampleDesc.Quality = 0;

	if (fullscreen)
	{
		swapChainDesc.Windowed = false;
	}
	else
	{
		swapChainDesc.Windowed = true;
	}

	//set scan line ordering and scaling to unspecified
	swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	// discard back buffer contents after presenting
	swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

	swapChainDesc.Flags = 0;

	featureLevel = D3D_FEATURE_LEVEL_11_0;

	result = D3D11CreateDeviceAndSwapChain(
		NULL, 
		D3D_DRIVER_TYPE_REFERENCE, 
		NULL, 
		0, 
		&featureLevel,
		1,
		D3D11_SDK_VERSION,
		&swapChainDesc,
		&m_swapChain,
		&m_device,
		NULL,
		&m_deviceContext);
	if (FAILED(result))
	{
		return false;
	}

	// Get the pointer to the back buffer
	result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
	if (FAILED(result))
	{
		return false;
	}

	result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView);
	if (FAILED(result))
	{
		return false;
	}

	//Release pointer to the back buffer as we no longer need it
	backBufferPtr->Release();
	backBufferPtr = 0;

	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
	depthBufferDesc.Width = screenWidth;
	depthBufferDesc.Height = screenHeight;
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 1;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;

	result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer);
	if (FAILED(result))
	{
		return false;
	}

	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
	depthStencilDesc.DepthEnable = true;
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0xFF;

	// Stencil operations if pixel is front-facing.
	depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Stencil operations if pixel is back-facing.
	depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Create the depth stencil state.
	result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState);
	if(FAILED(result))
	{
		return false;
	}

	// Set the depth stencil state.
	m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);

	// Initailze the depth stencil view.
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

	// Set up the depth stencil view description.
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	// Create the depth stencil view.
	result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView);
	if(FAILED(result))
	{
		return false;
	}

	// Bind the render target view and depth stencil buffer to the output render pipeline.
	m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);

	// Setup the raster description which will determine how and what polygons will be drawn.
	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_BACK;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = true;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	// Create the rasterizer state from the description we just filled out.
	result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState);
	if(FAILED(result))
	{
		return false;
	}

	// Now set the rasterizer state.
	m_deviceContext->RSSetState(m_rasterState);

	viewport.Width = (float)screenWidth;
	viewport.Height = (float)screenHeight;
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.TopLeftX = 0.0f;
	viewport.TopLeftY = 0.0f;

	m_deviceContext->RSSetViewports(1, &viewport);

	fieldOfView = (float)D3DX_PI / 4.0f;
	screenAspect = (float)screenWidth / (float)screenHeight;

	D3DXMatrixPerspectiveFovLH(&m_projectionMatrix, fieldOfView, screenAspect, screenNear, screenDepth);

	// Initialize the world matrix to the identity matrix.
	D3DXMatrixIdentity(&m_worldMatrix);

	// Create an orthographic projection matrix for 2D rendering.
	D3DXMatrixOrthoLH(&m_orthoMatrix, (float)screenWidth, (float)screenHeight, screenNear, screenDepth);

	return true;
}
コード例 #12
0
ファイル: D3DClass.cpp プロジェクト: jel-massih/TerrainEngine
bool D3DClass::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenDepth, float screenNear)
{
	HRESULT result;
	IDXGIFactory* factory;
	IDXGIAdapter* adapter;
	IDXGIOutput* adapterOutput;
	unsigned int numModes, i, numerator, denominator, stringLength;
	DXGI_MODE_DESC* displayModeList;
	DXGI_ADAPTER_DESC adapterDesc;
	int error;
	DXGI_SWAP_CHAIN_DESC swapChainDesc;
	D3D_FEATURE_LEVEL featureLevel;
	ID3D11Texture2D* backBufferPtr;
	D3D11_TEXTURE2D_DESC depthBufferDesc;
	D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
	D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
	D3D11_RASTERIZER_DESC rasterDesc;
	D3D11_VIEWPORT viewport;
	float fieldOfView, screenAspect;
	D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
	D3D11_BLEND_DESC blendStateDesc;

	m_vsync_enabled = vsync;

	result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
	if(FAILED(result))
	{
		return false;
	}

	result = factory->EnumAdapters(0, &adapter);
	if(FAILED(result))
	{
		return false;
	}

	result = adapter->EnumOutputs(0, &adapterOutput);
	if(FAILED(result))
	{
		return false;
	}

	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	if(FAILED(result))
	{
		return false;
	}

	displayModeList = new DXGI_MODE_DESC[numModes];
	if(!displayModeList)
	{
		return false;
	}

	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	if(FAILED(result))
	{
		return false;
	}

	for(i=0; i<numModes; i++)
	{
		if(displayModeList[i].Width == (unsigned int) screenWidth)
		{
			if(displayModeList[i].Height == (unsigned int) screenHeight)
			{
				numerator = displayModeList[i].RefreshRate.Numerator;
				denominator = displayModeList[i].RefreshRate.Denominator;
			}
		}
	}

	result = adapter->GetDesc(&adapterDesc);
	if(FAILED(result))
	{
		return false;
	}

	m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

	error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128);
	if(error != 0)
	{
		return false;
	}

	delete [] displayModeList;
	displayModeList = 0;

	adapterOutput->Release();
	adapterOutput = 0;

	adapter->Release();
	adapter = 0;

	factory->Release();
	factory = 0;

	ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

	swapChainDesc.BufferCount = 1;

	swapChainDesc.BufferDesc.Width = screenWidth;
	swapChainDesc.BufferDesc.Height = screenHeight;

	swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

	if(m_vsync_enabled)
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
	}
	else
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
	}

	swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

	swapChainDesc.OutputWindow = hwnd;

	swapChainDesc.SampleDesc.Count = 1;
	swapChainDesc.SampleDesc.Quality = 0;

	if(fullscreen)
	{
		swapChainDesc.Windowed = false;
	}
	else
	{
		swapChainDesc.Windowed = true;
	}

	swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

	swapChainDesc.Flags = 0;

	featureLevel = D3D_FEATURE_LEVEL_11_0;

	result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1,
				D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext); 
	if(FAILED(result))
	{
		return false;
	}

	result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
	if(FAILED(result))
	{
		return false;
	}

	result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView);
	if(FAILED(result))
	{
		return false;
	}

	backBufferPtr->Release();
	backBufferPtr = 0;

	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

	depthBufferDesc.Width = screenWidth;
	depthBufferDesc.Height = screenHeight;
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 1;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;

	result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer);
	if(FAILED(result))
	{
		return false;
	}

	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

	depthStencilDesc.DepthEnable = true;
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0XFF;

	depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState);
	if(FAILED(result))
	{
		return false;
	}

	m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);

	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView);
	if(FAILED(result))
	{
		return false;
	}

	m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);

	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_BACK;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = false;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState);
	if(FAILED(result))
	{
		return false;
	}

	m_deviceContext->RSSetState(m_rasterState);

	viewport.Width = (float)screenWidth;
	viewport.Height = (float)screenHeight;
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.TopLeftX = 0.0f;
	viewport.TopLeftY = 0.0f;

	m_deviceContext->RSSetViewports(1, &viewport);

	fieldOfView = (float)DirectX::XM_PI / 4.0f;
	screenAspect = (float)screenWidth / (float)screenHeight;

	m_projectionMatrix = DirectX::XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth);

	m_worldMatrix = DirectX::XMMatrixIdentity();

	m_orthoMatrix = DirectX::XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth);

	ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));

	depthDisabledStencilDesc.DepthEnable = false;
	depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

	depthDisabledStencilDesc.StencilEnable = true;
	depthDisabledStencilDesc.StencilReadMask = 0xFF;
	depthDisabledStencilDesc.StencilWriteMask = 0XFF;

	depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	result = m_device->CreateDepthStencilState(&depthDisabledStencilDesc, &m_depthDisabledStencilState);
	if(FAILED(result))
	{
		return false;
	}

	ZeroMemory(&blendStateDesc, sizeof(D3D11_BLEND_DESC));

	blendStateDesc.RenderTarget[0].BlendEnable = TRUE;
	blendStateDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
	blendStateDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
	blendStateDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
	blendStateDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
	blendStateDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
	blendStateDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
	blendStateDesc.RenderTarget[0].RenderTargetWriteMask = 0x0f;

	result = m_device->CreateBlendState(&blendStateDesc, &m_alphaEnableBlendingState);
	if(FAILED(result))
	{
		return false;
	}

	blendStateDesc.RenderTarget[0].BlendEnable = FALSE;

	result = m_device->CreateBlendState(&blendStateDesc, &m_alphaDisableBlendingState);
	if(FAILED(result))
	{
		return false;
	}

	return true;
}
コード例 #13
0
ファイル: CD3D11Driver.cpp プロジェクト: Wu1994/GameFinal
	bool CD3D11Driver::init(SCreationParameters& createParam)
	{
		HRESULT result;
		IDXGIFactory* factory;
		IDXGIAdapter* adapter;
		IDXGIOutput* adapterOutput;
		unsigned int numModes, i, numerator = 0, denominator = 1, stringLength;
		DXGI_MODE_DESC* displayModeList;
		DXGI_ADAPTER_DESC adapterDesc;
		int error;
		D3D11_TEXTURE2D_DESC depthBufferDesc;
		//D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
		//D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
		//D3D11_RASTERIZER_DESC rasterDesc;
		//D3D11_VIEWPORT viewport;

		//const SCreationParameters& params = mDevice->getCreationParameters();

		// Create a DirectX graphics interface factory.

		mBackBufferWidth = createParam.BackBufferWidth;
		mBackBufferHeight = createParam.BackBufferHeight;

		result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
		if (FAILED(result))
		{
			return false;
		}

		// Use the factory to create an adapter for the primary graphics interface (video card).
		result = factory->EnumAdapters(0, &adapter);
		if (FAILED(result))
		{
			return false;
		}

		// Enumerate the primary adapter output (monitor).
		result = adapter->EnumOutputs(0, &adapterOutput);
		if (FAILED(result))
		{
			return false;
		}

		// Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
		result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
		if (FAILED(result))
		{
			return false;
		}

		// Create a list to hold all the possible display modes for this monitor/video card combination.
		displayModeList = new DXGI_MODE_DESC[numModes];
		if (!displayModeList)
		{
			return false;
		}

		// Now fill the display mode list structures.
		result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
		if (FAILED(result))
		{
			return false;
		}

		// Now go through all the display modes and find the one that matches the screen width and height.
		// When a match is found store the numerator and denominator of the refresh rate for that monitor.
		for (i = 0; i < numModes; i++)
		{
			if (displayModeList[i].Width == (unsigned int)createParam.BackBufferWidth)
			{
				if (displayModeList[i].Height == (unsigned int)createParam.BackBufferHeight)
				{
					numerator = displayModeList[i].RefreshRate.Numerator;
					denominator = displayModeList[i].RefreshRate.Denominator;
				}
			}
		}

		// Get the adapter (video card) description.
		result = adapter->GetDesc(&adapterDesc);
		if (FAILED(result))
		{
			return false;
		}

		// Store the dedicated video card memory in megabytes.
		mVideoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

		// Convert the name of the video card to a character array and store it.
		error = wcstombs_s(&stringLength, mVideoCardDescription, 128, adapterDesc.Description, 128);
		if (error != 0)
		{
			return false;
		}

		// Release the display mode list.
		delete[] displayModeList;
		displayModeList = 0;

		// Release the adapter output.
		adapterOutput->Release();
		adapterOutput = 0;

		// Release the adapter.
		adapter->Release();
		adapter = 0;

		// Release the factory.
		factory->Release();
		factory = 0;

		UINT createDeviceFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)
		createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

		D3D_FEATURE_LEVEL featureLevel;

		/* 如果将这个标志设为DEBUG,则绘制效率大大降低,且帧频极不稳定 */
		//createDeviceFlags = 0;

		HRESULT hr;
		hr = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE,
			NULL, createDeviceFlags, 0, 0, D3D11_SDK_VERSION, &md3dDevice, &featureLevel, &md3dDeviceContext);

		if (FAILED(hr))
			return false;

#if defined(DEBUG) || defined(_DEBUG)
		md3dDevice->QueryInterface(__uuidof(ID3D11Debug), reinterpret_cast<void**>(&md3dDebug));
#endif

		if (featureLevel != D3D_FEATURE_LEVEL_11_0)
		{
			throw std::runtime_error("DirectX11 is not supported!");
			return false;
		}

		UINT numQualityLevels;
		md3dDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &numQualityLevels);

		IDXGIDevice* dxgiDevice = 0;
		md3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice);
		IDXGIAdapter* dxgiAdapter = 0;
		dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter);
		IDXGIFactory* dxgiFactory = 0;
		dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory);

		DXGI_SWAP_CHAIN_DESC swapChainDesc;

		// Initialize the swap chain description.
		ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

		// Set the width and height of the back buffer.
		swapChainDesc.BufferDesc.Width = createParam.BackBufferWidth;
		swapChainDesc.BufferDesc.Height = createParam.BackBufferHeight;

		// Set regular 32-bit surface for the back buffer.
		swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

		// Set the refresh rate of the back buffer.
		if (createParam.VsyncEnabled)
		{
			swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
			swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
		}
		else
		{
			swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
			swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
		}

		// Set multisampling.
		if (createParam.MultiSamplingQuality == 0)
		{
			swapChainDesc.SampleDesc.Count = 1;
			swapChainDesc.SampleDesc.Quality = 0;

			createParam.MultiSamplingCount = 1;
		}
		else
		{
			swapChainDesc.SampleDesc.Count = createParam.MultiSamplingCount;
			UINT numQualityLevels;
			md3dDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &numQualityLevels);

			swapChainDesc.SampleDesc.Quality = min(numQualityLevels - 1, createParam.MultiSamplingQuality);

			createParam.MultiSamplingQuality = swapChainDesc.SampleDesc.Quality;
		}
		
		// set member attributes of class


		// Set to a single back buffer.
		swapChainDesc.BufferCount = 1;

		// Set the usage of the back buffer.
		swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

		// Set the handle for the window to render to.
		swapChainDesc.OutputWindow = (HWND)createParam.BackBufferWindowHandle;

		// Set to full screen or windowed mode.
		if (createParam.WindowStyle & EWS_FULLSCREEN)
		{
			swapChainDesc.Windowed = false;
		}
		else
		{
			swapChainDesc.Windowed = true;
		}

		// Set the scan line ordering and scaling to unspecified.
		swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
		swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

		// Discard the back buffer contents after presenting.
		swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

		// Don't set the advanced flags.
		swapChainDesc.Flags = 0;

		hr = dxgiFactory->CreateSwapChain(md3dDevice, &swapChainDesc, &md3dSwapChain);
		if (FAILED(hr))
			return false;
		ReleaseCOM(dxgiDevice);
		ReleaseCOM(dxgiAdapter);
		ReleaseCOM(dxgiFactory);
		// Get the pointer to the back buffer.

		ID3D11Texture2D* backBuffer;
		result = md3dSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBuffer);
		if (FAILED(result))
		{
			return false;
		}
		md3dDevice->CreateRenderTargetView(backBuffer, 0, &mDefaultRenderTargetView);
		ReleaseCOM(backBuffer);

		mDefaultRenderTarget = new CD3D11RenderTarget(md3dDevice, md3dDeviceContext, mDefaultRenderTargetView,
			createParam.BackBufferWidth, createParam.BackBufferHeight);

		// Initialize the description of the depth buffer.
		ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

		// Setup the viewport for rendering.
		setViewport(0, 0, static_cast<f32>(mBackBufferWidth), static_cast<f32>(mBackBufferHeight));

		//create resource factory
		mResourceFactory = new CD3D11ResourceFactory(
			md3dDevice, md3dDeviceContext, this);
		IResourceFactory::_setInstance(mResourceFactory);

		//create geometry creator
		mGeometryCreator = new CGeometryCreator;
		IGeometryCreator::_setInstance(mGeometryCreator);

		//create material manager
		mMaterialManager = new CMaterialManager;
		IMaterialManager::_setInstance(mMaterialManager);

		//create sampler manager
		mSamplerManager = new CSamplerManager(mResourceFactory);
		ISamplerManager::_setInstance(mSamplerManager);


		// create shadermanager
		mShaderManager = new CShaderManager(mResourceFactory);
		IShaderManager::_setInstance(mShaderManager);

		// create inputlayout manager
		mInputLayoutManager = new CInputLayoutManager(mResourceFactory);
		IInputLayoutManager::_setInstance(mInputLayoutManager);

		//create texture manager
		mTextureManager = new CTextureManager(mDevice, mResourceFactory);
		ITextureManager::_setInstance(mTextureManager);

		//create render state manager
		mRenderStateManager = new CRenderStateManager(mResourceFactory);
		IRenderStateManager::_setInstance(mRenderStateManager);

		//create mesh manager
		mMeshManager = new CMeshManager(mResourceFactory, mGeometryCreator, mTextureManager);
		IMeshManager::_setInstance(mMeshManager);

		
		//create pipeline manager
		mPipeManager = new CPipelineManager(mResourceFactory);
		IPipelineManager::_setInstance(mPipeManager);

		//create resource group manager
		mResourceGroupManager = new CResourceGroupManager(mTextureManager, mShaderManager,
			mInputLayoutManager, mRenderStateManager, mPipeManager, mMaterialManager, mMeshManager, mSamplerManager);
		IResourceGroupManager::_setInstance(mResourceGroupManager);

		//mResourceFactory->setResourceGroupManager(mResourceGroupManager);

		// create default depth-stencil-buffer
		bool multiSampling = (createParam.MultiSamplingCount > 1);


		mDepthStencilSurface = mTextureManager->createDepthStencilSurface("_default_depth_stencil_surface",
			0, 0, createParam.DepthBits, createParam.StencilBits,
			multiSampling, createParam.MultiSamplingCount, createParam.MultiSamplingQuality, true);

		if (!mDepthStencilSurface)
		{
			GF_PRINT_CONSOLE_INFO("Depth Stencil Surface has failed to be created.\n");
			return false;
		}

		D3D11DriverState.DepthStencilSurface = mDepthStencilSurface;
		CD3D11DepthStencilSurface* d3dDepthStencilSurface = dynamic_cast<CD3D11DepthStencilSurface*>(mDepthStencilSurface);
		mDefaultDepthStencilView = d3dDepthStencilSurface->getDepthStencilView();
		D3D11DriverState.DepthStencilView = mDefaultDepthStencilView;


		// create mShadowMapRasterizeState. This state is only for rendering shadow maps.
		D3D11_RASTERIZER_DESC shadowRasterizeState;
		shadowRasterizeState.FillMode = D3D11_FILL_SOLID;
		shadowRasterizeState.CullMode = D3D11_CULL_BACK; // RENDER BACK FACE
		shadowRasterizeState.FrontCounterClockwise = TRUE; 
		shadowRasterizeState.DepthBiasClamp = 0.0f;
		//shadowRasterizeState.DepthBias = 100000;
		//shadowRasterizeState.SlopeScaledDepthBias = 1.0f;
		shadowRasterizeState.DepthBias = 0;
		shadowRasterizeState.SlopeScaledDepthBias = 0;
		shadowRasterizeState.DepthClipEnable = TRUE;
		shadowRasterizeState.ScissorEnable = FALSE;
		shadowRasterizeState.MultisampleEnable = FALSE;
		shadowRasterizeState.AntialiasedLineEnable = FALSE;

		hr = md3dDevice->CreateRasterizerState(&shadowRasterizeState, &mShadowMapRasterizeState);
		if (FAILED(hr))
			return false;

		D3D11DriverState.ShadowMapRasterizerState = mShadowMapRasterizeState;

		return true;
	}
コード例 #14
0
ファイル: processtool.cpp プロジェクト: louk78/GetSystemInfo
BOOL CProcessTool::GetProcessExtendInfo(PSYSTEM_PROCESS_INFORMATION pSPI,PPROCESS_EXTEND_INFO pExtendInfo)
{
	HANDLE hProcess;
	TCHAR szBuf[2048] ={0};

	memset(pExtendInfo,0,sizeof(PPROCESS_EXTEND_INFO));

	hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,pSPI->UniqueProcessId);
	if(hProcess==NULL)return FALSE;

	//Get Exe Path,Description,Company Name
	if(GetModuleFileNameEx(hProcess,NULL,szBuf,MAX_PATH)!=0)
	{
		pExtendInfo->strExeFilePath = szBuf;
		GetFileDescription(szBuf,pExtendInfo->strDescription,
			pExtendInfo->strCompanyName);
	}

	//Get Virtual Memory Size
	PROCESS_MEMORY_COUNTERS pmc;
	if(GetProcessMemoryInfo(hProcess,&pmc,sizeof(PROCESS_MEMORY_COUNTERS)))
	{
		pExtendInfo->dwVirtualMemorySize = pmc.PagefileUsage;
	}


	//Get Parent Process File Path
	HANDLE hParent =NULL;
	hParent = OpenProcess(PROCESS_VM_READ|PROCESS_QUERY_INFORMATION,
		FALSE,pSPI->InheritedFromUniqueProcessId);
	if(hParent!=NULL)
	{
		memset(szBuf,0,sizeof(szBuf));
		if(GetModuleFileNameEx(hParent,NULL,szBuf,MAX_PATH)!=0)
		{
			pExtendInfo->strParentFilePath = szBuf;
		}
	}

	//Get Username
	if(WinStationGetProcessSid&&CachedGetUserFromSid)
	{
		wchar_t wcsUserName[100]={0};
		char mbsUserName[100]={0};
		size_t NumOfCharConverted;

		DWORD dwSize = sizeof(szBuf)/sizeof(TCHAR);
		FILETIME ftStartTime;
		CopyMemory(&ftStartTime,&pSPI->CreateTime,sizeof(FILETIME));
		if(WinStationGetProcessSid(NULL,pSPI->UniqueProcessId,ftStartTime,
			(LPBYTE)szBuf,&dwSize))
		{
			CachedGetUserFromSid(szBuf,wcsUserName,&dwSize);
#ifdef _UNICODE
			pExtendInfo->strUserName = wcsUserName;
#else
			wcstombs_s(&NumOfCharConverted,mbsUserName,wcsUserName,
				sizeof(mbsUserName));
			pExtendInfo->strUserName = mbsUserName;
#endif
		}

	}
	//Get Start time
	{
		SYSTEMTIME st;
		ZeroMemory(&st,sizeof(SYSTEMTIME));
		FileTimeToSystemTime((FILETIME *)&pSPI->CreateTime,&st);
		CTime Time(st);

		Time +=CTimeSpan(0,8,0,0);
		pExtendInfo->strStartTime = Time.Format(TEXT("%Y-%m-%d %H:%M:%S"));
	}
	


	return TRUE;
}
コード例 #15
0
ColladaTexture::ColladaTexture(FCDImage * _image)
{
	image = _image;
//
//	// Create an image container in DevIL.
//	ILuint imageId;
//
//	ilGenImages(1, &imageId);
//	ilBindImage(imageId);

	// do it square
	// reduce it if it is necessaryt
	// test this
	//GL_MAX_TEXTURE_SIZE.

	// initializate some variables
	hasOpacity = false;

	wchar_t orig[512];
	const size_t newsize = 256;
	char nstring[newsize];
#ifdef _WIN32
	// convert fstring to char*, amazing code based on http://msdn2.microsoft.com/en-us/library/ms235631(vs.80).aspx
	size_t convertedChars = 0;
	
	swprintf(orig, 512,L"%S", image->GetFilename().c_str() );
	size_t origsize = wcslen(orig) + 1;
	for(int i = 0; i < (int)origsize; ++i)
	{
		if(orig[i] == '\\')
		{
			orig[i] = '/';
		}
	}
	
	//wcstombs_s(&convertedChars, nstring, origsize, orig+2/*remove C:*/, _TRUNCATE);
	wcstombs_s(&convertedChars, nstring, origsize, orig, _TRUNCATE);
#else
	swprintf(orig, 512,L"%s", image->GetFilename().c_str() );
	const wchar_t * origTmp = &orig[0];
	wcsnrtombs( nstring, &origTmp, 512, 256, NULL);
#endif
	texturePathName =  nstring;
    
    TextureDescriptorUtils::CreateDescriptorIfNeed(String(texturePathName));
    
 	/*try 
	{
        std::vector<Magick::Image> layers;
		Magick::readImages(&layers, fileName);
		
		if (layers.size() != 1)
		{
			Logger::Error("Number of layers is wrong: %s", fileName.c_str());
		}
        
        Magick::Image & magickImage = layers[0];
        Magick::Geometry geo = magickImage.size();
        //magickImage.magick("RGBA");
		magickImage.modifyImage();
        
        bool opacityFound = false;
        if (magickImage.type() == Magick::TrueColorMatteType)
        {  
//        magickImage.type(Magick::TrueColorMatteType);
            Magick::PixelPacket *pixelCache = magickImage.getPixels(0, 0, geo.width(), geo.height());

            
            int32 height = geo.height();
            int32 width = geo.width();
            
            int32 size = sizeof(pixelCache[0].opacity);
            int32 opaqueValue = 255;
            if (size == 2)opaqueValue = 65535;
            
            for (int32 y = 0; y < height; ++y)
            {
                for (int32 x = 0; x < width; ++x)
                {
                    
                    if (pixelCache[y * width + x].opacity != opaqueValue)
                    {
                        opacityFound = true;
                        break;
                    }
                }
                if (opacityFound)break;
            }
        }
        Logger::FrameworkDebug("Image opened: %s - %d x %d - opacity: %s", fileName.c_str(), geo.width(), geo.height(), (opacityFound) ? ("yes"):("no"));
		
	}
	catch( Magick::Exception &error_ )
    {
        Logger::Error("Caught exception: %s file: %s", error_.what(), fileName.c_str());
		//std::cout << "Caught exception: " << error_.what() << " file: "<< psdPathname << std::endl;
    }*/
    
    
//	
//	wprintf(L"* added texture: %s", (wchar_t*)(image->GetFilename().c_str()));
//	printf(" name: %s\n", image->GetDaeId().c_str());
//
//	// Read in the image file into DevIL.
//	if (!ilLoadImage(nstring))	
//	{
//		wchar_t error_message[256];
//		swprintf(error_message, 256, L"This texture could not be opened: %s\n", (wchar_t*)(image->GetFilename().c_str()));
//		wprintf(error_message);
//		
//		ilDeleteImages(1, &imageId);
//		textureId = -1;
//	} else 
//	{
//		// resize if necessary
//		ProcessDevilImage();
//
//
//		// gl work
//		glGenTextures(1, &textureId); /* Texture name generation */
//		GLenum error;
//		if ((error = glGetError()) != GL_NO_ERROR)
//		{
//			printf("OpenGL Error: %x\n", error);
//		}
//
//		glBindTexture(GL_TEXTURE_2D, textureId); /* Binding of texture name */
//
//		// if 4 channels, the last one is the alpha channel
//		if (ilGetInteger(IL_IMAGE_CHANNELS) == 4) 
//			hasAlphaChannel = true;
//
//		// create mipmaps and upload texture to video card memory
//		gluBuild2DMipmaps
//		(
//			GL_TEXTURE_2D,
//			ilGetInteger(IL_IMAGE_CHANNELS),
//			ilGetInteger(IL_IMAGE_WIDTH),
//			ilGetInteger(IL_IMAGE_HEIGHT), 
//			ilGetInteger(IL_IMAGE_FORMAT), 
//			GL_UNSIGNED_BYTE,
//			ilGetData()
//		); 
//
//
//
//
//		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
//		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
//		glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
//
//		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
//
//		printf("texture size: %d x %d\n", ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT));
//
//		// release memory, now opengl have it !
//		ilDeleteImages(1, &imageId); 
//	}
	
}
コード例 #16
0
VOID ResourceDatabase::AddBundledResources( PackedResource* pBundledResourceTable )
{
    assert( pBundledResourceTable != NULL );
    m_BundledResources.push_back( pBundledResourceTable );

    RESOURCE* pTags = NULL;
    DWORD dwResourceCount = 0;
    WCHAR strNameTemp[256];
    pBundledResourceTable->GetResourceTags( &dwResourceCount, &pTags );
    DWORD i = 0;
    while( i < dwResourceCount )
    {
        MultiByteToWideChar( CP_ACP, 0, pTags[i].strName, strlen( pTags[i].strName ) + 1, strNameTemp, 256 );
        _wcslwr_s( strNameTemp );
        switch( pTags[i].dwType )
        {
        case RESOURCETYPE_TEXTURE:
            {
                Texture2D* pTexture = new Texture2D();
                pTexture->SetName( strNameTemp );
                pTexture->bFromPackedResource = TRUE;
                DWORD dwOffset = pTags[ i ].dwOffset;
                D3DTexture* pD3DTexture = pBundledResourceTable->GetTexture( dwOffset );
                pTexture->SetD3DTexture( pD3DTexture );
                AddResource( pTexture );
#ifdef PROFILE
                // Report texture to texture tracker
                PIXReportNewTexture( pD3DTexture );
                CHAR strConverted[256];
                strConverted[0] = 0;
                wcstombs_s( 0, strConverted, strNameTemp, _countof(strConverted) );  
                PIXSetTextureName( pD3DTexture, TEXT(strConverted) );
#endif
                break;
            }
        case RESOURCETYPE_CUBEMAP:
            {
                TextureCube* pTexture = new TextureCube();
                pTexture->SetName( strNameTemp );
                pTexture->bFromPackedResource = TRUE;
                DWORD dwOffset = pTags[ i ].dwOffset;
                D3DCubeTexture* pD3DTexture = pBundledResourceTable->GetCubemap( dwOffset );
                pTexture->SetD3DTexture( pD3DTexture );
                AddResource( pTexture );
#ifdef PROFILE
                // Report texture to texture tracker
                PIXReportNewTexture( pD3DTexture );
                CHAR strConverted[256];
                strConverted[0] = 0;
                wcstombs_s( 0, strConverted, strNameTemp, _countof(strConverted) );  
                PIXSetTextureName( pD3DTexture, TEXT(strConverted) );
#endif
               break;
            }
        case RESOURCETYPE_VOLUMETEXTURE:
            {
                TextureVolume* pTexture = new TextureVolume();
                pTexture->SetName( strNameTemp );
                pTexture->bFromPackedResource = TRUE;
                DWORD dwOffset = pTags[ i ].dwOffset;
                D3DVolumeTexture* pD3DTexture = pBundledResourceTable->GetVolumeTexture( dwOffset );
                pTexture->SetD3DTexture( pD3DTexture );
                AddResource( pTexture );
#ifdef PROFILE
                // Report texture to texture tracker
                PIXReportNewTexture( pD3DTexture );
                CHAR strConverted[256];
                strConverted[0] = 0;
                wcstombs_s( 0, strConverted, strNameTemp, _countof(strConverted) );  
                PIXSetTextureName( pD3DTexture, TEXT(strConverted) );
#endif
              break;
            }
        case RESOURCETYPE_VERTEXBUFFER:
        case RESOURCETYPE_INDEXBUFFER:
        case RESOURCETYPE_USERDATA:
        default:
            {
                // not supported yet
                DebugSpew( "Unsupported resource type %d for resource \"%s\".\n", pTags[i].dwType, pTags[i].strName );
                break;
            }
        }
        ++i;
    }
}
コード例 #17
0
ファイル: WinLauncher.cpp プロジェクト: maiklos-mirrors/jfx78
bool startJVM(TCHAR* basedir, TCHAR* appFolder, TCHAR* jar, int argCount, LPTSTR *szArgList) {
    TCHAR jvmPath[LAUNCHER_MAXPATH+1] = {0};
    JavaVMInitArgs jvmArgs;
    JavaVMOption options[MAX_OPTIONS+1];
    JVM_CREATE createProc;
    JNIEnv* env;
    JavaVM* jvm = NULL;
    char jarASCII[LAUNCHER_MAXPATH] = {0};
    char classpath[LAUNCHER_MAXPATH*2] = {0};
    char mainclassASCII[LAUNCHER_MAXPATH] = {0},
        appClasspath[LAUNCHER_MAXPATH] = {0};
    size_t outlen = 0;
    jclass cls;
    jmethodID mid;
    TCHAR argname[MAX_OPTION_NAME + 1] = {0};
    TCHAR argvalue[LAUNCHER_MAXPATH] = {0},
    mainclass[LAUNCHER_MAXPATH] = {0};
    CHAR  argvalueASCII[LAUNCHER_MAXPATH] = {0};
    HMODULE msvcrtdll;
    bool runtimeBundled;
    TCHAR tmpPath[LAUNCHER_MAXPATH] = {0};
    TCHAR appid[LAUNCHER_MAXPATH] = {0};

    memset(&options, 0, sizeof(JavaVMOption)*(MAX_OPTIONS + 1));
    memset(&jvmArgs, 0, sizeof(JavaVMInitArgs));

    makeFullFileName(basedir, _T("\\runtime"), tmpPath, sizeof(tmpPath)/sizeof(TCHAR));
    runtimeBundled = fileExists(tmpPath);
    if (runtimeBundled) {
       if (!getJvmPath(basedir, jvmPath, LAUNCHER_MAXPATH)) {
            showError(_T("jvm.dll is not found in bundled runtime."), jvmPath);
            return false;
       }
       //make sure msvcr100 is loaded (or we may fail if copy of it is not installed into system)
       makeFullFileName(basedir, _T("runtime\\jre\\bin\\msvcr100.dll"), tmpPath, sizeof(tmpPath)/sizeof(TCHAR));
       msvcrtdll = ::LoadLibrary(tmpPath);
    } else {
        if (!getSystemJvmPath(jvmPath, LAUNCHER_MAXPATH)) {
            showError(_T("No bundled runtime and can not find system JRE."), jvmPath);
            return false;
        }
       //make sure msvcr100 is loaded (or we may fail if copy of it is not installed into system)
       makeFullFileName(basedir, _T("\\bin\\msvcr100.dll"), tmpPath, sizeof(tmpPath)/sizeof(TCHAR));
       msvcrtdll = ::LoadLibrary(tmpPath);
    }

    // Dynamically load the JVM
    HMODULE jvmLibHandle = LoadLibrary(jvmPath);
    if (jvmLibHandle == NULL) {
        DWORD dwErr = GetLastError();
        showError(_T("Error loading jvm.dll"), jvmPath);
        return false;
    }

    //convert argument to ASCII string as this is what CreateJVM needs
    wcstombs_s(&outlen, jarASCII, LAUNCHER_MAXPATH, jar, (size_t) wcslen(jar) + 1);
    strcpy_s(classpath, LAUNCHER_MAXPATH*2, "-Djava.class.path=");
    strcat_s(classpath, LAUNCHER_MAXPATH, jarASCII);

    if (getConfigValue(basedir, CONFIG_CLASSPATH_KEY, argvalue, LAUNCHER_MAXPATH)) {
           size_t inLen = (size_t) wcslen(argvalue);
           //convert argument to ASCII string as this is what CreateJVM needs
           wcstombs_s(&outlen, argvalueASCII, sizeof(argvalueASCII), argvalue, inLen + 1);
           //compress spaces and replaces them with ;
           {
               char *in = argvalueASCII;
               char *out = argvalueASCII;
               bool needSemicolon = false;

               while (*in != 0) {
                   if (*in == ' ') {
                       if (needSemicolon) {
                          *out = ';';
                          out++;
                          needSemicolon = false;
                       }
                   } else {
                       needSemicolon = true;
                       *out = *in;
                       out++;
                   }
                   in++;
               }
               *out = 0;
           }
           if (strlen(argvalueASCII) > 0) {
               strcat_s(classpath, LAUNCHER_MAXPATH, ";");
               strcat_s(classpath, LAUNCHER_MAXPATH, argvalueASCII);
           }
    }

    // Set up the VM init args
    jvmArgs.version = JNI_VERSION_1_2;

    options[0].optionString = _strdup(classpath);

    int cnt = 1;
    if (isDebug) {
       options[cnt].optionString = _strdup("vfprintf");
       options[cnt].extraInfo    = vfprintfHook;
       cnt++;
    }

    //Note: should not try to quote the path. Spaces are fine here
    _stprintf_s(argvalue, _T("-Djava.library.path=%s"), appFolder);
    wcstombs_s(&outlen, argvalueASCII, sizeof(argvalueASCII),
               argvalue, wcslen(argvalue) + 1);
    options[cnt].optionString = _strdup(argvalueASCII);
    cnt++;

    //add app specific JVM parameters
    int idx = 1;
    int found = 0;
    do {
       _stprintf_s(argname, MAX_OPTION_NAME, _T("jvmarg.%d"), idx);
       found = getConfigValue(basedir, argname, argvalue, LAUNCHER_MAXPATH);
       if (found) {
            TCHAR* option = replaceStr(argvalue, _T("$APPDIR"), basedir);
            char* jvmOption = convertToDupedChar(option);
            if (jvmOption != NULL) {
                options[cnt].optionString = jvmOption;
                cnt++;
            }
            idx++;
        }
    } while (found && idx < MAX_OPTIONS);

	cnt = addUserOptions(basedir, options, cnt);

    jvmArgs.version = 0x00010002;
    jvmArgs.options = options;
    jvmArgs.nOptions = cnt;
    jvmArgs.ignoreUnrecognized = JNI_TRUE;

    // Create the JVM
    // NB: need to use ASCII string as UNICODE is not supported
    createProc = (JVM_CREATE) GetProcAddress(jvmLibHandle, "JNI_CreateJavaVM");
    if (createProc == NULL) {
        showError(_T("Failed to locate JNI_CreateJavaVM"), jvmPath);
        return false;
    }

    if ((*createProc)(&jvm, &env, &jvmArgs) < 0) {
        showError(_T("Failed to create JVM"), jvmPath);
        return false;
    }

    if (!getConfigValue(basedir, CONFIG_MAINCLASS_KEY, mainclass, LAUNCHER_MAXPATH)) {
        showError(_T("Package error"), _T("No main class specified. Nothing to launch"));
        return false;
    } else {
           size_t inLen = (size_t) wcslen(mainclass);
           //convert argument to ASCII string as this is what CreateJVM needs
           wcstombs_s(&outlen, mainclassASCII, sizeof(mainclassASCII), mainclass, inLen + 1);
    }

    cls = env->FindClass(mainclassASCII);
    if (cls != NULL) {
        mid = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");
         if (mid != NULL) {
            jclass stringClass = env->FindClass("java/lang/String");
            //prepare app arguments if any. Skip value at index 0 - this is path to executable ...
            //NOTE:
            //  - what if user run in non-English/UTF-8 locale? do we need to convert args?
            //  - extend to pass jvm args and debug args (allow them in front, use marker option to separate them?)
            int startArgIndex = countNumberOfSystemArguments(argCount, szArgList);
            jobjectArray args = env->NewObjectArray(argCount - startArgIndex, stringClass, NULL);
            for(int i=startArgIndex; i<argCount; i++) {
                size_t inLen = (size_t) wcslen(szArgList[i]);
                env->SetObjectArrayElement(args, i-startArgIndex, env->NewString((jchar*)szArgList[i], inLen));
            }
            env->CallStaticVoidMethod(cls, mid, args);
        } else {
            showError(_T("no main method in the main class!"), mainclass);
            return false;
        }
    } else {
        showError(_T("no main class."), mainclass);
        return false;
    }

    if (env->ExceptionOccurred()) {
        showError(_T("Failed due to exception from main class."), mainclass);
        env->ExceptionDescribe();
    }

    // If application main() exits quickly but application is run on some other thread
    //  (e.g. Swing app performs invokeLater() in main and exits)
    // then if we return execution to tWinMain it will exit.
    // This will cause process to exit and application will not actually run.
    //
    // To avoid this we are trying to detach jvm from current thread (java.exe does the same)
    // Because we are doing this on the main JVM thread (i.e. one that was used to create JVM)
    // this call will spawn "Destroy Java VM" java thread that will shut JVM once there are
    // no non-daemon threads running, and then return control here.
    // I.e. this will happen when EDT and other app thread will exit.
    if (jvm->DetachCurrentThread() != 0) {
        showError(_T("Detach failed."), NULL);
    }
    jvm->DestroyJavaVM();

    return true;
}
コード例 #18
0
ファイル: safembyt.c プロジェクト: ABratovic/open-watcom-v2
void TestFromWide( void )
{
    char                mbs[20];
    wchar_t             wc = L'\0';
    wchar_t             wcs[] = { 'H', 'e', 'l', 'l', 'o', '\0' };

    errno_t             rc;
    size_t              retval;
    size_t              retval2;
    int                 status;
    int                 violations = NumViolations;

    rc = wctomb_s( &status, mbs, 20, wc );
    VERIFY( rc == 0 );
    VERIFY( mbs[0] == '\0' );
    VERIFY( status == 1 );
    VERIFY( violations == NumViolations );

    rc = wctomb_s( &status, mbs, 20, L'X' );
    VERIFY( rc == 0 );
    VERIFY( mbs[0] == 'X' );
    VERIFY( status == 1 );
    VERIFY( violations == NumViolations );

    rc = wctomb_s( &status, NULL, 0, L'X' );
    VERIFY( rc == 0 );
    VERIFY( status == 0 );  /* no state-dependant encodings */
    VERIFY( violations == NumViolations );


    rc = wcstombs_s( &retval, mbs, 20, wcs, 10 );
    VERIFY( rc == 0 );
    VERIFY( retval == 5 );
    VERIFY( !_mbscmp(mbs,"Hello") );
    VERIFY( violations == NumViolations );

    rc = wcstombs_s( &retval2, NULL, 0, wcs, 10 );
    VERIFY( rc == 0 );
    VERIFY( retval2 == 5 );
    VERIFY( violations == NumViolations );


    /***********************************************************************/
    /*  test runtime-constraints                                           */
    /***********************************************************************/
    rc = wctomb_s( &status, NULL, 20, wc );
    VERIFY( rc != 0 );
    VERIFY( ++violations == NumViolations );

    rc = wctomb_s( &status, mbs, 0, wc );
    VERIFY( rc != 0 );
    VERIFY( ++violations == NumViolations );

#if RSIZE_MAX != SIZE_MAX
    rc = wctomb_s( &status, mbs, ~0, wc );
    VERIFY( rc != 0 );
    VERIFY( ++violations == NumViolations );
#endif

    rc = wctomb_s( &status, mbs, 1, '\x81\xFC' );
    VERIFY( rc != 0 );
    VERIFY( ++violations == NumViolations );


    mbs[0]= 'X';
    rc = wcstombs_s( NULL, mbs, 20, wcs, 10 );
    VERIFY( rc != 0 );
    VERIFY( mbs[0] == '\0' );
    VERIFY( ++violations == NumViolations );

    mbs[0]= 'X';
    rc = wcstombs_s( &retval, mbs, 20, NULL, 10 );
    VERIFY( rc != 0 );
    VERIFY( retval == -1 );
    VERIFY( mbs[0] == '\0' );
    VERIFY( ++violations == NumViolations );

#if RSIZE_MAX != SIZE_MAX
    mbs[0]= 'X';
    rc = wcstombs_s( &retval, mbs, ~0, wcs, 10 );
    VERIFY( rc != 0 );
    VERIFY( retval == -1 );
    VERIFY( mbs[0] == 'X' );
    VERIFY( ++violations == NumViolations );

    mbs[0]= 'X';
    rc = wcstombs_s( &retval, mbs, 20, wcs, ~0 );
    VERIFY( rc != 0 );
    VERIFY( retval == -1 );
    VERIFY( mbs[0] == '\0' );
    VERIFY( ++violations == NumViolations );
#endif



}
コード例 #19
0
bool D3DClass::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenDepth, float screenNear)
{
	HRESULT result;
	IDXGIFactory* factory;
	IDXGIAdapter* adapter;
	IDXGIOutput* adapterOutput;
	unsigned int numModes, i, numerator, denominator, stringLength;
	DXGI_MODE_DESC* displayModeList;
	DXGI_ADAPTER_DESC adapterDesc;
	int error;
	DXGI_SWAP_CHAIN_DESC swapChainDesc;
	D3D_FEATURE_LEVEL featureLevel;
	ID3D11Texture2D* backBufferPtr;
	D3D11_TEXTURE2D_DESC depthBufferDesc;
	D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
	D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
	D3D11_RASTERIZER_DESC rasterDesc;
	D3D11_VIEWPORT viewport;
	float fieldOfView, screenAspect;


	// vsync(수직동기화) 설정을 저장합니다.
	m_vsync_enabled = vsync;
	// DirectX 그래픽 인터페이스 팩토리를 만듭니다.
	result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
	if (FAILED(result))
	{
		return false;
	}

	// 팩토리 객체를 사용하여 첫번째 그래픽 카드 인터페이스에 대한 아답터를 만듭니다.
	result = factory->EnumAdapters(0, &adapter);
	if (FAILED(result))
	{
		return false;
	}

	// 출력(모니터)에 대한 첫번째 아답터를 나열합니다.
	result = adapter->EnumOutputs(0, &adapterOutput);
	if (FAILED(result))
	{
		return false;
	}

	// DXGI_FORMAT_R8G8B8A8_UNORM 모니터 출력 디스플레이 포맷에 맞는 모드의 개수를 구합니다.
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	if (FAILED(result))
	{
		return false;
	}

	// 가능한 모든 모니터와 그래픽카드 조합을 저장할 리스트를 생성합니다.
	displayModeList = new DXGI_MODE_DESC[numModes];
	if (!displayModeList)
	{
		return false;
	}

	// 디스플레이 모드에 대한 리스트 구조를 채워넣습니다.
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	if (FAILED(result))
	{
		return false;
	}

	// 이제 모든 디스플레이 모드에 대해 화면 너비/높이에 맞는 디스플레이 모드를 찾습니다.
	// 적합한 것을 찾으면 모니터의 새로고침 비율의 분모와 분자 값을 저장합니다.
	for (i = 0; i<numModes; i++)
	{
		if (displayModeList[i].Width == (unsigned int)screenWidth)
		{
			if (displayModeList[i].Height == (unsigned int)screenHeight)
			{
				numerator = displayModeList[i].RefreshRate.Numerator;
				denominator = displayModeList[i].RefreshRate.Denominator;
			}
		}
	}

	// 아답터(그래픽카드)의 description을 가져옵니다.
	result = adapter->GetDesc(&adapterDesc);
	if (FAILED(result))
	{
		return false;
	}

	// 현재 그래픽카드의 메모리 용량을 메가바이트 단위로 저장합니다.
	m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

	// 그래픽카드의 이름을 char형 문자열 배열로 바꾼 뒤 저장합니다.
	error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128);
	if (error != 0)
	{
		return false;
	}
	// 디스플레이 모드 리스트의 할당을 해제합니다.
	delete[] displayModeList;
	displayModeList = 0;

	// 출력 아답터를 할당 해제합니다.
	adapterOutput->Release();
	adapterOutput = 0;

	// 아답터를 할당 해제합니다.
	adapter->Release();
	adapter = 0;

	// 팩토리 객체를 할당 해제합니다.
	factory->Release();
	factory = 0;


	// 스왑 체인 description을 초기화합니다.
	ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

	// 하나의 백버퍼만을 사용하도록 합니다.
	swapChainDesc.BufferCount = 1;

	// 백버퍼의 너비와 높이를 설정합니다.
	swapChainDesc.BufferDesc.Width = screenWidth;
	swapChainDesc.BufferDesc.Height = screenHeight;

	// 백퍼버로 일반적인 32bit의 서페이스를 지정합니다.
	swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

	// 백버퍼의 새로고침 비율을 설정합니다.
	if (m_vsync_enabled)
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
	}
	else
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
	}

	// 백버퍼의 용도를 설정합니다.
	swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

	// 렌더링이 이루어질 윈도우의 핸들을 설정합니다.
	swapChainDesc.OutputWindow = hwnd;

	// 멀티샘플링을 끕니다.
	swapChainDesc.SampleDesc.Count = 1;
	swapChainDesc.SampleDesc.Quality = 0;

	// 윈도우 모드 또는 풀스크린 모드를 설정합니다.
	if (fullscreen)
		swapChainDesc.Windowed = false;
	else
		swapChainDesc.Windowed = true;

	// 스캔라인의 정렬과 스캔라이닝을 지정되지 않으므로 (unspecified) 설정합니다.
	swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	// 출력된 이후의 백버퍼의 내용을 버리도록 합니다.
	swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

	// 추가 옵션 플래그를  사용하지 않습니다.
	swapChainDesc.Flags = 0;

	// 피쳐 레벨을 DirectX 11로 설정합니다.
	featureLevel = D3D_FEATURE_LEVEL_11_0;

	// 스왑 체인, Direct3D 디바이스, Direct3D 디바이스 컨텍스트를 생성합니다.
	result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext);
	if (FAILED(result))
		return false;

	// 백버퍼의 포인터를 가져옵니다.
	result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
	if (FAILED(result))
		return false;

	// 백버퍼의 포인터로 렌더타겟 뷰를 생성합니다.
	result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView);
	if (FAILED(result))
		return false;

	// 백버퍼 포인터를 더이상 사용하지 않으므로 할당 해제합니다.
	backBufferPtr->Release();
	backBufferPtr = 0;

	// 깊이 버퍼의 description을 초기화합니다.
	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

	// 깊이 버퍼의 description을 작성합니다.
	depthBufferDesc.Width = screenWidth;
	depthBufferDesc.Height = screenHeight;
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 1;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;

	// description을 사용하여 깊이 버퍼의 텍스쳐를 생성합니다.
	result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer);
	if (FAILED(result))
		return false;

	// 스텐실 상태의 description을 초기화합니다.
	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

	// 스텐실 상태의 description을 작성합니다.
	depthStencilDesc.DepthEnable = true;
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0xFF;

	// Stencil operations if pixel is front-facing.
	depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Stencil operations if pixel is back-facing.
	depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// 깊이 - 스텐실 상태를 생성합니다.
	result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState);
	if (FAILED(result))
		return false;

	// 깊이 - 스텐실 상태를 설정합니다.
	m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);

	// 깊이 - 스텐실 뷰의 description을 초기화 합니다.
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

	// 깊이 - 스텐실 부의 description을 작성합니다.
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	// 깊이 - 스텐실 뷰를 생성합니다.
	result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView);
	if (FAILED(result))
		return false;

	// 렌더타겟 뷰와 깊이 - 스텐실 버퍼를 각각 출력 파이프라인에 바인딩합니다.
	m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);

	// 어떤 도형을 어떻게 그릴 것인지 결정하는 래스터화기 description을 작성합니다.
	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_BACK;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = true;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	// 작성한 description으로부터 래스터화기 상태를 생성합니다.
	result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState);
	if (FAILED(result))
		return false;

	// 래스터화기 상태를 설정합니다.
	m_deviceContext->RSSetState(m_rasterState);

	// 렌더링을 위한 뷰포트를 설정합니다.
	viewport.Width = (float)screenWidth;
	viewport.Height = (float)screenHeight;
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.TopLeftX = 0.0f;
	viewport.TopLeftY = 0.0f;

	// 뷰포트를 생성합니다.
	m_deviceContext->RSSetViewports(1, &viewport);

	// 투영 행렬을 설정합니다.
	fieldOfView = (float)D3DX_PI / 4.0f;
	screenAspect = (float)screenWidth / (float)screenHeight;

	// 3D 렌더링을 위한 투영 행렬을 생성합니다.
	D3DXMatrixPerspectiveFovLH(&m_projectionMatrix, fieldOfView, screenAspect, screenNear, screenDepth);

	// 월드 행렬을 단위 행렬로 초기화 합니다.
	D3DXMatrixIdentity(&m_worldMatrix);

	// 2D 렌더링에 사용될 정사영 행렬을 생성합니다.
	D3DXMatrixOrthoLH(&m_orthoMatrix, (float)screenWidth, (float)screenHeight, screenNear, screenDepth);

	return true;
}
コード例 #20
0
HRESULT DXManager::getVideoCardInfo()
{
	HRESULT result;
	IDXGIFactory* factory;
	IDXGIAdapter* adapter;
	IDXGIOutput* adapterOutput;
	DXGI_MODE_DESC* displayModeList;
	DXGI_ADAPTER_DESC adapterDesc;
	unsigned int numModes, i, stringLength;
	int error;

	result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
	if (FAILED(result))	{ return false; }

	result = factory->EnumAdapters(0, &adapter);
	if (FAILED(result))	{ return false; }

	result = adapter->EnumOutputs(0, &adapterOutput);
	if (FAILED(result))	{ return false; }

	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	if (FAILED(result))	{ return false; }

	displayModeList = new DXGI_MODE_DESC[numModes];
	if (!displayModeList)	{ return false; }

	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	if (FAILED(result))	{ return false; }

	for (i = 0; i<numModes; i++)
	{
		if (displayModeList[i].Width == (unsigned int)m_ScreenWidth)
		{
			if (displayModeList[i].Height == (unsigned int)m_ScreenHeight)
			{
				mNumerator = displayModeList[i].RefreshRate.Numerator;
				mDenominator = displayModeList[i].RefreshRate.Denominator;
			}
		}
	}

	result = adapter->GetDesc(&adapterDesc);
	if (FAILED(result))	{ return false; }

	m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); //MB Video Ram

	error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128);
	if (error != 0)	{ return false; }

	delete[] displayModeList;
	displayModeList = 0;

	adapterOutput->Release();
	adapterOutput = 0;

	adapter->Release();
	adapter = 0;

	factory->Release();
	factory = 0;
	return S_OK;
}
コード例 #21
0
bool D3DClass::Initialise(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, 
						  float screenDepth, float screenNear)
{
	HRESULT result;
	IDXGIFactory* factory;
	IDXGIAdapter* adapter;
	IDXGIOutput* adapterOutput;
	unsigned int numModes, i, numerator, denominator, stringLength;
	DXGI_MODE_DESC* displayModeList;
	DXGI_ADAPTER_DESC adapterDesc;
	int error;
	DXGI_SWAP_CHAIN_DESC swapChainDesc;
	D3D_FEATURE_LEVEL featureLevel;
	ID3D11Texture2D* backBufferPtr;
	D3D11_TEXTURE2D_DESC depthBufferDesc;

	D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
	D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;

	D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
	D3D11_BLEND_DESC blendStateDescription;
	
	D3D11_RASTERIZER_DESC rasterDesc;
	float fieldOfView, screenAspect;


	// Store the vsync setting.
	m_vsync_enabled = vsync;

	// Create a DirectX graphics interface factory.
	result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
	if(FAILED(result))
	{
		return false;
	}

	// Use the factory to create an adapter for the primary graphics interface (video card).
	result = factory->EnumAdapters(0, &adapter);
	if(FAILED(result))
	{
		return false;
	}

	// Enumerate the primary adapter output (monitor).
	result = adapter->EnumOutputs(0, &adapterOutput);
	if(FAILED(result))
	{
		return false;
	}

	// Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	if(FAILED(result))
	{
		return false;
	}

	// Create a list to hold all the possible display modes for this monitor/video card combination.
	displayModeList = new DXGI_MODE_DESC[numModes];
	if(!displayModeList)
	{
		return false;
	}

	// Now fill the display mode list structures.
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	if(FAILED(result))
	{
		return false;
	}

	// Now go through all the display modes and find the one that matches the screen width and height.
	// When a match is found store the numerator and denominator of the refresh rate for that monitor.
	for(i=0; i<numModes; i++)
	{
		if(displayModeList[i].Width == (unsigned int)screenWidth)
		{
			if(displayModeList[i].Height == (unsigned int)screenHeight)
			{
				numerator = displayModeList[i].RefreshRate.Numerator;
				denominator = displayModeList[i].RefreshRate.Denominator;
			}
		}
	}

	// Get the adapter (video card) description.
	result = adapter->GetDesc(&adapterDesc);
	if(FAILED(result))
	{
		return false;
	}

	// Store the dedicated video card memory in megabytes.
	m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

	// Convert the name of the video card to a character array and store it.
	error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128);
	if(error != 0)
	{
		return false;
	}

	// Release the display mode list.
	delete [] displayModeList;
	displayModeList = 0;

	// Release the adapter output.
	adapterOutput->Release();
	adapterOutput = 0;

	// Release the adapter.
	adapter->Release();
	adapter = 0;

	// Release the factory.
	factory->Release();
	factory = 0;

	// Initialise the swap chain description.
    ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

	// Set to a single back buffer.
    swapChainDesc.BufferCount = 1;

	// Set the width and height of the back buffer.
    swapChainDesc.BufferDesc.Width = screenWidth;
    swapChainDesc.BufferDesc.Height = screenHeight;

	// Set regular 32-bit surface for the back buffer.
    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

	// Set the refresh rate of the back buffer.
	if(m_vsync_enabled)
	{
	    swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
	}
	else
	{
	    swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
	}

	// Set the usage of the back buffer.
    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

	// Set the handle for the window to render to.
    swapChainDesc.OutputWindow = hwnd;

	// Turn multisampling off.
    swapChainDesc.SampleDesc.Count = 1;
    swapChainDesc.SampleDesc.Quality = 0;

	// Set to full screen or windowed mode.
	if(fullscreen)
	{
		swapChainDesc.Windowed = false;
	}
	else
	{
		swapChainDesc.Windowed = true;
	}

	// Set the scan line ordering and scaling to unspecified.
	swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	// Discard the back buffer contents after presenting.
	swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

	// Don't set the advanced flags.
	swapChainDesc.Flags = 0;

	// Set the feature level to DirectX 11.
	featureLevel = D3D_FEATURE_LEVEL_11_0;

	// Create the swap chain, Direct3D device, and Direct3D device context.
	result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, 
										   D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext);
	if(FAILED(result))
	{
		return false;
	}

	// Get the pointer to the back buffer.
	result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
	if(FAILED(result))
	{
		return false;
	}

	// Create the render target view with the back buffer pointer.
	result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView);
	if(FAILED(result))
	{
		return false;
	}

	// Release pointer to the back buffer as we no longer need it.
	backBufferPtr->Release();
	backBufferPtr = 0;

	// Initialise the description of the depth buffer.
	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

	// Set up the description of the depth buffer.
	depthBufferDesc.Width = screenWidth;
	depthBufferDesc.Height = screenHeight;
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 1;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;

	// Create the texture for the depth buffer using the filled out description.
	result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer);
	if(FAILED(result))
	{
		return false;
	}

	// Initialise the description of the stencil state.
	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

	// Set up the description of the stencil state.
	depthStencilDesc.DepthEnable = true;
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0xFF;

	// Stencil operations if pixel is front-facing.
	depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Stencil operations if pixel is back-facing.
	depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Create the depth stencil state.
	result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState);
	if(FAILED(result))
	{
		return false;
	}

	// Set the depth stencil state.
	m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);

	// Initialise the depth stencil view.
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

	// Set up the depth stencil view description.
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	// Create the depth stencil view.
	result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView);
	if(FAILED(result))
	{
		return false;
	}

	// Bind the render target view and depth stencil buffer to the output render pipeline.
	m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);

	// Setup the raster description which will determine how and what polygons will be drawn.
	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_BACK;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = true;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	// Create the rasterizer state from the description we just filled out.
	result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState);
	if(FAILED(result))
	{
		return false;
	}

	// Now set the rasterizer state.
	m_deviceContext->RSSetState(m_rasterState);
	
	// Setup the viewport for rendering.
    m_viewport.Width = (float)screenWidth;
    m_viewport.Height = (float)screenHeight;
    m_viewport.MinDepth = 0.0f;
    m_viewport.MaxDepth = 1.0f;
    m_viewport.TopLeftX = 0.0f;
    m_viewport.TopLeftY = 0.0f;

	// Create the viewport.
    m_deviceContext->RSSetViewports(1, &m_viewport);

	// Setup the projection matrix.
	fieldOfView = (float)D3DX_PI / 4.0f;
	screenAspect = (float)screenWidth / (float)screenHeight;

	// Create the projection matrix for 3D rendering.
	D3DXMatrixPerspectiveFovLH(&m_projectionMatrix, fieldOfView, screenAspect, screenNear, screenDepth);

    // Initialise the world matrix to the identity matrix.
    D3DXMatrixIdentity(&m_worldMatrix);

	// Create an orthographic projection matrix for 2D rendering.
	D3DXMatrixOrthoLH(&m_orthoMatrix, (float)screenWidth, (float)screenHeight, screenNear, screenDepth);



	// Clear the second depth stencil state before setting the parameters.
	ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));

	// Now create a second depth stencil state which turns off the Z buffer for 2D rendering.  The only difference is 
	// that DepthEnable is set to false, all other parameters are the same as the other depth stencil state.
	depthDisabledStencilDesc.DepthEnable = false;
	depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
	depthDisabledStencilDesc.StencilEnable = false;
	depthDisabledStencilDesc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK;
	depthDisabledStencilDesc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK;
	depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
	depthDisabledStencilDesc.BackFace = depthDisabledStencilDesc.FrontFace;

	// Create the state using the device.
	result = m_device->CreateDepthStencilState(&depthDisabledStencilDesc, &m_depthDisabledStencilState);
	if(FAILED(result))
	{
		return false;
	}

	// Clear the blend state description.
	ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC));

	// Create an alpha enabled blend state description.
	blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
	//blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
	blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
	blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
	blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
	blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
	blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
	blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_SUBTRACT;
	blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f;

	// Create the blend state using the description.
	result = m_device->CreateBlendState(&blendStateDescription, &m_alphaEnableBlendingState);
	if (FAILED(result))
	{
		return false;
	}

	// Modify the description to create an alpha disabled blend state description.
	blendStateDescription.RenderTarget[0].BlendEnable = FALSE;

	// Create the blend state using the description.
	result = m_device->CreateBlendState(&blendStateDescription, &m_alphaDisableBlendingState);
	if (FAILED(result))
	{
		return false;
	}

    return true;
}
コード例 #22
0
ファイル: summinfo.cpp プロジェクト: zxlooong/bcgexp
LPCSTR tcstocs(LPCTSTR lpctStr) {                       // typed char (WCHAR) to CHAR
	size_t numConv = 0;
	static CHAR strTemp[1024];
	wcstombs_s(&numConv, strTemp, 1024, lpctStr, 1024);
	return strTemp;
}
コード例 #23
0
ファイル: session.c プロジェクト: mwt5175/ndbg
/**
*	Process session event
*
*	This service implements the OS independent API for processing equests
*	sent from the environment. Under Windows, this service would process
*	DEBUG_EVENTs when called from the operating system. Under the NDBG
*	executive debugger server, these events would be sent over a PIPE.
*
*	This method calls the environment independent session event procedure.
*
*	\param session Debug session
*	\param e Output DEBUG_EVENT descriptor
*	\ret Session state
*/
dbgSessionState DbgSessionProcessEvent (dbgSession* session, DEBUG_EVENT* e) {

	/* clear event descriptor */
	dbgEventDescr descr;
	memset (&descr,0,sizeof(dbgEventDescr));

	/* process debug event */
	switch (e->dwDebugEventCode) {
		/*
			Create process
		*/
		case CREATE_PROCESS_DEBUG_EVENT: {
			unsigned long long base = 0;

			dbgCreateProcessDescr* record;
			record      = &descr.u.createProcess;
			descr.event = DBG_EVENT_CREATEPROCESS;
			record->entry     = (vaddr_t) e->u.CreateProcessInfo.lpStartAddress;
			record->imageBase = (vaddr_t) e->u.CreateProcessInfo.lpBaseOfImage;
			record->imageName = (vaddr_t) e->u.CreateProcessInfo.lpImageName;
			return session->proc (session, &descr);
		}
		/*
			Create thread
		*/
		case CREATE_THREAD_DEBUG_EVENT: {
			dbgCreateThreadDescr* record;
			record = &descr.u.createThread;
			descr.event = DBG_EVENT_CREATETHREAD;
			record->entry = (vaddr_t) e->u.CreateThread.lpStartAddress;
			return session->proc (session, &descr);
		}
		/*
			Exception
		*/
		case EXCEPTION_DEBUG_EVENT: {
			dbgExceptionDescr* record;
			record = &descr.u.exception;
			record->firstChance = e->u.Exception.dwFirstChance;
			descr.event = DBG_EVENT_EXCEPTION;
			/*
				Converts Windows exception code to internal format
			*/
			switch (e->u.Exception.ExceptionRecord.ExceptionCode) {
				case EXCEPTION_ACCESS_VIOLATION:
					descr.u.exception.code = DBG_EXCEPTION_SEGMENT;
					break;
				case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
					descr.u.exception.code = DBG_EXCEPTION_BOUNDS;
					break;
				case EXCEPTION_BREAKPOINT:
					descr.u.exception.code = DBG_EXCEPTION_BREAKPOINT;
					break;
				case EXCEPTION_DATATYPE_MISALIGNMENT:
					descr.u.exception.code = DBG_EXCEPTION_ALIGNMENT;
					break;
				case EXCEPTION_FLT_DENORMAL_OPERAND:
					descr.u.exception.code = DBG_EXCEPTION_FLT_DENORMAL_OPERAND;
					break;
				case EXCEPTION_FLT_DIVIDE_BY_ZERO:
					descr.u.exception.code = DBG_EXCEPTION_FLT_DIVIDE;
					break;
				case EXCEPTION_FLT_INEXACT_RESULT:
					descr.u.exception.code = DBG_EXCEPTION_FLT_INEXACT_RESULT;
					break;
				case EXCEPTION_FLT_INVALID_OPERATION:
					descr.u.exception.code = DBG_EXCEPTION_FLT_INVALID_OP;
					break;
				case EXCEPTION_FLT_OVERFLOW:
					descr.u.exception.code = DBG_EXCEPTION_FLT_OVERFLOW;
					break;
				case EXCEPTION_FLT_STACK_CHECK:
					descr.u.exception.code = DBG_EXCEPTION_FLT_STACK_CHECK;
					break;
				case EXCEPTION_FLT_UNDERFLOW:
					descr.u.exception.code = DBG_EXCEPTION_FLT_UNDERFLOW;
					break;
				case EXCEPTION_ILLEGAL_INSTRUCTION:
					descr.u.exception.code = DBG_EXCEPTION_INVALID_OPCODE;
					break;
				case EXCEPTION_INT_DIVIDE_BY_ZERO:
					descr.u.exception.code = DBG_EXCEPTION_INT_DIVIDE;
					break;
				case EXCEPTION_INT_OVERFLOW:
					descr.u.exception.code = DBG_EXCEPTION_INT_OVERFLOW;
					break;
				case EXCEPTION_SINGLE_STEP:
					descr.u.exception.code = DBG_EXCEPTION_SINGLE_STEP;
					break;
				case EXCEPTION_STACK_OVERFLOW:
					descr.u.exception.code = DBG_EXCEPTION_STACK;
					break;
				case EXCEPTION_IN_PAGE_ERROR:
				case EXCEPTION_INVALID_DISPOSITION:
				case EXCEPTION_NONCONTINUABLE_EXCEPTION:
				case EXCEPTION_PRIV_INSTRUCTION:
					descr.u.exception.code = DBG_EXCEPTION_GPF;
					break;
				case DBG_CONTROL_C:
					printf ("\n\rCtrl+c event not currently implemented.");
					break;
			}
			record->address = (vaddr_t) e->u.Exception.ExceptionRecord.ExceptionAddress;
			return session->proc (session, &descr);
		}
		/*
			Exit process
		*/
		case EXIT_PROCESS_DEBUG_EVENT: {
			dbgExitProcessDescr* record;
			record = &descr.u.exitProcess;
			descr.event = DBG_EVENT_EXITPROCESS;
			record->exitCode = e->u.ExitProcess.dwExitCode;
			return session->proc (session, &descr);
		}
		/*
			Exit thread
		*/
		case EXIT_THREAD_DEBUG_EVENT: {
			dbgExitThreadDescr* record;
			record = &descr.u.exitThread;
			descr.event = DBG_EVENT_EXITTHREAD;
			record->exitCode = e->u.ExitThread.dwExitCode;
			return session->proc (session, &descr);
		}
		/*
			Output string
		*/
		case OUTPUT_DEBUG_STRING_EVENT: {
			dbgDebugStringDescr* record;		
			char* str = 0;
			dbgSessionState state = DBG_STATE_CONTINUE;

			/* create record */
			record = &descr.u.debugString;
			descr.event = DBG_EVENT_PRINT;
			record->length = e->u.DebugString.nDebugStringLength;

			/* string located in process address space so we buffer it */
			str = (char*)malloc(record->length);
			DbgProcessRequest (DBG_REQ_READ,session, e->u.DebugString.lpDebugStringData,str,record->length);
			record->string = (vaddr_t) str;
			str[record->length-1] = 0; /* 0 terminate */

			/* process event and release memory */
			state = session->proc (session, &descr);
			free(str);
			return state;
		}

		/*
			The following events are processed internally and are not passed
			to the core debugger. They are Windows specific events.
		*/

		/*
			Load DLL
		*/
		case LOAD_DLL_DEBUG_EVENT: {
			dbgSharedLibrary* libraryDescr;
			char path[64];
			memset (path,0,64);
			/*
				lpImageName is a pointer in the process address space
				that contains a pointer to the real string in that address space.
			*/
			if (e->u.LoadDll.lpImageName) {
				vaddr_t imageName = 0;
				DbgProcessRequest (DBG_REQ_READ,session, e->u.LoadDll.lpImageName,&imageName,4);
				if (imageName) {
					wchar_t image[128];
					memset (image,128,0);
					DbgProcessRequest (DBG_REQ_READ,session,(void*)imageName,image,127);
#ifdef _MSC_VER
					{
						size_t numConverted = 0;
						wcstombs_s (&numConverted, path, 64, image,63);
					}
#else
					wcstombs (path,image,63);
#endif
				}
			}

			/* there is no debug event for this since its Windows specific */
			DbgDisplayMessage ("(%i) Loaded '%s'", session->process.id.pid, path);
			break;
		}
		/*
			RIP Event
		*/
		case RIP_EVENT: {
			/* there is no debug event for this since its Windows specific */
			DbgDisplayMessage ("RIP Event");
			break;
		}
		/*
			Unload DLL
		*/
		case UNLOAD_DLL_DEBUG_EVENT: {
			/*
				Locate library object
			*/
			dbgSharedLibrary* descr = 0;
			listNode* cur = session->process.libraryList.first;
			size_t c;
			for (c = 0; c < session->process.libraryList.count; c++) {
				descr = (dbgSharedLibrary*) cur->data;
				if (descr->base == (vaddr_t) e->u.UnloadDll.lpBaseOfDll)
					break;
				cur = cur->next;
			}
			/*
				Display library and unload it
			*/
			if (cur) {
				DbgDisplayMessage("(%i) Unloaded '%s'",
					session->process.id.pid,
					descr->name);
				free (descr->name);
				listRemoveElement(c, &session->process.libraryList);
			}
			else
				DbgDisplayMessage ("(%i) Unloaded unknown DLL", session->process.id.pid);

			/* there is no debug event for this since its Windows specific */
			break;
		}
	}

	/* we just continue this session for all events that dont need processing */
	return DBG_STATE_CONTINUE;
}
コード例 #24
0
ファイル: NFS3Prog.cpp プロジェクト: philr/winnfsd
nfsstat3 CNFS3Prog::ProcedureREADLINK(void)
{
    PrintLog("READLINK");
    char *path;
    char *pMBBuffer = 0;

    post_op_attr symlink_attributes;
    nfspath3 data = nfspath3();

    //opaque data;
    nfsstat3 stat;

    HANDLE hFile;
    REPARSE_DATA_BUFFER *lpOutBuffer;
    lpOutBuffer = (REPARSE_DATA_BUFFER*)malloc(MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
    DWORD bytesReturned;

    path = GetPath();
    stat = CheckFile(path);
    if (stat == NFS3_OK) {

        hFile = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_REPARSE_POINT | FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);

        if (hFile == INVALID_HANDLE_VALUE) {
            stat = NFS3ERR_IO;
        }
        else
        {
            lpOutBuffer = (REPARSE_DATA_BUFFER*)malloc(MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
            if (!lpOutBuffer) {
                stat = NFS3ERR_IO;
            }
            else {
                DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, NULL, 0, lpOutBuffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &bytesReturned, NULL);

                if (lpOutBuffer->ReparseTag == IO_REPARSE_TAG_SYMLINK || lpOutBuffer->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
                {
                    if (lpOutBuffer->ReparseTag == IO_REPARSE_TAG_SYMLINK)
                    {
                        size_t plen = lpOutBuffer->SymbolicLinkReparseBuffer.PrintNameLength / sizeof(WCHAR);
                        pMBBuffer = (char *)malloc((plen + 1));
                        WCHAR *szPrintName = new WCHAR[plen + 1];
                        wcsncpy_s(szPrintName, plen + 1, &lpOutBuffer->SymbolicLinkReparseBuffer.PathBuffer[lpOutBuffer->SymbolicLinkReparseBuffer.PrintNameOffset / sizeof(WCHAR)], plen);
                        szPrintName[plen] = 0;
                        size_t i;
                        wcstombs_s(&i, pMBBuffer, (plen + 1), szPrintName, (plen + 1));
                        // TODO: Revisit with cleaner solution
                        if (!PathIsRelative(pMBBuffer))
                        {
                            std::string strFromChar;
                            strFromChar.append("\\\\?\\");
                            strFromChar.append(pMBBuffer);
                            char *target = _strdup(strFromChar.c_str());
                            // remove last folder
                            char *pos = strrchr(path, '\\');
                            if (pos != NULL) {
                                *pos = '\0';
                            }
                            PathRelativePathTo(pMBBuffer, path, FILE_ATTRIBUTE_DIRECTORY, target, FILE_ATTRIBUTE_DIRECTORY);
                        }
                    }

                    // TODO: Revisit with cleaner solution
                    if (lpOutBuffer->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
                    {
                        size_t slen = lpOutBuffer->MountPointReparseBuffer.SubstituteNameLength / sizeof(WCHAR);
                        pMBBuffer = (char *)malloc((slen + 1));
                        WCHAR *szSubName = new WCHAR[slen + 1];
                        wcsncpy_s(szSubName, slen + 1, &lpOutBuffer->MountPointReparseBuffer.PathBuffer[lpOutBuffer->MountPointReparseBuffer.SubstituteNameOffset / sizeof(WCHAR)], slen);
                        szSubName[slen] = 0;
                        std::wstring wStringTemp(szSubName);
                        std::string target(wStringTemp.begin(), wStringTemp.end());
                        target.erase(0, 2);
                        target.insert(0, 2, '\\');
                        // remove last folder, see above
                        char *pos = strrchr(path, '\\');
                        if (pos != NULL) {
                            *pos = '\0';
                        }
                        PathRelativePathTo(pMBBuffer, path, FILE_ATTRIBUTE_DIRECTORY, target.c_str(), FILE_ATTRIBUTE_DIRECTORY);
                    }

                    // write path always with / separator, so windows created symlinks work too
                    std::string strFromChar;
                    strFromChar.append(pMBBuffer);
                    std::replace(strFromChar.begin(), strFromChar.end(), '\\', '/');
                    char *result = _strdup(strFromChar.c_str());

                    data.Set(result);
                    free(pMBBuffer);
                    free(result);
                }
                free(lpOutBuffer);
            }
        }
        CloseHandle(hFile);
    }

    symlink_attributes.attributes_follow = GetFileAttributesForNFS(path, &symlink_attributes.attributes);

    Write(&stat);
    Write(&symlink_attributes);
    if (stat == NFS3_OK) {
        Write(&data);
    }

    return stat;
}
コード例 #25
0
ファイル: registry.cpp プロジェクト: zwass/osquery
/// Microsoft helper function for getting the contents of a registry key
void queryKey(const std::string& hive,
              const std::string& key,
              QueryData& results) {
  if (kRegistryHives.count(hive) != 1) {
    return;
  }

  HKEY hRegistryHandle;
  auto ret = RegOpenKeyEx(kRegistryHives.at(hive),
                          TEXT(key.c_str()),
                          0,
                          KEY_READ,
                          &hRegistryHandle);

  if (ret != ERROR_SUCCESS) {
    return;
  }

  const DWORD maxKeyLength = 255;
  const DWORD maxValueName = 16383;
  TCHAR achClass[MAX_PATH] = TEXT("");
  DWORD cchClassName = MAX_PATH;
  DWORD cSubKeys = 0;
  DWORD cbMaxSubKey;
  DWORD cchMaxClass;
  DWORD cValues;
  DWORD cchMaxValueName;
  DWORD cbMaxValueData;
  DWORD cbSecurityDescriptor;
  DWORD retCode;
  FILETIME ftLastWriteTime;
  retCode = RegQueryInfoKey(hRegistryHandle,
                            achClass,
                            &cchClassName,
                            nullptr,
                            &cSubKeys,
                            &cbMaxSubKey,
                            &cchMaxClass,
                            &cValues,
                            &cchMaxValueName,
                            &cbMaxValueData,
                            &cbSecurityDescriptor,
                            &ftLastWriteTime);

  TCHAR achKey[maxKeyLength];
  DWORD cbName;

  // Process registry subkeys
  if (cSubKeys > 0) {
    for (DWORD i = 0; i < cSubKeys; i++) {
      cbName = maxKeyLength;
      retCode = RegEnumKeyEx(hRegistryHandle,
                             i,
                             achKey,
                             &cbName,
                             nullptr,
                             nullptr,
                             nullptr,
                             &ftLastWriteTime);
      if (retCode != ERROR_SUCCESS) {
        continue;
      }
      Row r;
      fs::path keyPath(key);
      r["hive"] = hive;
      r["key"] = keyPath.string();
      r["subkey"] = (keyPath / achKey).string();
      r["name"] = "(Default)";
      r["type"] = "REG_SZ";
      r["data"] = "(value not set)";
      r["mtime"] = std::to_string(osquery::filetimeToUnixtime(ftLastWriteTime));
      results.push_back(r);
    }
  }

  if (cValues <= 0) {
    return;
  }

  BYTE* bpDataBuff = new BYTE[cbMaxValueData];
  DWORD cchValue = maxKeyLength;
  TCHAR achValue[maxValueName];

  // Process registry values
  for (size_t i = 0, retCode = ERROR_SUCCESS; i < cValues; i++) {
    size_t cnt = 0;
    ZeroMemory(bpDataBuff, cbMaxValueData);
    cchValue = maxValueName;
    achValue[0] = '\0';

    retCode = RegEnumValue(hRegistryHandle,
                           static_cast<DWORD>(i),
                           achValue,
                           &cchValue,
                           nullptr,
                           nullptr,
                           nullptr,
                           nullptr);

    if (retCode != ERROR_SUCCESS) {
      continue;
    }

    DWORD lpData = cbMaxValueData;
    DWORD lpType;
    retCode = RegQueryValueEx(
        hRegistryHandle, achValue, 0, &lpType, bpDataBuff, &lpData);

    if (retCode != ERROR_SUCCESS) {
      continue;
    }

    Row r;
    fs::path keyPath(key);
    r["hive"] = hive;
    r["key"] = keyPath.string();
    r["subkey"] = keyPath.string();
    r["name"] = achValue;
    if (kRegistryTypes.count(lpType) > 0) {
      r["type"] = kRegistryTypes.at(lpType);
    } else {
      r["type"] = "UNKNOWN";
    }
    r["mtime"] = std::to_string(osquery::filetimeToUnixtime(ftLastWriteTime));

    bpDataBuff[cbMaxValueData - 1] = 0x00;

    /// REG_LINK is a Unicode string, which in Windows is wchar_t
    char* regLinkStr = nullptr;
    if (lpType == REG_LINK) {
      regLinkStr = new char[cbMaxValueData];
      const size_t newSize = cbMaxValueData;
      size_t convertedChars = 0;
      wcstombs_s(&convertedChars,
                 regLinkStr,
                 newSize,
                 (wchar_t*)bpDataBuff,
                 _TRUNCATE);
    }

    BYTE* bpDataBuffTmp = bpDataBuff;
    std::vector<std::string> multiSzStrs;
    std::vector<char> regBinary;
    std::string data;

    switch (lpType) {
    case REG_FULL_RESOURCE_DESCRIPTOR:
    case REG_RESOURCE_LIST:
    case REG_BINARY:
      for (unsigned int i = 0; i < cbMaxValueData; i++) {
        regBinary.push_back((char)bpDataBuff[i]);
      }
      boost::algorithm::hex(
          regBinary.begin(), regBinary.end(), std::back_inserter(data));
      r["data"] = data;
      break;
    case REG_DWORD:
      r["data"] = std::to_string(*((int*)bpDataBuff));
      break;
    case REG_DWORD_BIG_ENDIAN:
      r["data"] = std::to_string(_byteswap_ulong(*((int*)bpDataBuff)));
      break;
    case REG_EXPAND_SZ:
      r["data"] = std::string((char*)bpDataBuff);
      break;
    case REG_LINK:
      r["data"] = std::string(regLinkStr);
      break;
    case REG_MULTI_SZ:
      while (*bpDataBuffTmp != 0x00) {
        std::string s((char*)bpDataBuffTmp);
        bpDataBuffTmp += s.size() + 1;
        multiSzStrs.push_back(s);
      }
      r["data"] = boost::algorithm::join(multiSzStrs, ",");
      break;
    case REG_NONE:
      r["data"] = std::string((char*)bpDataBuff);
      break;
    case REG_QWORD:
      r["data"] = std::to_string(*((unsigned long long*)bpDataBuff));
      break;
    case REG_SZ:
      r["data"] = std::string((char*)bpDataBuff);
      break;
    default:
      r["data"] = "";
      break;
    }
    results.push_back(r);
    if (regLinkStr != nullptr) {
      delete[](regLinkStr);
    }
  }
  delete[](bpDataBuff);
  RegCloseKey(hRegistryHandle);
};
コード例 #26
0
bool D3DManager::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullScreen)
{
	HRESULT result;
	IDXGIFactory * factory = nullptr;
	IDXGIAdapter * adapter = nullptr;
	IDXGIOutput * adapterOutput = nullptr;
	unsigned int numModes;
	unsigned int numerator = 0;
	unsigned int denominator = 0;
	unsigned int stringLenht;
	DXGI_MODE_DESC * displayModeList = nullptr;
	DXGI_ADAPTER_DESC adapterDesc;
	int error;
	ID3D11Texture2D * backBuffer = nullptr;

	// Guardo el vsycn
	m_vsync_enable = vsync;

	// Creo una interfas con DirectX (IDXGIFactory)
	result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
	if (FAILED(result))
	{
		// TODO: Informar del Error
		return false;
	}

	// Uso el IDXGIFactory para crear un adapatador(Placa de Video)
	result = factory->EnumAdapters(0, &adapter);
	if (FAILED(result))
	{
		// TODO: Informar del Error
		return false;
	}

	// Enumero la cantidad de monitores (Adaptador de salida)
	result = adapter->EnumOutputs(0, &adapterOutput);
	if (FAILED(result))
	{
		// TODO: Informar del Error
		return false;
	}
	
	// Obtengo el numero de modos que se ajustan al formato DXGI_FORMAT_R8G8B8A8 para el monitor
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	if (FAILED(result))
	{
		// TODO: Informar del Error
		return false;
	}

	// Creo una lista con todos los posbles modos para esta combinacion placa de video monitor.
	displayModeList = new DXGI_MODE_DESC[numModes];

	// Cargo la lista de display Mode
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	if (FAILED(result))
	{
		// TODO: Informar del Error
		return false;
	}


	for (int i = 0; i < (int)numModes; ++i) 
	{

		if (displayModeList[i].Width == (unsigned int)screenWidth && displayModeList[i].Height == (unsigned int)screenHeight)
		{
			numerator = displayModeList[i].RefreshRate.Numerator;
			denominator = displayModeList[i].RefreshRate.Denominator;
			//TODO: Loquidar el for al encontrar el valor correcto
		}

	}


	if (numerator == 0 && denominator == 0)
	{
		// Informar Error
		return false;
	}

	// Obtengo la descripcion del adaptador
	result = adapter->GetDesc(&adapterDesc);
	if (FAILED(result))
	{
		// TODO: Informar del Error
		return false;
	}

	// Guardo la cantidad de memorya de video
	m_videoCardMemory = adapterDesc.DedicatedVideoMemory;

	// Convierto el nombre de la VGA a string
	char tmp_string[128];

	error = wcstombs_s(&stringLenht, tmp_string, 128, adapterDesc.Description, 128);
	if (error != 0)
	{
		// TODO: Informar del Error
		return false;
	}

	m_videoCardDescription = tmp_string;

	// Released Memory
	delete [] displayModeList;
	displayModeList = nullptr;

	adapterOutput->Release();
	adapterOutput = nullptr;

	adapter->Release();
	adapter = nullptr;

	factory->Release();
	factory = nullptr;


	if (!InitializeSwapChain(hwnd, fullScreen, screenWidth, screenHeight, numerator, denominator))
	{
		// Todo: Informar El Error
		return false;
	}

	// Obtengo el puntero al BackBuffer
	result = mp_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBuffer);
	if (FAILED(result))
	{
		// TODO: Informar del Error
		return false;
	}

	// Creo el render Target View
	result = mp_device->CreateRenderTargetView(backBuffer, NULL, &mp_renderTargetView);
	if (FAILED(result))
	{
		// TODO: Informar del Error
		return false;
	}

	// No te Nesesito MUERE
	backBuffer->Release();
	backBuffer = nullptr;

	if (!InitializeDepthBuffer(screenWidth, screenHeight)) 
	{
		// TODO: Informar del Error
		return false;
	}

	if (!InitializeDepthStencilBuffer())
	{
		// TODO: Informar del Error
		return false;
	}

	if (!InitializeStencilView()) 
	{
		// TODO: Informar del Error
		return false;
	}

	mp_deviceContext->OMSetRenderTargets(1, &mp_renderTargetView, mp_depthStencilView);
	if (!InitializeRasterizerStete())
	{
		// TODO: Informar del Error
		return false;
	}

	InitializeViewport(screenWidth, screenHeight);

	if (!InitializeAlphaBlending())
	{
		// TODO: Informar del Error
		return false;
	}

	if (!InitializeZBuffer()) 
	{
		// TODO: Informar del Error
		return false;
	}

	return true;
}
コード例 #27
0
STDAPI DllRegisterServer(void)
{   
    char       szID[128];
    WCHAR      wcID[128];
    char       szCLSID[128];
    TCHAR       szModule[MAX_PATH+ 1];
    char * pName = "WMI Sample Prop Provider";
    char * pModel = "Both";
	size_t * intReturnValue = NULL;
    HKEY hKey1, hKey2;

	 // Create the path.

	memset(wcID, NULL, sizeof(wcID));
	memset(szID, NULL, sizeof(szID));	

    StringFromGUID2(CLSID_PropProvider, wcID, sizeof(wcID)/sizeof(WCHAR) - 1);
    wcstombs_s(intReturnValue, szID, sizeof(szID), wcID,  sizeof(szID));
	StringCbCopy(szCLSID, sizeof(szCLSID), "Software\\classes\\CLSID\\");
	StringCbCat(szCLSID, sizeof(szCLSID), (LPCTSTR)szID);


    // Create entries under CLSID

	LONG lRet = RegCreateKeyEx( HKEY_LOCAL_MACHINE, szCLSID, 0, NULL,
                    REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, 
                    &hKey1, NULL );
	if (lRet != ERROR_SUCCESS)
	{
		return E_FAIL;
	}

    lRet = RegSetValueEx(hKey1, NULL, 0, REG_SZ, (BYTE *)pName, strlen(pName)+1);
	if (lRet != ERROR_SUCCESS)
	{
		RegCloseKey(hKey1);
		return E_FAIL;
	}

	lRet = RegCreateKeyEx( hKey1, "InprocServer32", 0, NULL,
                    REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, 
                    &hKey2, NULL );
	if (lRet != ERROR_SUCCESS)
	{
		RegCloseKey(hKey1);
		return E_FAIL;
	}

	memset(&szModule, NULL, sizeof(szModule));
    GetModuleFileName(ghModule, szModule,  sizeof(szModule)/sizeof(TCHAR) - 1);
    lRet = RegSetValueEx(hKey2, NULL, 0, REG_SZ, (BYTE *)szModule, 
                                        strlen(szModule)+1);
	if (lRet != ERROR_SUCCESS)
	{
	    RegCloseKey(hKey2);
		RegCloseKey(hKey1);
		return E_FAIL;
	}
    lRet = RegSetValueEx(hKey2, "ThreadingModel", 0, REG_SZ, 
                                        (BYTE *)pModel, strlen(pModel)+1);
	if (lRet != ERROR_SUCCESS)
	{
	    RegCloseKey(hKey2);
		RegCloseKey(hKey1);
		return E_FAIL;
	}
    RegCloseKey(hKey1);
    RegCloseKey(hKey2);

    return NOERROR;
  
}
コード例 #28
0
ファイル: D3D11.cpp プロジェクト: xfate/WaveGame
void D3D11::init( int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenDepth, float screenNear )
{
	m_vsyncEnabled = vsync;
	m_isWindows = fullscreen;
	IDXGIFactory * pfactory;
	if(FAILED(CreateDXGIFactory(__uuidof(IDXGIFactory),(void**)&pfactory)))
		return;

	IDXGIAdapter * pAdapter;
	if(FAILED(pfactory->EnumAdapters(0,&pAdapter)))
		return;

	IDXGIOutput * out;
	if(FAILED(pAdapter->EnumOutputs(0,&out)))
		return;

	int numModes;
	DXGI_MODE_DESC * displaymodeList;
	if(FAILED(out->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,DXGI_ENUM_MODES_INTERLACED,&numModes,NULL)))
		return;
	displaymodeList = new DXGI_MODE_DESC[numModes];
	if(FAILED(out->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,DXGI_ENUM_MODES_INTERLACED,&numModes,displaymodeList)))
		return;
	int numerator,denomerator;
	for(int i = 0; i < numModes; ++i)
	{
		if(displaymodeList[i].Height == screenHeight && displaymodeList[i].Width == screenWidth)
		{
			numerator = displaymodeList[i].RefreshRate.Numerator;
			denomerator = displaymodeList[i].RefreshRate.Denominator;
		}
	}

	DXGI_ADAPTER_DESC desc;
	if(FAILED(pAdapter->GetDesc(&desc)))
		return;
	int length;
	m_videoCardMemory = static_cast<int>(desc.DedicatedVideoMemory/1024/1024);
	wcstombs_s(&length,m_videoCardDescription,128,desc.Description,128);

	delete[] displaymodeList;
	displaymodeList = NULL;
	out->Release();
	out = NULL;
	pAdapter->Release();
	pAdapter = NULL;
	pfactory->Release();
	pfactory = NULL;

	DXGI_SWAP_CHAIN_DESC swapChainDesc;
	ZeroMemory(&swapChainDesc,sizeof(DXGI_SWAP_CHAIN_DESC));
	swapChainDesc.BufferCount = 1;
	swapChainDesc.BufferDesc.Width = screenWidth;
	swapChainDesc.BufferDesc.Height = screenHeight;
	swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	if(m_vsyncEnabled)
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = denomerator;
	}
	else
	{
		swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
		swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
	}

	swapChainDesc.Windowed = m_isWindows;
	swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
	swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

	D3D_FEATURE_LEVEL level =  D3D_FEATURE_LEVEL_11_0;
	if(FAILED(D3D11CreateDeviceAndSwapChain(NULL,D3D_DRIVER_TYPE_HARDWARE,NULL,0,
		&level,1,D3D11_SDK_VERSION,&swapChainDesc,&m_swapChain,&m_device,NULL,&m_deviceContext)))
		return;

	ID3D11Texture2D *backbufferTex;
	if(FAILED(m_swapChain->GetBuffer(0,__uuidof(ID3D11Texture2D),(LPVOID*)&backbufferTex)))
		return;
	if(FAILED(m_device->CreateRenderTargetView(backbufferTex,NULL,&m_renderView)))
		return;
	backbufferTex->Release();
	backbufferTex = 0;
	D3D11_TEXTURE2D_DESC depthBufferDesc;
	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

	depthBufferDesc.Width = screenWidth;
	depthBufferDesc.Height = screenHeight;
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 1;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;

	if(FAILED(m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer)))
		return ;
	D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
	// Initialize the description of the stencil state.
	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

	// Set up the description of the stencil state.
	depthStencilDesc.DepthEnable = true;
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0xFF;

	// Stencil operations if pixel is front-facing.
	depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Stencil operations if pixel is back-facing.
	depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Create the depth stencil state.
	if(FAILED(m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState)))
		return;
	// Set the depth stencil state.
	m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);

	D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
	// Initialize the depth stencil view.
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

	// Set up the depth stencil view description.
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	// Create the depth stencil view.
	if(FAILED(m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView)))
		return ;

	// Bind the render target view and depth stencil buffer to the output render pipeline.
	m_deviceContext->OMSetRenderTargets(1, &m_renderView, m_depthStencilView);

	D3D11_RASTERIZER_DESC rasterDesc;
	// Setup the raster description which will determine how and what polygons will be drawn.
	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_BACK;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = true;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	// Create the rasterizer state from the description we just filled out.
	if(FAILED(m_device->CreateRasterizerState(&rasterDesc, &m_rasterState)))
		return ;

	// Now set the rasterizer state.
	m_deviceContext->RSSetState(m_rasterState);

	D3D11_VIEWPORT viewport;
	// Setup the viewport for rendering.
	viewport.Width = (float)screenWidth;
	viewport.Height = (float)screenHeight;
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.TopLeftX = 0.0f;
	viewport.TopLeftY = 0.0f;

	// Create the viewport.
	m_deviceContext->RSSetViewports(1, &viewport);

	float fieldOfView, screenAspect;
	// Setup the projection matrix.
	fieldOfView = (float)D3DX_PI / 4.0f;
	screenAspect = (float)screenWidth / (float)screenHeight;

	// Create the projection matrix for 3D rendering.
	D3DXMatrixPerspectiveFovLH(&m_projMat, fieldOfView, screenAspect, screenNear, screenDepth);

	// Initialize the world matrix to the identity matrix.
	D3DXMatrixIdentity(&m_worldMat);

	// Create an orthographic projection matrix for 2D rendering.
	D3DXMatrixOrthoLH(&m_orthoMat, (float)screenWidth, (float)screenHeight, screenNear, screenDepth);


}
コード例 #29
0
ファイル: tinyXMLPrase.cpp プロジェクト: coder352/lineCircle
bool tinyXMLPrase()
{
	bool succeed = false;

	//ת»»¿í×Ö½Úµ½char
	setlocale(LC_ALL, "zh-CN");
	size_t len = wcslen(strFile) + 1;
	size_t converted = 0;
	char *CStr;
	CStr = (char*)malloc(len*sizeof(char)*2);
	wcstombs_s(&converted, CStr, len*2, strFile, len*2);

	TiXmlDocument * myDocument = new TiXmlDocument(CStr);

	myDocument->LoadFile();

	if (myDocument->Error())
	{
		MessageBox(theHWND, L"XML¶Áȡʧ°Ü", L"´íÎó", 0);
		return false;
	}
	
	try
	{
		TiXmlElement * RootElement = myDocument->RootElement();

		for (TiXmlElement * TestCase = RootElement->FirstChildElement();
				TestCase != NULL;
				TestCase = TestCase->NextSiblingElement())
		{
			int ID;
			TestCase->QueryIntAttribute("ID", &ID);
			if (ID != SETTING_XML_TESTCASE)
			{
				TestCase->Clear();
				continue;
			}
				

			succeed = true;

			for (TiXmlElement * DataNode = TestCase->FirstChildElement();
				DataNode != NULL;
				DataNode = DataNode->NextSiblingElement())
			{
				if (strcmp(DataNode->Value(), "Entity") == 0)
				{
					if (strcmp(DataNode->Attribute("Type"), "Line") == 0)
					{
						Line * line = (Line *)mempool->Alloc(sizeof(Line));

						for (TiXmlElement * pointNode = DataNode->FirstChildElement();
							pointNode != NULL;
							pointNode = pointNode->NextSiblingElement())
						{
							if (strcmp(pointNode->Value(), "StartPoint") == 0)
							{
								sscanf_s(pointNode->GetText(), "%hd,%hd", &line->x1, &line->y1);
							}
							else if (strcmp(pointNode->Value(), "EndPoint") == 0)
							{
								sscanf_s(pointNode->GetText(), "%hd,%hd", &line->x2, &line->y2);
							}
						}

						lineList.push_back(line);
					}
					else if (strcmp(DataNode->Attribute("Type"), "Circle") == 0)
					{
						Circle * circle = (Circle *)mempool->Alloc(sizeof(Circle));;

						for (TiXmlElement * pointNode = DataNode->FirstChildElement();
							pointNode != NULL;
							pointNode = pointNode->NextSiblingElement())
						{
							if (strcmp(pointNode->Value(), "CenterPoint") == 0)
							{
								sscanf_s(pointNode->GetText(), "%hd,%hd", &circle->x, &circle->y);
							}
							else if (strcmp(pointNode->Value(), "Radius") == 0)
							{
								sscanf_s(pointNode->GetText(), "%hd", &circle->r);
							}
						}

						circleList.push_back(circle);
					}
				}
				else if (strcmp(DataNode->Value(), "Boundary") == 0)
				{
					for (TiXmlElement * pointNode = DataNode->FirstChildElement();
						pointNode != NULL;
						pointNode = pointNode->NextSiblingElement())
					{
						if (strcmp(pointNode->Value(), "Vertex") != 0)
							continue;

						Point * point = (Point *)mempool->Alloc(sizeof(Point));
						sscanf_s(pointNode->GetText(), "%hd,%hd", &point->x, &point->y);
						
						polygonList.push_back(point);
					}
				}
				else
				{
					//Òì³££¬»¹ÊǺöÂÔÁË°É
				}
			}
		}
	}
	catch (...)
	{
		myDocument->Clear();
		delete(myDocument);
		MessageBox(theHWND, L"δ֪´íÎó", L"´íÎó", 0);
		return false;
	}
	

	if (!succeed)
	{
		myDocument->Clear();
		delete(myDocument);
		MessageBox(theHWND, L"ûÓÐÕÒµ½Êý¾Ý½Úµã", L"´íÎó", 0);
		return false;
	}
		
	myDocument->Clear();
	delete(myDocument);

	return true;
}
コード例 #30
-1
ファイル: D3D.cpp プロジェクト: IdiotCoderCodie/paper-planes
bool D3D::InitializeD3D(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen)
{
	HRESULT result; //used to test things are created ok.
    vsync;
    //----------------------------------------------------------------------------------------------
    // Fetch the numerator and denominator for refresh rate and video card description.
    // Create DirectX Graphics Interface factory.
	IDXGIFactory* factory;
    result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
    if(FAILED(result))
        return false;

    // Create adapter.
	IDXGIAdapter* adapter;
    result = factory->EnumAdapters(0, &adapter);
    if(FAILED(result))
        return false;

    // Enumerate primary adapter output (monitor).
	IDXGIOutput* adapterOutput;
    result = adapter->EnumOutputs(0, &adapterOutput);
    if(FAILED(result))
        return false;

    // Get the number of modes that fit the DXGI_R8G8B8A8_UNORM display format for adpater output.
    unsigned int numModes;
    result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 
                                DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
    if(FAILED(result))
        return false;

    // Create a list to hold all possible display modes.
    DXGI_MODE_DESC* displayModeList;
    displayModeList = new DXGI_MODE_DESC[numModes];
    if(!displayModeList)
        return false;

    // Fill list.
    result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 
                                DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
    if(FAILED(result))
        return false;

    // Loop through modes and find one that matches screen width and height, store numerator and
    // denominator for corresponding refresh rate.
    unsigned int numerator, denominator;
    for(unsigned int i = 0; i < numModes; ++i)
    {
        if(displayModeList[i].Width  == (unsigned int)screenWidth &&
           displayModeList[i].Height == (unsigned int)screenHeight)
        {
            numerator = displayModeList[i].RefreshRate.Numerator;
            denominator = displayModeList[i].RefreshRate.Denominator;
        }
    }

    // Get adapter description.
    DXGI_ADAPTER_DESC adapterDesc;
    result = adapter->GetDesc(&adapterDesc);
    if(FAILED(result))
        return false;

    // Store dedicated video card memory (in mb).
    m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

    // Convert the name of the video card to char array and store.
    unsigned int stringLength;
    int error = wcstombs_s(&stringLength, m_videoCardDesc, 128, adapterDesc.Description, 128);
    if(error != 0)
        return false;

    // Release unneeded memory.
    delete[] displayModeList;
    displayModeList = 0;

    adapterOutput->Release();
    adapterOutput = 0;

    adapter->Release();
    adapter = 0;

    factory->Release();
    factory = 0;
    //----------------------------------------------------------------------------------------------


    //----------------------------------------------------------------------------------------------
    // Set up SwapChain description and create swap chain.
    DXGI_SWAP_CHAIN_DESC swapChainDesc;
    ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
    
    // Setup back buffer.
    swapChainDesc.BufferCount       = 1;
    swapChainDesc.BufferDesc.Width  = screenWidth;
    swapChainDesc.BufferDesc.Height = screenHeight;
    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    // Refresh Rate.
    if(m_vsyncEnabled)
    {
        swapChainDesc.BufferDesc.RefreshRate.Numerator      = numerator;
        swapChainDesc.BufferDesc.RefreshRate.Denominator    = denominator;  
    }
    else
    { // Draw as soon as possible.
        swapChainDesc.BufferDesc.RefreshRate.Numerator      = 0;
        swapChainDesc.BufferDesc.RefreshRate.Denominator    = 1;
    }

    swapChainDesc.BufferUsage           = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    swapChainDesc.OutputWindow          = hwnd;
    // Turn off multisampling.
    swapChainDesc.SampleDesc.Count      = 1;
    swapChainDesc.SampleDesc.Quality    = 0;

    swapChainDesc.Windowed = !fullscreen;

    swapChainDesc.BufferDesc.ScanlineOrdering   = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
    swapChainDesc.BufferDesc.Scaling            = DXGI_MODE_SCALING_UNSPECIFIED;
    swapChainDesc.SwapEffect                    = DXGI_SWAP_EFFECT_DISCARD;
    swapChainDesc.Flags                         = 0;

    // Create the swap chain.
    D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;
    result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 
                1, D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, 
                &m_deviceContext);
    if(FAILED(result))
        return false;
    //----------------------------------------------------------------------------------------------


    //----------------------------------------------------------------------------------------------
    // Set up render target view.
    ID3D11Texture2D* backBufferPtr;
    result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
	if(FAILED(result))
		return false;

    // Create render target view with back buffer ptr.
    result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView);
    if(FAILED(result))
        return false;

    backBufferPtr->Release();
    backBufferPtr = 0;
    //----------------------------------------------------------------------------------------------


    //----------------------------------------------------------------------------------------------
    // Set up depthStencilBuffer.
	D3D11_TEXTURE2D_DESC depthBufferDesc;
    ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
    
    // Set up description.
    depthBufferDesc.Width               = screenWidth;
	depthBufferDesc.Height              = screenHeight;
	depthBufferDesc.MipLevels           = 1;
	depthBufferDesc.ArraySize           = 1;
	depthBufferDesc.Format              = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count    = 1;
	depthBufferDesc.SampleDesc.Quality  = 0;
	depthBufferDesc.Usage               = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags           = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags      = 0;
	depthBufferDesc.MiscFlags           = 0;

    // Create depth/stencil buffer.
    result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer);
    if(FAILED(result))
        return false;

    // Setup depth stencil description.
    D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
    ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
    
    depthStencilDesc.DepthEnable                    = true;
	depthStencilDesc.DepthWriteMask                 = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc                      = D3D11_COMPARISON_LESS;

	depthStencilDesc.StencilEnable                  = true;
	depthStencilDesc.StencilReadMask                = 0xFF;
	depthStencilDesc.StencilWriteMask               = 0xFF;

	depthStencilDesc.FrontFace.StencilFailOp        = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp   = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp        = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc          = D3D11_COMPARISON_ALWAYS;

	depthStencilDesc.BackFace.StencilFailOp         = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp    = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp         = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc           = D3D11_COMPARISON_ALWAYS;

    // Create depth stencil state.
    result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState);
    if(FAILED(result))
        return false;

    // Set depth stencil state.
    m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);
    //----------------------------------------------------------------------------------------------



    //----------------------------------------------------------------------------------------------
    // Create second depth stencil state with depth disabled. (for 2D rendering)
    D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
    ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));

    depthDisabledStencilDesc.DepthEnable                    = false;
	depthDisabledStencilDesc.DepthWriteMask                 = D3D11_DEPTH_WRITE_MASK_ALL;
	depthDisabledStencilDesc.DepthFunc                      = D3D11_COMPARISON_LESS;
	depthDisabledStencilDesc.StencilEnable                  = true;
	depthDisabledStencilDesc.StencilReadMask                = 0xFF;
	depthDisabledStencilDesc.StencilWriteMask               = 0xFF;
	depthDisabledStencilDesc.FrontFace.StencilFailOp        = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.FrontFace.StencilDepthFailOp   = D3D11_STENCIL_OP_DECR;
	depthDisabledStencilDesc.FrontFace.StencilPassOp        = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.FrontFace.StencilFunc          = D3D11_COMPARISON_ALWAYS;
	depthDisabledStencilDesc.BackFace.StencilFailOp         = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.BackFace.StencilDepthFailOp    = D3D11_STENCIL_OP_DECR;
	depthDisabledStencilDesc.BackFace.StencilPassOp         = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.BackFace.StencilFunc           = D3D11_COMPARISON_ALWAYS;

    result = m_device->CreateDepthStencilState(&depthDisabledStencilDesc, 
                            &m_depthDisabledStencilState);
    if(FAILED(result))
        return false;
    //----------------------------------------------------------------------------------------------


    //----------------------------------------------------------------------------------------------
    // Create description of the view of the depth stencil buffer.
    // Do this so D3D knows to use the depth buffer as a depth stencil texture.
    D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
    ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

    depthStencilViewDesc.Format             = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension      = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

    result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc,
                            &m_depthStencilView);
    if(FAILED(result))
        return false;

    // Bind render target view and depth stencil buffer to output render pipeline.
    m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);
    //----------------------------------------------------------------------------------------------


    //----------------------------------------------------------------------------------------------
    // Create rasterizer state and viewport.
    D3D11_RASTERIZER_DESC rasterDesc;
    rasterDesc.AntialiasedLineEnable    = false;
	rasterDesc.CullMode                 = D3D11_CULL_BACK;
	rasterDesc.DepthBias                = 0;
	rasterDesc.DepthBiasClamp           = 0.0f;
	rasterDesc.DepthClipEnable          = true;
	rasterDesc.FillMode                 = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise    = false;
	rasterDesc.MultisampleEnable        = false;
	rasterDesc.ScissorEnable            = false;
	rasterDesc.SlopeScaledDepthBias     = 0.0;

    result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState);
    if(FAILED(result))
        return false;

    m_deviceContext->RSSetState(m_rasterState);

    // Set up viewport.
    D3D11_VIEWPORT viewport;
    viewport.Width     = (float)screenWidth;
    viewport.Height    = (float)screenHeight;
    viewport.MinDepth  = 0.0f;
    viewport.MaxDepth  = 1.0f;
    viewport.TopLeftX  = 0.0f;
    viewport.TopLeftY  = 0.0f;

    m_deviceContext->RSSetViewports(1, &viewport);
    //----------------------------------------------------------------------------------------------


    //----------------------------------------------------------------------------------------------
    // Create blend states.
    D3D11_BLEND_DESC blendStateDesc;
    ZeroMemory(&blendStateDesc, sizeof(D3D11_BLEND_DESC));
    blendStateDesc.RenderTarget[0].BlendEnable           = TRUE;
    blendStateDesc.RenderTarget[0].SrcBlend              = D3D11_BLEND_ONE;
    blendStateDesc.RenderTarget[0].DestBlend             = D3D11_BLEND_ONE;
    blendStateDesc.RenderTarget[0].BlendOp               = D3D11_BLEND_OP_ADD;
    blendStateDesc.RenderTarget[0].SrcBlendAlpha         = D3D11_BLEND_ONE;
    blendStateDesc.RenderTarget[0].DestBlendAlpha        = D3D11_BLEND_ZERO;
    blendStateDesc.RenderTarget[0].BlendOpAlpha          = D3D11_BLEND_OP_ADD;
    blendStateDesc.RenderTarget[0].RenderTargetWriteMask = 0x0f;

    result = m_device->CreateBlendState(&blendStateDesc, &m_alphaEnableBlendingState);
    if(FAILED(result))
    {
        return false;
    }

    blendStateDesc.RenderTarget[0].BlendEnable = FALSE;
    result = m_device->CreateBlendState(&blendStateDesc, &m_alphaDisableBlendingState);
    if(FAILED(result))
    {
        return false;
    }
    //----------------------------------------------------------------------------------------------

    return true;
}