//----------------------------------------------------------------------------//
void CEGuiD3D10BaseApplication::cleanupDirect3D()
{
    if (pimpl->d_device)
    {
        // get render target view
        ID3D10RenderTargetView* rtview;
        pimpl->d_device->OMGetRenderTargets(1, &rtview, 0);

        if (rtview)
        {
            // we release once for the reference we just asked for
            rtview->Release();
            // we release again for the original reference made at creation.
            rtview->Release();
        }
        
        pimpl->d_swapChain->Release();
        pimpl->d_device->Release();

        pimpl->d_swapChain = 0;
        pimpl->d_device = 0;
    }
}
//----------------------------------------------------------------------------//
bool CEGuiD3D10BaseApplication::initialiseDirect3D(unsigned int width,
    unsigned int height, bool windowed)
{
    HRESULT res;

    // init sqap chain descriptor structure
    DXGI_SWAP_CHAIN_DESC scd;
    ZeroMemory(&scd, sizeof(scd));
    scd.BufferCount = 1;
    scd.BufferDesc.Width = width;
    scd.BufferDesc.Height = height;
    scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    scd.BufferDesc.RefreshRate.Numerator = 60;
    scd.BufferDesc.RefreshRate.Denominator = 1;
    scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    scd.OutputWindow = pimpl->d_window;
    scd.SampleDesc.Count = 1;
    scd.SampleDesc.Quality = 0;
    scd.Windowed = windowed;

    // initialise main parts of D3D
    res = D3D10CreateDeviceAndSwapChain(0, D3D10_DRIVER_TYPE_HARDWARE,
                                        0, 0, D3D10_SDK_VERSION,
                                        &scd, &pimpl->d_swapChain,
                                        &pimpl->d_device);
    if (SUCCEEDED(res))
    {

        // obtain handle to thr back buffer of the swap chain
        ID3D10Texture2D* back_buffer;
        res = pimpl->d_swapChain->GetBuffer(0, __uuidof(ID3D10Texture2D),
                                            (LPVOID*)&back_buffer);

        if (SUCCEEDED(res))
        {
            ID3D10RenderTargetView* rtview;

            // create render target view using the back buffer
            res = pimpl->d_device->
                CreateRenderTargetView(back_buffer, 0, &rtview);

            // release handle to buffer - we have done all we needed to with it.
            back_buffer->Release();

            if (SUCCEEDED(res))
            {
                // bind the back-buffer render target to get the output.
                pimpl->d_device->
                    OMSetRenderTargets(1, &rtview, 0);

                // set a basic viewport.
                D3D10_VIEWPORT view_port;
                view_port.Width    = width;
                view_port.Height   = height;
                view_port.MinDepth = 0.0f;
                view_port.MaxDepth = 1.0f;
                view_port.TopLeftX = 0;
                view_port.TopLeftY = 0;
                pimpl->d_device->RSSetViewports(1, &view_port);

                // complete window initialisation
                ShowWindow(pimpl->d_window, SW_NORMAL);
                UpdateWindow(pimpl->d_window);

                return true;
            }

            rtview->Release();
        }

        pimpl->d_swapChain->Release();
        pimpl->d_device->Release();
        pimpl->d_swapChain = 0;
        pimpl->d_device = 0;
    }

    MessageBox(0, "Failed to correctly initialise Direct3D 10",
               Win32AppHelper::APPLICATION_NAME, MB_ICONERROR|MB_OK);

    return false;
}
// Detour function that replaces the IDXGISwapChain::Present() API
DllExport HRESULT __stdcall
hook_DXGISwapChainPresent(
		IDXGISwapChain * This,
		UINT SyncInterval,
		UINT Flags
	)
{
	static int frame_interval;
	static LARGE_INTEGER initialTv, captureTv, freq;
	static int capture_initialized = 0;
	//
	int i;
	struct pooldata *data;
	struct vsource_frame *frame;
	//
	DXGI_SWAP_CHAIN_DESC pDESC;
	HRESULT hr = pDXGISwapChainPresent(This, SyncInterval, Flags);	
		
	if(resolution_retrieved == 0) {
		if(DXGI_get_resolution(This) >= 0) {
			resolution_retrieved = 1;
		}
		return hr;
	}
	
	if(vsource_initialized == 0) {
		ga_error("video source not initialized.\n");
		return hr;
	}
	
	This->GetDesc(&pDESC);
	pDXGI_FORMAT = pDESC.BufferDesc.Format;   // extract screen format for sws_scale
	
	if(pDESC.BufferDesc.Width != game_width
	|| pDESC.BufferDesc.Height != game_height) {
		ga_error("game width/height mismatched (%dx%d) != (%dx%d)\n",
			pDESC.BufferDesc.Width, pDESC.BufferDesc.Height,
			game_width, game_height);
		return hr;
	}
	
	//
	if (enable_server_rate_control && ga_hook_video_rate_control() < 0)
		return hr;
	
	if (dx_version == dx_none) {
		//bool check_result = FALSE;
		if (check_dx_device_version(This, IID_ID3D10Device)) {
			dx_version = dx_10;
			ga_error("[DXGISwapChain] DirectX 10\n");
		} else if (check_dx_device_version(This, IID_ID3D10Device1)) {
			dx_version = dx_10_1;
			ga_error("[DXGISwapChain] DirectX 10.1\n");
		} else if (check_dx_device_version(This, IID_ID3D11Device)) {
			dx_version = dx_11;
			ga_error("[DXGISwapChain] DirectX 11\n");
		}
	}
	
	if (capture_initialized == 0) {
		frame_interval = 1000000/video_fps; // in the unif of us
		frame_interval++;
		QueryPerformanceFrequency(&freq);
		QueryPerformanceCounter(&initialTv);
		capture_initialized = 1;
	} else {
		QueryPerformanceCounter(&captureTv);
	}

	hr = 0;

	// d3d10 / d3d10.1
	if (dx_version == dx_10 || dx_version == dx_10_1) {
		
		void *ppDevice;	
		ID3D10Device *pDevice;
		//IUnknown *pDevice;

		if (dx_version == dx_10) {
			This->GetDevice(IID_ID3D10Device, &ppDevice);
			pDevice = (ID3D10Device *)ppDevice;
		} else if (dx_version == dx_10_1) {
			This->GetDevice(IID_ID3D10Device1, &ppDevice);
			pDevice = (ID3D10Device1 *)ppDevice;
		} else {
			OutputDebugString("Invalid DirectX version in IDXGISwapChain::Present");
			return hr;
		}

		ID3D10RenderTargetView *pRTV = NULL;
		ID3D10Resource *pSrcResource = NULL;
		pDevice->OMGetRenderTargets(1, &pRTV, NULL);
		pRTV->GetResource(&pSrcResource);

		ID3D10Texture2D* pSrcBuffer = (ID3D10Texture2D *)pSrcResource;
		ID3D10Texture2D* pDstBuffer = NULL;

		D3D10_TEXTURE2D_DESC desc;
		pSrcBuffer->GetDesc(&desc);
		desc.BindFlags = 0;
		desc.CPUAccessFlags = D3D10_CPU_ACCESS_READ;
		desc.Usage = D3D10_USAGE_STAGING;

		hr = pDevice->CreateTexture2D(&desc, NULL, &pDstBuffer);
		if (FAILED(hr)) {
			OutputDebugString("Failed to create texture2D");
			//assert(exp_state == exp_none);
		}

		pDevice->CopyResource(pDstBuffer, pSrcBuffer);

		D3D10_MAPPED_TEXTURE2D mapped_screen;
		hr = pDstBuffer->Map(0, D3D10_MAP_READ, 0, &mapped_screen);
		if (FAILED(hr)) {
			OutputDebugString("Failed to map from DstBuffer");
			//assert(exp_state == exp_none);
		}

		// copy image 
		do {
			unsigned char *src, *dst;
			data = g_pipe[0]->allocate_data();
			frame = (struct vsource_frame*) data->ptr;
			frame->pixelformat = PIX_FMT_BGRA;
			frame->realwidth = desc.Width;
			frame->realheight = desc.Height;
			frame->realstride = desc.Width<<2;
			frame->realsize = frame->realwidth * frame->realstride;
			frame->linesize[0] = frame->realstride;//frame->stride;
			//
			src = (unsigned char*) mapped_screen.pData;
			dst = (unsigned char*) frame->imgbuf;
			for (i = 0; i < encoder_height; i++) {				
				CopyMemory(dst, src, frame->realstride/*frame->stride*/);
				src += mapped_screen.RowPitch;
				dst += frame->realstride;//frame->stride;
			}
			frame->imgpts = pcdiff_us(captureTv, initialTv, freq)/frame_interval;
		} while(0);
	
		// duplicate from channel 0 to other channels
		for(i = 1; i < SOURCES; i++) {
			int j;
			struct pooldata *dupdata;
			struct vsource_frame *dupframe;
			dupdata = g_pipe[i]->allocate_data();
			dupframe = (struct vsource_frame*) dupdata->ptr;
			//
			vsource_dup_frame(frame, dupframe);
			//
			g_pipe[i]->store_data(dupdata);
			g_pipe[i]->notify_all();
		}
		g_pipe[0]->store_data(data);
		g_pipe[0]->notify_all();
		
		pDstBuffer->Unmap(0);

		pDevice->Release();
		pSrcResource->Release();
		pSrcBuffer->Release();
		pRTV->Release();
		pDstBuffer->Release();

	// d11
	} else if (dx_version == dx_11) {
		void *ppDevice;	
		This->GetDevice(IID_ID3D11Device, &ppDevice);
		ID3D11Device *pDevice = (ID3D11Device*) ppDevice;

		This->GetDevice(IID_ID3D11DeviceContext, &ppDevice);
		ID3D11DeviceContext *pDeviceContext = (ID3D11DeviceContext *) ppDevice;
		
		ID3D11RenderTargetView *pRTV = NULL;
		ID3D11Resource *pSrcResource = NULL;
		pDeviceContext->OMGetRenderTargets(1, &pRTV, NULL);
		pRTV->GetResource(&pSrcResource);
	
		ID3D11Texture2D *pSrcBuffer = (ID3D11Texture2D *)pSrcResource;
		ID3D11Texture2D *pDstBuffer = NULL;
		
		D3D11_TEXTURE2D_DESC desc;
		pSrcBuffer->GetDesc(&desc);
		desc.BindFlags = 0;
		desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
		desc.Usage = D3D11_USAGE_STAGING;

		hr = pDevice->CreateTexture2D(&desc, NULL, &pDstBuffer);
		if (FAILED(hr)) {
			OutputDebugString("Failed to create buffer");
			//assert(exp_state == exp_none);
		}
		pDeviceContext->CopyResource(pDstBuffer, pSrcBuffer);

		D3D11_MAPPED_SUBRESOURCE mapped_screen;
		hr = pDeviceContext->Map(pDstBuffer, 0, D3D11_MAP_READ, 0, &mapped_screen);
		if (FAILED(hr)) {
			OutputDebugString("Failed to map from DeviceContext");
			//assert(exp_state == exp_none);
		}
		
		// copy image 
		do {
			unsigned char *src, *dst;
			data = g_pipe[0]->allocate_data();
			frame = (struct vsource_frame*) data->ptr;
			frame->pixelformat = PIX_FMT_BGRA;
			frame->realwidth = desc.Width;
			frame->realheight = desc.Height;
			frame->realstride = desc.Width<<2;
			frame->realsize = frame->realwidth * frame->realstride;
			frame->linesize[0] = frame->realstride;//frame->stride;
			//
			src = (unsigned char*) mapped_screen.pData;
			dst = (unsigned char*) frame->imgbuf;
			for (i = 0; i < encoder_height; i++) {				
				CopyMemory(dst, src, frame->realstride/*frame->stride*/);
				src += mapped_screen.RowPitch;
				dst += frame->realstride;//frame->stride;
			}
			frame->imgpts = pcdiff_us(captureTv, initialTv, freq)/frame_interval;
		} while(0);
	
		// duplicate from channel 0 to other channels
		for(i = 1; i < SOURCES; i++) {
			int j;
			struct pooldata *dupdata;
			struct vsource_frame *dupframe;
			dupdata = g_pipe[i]->allocate_data();
			dupframe = (struct vsource_frame*) dupdata->ptr;
			//
			vsource_dup_frame(frame, dupframe);
			//
			g_pipe[i]->store_data(dupdata);
			g_pipe[i]->notify_all();
		}
		g_pipe[0]->store_data(data);
		g_pipe[0]->notify_all();

		pDeviceContext->Unmap(pDstBuffer, 0);

		pDevice->Release();
		pDeviceContext->Release();
		pSrcResource->Release();
		pSrcBuffer->Release();
		pRTV->Release();
		pDstBuffer->Release();
	}

	return hr;
}
//----------------------------------------------------------------------------//
bool CEGuiD3D10BaseApplication::execute(CEGuiSample* sampleApp)
{
    sampleApp->initialiseSample();

    float clear_colour[4] = { 0.0f, 0.0f, 0.0f, 1.0f };

    //
    //  This is basically a modified Win32 message pump
    //
    bool idle;

    while (Win32AppHelper::doWin32Events(idle))
    {
        if (idle)
        {
            CEGUI::System& guiSystem = CEGUI::System::getSingleton();

            // do time based updates
            DWORD thisTime = GetTickCount();
            float elapsed = static_cast<float>(thisTime - d_lastFrameTime);
            d_lastFrameTime = thisTime;
            // inject the time pulse
            guiSystem.injectTimePulse(elapsed / 1000.0f);

            updateFPS();
            char fpsbuff[16];
            sprintf(fpsbuff, "FPS: %d", d_FPS);

            Win32AppHelper::doDirectInputEvents(pimpl->d_directInput);

            // get render target view
            // this is a bit wasteful, but done like this for now since the
            // resize code can change the view from under us.
            ID3D10RenderTargetView* rtview;
            pimpl->d_device->OMGetRenderTargets(1, &rtview, 0);

            // clear display
            pimpl->d_device->ClearRenderTargetView(rtview, clear_colour);

            // main CEGUI rendering call
            guiSystem.renderGUI();

            // render FPS:
            CEGUI::Font* fnt = guiSystem.getDefaultFont();
            if (fnt)
            {
                guiSystem.getRenderer()->setQueueingEnabled(false);
                fnt->drawText(fpsbuff, CEGUI::Vector3(0, 0, 0),
                              guiSystem.getRenderer()->getRect());
            }

            pimpl->d_swapChain->Present(0, 0);
            rtview->Release();
        }

        // check if the application is quitting, and break the loop next time
        // around if so.
        if (isQuitting())
            PostQuitMessage(0);
    }

    return true;
}
예제 #5
0
void DXMessD3D10Handler::RenderOverlay()
{
	int i;
	if (Valid)
	{
		//render the overlay
		POINT clientMousepos;
		BOOL hasLock=FALSE;

		clientMousepos.x=-1;
		clientMousepos.y=-1;

		//check if the overlay has an update
		//if so, first update the texture		

		DXGI_SWAP_CHAIN_DESC desc;
		swapchain->GetDesc(&desc);
		shared->lastHwnd=(DWORD)desc.OutputWindow;

		if (shared->texturelistHasUpdate)
			UpdateTextures();

		
		UINT stride = sizeof( SpriteVertex );
		UINT offset = 0;
		float blendFactor[] = {0.0f, 0.0f, 0.0f, 0.0f};

		ID3D10VertexShader *oldvs=NULL;
		ID3D10PixelShader *oldps=NULL;
		ID3D10GeometryShader *oldgs=NULL;

		ID3D10SamplerState *oldPSSampler=NULL;
		ID3D10ShaderResourceView *oldPSShaderResource=NULL;
		ID3D10BlendState *oldBlendState=NULL;
		float oldblendFactor[4];
		UINT oldblendsamplemask;

		ID3D10DepthStencilState *oldDepthStencilState=NULL;
		UINT oldstencilref;

		D3D10_PRIMITIVE_TOPOLOGY oldPrimitiveTopology;

		ID3D10InputLayout *oldInputLayout=NULL;
		ID3D10Buffer *oldIndexBuffer=NULL;
		DXGI_FORMAT oldIndexBufferFormat;
		UINT oldIndexBufferOffset;

		ID3D10Buffer *oldVertexBuffer=NULL;
		UINT oldVertexBufferStrides;
		UINT oldVertexBufferOffset;

		ID3D10RasterizerState *oldRastersizerState=NULL;
		ID3D10RenderTargetView *oldRenderTarget;
		ID3D10DepthStencilView *oldDepthStencilView=NULL;

		ID3D10Buffer *oldConstantBuffersVS=NULL;
		ID3D10Buffer *oldConstantBuffersPS=NULL;

		D3D10_VIEWPORT vp;
		UINT oldviewports=0;
		D3D10_VIEWPORT viewports[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];

		//save state
		
		dev->VSGetShader( &oldvs);
		

		dev->VSGetConstantBuffers(0,1, &oldConstantBuffersVS);
		

		dev->GSGetShader(&oldgs);

		dev->PSGetShader( &oldps);
		dev->PSGetSamplers(0,1, &oldPSSampler);
		dev->PSGetShaderResources(0,1, &oldPSShaderResource);
		dev->PSGetConstantBuffers(0,1, &oldConstantBuffersPS);

		
		

		dev->OMGetRenderTargets(1, &oldRenderTarget, &oldDepthStencilView);
		dev->OMGetBlendState( &oldBlendState, oldblendFactor, &oldblendsamplemask);
		dev->OMGetDepthStencilState( &oldDepthStencilState, &oldstencilref);
		
	

		
		dev->IAGetPrimitiveTopology(&oldPrimitiveTopology);
		dev->IAGetInputLayout(&oldInputLayout);
		dev->IAGetIndexBuffer( &oldIndexBuffer, &oldIndexBufferFormat, &oldIndexBufferOffset);
		dev->IAGetVertexBuffers(0,1,&oldVertexBuffer, &oldVertexBufferStrides, &oldVertexBufferOffset);

		

		dev->RSGetState(&oldRastersizerState);

		
		
		dev->RSGetViewports(&oldviewports, NULL);
		dev->RSGetViewports(&oldviewports, viewports);

		

		//change state
		dev->GSSetShader(NULL); //not used
	    dev->VSSetShader(pVertexShader);
		dev->PSSetShader(pPixelShaderNormal);
		dev->PSSetSamplers( 0, 1, &pSamplerLinear );



		

		
		vp.Width = desc.BufferDesc.Width;
		vp.Height = desc.BufferDesc.Height;
		vp.MinDepth = 0.0f;
		vp.MaxDepth = 1.0f;
		vp.TopLeftX = 0;
		vp.TopLeftY = 0;
		dev->RSSetViewports( 1, &vp );
		

		dev->OMSetRenderTargets(1, &pRenderTargetView, NULL); //pDepthStencilView);		
		dev->ClearDepthStencilView( pDepthStencilView, D3D10_CLEAR_DEPTH, 1.0f, 0 );

		dev->OMSetBlendState(pTransparency, blendFactor, 0xffffffff);
		dev->OMSetDepthStencilState(pDisabledDepthStencilState, 0);;

		

		dev->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
		dev->IASetInputLayout( pVertexLayout );
	
//		dev->IASetIndexBuffer( pSpriteIB, DXGI_FORMAT_R16_UINT, 0 );
		dev->IASetIndexBuffer( NULL, DXGI_FORMAT_R16_UINT, 0 );
		

		dev->RSSetState(pSpriteRasterizer);

		
		if (shared->UseCommandlistLock)
			hasLock=WaitForSingleObject((HANDLE)shared->CommandlistLock, INFINITE)==WAIT_OBJECT_0;

		i=0;
		while (shared->RenderCommands[i].Command)
		{
			switch (shared->RenderCommands[i].Command)
			{
				case rcDrawSprite:
				{
					if (shared->RenderCommands[i].sprite.textureid<TextureCount)
					{
					
						XMFLOAT3 position;				

						dev->IASetVertexBuffers( 0, 1, &pSpriteVB, &stride, &offset );
						dev->PSSetShader( pPixelShaderNormal);

						dev->PSSetSamplers( 0, 1, &pSamplerLinear );						
						dev->PSSetShaderResources( 0, 1, &textures[shared->RenderCommands[i].sprite.textureid].pTexture );

						if (shared->RenderCommands[i].x==-1) //center	
						{
							position.x=((float)vp.Width / 2.0f) - ((float)shared->RenderCommands[i].sprite.width / 2.0f);						
						}
						else
						if (shared->RenderCommands[i].x==-2) //mouse
						{
							if (clientMousepos.x==-1)
							{
								//get the mouse position
								GetCursorPos(&clientMousepos);
								ScreenToClient((HWND)shared->lastHwnd, &clientMousepos);	
							}

							position.x=(float)clientMousepos.x-((float)shared->RenderCommands[i].sprite.width / 2.0f); 
						}
						else
							position.x=(float)shared->RenderCommands[i].x;


						if (shared->RenderCommands[i].y==-1) //center
						{
							position.y=((float)vp.Height / 2.0f) - ((float)shared->RenderCommands[i].sprite.height / 2.0f);
						}
						else
						if (shared->RenderCommands[i].y==-2) //mouse
						{
							if (clientMousepos.y==-1)
							{
								//get the mouse position
								GetCursorPos(&clientMousepos);
								ScreenToClient((HWND)shared->lastHwnd, &clientMousepos);	
							}
							position.y=(float)clientMousepos.y-((float)shared->RenderCommands[i].sprite.height / 2.0f);	

						}
						else
							position.y=(float)shared->RenderCommands[i].y;


						//truncate the position to an exact pixel
						position.x=(float)(int)position.x;
						position.y=(float)(int)position.y;

			
						ConstantBuffer cb;					
						cb.transparency=shared->RenderCommands[i].alphablend;

						if (shared->RenderCommands[i].sprite.width==-1)
							cb.scaling.x=(float)vp.Width/(float)vp.Width; //1.0
						else						
							cb.scaling.x=(float)shared->RenderCommands[i].sprite.width/(float)vp.Width;

						cb.scaling.y=(float)shared->RenderCommands[i].sprite.height/(float)vp.Height;
	
						cb.translation.x=-1.0f+((float)((float)position.x * 2)/(float)vp.Width);
						cb.translation.y=-1.0f+((float)((float)position.y * 2)/(float)vp.Height);

						dev->UpdateSubresource( pConstantBuffer, 0, NULL, &cb, 0, 0 );

						dev->VSSetConstantBuffers(0,1, &pConstantBuffer);
						dev->PSSetConstantBuffers(0,1, &pConstantBuffer);


						
						
						dev->Draw(6,0);
					
					}
				
					break;
				}

				case rcDrawFont:
				{
					int tid=shared->RenderCommands[i].font.fontid;							

					if ((tid<TextureCount) && (textures[tid].pTexture))
					{
							
						XMFLOAT3 position;	
						PTextureData10 td;
						char *s;

						if (!hasLock)
							hasLock=WaitForSingleObject((HANDLE)shared->CommandlistLock, INFINITE)==WAIT_OBJECT_0; //fonts demand a lock  (stringpointer)

						position.x=(float)shared->RenderCommands[i].x;
						position.y=(float)shared->RenderCommands[i].y;		

						td=&textures[tid];
						s=(char *)shared->RenderCommands[i].font.addressoftext;

						if (position.x==-1) 
						{
							//horizontal center
							//calculate the width
							float width=0;
							int slen=strlen(s);
							int j;

							for (j=0; j<slen; j++)
							{
								width+=td->DefinedFontMap->charinfo[32-j].charwidth;
							}
							position.x=((float)vp.Width / 2.0f) - ((float)width / 2.0f);
							
						}

						if (position.y==-1)
						{						
							//vertical center						
							position.y=((float)vp.Height / 2.0f) - ((float)td->DefinedFontMap->charheight / 2.0f);
						}

						//truncate the position to an exact pixel
						position.x=(float)(int)position.x;
						position.y=(float)(int)position.y;

					
						dev->PSSetShader( pPixelShaderNormal);
						dev->PSSetSamplers( 0, 1, &pSamplerLinear );						
						

						ConstantBuffer cb;					
						cb.transparency=shared->RenderCommands[i].alphablend;						
						cb.scaling.x=1.0f;
						cb.scaling.y=1.0f;//if you wish a bigger font, use a bigger font, don't scale (ugly)
						
						cb.translation.x=-1.0f;
						cb.translation.y=-1.0f;

						cb.translation.x=-1.0f+((float)((float)position.x * 2)/(float)vp.Width);
						cb.translation.y=-1.0f+((float)((float)position.y * 2)/(float)vp.Height);


						dev->UpdateSubresource( pConstantBuffer, 0, NULL, &cb, 0, 0 );

						dev->VSSetConstantBuffers(0,1, &pConstantBuffer);
						dev->PSSetConstantBuffers(0,1, &pConstantBuffer);

						DrawString(vp, &textures[tid], s,strlen(s));
					}

					
					break;
				}
			}

			i++;				
		}

		if (hasLock) //release the lock if it was obtained
			SetEvent((HANDLE)shared->CommandlistLock);


		//restore
		dev->GSSetShader(oldgs);
		if (oldgs)
			oldgs->Release();

		dev->VSSetShader(oldvs);
		if (oldvs)
			oldvs->Release();

		dev->PSSetShader(oldps);
		if (oldps)
			oldps->Release();

		dev->PSSetSamplers(0, 1, &oldPSSampler);
		if (oldPSSampler)
			oldPSSampler->Release();
			
		dev->PSSetShaderResources(0,1, &oldPSShaderResource);
		if (oldPSShaderResource)
			oldPSShaderResource->Release();

		dev->VSSetConstantBuffers(0,1, &oldConstantBuffersVS);
		if (oldConstantBuffersVS)
			oldConstantBuffersVS->Release();


		dev->PSSetConstantBuffers(0,1, &oldConstantBuffersPS);
		if (oldConstantBuffersPS)
			oldConstantBuffersPS->Release();

		dev->OMSetRenderTargets(1, &oldRenderTarget, oldDepthStencilView);
		if (oldRenderTarget)
			oldRenderTarget->Release();

		if (oldDepthStencilView)
			oldDepthStencilView->Release();

		dev->OMSetBlendState(oldBlendState, oldblendFactor, oldblendsamplemask);
		if (oldBlendState)
			oldBlendState->Release();

		dev->OMSetDepthStencilState(oldDepthStencilState, oldstencilref);
		if (oldDepthStencilState)
			oldDepthStencilState->Release();

		
		dev->IASetPrimitiveTopology(oldPrimitiveTopology);
		dev->IASetInputLayout(oldInputLayout);
		if (oldInputLayout)
			oldInputLayout->Release();

		dev->IASetIndexBuffer(oldIndexBuffer, oldIndexBufferFormat, oldIndexBufferOffset);
		if (oldIndexBuffer)
			oldIndexBuffer->Release();

		dev->IASetVertexBuffers(0,1,&oldVertexBuffer, &oldVertexBufferStrides, &oldVertexBufferOffset);
		if (oldVertexBuffer)
			oldVertexBuffer->Release();

		dev->RSSetState(oldRastersizerState);
		if (oldRastersizerState)
			oldRastersizerState->Release();

		dev->RSSetViewports(oldviewports, viewports);
	}

}
//----------------------------------------------------------------------------//
void DeviceReset_Direct3D10(HWND window, CEGUI::Renderer* renderer)
{
    // this is the 'other side' of our earlier hack to save from having to
    // totally rewrite the samples framework.
    //
    // Extract the pointer to the CEGuiD3D10BaseApplication from the window
    //CEGuiD3D10BaseApplication* app =
    //    reinterpret_cast<CEGuiD3D10BaseApplication*>(
    //        GetWindowLongPtr(window,GWLP_USERDATA));

    IDXGISwapChain* swap_chain = reinterpret_cast<IDXGISwapChain*>(
        GetWindowLongPtr(window, GWLP_USERDATA));

    // if the swap_chain pointer is 0, something obviously is amiss, so bail
    if (!swap_chain)
        return;

    CEGUI::Direct3D10Renderer* d3d_renderer =
        static_cast<CEGUI::Direct3D10Renderer*>(renderer);

    ID3D10Device& d3d_device = d3d_renderer->getDirect3DDevice();

    ID3D10RenderTargetView* rtview;
    d3d_device.OMGetRenderTargets(1, &rtview, 0);

    // we release once for the reference we just asked for
    rtview->Release();
    // we release again for the original reference made at creation.
    rtview->Release();

    if (FAILED(swap_chain->ResizeBuffers(1, 0, 0, 
                                         DXGI_FORMAT_R8G8B8A8_UNORM, 0)))
    {
        CEGUI::Logger::getSingleton().logEvent("Direct3D 10: Failed to resize "
            "swap chain buffers.", CEGUI::Errors);

        return;
    }

    RECT wnd_rect;
    GetClientRect(window, &wnd_rect);

    int width  = wnd_rect.right;// - wnd_rect.left;
    int height = wnd_rect.bottom;// - wnd_rect.top;

    HRESULT res;
    // obtain handle to thr back buffer of the swap chain
    ID3D10Texture2D* back_buffer;
    res = swap_chain->GetBuffer(0, __uuidof(ID3D10Texture2D),
                                (LPVOID*)&back_buffer);

    if (SUCCEEDED(res))
    {
        // create render target view using the back buffer
        res = d3d_device.CreateRenderTargetView(back_buffer, 0, &rtview);

        // release handle to buffer - we have done all we needed to with it.
        back_buffer->Release();

        if (SUCCEEDED(res))
        {
            // bind the back-buffer render target to get the output.
            d3d_device.OMSetRenderTargets(1, &rtview, 0);

            // set a basic viewport.
            D3D10_VIEWPORT view_port;
            view_port.Width    = width;
            view_port.Height   = height;
            view_port.MinDepth = 0.0f;
            view_port.MaxDepth = 1.0f;
            view_port.TopLeftX = 0;
            view_port.TopLeftY = 0;
            d3d_device.RSSetViewports(1, &view_port);

            // notify CEGUI of change.
            CEGUI::System::getSingleton().notifyDisplaySizeChanged(
                CEGUI::Size((float)width, (float)height));
        }
    }
}
예제 #7
0
int
main(int argc, char *argv[])
{
    HRESULT hr;

    HINSTANCE hInstance = GetModuleHandle(NULL);

    WNDCLASSEX wc = {
        sizeof(WNDCLASSEX),
        CS_CLASSDC,
        DefWindowProc,
        0,
        0,
        hInstance,
        NULL,
        NULL,
        NULL,
        NULL,
        "SimpleDX10",
        NULL
    };
    RegisterClassEx(&wc);

    const int WindowWidth = 250;
    const int WindowHeight = 250;
    BOOL Windowed = TRUE;

    DWORD dwStyle = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW;

    RECT rect = {0, 0, WindowWidth, WindowHeight};
    AdjustWindowRect(&rect, dwStyle, FALSE);

    HWND hWnd = CreateWindow(wc.lpszClassName,
                             "Simple example using DirectX10",
                             dwStyle,
                             CW_USEDEFAULT, CW_USEDEFAULT,
                             rect.right - rect.left,
                             rect.bottom - rect.top,
                             NULL,
                             NULL,
                             hInstance,
                             NULL);
    if (!hWnd) {
        return 1;
    }

    ShowWindow(hWnd, SW_SHOW);

    UINT Flags = 0;
    if (LoadLibraryA("d3d10sdklayers")) {
        Flags |= D3D10_CREATE_DEVICE_DEBUG;
    }

    hr = CreateDXGIFactory1(IID_IDXGIFactory1, (void**)(&g_pFactory) );
    if (FAILED(hr)) {
        return 1;
    }

    hr = g_pFactory->EnumAdapters(0, &g_pAdapter);
    if (FAILED(hr)) {
        return 1;
    }

    hr = D3D10CreateDevice1(g_pAdapter,
                            D3D10_DRIVER_TYPE_HARDWARE,
                            NULL,
                            Flags,
                            D3D10_FEATURE_LEVEL_10_0,
                            D3D10_1_SDK_VERSION,
                            &g_pDevice);
    if (FAILED(hr)) {
        return 1;
    }

    DXGI_SWAP_CHAIN_DESC SwapChainDesc;
    ZeroMemory(&SwapChainDesc, sizeof SwapChainDesc);
    SwapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;;
    SwapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
    SwapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
    SwapChainDesc.SampleDesc.Quality = 0;
    SwapChainDesc.SampleDesc.Count = 1;
    SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    SwapChainDesc.BufferCount = 2;
    SwapChainDesc.OutputWindow = hWnd;
    SwapChainDesc.Windowed = true;
    SwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

    hr = g_pFactory->CreateSwapChain(g_pDevice, &SwapChainDesc, &g_pSwapChain);
    if (FAILED(hr)) {
        return 1;
    }

    ID3D10RenderTargetView *pRenderTargetView = NULL;
    ID3D10Texture2D* pBackBuffer;
    hr = g_pSwapChain->GetBuffer(0, IID_ID3D10Texture2D, (void **)&pBackBuffer);
    if (FAILED(hr)) {
        return 1;
    }
    D3D10_RENDER_TARGET_VIEW_DESC RenderTargetViewDesc;
    ZeroMemory(&RenderTargetViewDesc, sizeof RenderTargetViewDesc);
    RenderTargetViewDesc.Format = SwapChainDesc.BufferDesc.Format;
    RenderTargetViewDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
    RenderTargetViewDesc.Texture2D.MipSlice = 0;
    hr = g_pDevice->CreateRenderTargetView(pBackBuffer, &RenderTargetViewDesc, &pRenderTargetView);
    if (FAILED(hr)) {
        return 1;
    }
    pBackBuffer->Release();

    g_pDevice->OMSetRenderTargets(1, &pRenderTargetView, NULL);

    const float clearColor[4] = { 0.3f, 0.1f, 0.3f, 1.0f };
    g_pDevice->ClearRenderTargetView(pRenderTargetView, clearColor);

    ID3D10VertexShader * pVertexShader;
    hr = g_pDevice->CreateVertexShader(g_VS, sizeof g_VS, &pVertexShader);
    if (FAILED(hr)) {
        return 1;
    }

    struct Vertex {
        float position[4];
        float color[4];
    };

    static const D3D10_INPUT_ELEMENT_DESC InputElementDescs[] = {
        { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, offsetof(Vertex, position), D3D10_INPUT_PER_VERTEX_DATA, 0 },
        { "COLOR",    0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, offsetof(Vertex, color),    D3D10_INPUT_PER_VERTEX_DATA, 0 }
    };

    ID3D10InputLayout *pVertexLayout = NULL;
    hr = g_pDevice->CreateInputLayout(InputElementDescs,
                                      2,
                                      g_VS,
                                      sizeof g_VS,
                                      &pVertexLayout);
    if (FAILED(hr)) {
        return 1;
    }

    g_pDevice->IASetInputLayout(pVertexLayout);

    ID3D10PixelShader * pPixelShader;
    hr = g_pDevice->CreatePixelShader(g_PS, sizeof g_PS, &pPixelShader);
    if (FAILED(hr)) {
        return 1;
    }

    g_pDevice->VSSetShader(pVertexShader);
    g_pDevice->PSSetShader(pPixelShader);

    static const Vertex vertices[] = {
        { { -0.9f, -0.9f, 0.5f, 1.0f}, { 0.8f, 0.0f, 0.0f, 0.1f } },
        { {  0.9f, -0.9f, 0.5f, 1.0f}, { 0.0f, 0.9f, 0.0f, 0.1f } },
        { {  0.0f,  0.9f, 0.5f, 1.0f}, { 0.0f, 0.0f, 0.7f, 0.1f } },
    };

    D3D10_BUFFER_DESC BufferDesc;
    ZeroMemory(&BufferDesc, sizeof BufferDesc);
    BufferDesc.Usage = D3D10_USAGE_DYNAMIC;
    BufferDesc.ByteWidth = sizeof vertices;
    BufferDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
    BufferDesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
    BufferDesc.MiscFlags = 0;

    ID3D10Buffer *pVertexBuffer;
    hr = g_pDevice->CreateBuffer(&BufferDesc, NULL, &pVertexBuffer);
    if (FAILED(hr)) {
        return 1;
    }

    void *pMap = NULL;
    pVertexBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &pMap);
    memcpy(pMap, vertices, sizeof vertices);
    pVertexBuffer->Unmap();

    UINT Stride = sizeof(Vertex);
    UINT Offset = 0;
    g_pDevice->IASetVertexBuffers(0, 1, &pVertexBuffer, &Stride, &Offset);
    
    D3D10_VIEWPORT ViewPort;
    ViewPort.TopLeftX = 0;
    ViewPort.TopLeftY = 0;
    ViewPort.Width = WindowWidth;
    ViewPort.Height = WindowHeight;
    ViewPort.MinDepth = 0.0f;
    ViewPort.MaxDepth = 1.0f;
    g_pDevice->RSSetViewports(1, &ViewPort);
    
    D3D10_RASTERIZER_DESC RasterizerDesc;
    ZeroMemory(&RasterizerDesc, sizeof RasterizerDesc);
    RasterizerDesc.CullMode = D3D10_CULL_NONE;
    RasterizerDesc.FillMode = D3D10_FILL_SOLID;
    RasterizerDesc.FrontCounterClockwise = true;
    RasterizerDesc.DepthClipEnable = true;
    ID3D10RasterizerState* pRasterizerState = NULL;
    hr = g_pDevice->CreateRasterizerState(&RasterizerDesc, &pRasterizerState);
    if (FAILED(hr)) {
        return 1;
    }
    g_pDevice->RSSetState(pRasterizerState);

    g_pDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
    g_pDevice->Draw(3, 0);

    g_pSwapChain->Present(0, 0);


    ID3D10Buffer *pNullBuffer = NULL;
    UINT NullStride = 0;
    UINT NullOffset = 0;
    g_pDevice->IASetVertexBuffers(0, 1, &pNullBuffer, &NullStride, &NullOffset);
    pVertexBuffer->Release();

    g_pDevice->OMSetRenderTargets(0, NULL, NULL);
    pRenderTargetView->Release();

    g_pDevice->IASetInputLayout(NULL);
    pVertexLayout->Release();

    g_pDevice->VSSetShader(NULL);
    pVertexShader->Release();

    g_pDevice->PSSetShader(NULL);
    pPixelShader->Release();

    g_pDevice->RSSetState(NULL);
    pRasterizerState->Release();

    g_pSwapChain->Release();
    g_pSwapChain = NULL;

    g_pDevice->Release();
    g_pDevice = NULL;

    g_pAdapter->Release();
    g_pAdapter = NULL;

    g_pFactory->Release();
    g_pFactory = NULL;

    DestroyWindow(hWnd);

    return 0;
}
예제 #8
0
int main(int argc, char** argv)
{
	Display* dpy = XOpenDisplay(0);
	Visual* visual = DefaultVisual(dpy, DefaultScreen(dpy));
	Colormap cmap = XCreateColormap(dpy, RootWindow(dpy, DefaultScreen(dpy)), visual, AllocNone);
	XSetWindowAttributes swa;
	swa.colormap = cmap;
	swa.border_pixel = 0;
	swa.event_mask = StructureNotifyMask;
	width = 512;
	height = 512;
	Window win = XCreateWindow(dpy, RootWindow(dpy, DefaultScreen(dpy)), 0, 0, width, height, 0, CopyFromParent, InputOutput, visual, CWBorderPixel | CWColormap| CWEventMask, &swa);
	XMapWindow(dpy, win);

	GalliumDXGIUseX11Display(dpy, 0);

	DXGI_SWAP_CHAIN_DESC swap_chain_desc;
	memset(&swap_chain_desc, 0, sizeof(swap_chain_desc));
	swap_chain_desc.BufferDesc.Width = width;
	swap_chain_desc.BufferDesc.Height = height;
	swap_chain_desc.BufferDesc.Format = format;
	swap_chain_desc.SampleDesc.Count = 1;
	swap_chain_desc.SampleDesc.Quality = 0;
	swap_chain_desc.OutputWindow = (HWND)win;
	swap_chain_desc.Windowed = TRUE;
	swap_chain_desc.BufferCount = 3;
	swap_chain_desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
	swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

	D3D10_FEATURE_LEVEL1 feature_level = D3D10_FEATURE_LEVEL_10_0;

	HRESULT hr;
	if(0)
	{
		hr = D3D10CreateDeviceAndSwapChain(
			NULL,
			D3D10_DRIVER_TYPE_HARDWARE,
			NULL,
			D3D10_CREATE_DEVICE_SINGLETHREADED,
			D3D10_SDK_VERSION,
			&swap_chain_desc,
			&swap_chain,
			&dev);
	}
	else
	{
		hr = D3D10CreateDeviceAndSwapChain1(
			NULL,
			D3D10_DRIVER_TYPE_HARDWARE,
			NULL,
			D3D10_CREATE_DEVICE_SINGLETHREADED,
			feature_level,
			D3D10_SDK_VERSION,
			&swap_chain_desc,
			&swap_chain,
			(ID3D10Device1**)&dev);
	}
	if(!SUCCEEDED(hr))
	{
		fprintf(stderr, "Failed to create D3D10 device (hresult %08x)\n", hr);
		return 1;
	}
	ctx = dev;

	app = d3d10_application_create();
	if(!app->init(dev, argc, argv))
		return 1;

	double start_time = get_time();

	MSG msg;
	for(;;)
	{
		XEvent event;
		if(XPending(dpy))
		{
			XNextEvent(dpy, &event);
			if(event.type == DestroyNotify)
				break;
			switch(event.type)
			{
			case ConfigureNotify:
				width = event.xconfigure.width;
				height = event.xconfigure.height;
				swap_chain->ResizeBuffers(3, width, height, format, 0);
				break;
			}
		}
		else if(width && height)
		{
			ID3D10Texture2D* tex;
			ID3D10RenderTargetView* rtv;
			ensure(swap_chain->GetBuffer(0, IID_ID3D10Texture2D, (void**)&tex));
			ensure(dev->CreateRenderTargetView(tex, NULL, &rtv));

			double ctime = get_time() - start_time;

			app->draw(ctx, rtv, width, height, ctime);
			ctx->OMSetRenderTargets(0, 0, 0);

			tex->Release();
			rtv->Release();
			swap_chain->Present(0, 0);
		}
		else
			XPeekEvent(dpy, &event);
	}
	return (int) msg.wParam;
}
예제 #9
0
bool CDX10Shader::Execute(std::vector<ID3D10RenderTargetView*> *vecRT, unsigned int vertexIndexStep)
{
	ID3D10Device* pDevice = m_rendererSystem->GetDevice();
	ID3D10RenderTargetView* oldRTV = 0;
	ID3D10DepthStencilView* oldDSV = 0;

	if (vecRT!=NULL && !vecRT->empty())
		pDevice->OMGetRenderTargets(1, &oldRTV, &oldDSV);

	D3D10_TECHNIQUE_DESC techDesc;
	m_effect.GetTechnique()->GetDesc(&techDesc);
	unsigned int cPasses = techDesc.Passes;

	unsigned int stride = m_vertsize;
	unsigned int offset = 0;
	ID3D10Buffer* buffer = m_vb.GetVertexBuffer();
	pDevice->IASetVertexBuffers(0, 1, &buffer, &stride, &offset);
	if (m_vb.m_type == D3DVertexBuffer::INDEXED_BUFFER) 
	{
		pDevice->IASetIndexBuffer(m_vb.GetIndexBuffer(), DXGI_FORMAT_R32_UINT, 0);
		pDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
	} else 
	{
		pDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
	}

	pDevice->IASetInputLayout(m_inputLayout);
	for (unsigned int iPass = 0; iPass < cPasses; iPass++)
	{
		if (!m_effect.BeginPass(iPass)) 
		{
			LOGERR("Failed to apply and begin pass %u in technique %s", iPass, techDesc.Name);
			break;
		}

		if (vecRT != NULL && vecRT->size() > iPass)
			pDevice->OMSetRenderTargets(1, &(*vecRT)[iPass], NULL);

		if (m_vb.m_type == D3DVertexBuffer::INDEXED_BUFFER && m_primitivesCount > 0) 
			for (int i = 0; i < m_primitivesCount; i++) 
				pDevice->DrawIndexed(m_indexCount, 0, iPass*vertexIndexStep+i*((m_vbsize/m_vertsize)/m_primitivesCount));
		else
			pDevice->Draw(m_primitivesCount, iPass*vertexIndexStep);
	}

	if (oldRTV != 0) 
	{
		if (oldDSV != 0) 
		{
			pDevice->OMSetRenderTargets(1, &oldRTV, oldDSV);
			oldRTV->Release();
			oldRTV->Release();
		} else 
		{
			pDevice->OMSetRenderTargets(1, &oldRTV, NULL);
			oldRTV->Release();
		}
	}
	pDevice->RSSetViewports(1, &m_rendererSystem->GetViewPort());
	return true;
}