static HRESULT STDMETHODCALLTYPE hook_present_swap(IDirect3DSwapChain9 *swap,
		CONST RECT *src_rect, CONST RECT *dst_rect,
		HWND override_window, CONST RGNDATA *dirty_region, DWORD flags)
{
	IDirect3DSurface9 *backbuffer = nullptr;
	IDirect3DDevice9 *device = nullptr;
	HRESULT hr;

	if (!present_recurse) {
		hr = swap->GetDevice(&device);
		if (SUCCEEDED(hr)) {
			device->Release();
		}
	}

	if (device) {
		if (!hooked_reset)
			setup_reset_hooks(device);

		present_begin(device, backbuffer);
	}

	unhook(&present_swap);
	present_swap_t call = (present_swap_t)present_swap.call_addr;
	hr = call(swap, src_rect, dst_rect, override_window, dirty_region,
			flags);
	rehook(&present_swap);

	if (device)
		present_end(device, backbuffer);

	return hr;
}
Beispiel #2
0
static IDirect3DDevice9* findOriginalDevice(IDirect3DDevice9 *device) {

	IDirect3DSwapChain9 *pSwap = NULL;
	device->GetSwapChain(0, &pSwap);
	if (pSwap) {

		IDirect3DDevice9 *originalDevice = NULL;
		if (SUCCEEDED(pSwap->GetDevice(&originalDevice))) {

			if (originalDevice == device) {
				// Found the original device. Release responsibility is passed
				// to the caller.
			} else {
				device = findOriginalDevice(originalDevice);
				originalDevice->Release();
			}

		} else {
			ods("D3D9: Failed to recurse to find original device. Could not get Device from Swapchain.");
		}

		pSwap->Release();
	} else {
		ods("D3D9: Failed to recurse to find original device. Could not get Swapchain.");
	}

	return device;
}
void D3DXCompressorDXT1::compress(nvtt::InputFormat inputFormat, nvtt::AlphaMode alphaMode, uint w, uint h, uint d, void * data, const nvtt::CompressionOptions::Private & compressionOptions, const nvtt::OutputOptions::Private & outputOptions)
{
    nvDebugCheck(d == 1);

    IDirect3D9 * d3d = Direct3DCreate9(D3D_SDK_VERSION);

    D3DPRESENT_PARAMETERS presentParams;
    ZeroMemory(&presentParams, sizeof(presentParams));
    presentParams.Windowed = TRUE;
    presentParams.SwapEffect = D3DSWAPEFFECT_COPY;
    presentParams.BackBufferWidth = 8;
    presentParams.BackBufferHeight = 8;
    presentParams.BackBufferFormat = D3DFMT_UNKNOWN;

    HRESULT err;

    IDirect3DDevice9 * device = NULL;
    err = d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_REF, GetDesktopWindow(), D3DCREATE_SOFTWARE_VERTEXPROCESSING, &presentParams, &device);

    IDirect3DTexture9 * texture = NULL;
    err = D3DXCreateTexture(device, w, h, 1, 0, D3DFMT_DXT1, D3DPOOL_SYSTEMMEM, &texture);

    IDirect3DSurface9 * surface = NULL;
    err = texture->GetSurfaceLevel(0, &surface);

    RECT rect;
    rect.left = 0;
    rect.top = 0;
    rect.bottom = h;
    rect.right = w;

    if (inputFormat == nvtt::InputFormat_BGRA_8UB)
    {
        err = D3DXLoadSurfaceFromMemory(surface, NULL, NULL, data, D3DFMT_A8R8G8B8, w * 4, NULL, &rect, D3DX_DEFAULT, 0);
    }
    else
    {
        err = D3DXLoadSurfaceFromMemory(surface, NULL, NULL, data, D3DFMT_A32B32G32R32F, w * 16, NULL, &rect, D3DX_DEFAULT, 0);
    }

    if (err != D3DERR_INVALIDCALL && err != D3DXERR_INVALIDDATA)
    {
        D3DLOCKED_RECT rect;
        ZeroMemory(&rect, sizeof(rect));

        err = surface->LockRect(&rect, NULL, D3DLOCK_READONLY);

	    if (outputOptions.outputHandler != NULL) {
	        int size = rect.Pitch * ((h + 3) / 4);
	        outputOptions.outputHandler->writeData(rect.pBits, size);
	    }

        err = surface->UnlockRect();
    }

    surface->Release();
    device->Release();
    d3d->Release();
}
Beispiel #4
0
			//應該重載此函數 在裡面增加 資源釋放操作 釋放資源
			virtual void release()
			{
				if(_device)
				{
					_device->Release();
					_device	=	NULL;
				}
			}
Beispiel #5
0
//I don't think this code work for allthing
bool h3d::BeginD3D9CaptureHook() {

	wchar_t sD3D9Path[MAX_PATH];
	SHGetFolderPathW(NULL, CSIDL_SYSTEM, NULL, SHGFP_TYPE_CURRENT, sD3D9Path);
	wcscat_s(sD3D9Path, MAX_PATH, L"\\d3d9.dll");

	bool d3d9_support = false;
	hD3D9Dll = GetModuleHandle(sD3D9Path);
	if (hD3D9Dll) {
		D3DPRESENT_PARAMETERS d3dpp;
		ZeroMemory(&d3dpp, sizeof(d3dpp));
		d3dpp.Windowed = true;
		d3dpp.SwapEffect = D3DSWAPEFFECT_FLIP;
		d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
		d3dpp.BackBufferCount = 1;
		d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
		d3dpp.hDeviceWindow = hSender;

		D3D9CREATEPROC fD3D9Create = (D3D9CREATEPROC)GetProcAddress(hD3D9Dll, "Direct3DCreate9");
		if (fD3D9Create) {
			LPDIRECT3D9 pD3D = fD3D9Create(D3D_SDK_VERSION);
			if (pD3D) {
				IDirect3DDevice9* device;
				if (SUCCEEDED(pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_NULLREF, hSender, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &device))) {

					end_scene.Do(h3d::GetVirtual(device, D3D9ENDSCENE_OFFSET), (h3d::WINAPIPROC)EndScne);

					device->Release();
					d3d9_support = true;
				}

				pD3D->Release();
			}
		}

		D3D9CREATEXPROC fD3D9CreateEx = (D3D9CREATEXPROC)GetProcAddress(hD3D9Dll, "Direct3DCreate9Ex");
		if (fD3D9CreateEx) {
			IDirect3D9Ex* pD3DEx = NULL;
			if (SUCCEEDED(fD3D9CreateEx(D3D_SDK_VERSION, &pD3DEx))) {
				IDirect3DDevice9Ex* deviceEx = NULL;
				if (SUCCEEDED(pD3DEx->CreateDeviceEx(D3DADAPTER_DEFAULT, D3DDEVTYPE_NULLREF, hSender, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, NULL, &deviceEx))) {
					if (end_scene.GetTarget() != h3d::GetVirtual(deviceEx, D3D9ENDSCENE_OFFSET)) {
						logstream << "IDirect3DDevice9Ex::EndScene != IDirect3DDevice9::EndScene" << std::endl;
						end_sceneex.Do(h3d::GetVirtual(deviceEx, D3D9ENDSCENE_OFFSET), (h3d::WINAPIPROC)EndScne);
					}
					d3d9ex_support = true;
				}

				pD3DEx->Release();
			}
		}
	}

	return d3d9ex_support || d3d9_support;
}
Beispiel #6
0
HRESULT APPLICATION::Cleanup()
{
	try
	{
		m_pFont->Release();
		m_pLine->Release();
		m_pDevice->Release();

		debug.Print("Application terminated");
	}
	catch(...){}

	return S_OK;
}
Beispiel #7
0
void D3DGLSwapChain::releaseIface()
{
    if(--mIfaceCount == 0)
    {
        if(mIsAuto)
            mParent->Release();
        else
        {
            IDirect3DDevice9 *device = mParent;
            delete this;
            device->Release();
        }
    }
}
Beispiel #8
0
uintptr_t* Edo::GetD3D9DeviceVTable(HWND window)
{
	IDirect3DDevice9* pDevice;

	//Create dummy device.
	CreateD3D9DummyDevice(window, &pDevice);

	//Get the VTable.
	uintptr_t* vTable = (uintptr_t*)*(uintptr_t*)pDevice;

	//Release.
	pDevice->Release();

	return vTable;
}
Beispiel #9
0
HRESULT APPLICATION::Cleanup()
{
	try
	{
		m_terrain.Release();
		UnloadObjectResources();

		m_pFont->Release();

		m_pDevice->Release();

		debug.Print("Application terminated");
	}
	catch(...){}

	return S_OK;
}
Beispiel #10
0
static HRESULT __stdcall mySwapPresent(IDirect3DSwapChain9 * ids, CONST RECT *pSourceRect, CONST RECT *pDestRect, HWND hDestWindowOverride, CONST RGNDATA *pDirtyRegion, DWORD dwFlags) {
	ods("D3D9: SwapChain Present");

	IDirect3DDevice9 *idd = NULL;
	ids->GetDevice(&idd);
	if (idd) {
		doPresent(idd);
		idd->Release();
	}

	//TODO: Move logic to HardHook.
	// Call base without active hook in case of no trampoline.
	SwapPresentType oSwapPresent = (SwapPresentType) hhSwapPresent.call;
	hhSwapPresent.restore();
	HRESULT hr = oSwapPresent(ids, pSourceRect,pDestRect,hDestWindowOverride,pDirtyRegion,dwFlags);
	hhSwapPresent.inject();

	return hr;
}
Beispiel #11
0
HRESULT APPLICATION::Cleanup()
{
	try
	{
		if(m_pHeightMap != NULL)
		{
			delete m_pHeightMap;
			m_pHeightMap = NULL;
		}

		m_pFont->Release();
		m_pDevice->Release();

		debug.Print("Application terminated");
	}
	catch(...){}

	return S_OK;
}
Beispiel #12
0
int EntryPoint()
{
	IDirect3D9* d3d = Direct3DCreate9(D3D_SDK_VERSION);
	if (d3d == NULL)
	{
		return 0;
	}

	g_dev_params.hDeviceWindow = InitWindow();
	IDirect3DDevice9* device = NULL;
	if (d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, g_dev_params.hDeviceWindow, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_dev_params, &device) != S_OK)
	{
		return 0;
	}

	DemoInit(device);

	MSG msg;
	while (GetCurrentSample() < MAX_SAMPLES)
	{
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			if (msg.message == WM_QUIT) break;
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		DemoUpdate(device, GetTickCount());
		Sleep(10);
	}

#ifndef RELEASE
	DemoDestroy(device);
	device->Release();
	d3d->Release();
	DestroyWindow(g_dev_params.hDeviceWindow);
	return 0;
#else
	ExitProcess(0);
#endif
}
Beispiel #13
0
static HRESULT __stdcall mySwapPresent(IDirect3DSwapChain9 *ids, CONST RECT *pSourceRect, CONST RECT *pDestRect, HWND hDestWindowOverride, CONST RGNDATA *pDirtyRegion, DWORD dwFlags) {
	// Present is called for each frame. Thus, we do not want to always log here.
	#ifdef EXTENDED_OVERLAY_DEBUGOUTPUT
	ods("D3D9: SwapChain Present");
	#endif

	IDirect3DDevice9 *idd = NULL;
	ids->GetDevice(&idd);
	if (idd) {
		doPresent(idd);
		idd->Release();
	}

	//TODO: Move logic to HardHook.
	// Call base without active hook in case of no trampoline.
	SwapPresentType oSwapPresent = (SwapPresentType) hhSwapPresent.call;
	hhSwapPresent.restore();
	HRESULT hr = oSwapPresent(ids, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags);
	hhSwapPresent.inject();

	return hr;
}
// Detour function that replaces the IDirect3dSwapChain9::Present() API
DllExport HRESULT __stdcall hook_D3D9SwapChainPresent(
		IDirect3DSwapChain9 * This,
		CONST RECT* pSourceRect,
		CONST RECT* pDestRect,
		HWND hDestWindowOverride,
		CONST RGNDATA* pDirtyRegion,
		DWORD dwFlags
	)
{
	static int present_hooked = 0;
	IDirect3DDevice9 *pDevice;

	if (present_hooked == 0) {
		OutputDebugString("[IDirect3dSwapChain9::Present()]");
		present_hooked = 1;
	}

	HRESULT hr = pSwapChainPresent(This, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags);

	This->GetDevice(&pDevice);

	if(resolution_retrieved == 0) {
		if(D3D9_get_resolution(pDevice) >= 0) {
			resolution_retrieved = 1;
		}
		return hr;
	}

	if (enable_server_rate_control) {
		if(ga_hook_video_rate_control() > 0)
			D3D9_screen_capture(pDevice);
	} else {
		D3D9_screen_capture(pDevice);
	}

	pDevice->Release();
	return hr;
}
Beispiel #15
0
static HRESULT __stdcall mySwapPresent(IDirect3DSwapChain9 * ids, CONST RECT *pSourceRect, CONST RECT *pDestRect, HWND hDestWindowOverride, CONST RGNDATA *pDirtyRegion, DWORD dwFlags) {
	ods("D3D9: SwapChain Present");

	if (bPresenting) {
		ods("D3D9: Not doublepresenting in chain!");
	}  else {
		IDirect3DDevice9 *idd = NULL;
		ids->GetDevice(&idd);
		if (idd) {
			myAdditions(idd);
			doPresent(idd);
			idd->Release();
		}
	}

	SwapPresentType oSwapPresent;
	oSwapPresent = (SwapPresentType) hhSwapPresent.call;

	hhSwapPresent.restore();
	HRESULT hr = oSwapPresent(ids, pSourceRect,pDestRect,hDestWindowOverride,pDirtyRegion,dwFlags);
	hhSwapPresent.inject();
	return hr;
}
Beispiel #16
0
HRESULT WINAPI D3D9SCPresent(IDirect3DSwapChain9 *pSc, CONST RECT* pSourceRect,CONST RECT* pDestRect,HWND hDestWindowOverride,CONST RGNDATA* pDirtyRegion, DWORD dwFlags) {

    D3D9FrameGrabber *d3d9FrameGrabber = D3D9FrameGrabber::getInstance();
    Logger *logger = d3d9FrameGrabber->m_logger;
    DWORD errorcode;
    if (WAIT_OBJECT_0 == (errorcode = WaitForSingleObject(d3d9FrameGrabber->m_syncRunMutex, 0))) {
        IPCContext *ipcContext = d3d9FrameGrabber->m_ipcContext;
        logger->reportLogDebug(L"D3D9SCPresent");
        IDirect3DSurface9 *pBackBuffer = NULL;
        D3DPRESENT_PARAMETERS params;
        RECT newRect = RECT();
        IDirect3DSurface9 *pDemultisampledSurf = NULL;
        IDirect3DSurface9 *pOffscreenSurf = NULL;
        IDirect3DDevice9 *pDev = NULL;

        HRESULT hRes = pSc->GetPresentParameters(&params);

        if (FAILED(hRes) || params.Windowed) {
            goto end;
        }

        if (FAILED(hRes = pSc->GetBackBuffer( 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer))) {
            logger->reportLogError(L"d3d9sc couldn't get backbuffer. errorcode = 0x%x", hRes);
            goto end;
        }
        D3DSURFACE_DESC surfDesc;
        pBackBuffer->GetDesc(&surfDesc);

        hRes = pSc->GetDevice(&pDev);
        if (FAILED(hRes))
        {
            logger->reportLogError(L"GetFramePrep: FAILED to get pDev. 0x%x, width=%u, height=%u, format=%x", hRes, surfDesc.Width, surfDesc.Height, surfDesc.Format );
            goto end;
        }
        hRes = pDev->CreateRenderTarget(
            surfDesc.Width, surfDesc.Height,
            surfDesc.Format, D3DMULTISAMPLE_NONE, 0, false,
            &pDemultisampledSurf, NULL );
        if (FAILED(hRes))
        {
            logger->reportLogError(L"GetFramePrep: FAILED to create demultisampled render target. 0x%x, width=%u, height=%u, format=%x", hRes, surfDesc.Width, surfDesc.Height, surfDesc.Format );
            goto end;
        }

        hRes = pDev->StretchRect(pBackBuffer, NULL, pDemultisampledSurf, NULL, D3DTEXF_LINEAR );
        if (FAILED(hRes))
        {
            logger->reportLogError(L"GetFramePrep: StretchRect FAILED for image surfacee. 0x%x, width=%u, height=%u, format=%x", hRes, surfDesc.Width, surfDesc.Height, surfDesc.Format );
            goto end;
        }

        hRes = pDev->CreateOffscreenPlainSurface(
            surfDesc.Width, surfDesc.Height,
            surfDesc.Format, D3DPOOL_SYSTEMMEM,
            &pOffscreenSurf, NULL );
        if (FAILED(hRes))
        {
            logger->reportLogError(L"GetFramePrep: FAILED to create image surface. 0x%x, width=%u, height=%u, format=%x", hRes, surfDesc.Width, surfDesc.Height, surfDesc.Format );
            goto end;
        }

        hRes = pDev->GetRenderTargetData(pDemultisampledSurf, pOffscreenSurf );
        if (FAILED(hRes))
        {
            logger->reportLogError(L"GetFramePrep: GetRenderTargetData() FAILED for image surfacee. 0x%x, width=%u, height=%u, format=%x", hRes, surfDesc.Width, surfDesc.Height, surfDesc.Format );
            goto end;
        }

        D3DLOCKED_RECT lockedSrcRect;
        newRect.right = surfDesc.Width;
        newRect.bottom = surfDesc.Height;

        hRes = pOffscreenSurf->LockRect( &lockedSrcRect, &newRect, 0);
        if (FAILED(hRes))
        {
            logger->reportLogError(L"GetFramePrep: FAILED to lock source rect. (0x%x)", hRes );
            goto end;
        }

        ipcContext->m_memDesc.width = surfDesc.Width;
        ipcContext->m_memDesc.height = surfDesc.Height;
        ipcContext->m_memDesc.rowPitch = lockedSrcRect.Pitch;
        ipcContext->m_memDesc.frameId++;
        ipcContext->m_memDesc.format = getCompatibleBufferFormat(surfDesc.Format);

        if (WAIT_OBJECT_0 == (errorcode = WaitForSingleObject(ipcContext->m_hMutex, 0))) {
            //            __asm__("int $3");
    //        reportLog(EVENTLOG_INFORMATION_TYPE, L"d3d9sc writing description to mem mapped file");
            memcpy(ipcContext->m_pMemMap, &ipcContext->m_memDesc, sizeof (ipcContext->m_memDesc));
    //        reportLog(EVENTLOG_INFORMATION_TYPE, L"d3d9sc writing data to mem mapped file");
            PVOID pMemDataMap = incPtr(ipcContext->m_pMemMap, sizeof (ipcContext->m_memDesc));
            if (static_cast<UINT>(lockedSrcRect.Pitch) == surfDesc.Width * 4) {
                memcpy(pMemDataMap, lockedSrcRect.pBits, surfDesc.Width * surfDesc.Height * 4);
            } else {
                UINT i = 0, cleanOffset = 0, pitchOffset = 0;
                while (i < surfDesc.Height) {
                    memcpy(incPtr(pMemDataMap, cleanOffset), incPtr(lockedSrcRect.pBits, pitchOffset), surfDesc.Width * 4);
                    cleanOffset += surfDesc.Width * 4;
                    pitchOffset += lockedSrcRect.Pitch;
                    i++;
                }
            }
            ReleaseMutex(ipcContext->m_hMutex);
            SetEvent(ipcContext->m_hFrameGrabbedEvent);
        } else {
            logger->reportLogError(L"d3d9sc couldn't wait mutex. errocode = 0x%x", errorcode);
        }
end:
        if(pOffscreenSurf) pOffscreenSurf->Release();
        if(pDemultisampledSurf) pDemultisampledSurf->Release();
        if(pBackBuffer) pBackBuffer->Release();
        if(pDev) pDev->Release();

        ProxyFuncJmp *d3d9SCPresentProxyFuncJmp = d3d9FrameGrabber->m_d3d9SCPresentProxyFuncJmp;

        if(d3d9SCPresentProxyFuncJmp->removeHook()) {
            int i = GetLastError();
            logger->reportLogError(L"d3d9sc error occured while trying to removeHook before original call0x%x", i);
        }
        HRESULT result = pSc->Present(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags);

        if(d3d9SCPresentProxyFuncJmp->installHook()) {
            int i = GetLastError();
            logger->reportLogError(L"d3d9sc error occured while trying to installHook after original call0x%x", i);
        }

        ReleaseMutex(d3d9FrameGrabber->m_syncRunMutex);

        return result;
    } else {
        logger->reportLogError(L"d3d9sc present is skipped because mutex is busy");
        return S_FALSE;
    }
}
bool DX9VertexShaderConstantsCompiler::compile( const std::string& shaderCode, const char* entryFunction, std::vector< ShaderConstantDesc >& outConstants )
{
   // create a renderer
   IDirect3D9* d3d9 = Direct3DCreate9( D3D_SDK_VERSION );
   DX9Initializer initializer( *d3d9 );

   IDirect3DDevice9* compileDevice = initializer.createNullDevice();
   const char* shaderProfile = D3DXGetVertexShaderProfile( compileDevice );

   DWORD flags = D3DXSHADER_DEBUG;

   ID3DXBuffer* shaderBuf = NULL;
   ID3DXBuffer* errorsBuf = NULL;
   ID3DXConstantTable* shaderConstants = NULL;
   DX9ShaderIncludeLoader includesLoader;
   HRESULT res = D3DXCompileShader( shaderCode.c_str(), shaderCode.length(), NULL, &includesLoader, entryFunction, shaderProfile, flags, &shaderBuf, &errorsBuf, &shaderConstants );

   // interpret the results
   bool result = true;
   if ( FAILED(res) || shaderBuf == NULL )
   {
      if ( errorsBuf != NULL )
      {
         std::string compilationErrors = ( const char* )errorsBuf->GetBufferPointer();
         errorsBuf->Release();
         m_errorMsg = std::string( "Shader compilation error: " ) + compilationErrors;
      }
      else
      {
         m_errorMsg = translateDxError( "Error while compiling a shader", res );
      }

      result = false;
   }
   else
   {
      std::vector< D3DXCONSTANT_DESC > constants;
      ShaderConstantDesc newConstant;
      result = ShaderCompilerUtils::parseConstants( shaderConstants, m_errorMsg, constants );
      if ( result )
      {
         unsigned int constantsCount = constants.size();
         for ( unsigned int i = 0; i < constantsCount; ++i )
         {
            if ( createConstant( constants[i], newConstant ) )
            {
               outConstants.push_back( newConstant );
            }
         }
      }
   }

   // cleanup
   if ( shaderConstants )
   {
      shaderConstants->Release();
   }
   compileDevice->Release();
   d3d9->Release();

   return result;
}
HRESULT CMpeg2DecoderDXVA2::CreateDecoderService(CTVTestVideoDecoder *pFilter)
{
	DBG_TRACE(TEXT("CMpeg2DecoderDXVA2::CreateDecoderService()"));

	if (!pFilter)
		return E_POINTER;
	if (!pFilter->m_pD3DDeviceManager || !pFilter->m_hDXVADevice)
		return E_UNEXPECTED;

	CloseDecoderService();

	m_pFilter = pFilter;
	m_pDeviceManager = pFilter->m_pD3DDeviceManager;
	m_pDeviceManager->AddRef();

	HRESULT hr;

	IDirect3DDevice9 *pDevice;
	hr = m_pDeviceManager->LockDevice(m_pFilter->m_hDXVADevice, &pDevice, TRUE);
	if (SUCCEEDED(hr)) {
		D3DDEVICE_CREATION_PARAMETERS CreationParams;
		hr = pDevice->GetCreationParameters(&CreationParams);
		if (SUCCEEDED(hr)) {
			IDirect3D9 *pD3D;
			hr = pDevice->GetDirect3D(&pD3D);
			if (SUCCEEDED(hr)) {
				D3DADAPTER_IDENTIFIER9 AdapterID;
				hr = pD3D->GetAdapterIdentifier(CreationParams.AdapterOrdinal, 0, &AdapterID);
				if (SUCCEEDED(hr)) {
					WCHAR szDriver[MAX_DEVICE_IDENTIFIER_STRING];
					WCHAR szDescription[MAX_DEVICE_IDENTIFIER_STRING];
					WCHAR szDeviceName[32];
					::MultiByteToWideChar(CP_ACP, 0, AdapterID.Driver, -1, szDriver, _countof(szDriver));
					::MultiByteToWideChar(CP_ACP, 0, AdapterID.Description, -1, szDescription, _countof(szDescription));
					::MultiByteToWideChar(CP_ACP, 0, AdapterID.DeviceName, -1, szDeviceName, _countof(szDeviceName));
					DBG_TRACE(TEXT("--- Adapter information ---"));
					DBG_TRACE(TEXT("     Driver : %s"), szDriver);
					DBG_TRACE(TEXT("Description : %s"), szDescription);
					DBG_TRACE(TEXT("Device name : %s"), szDeviceName);
					DBG_TRACE(TEXT("    Product : %08x"), HIWORD(AdapterID.DriverVersion.HighPart));
					DBG_TRACE(TEXT("    Version : %d.%d.%d"),
							  LOWORD(AdapterID.DriverVersion.HighPart),
							  HIWORD(AdapterID.DriverVersion.LowPart),
							  LOWORD(AdapterID.DriverVersion.LowPart));
					DBG_TRACE(TEXT("     Vendor : %08x"), AdapterID.VendorId);
					DBG_TRACE(TEXT("  Device ID : %08x"), AdapterID.DeviceId);
					DBG_TRACE(TEXT("  Subsystem : %08x"), AdapterID.SubSysId);
					DBG_TRACE(TEXT("   Revision : %08x"), AdapterID.Revision);
					m_AdapterIdentifier = AdapterID;
				}
				pD3D->Release();
			}
		}
		pDevice->Release();
		m_pDeviceManager->UnlockDevice(m_pFilter->m_hDXVADevice, FALSE);
	}
	if (FAILED(hr)) {
		::ZeroMemory(&m_AdapterIdentifier, sizeof(m_AdapterIdentifier));
	}

	IDirectXVideoDecoderService *pDecoderService;
	hr = m_pDeviceManager->GetVideoService(m_pFilter->m_hDXVADevice, IID_PPV_ARGS(&pDecoderService));
	if (FAILED(hr)) {
		DBG_ERROR(TEXT("GetVideoService() failed (%x)"), hr);
		CloseDecoderService();
		return hr;
	}
	m_pDecoderService = pDecoderService;

	if (!FindDecoder(nullptr, &m_SurfaceFormat, SurfaceFormatList, _countof(SurfaceFormatList))) {
		CloseDecoderService();
		return E_FAIL;
	}

	return S_OK;
}
Beispiel #19
0
static HRESULT __stdcall myCreateDevice(IDirect3D9 *id3d, UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS *pPresentationParameters, IDirect3DDevice9 **ppReturnedDeviceInterface) {
	Mutex m;

	ods("D3D9: Chaining CreateDevice");

//	BehaviorFlags &= ~D3DCREATE_PUREDEVICE;

	//TODO: Move logic to HardHook.
	// Call base without active hook in case of no trampoline.
	CreateDeviceType oCreateDevice = (CreateDeviceType) hhCreateDevice.call;
	hhCreateDevice.restore();
	HRESULT hr = oCreateDevice(id3d, Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, ppReturnedDeviceInterface);
	hhCreateDevice.inject();

	if (FAILED(hr))
		return hr;

	IDirect3DDevice9 *idd = *ppReturnedDeviceInterface;

	// Get real interface, please.
	IDirect3DDevice9 *originalDevice = findOriginalDevice(idd);
	if (idd != originalDevice) {
		ods("D3D9: Prepatched device, using original. %p => %p", idd, originalDevice);
		idd = originalDevice;
	}

	DevState *ds = new DevState;
	ds->dev = idd;

	idd->AddRef();
	ds->initRefCount = idd->Release();

	DevMapType::iterator it = devMap.find(idd);
	if (it != devMap.end()) {
		ods("Device exists in devMap already - canceling injection into device. Thread prev: %d ; new: %d", it->second->dwMyThread, GetCurrentThreadId());
		delete ds;

		return hr;
	}
	devMap[idd] = ds;

	// The offsets are dependent on the declaration order of the struct.
	// See IDirect3DDevice9 (2nd, 3rd, 17th, 18th functions)
	const unsigned int offsetAddref = 1;
	const unsigned int offsetRelease = 2;
	const unsigned int offsetReset = 16;
	const unsigned int offsetPresent = 17;
	if (bIsWin8) {
		hhAddRef.setupInterface(idd, offsetAddref, reinterpret_cast<voidFunc>(myWin8AddRef));
		hhRelease.setupInterface(idd, offsetRelease, reinterpret_cast<voidFunc>(myWin8Release));
	} else {
		hhAddRef.setupInterface(idd, offsetAddref, reinterpret_cast<voidFunc>(myAddRef));
		hhRelease.setupInterface(idd, offsetRelease, reinterpret_cast<voidFunc>(myRelease));
	}
	hhReset.setupInterface(idd, offsetReset, reinterpret_cast<voidFunc>(myReset));
	hhPresent.setupInterface(idd, offsetPresent, reinterpret_cast<voidFunc>(myPresent));

	IDirect3DSwapChain9 *pSwap = NULL;
	idd->GetSwapChain(0, &pSwap);
	if (pSwap) {
		// The offset is dependent on the declaration order of the struct.
		// See IDirect3DSwapChain9 (Present is the fourth function)
		const unsigned int offsetPresent = 3;
		hhSwapPresent.setupInterface(pSwap, offsetPresent, reinterpret_cast<voidFunc>(mySwapPresent));
		pSwap->Release();
	} else {
		ods("D3D9: Failed to get swapchain");
	}

	ds->createCleanState();

	return hr;
}
int main(int argc, char *argv[])
{
	int ret = 0;
	try {
		// initialize directx 
		IDirect3D9 *d3d = Direct3DCreate9(D3D_SDK_VERSION);
		if (!d3d)
			throw std::string("This application requires DirectX 9");

		// create a window
		HWND hwnd = CreateWindowEx(0, "static", "GNU Rocket Example",
		    WS_POPUP | WS_VISIBLE, 0, 0, width, height, 0, 0,
		    GetModuleHandle(0), 0);

		// create the device
		IDirect3DDevice9 *device = NULL;
		static D3DPRESENT_PARAMETERS present_parameters = {width,
		    height, D3DFMT_X8R8G8B8, 3, D3DMULTISAMPLE_NONE, 0,
		    D3DSWAPEFFECT_DISCARD, 0, WINDOWED, 1, D3DFMT_D24S8,
		    0, WINDOWED ? 0 : D3DPRESENT_RATE_DEFAULT, 0
		};
		if (FAILED(d3d->CreateDevice(D3DADAPTER_DEFAULT,
		    D3DDEVTYPE_HAL, hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING,
		    &present_parameters, &device)))
			throw std::string("Failed to create device");

		// init BASS
		int soundDevice = 1;
		if (!BASS_Init(soundDevice, 44100, 0, hwnd, 0))
			throw std::string("Failed to init bass");

		// load tune
		HSTREAM stream = BASS_StreamCreateFile(false, "tune.ogg", 0, 0,
		    BASS_MP3_SETPOS | (!soundDevice ? BASS_STREAM_DECODE : 0));
		if (!stream)
			throw std::string("Failed to open tune");

		// let's just assume 150 BPM (this holds true for the included tune)
		float bpm = 150.0f;

		// setup timer and construct sync-device
		BassTimer timer(stream, bpm, 8);
		std::auto_ptr<sync::Device> syncDevice = std::auto_ptr<sync::Device>(
		    sync::createDevice("sync", timer));
		if (!syncDevice.get())
			throw std::string("Failed to connect to host?");

		// get tracks
		sync::Track &clearRTrack = syncDevice->getTrack("clear.r");
		sync::Track &clearGTrack = syncDevice->getTrack("clear.g");
		sync::Track &clearBTrack = syncDevice->getTrack("clear.b");

		sync::Track &camRotTrack  = syncDevice->getTrack("cam.rot");
		sync::Track &camDistTrack = syncDevice->getTrack("cam.dist");

		LPD3DXMESH cubeMesh = NULL;
		if (FAILED(D3DXCreateBox(device, 1.0f, 1.0f, 1.0f, &cubeMesh, NULL)))
			return -1;

		// let's roll!
		BASS_Start();
		timer.play();

		bool done = false;
		while (!done) {
			float row = float(timer.getRow());
			if (!syncDevice->update(row))
				done = true;

			// setup clear color
			D3DXCOLOR clearColor(clearRTrack.getValue(row), clearGTrack.getValue(row), clearBTrack.getValue(row), 0.0);

			// paint the window
			device->BeginScene();
			device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, clearColor, 1.0f, 0);

/*			D3DXMATRIX world;
			device->SetTransform(D3DTS_WORLD, &world); */

			float rot = camRotTrack.getValue(row);
			float dist = camDistTrack.getValue(row);
			D3DXVECTOR3 eye(sin(rot) * dist, 0, cos(rot) * dist);
			D3DXVECTOR3 at(0, 0, 0);
			D3DXVECTOR3 up(0, 1, 0);
			D3DXMATRIX view;
			D3DXMatrixLookAtLH(&view, &(eye + at), &at, &up);
			device->SetTransform(D3DTS_WORLD, &view);

			D3DXMATRIX proj;
			D3DXMatrixPerspectiveFovLH(&proj, D3DXToRadian(60), 4.0f / 3, 0.1f, 1000.f);
			device->SetTransform(D3DTS_PROJECTION, &proj);

			cubeMesh->DrawSubset(0);

			device->EndScene();
			device->Present(0, 0, 0, 0);

			BASS_Update(0); // decrease the chance of missing vsync
			MSG msg;
			while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
				TranslateMessage(&msg);
				DispatchMessage(&msg);

				if (WM_QUIT == msg.message) done = true;
				if ((WM_KEYDOWN == msg.message) && (VK_ESCAPE == LOWORD(msg.wParam))) done = true;
			}
		}

		BASS_StreamFree(stream);
		BASS_Free();

		device->Release();
		d3d->Release();
		DestroyWindow(hwnd);
	} catch (const std::exception &e) {
#ifdef _CONSOLE
		fprintf(stderr, "*** error: %s\n", e.what());
#else
		MessageBox(NULL, e.what(), NULL, MB_OK | MB_ICONERROR | MB_SETFOREGROUND);
#endif
		ret = -1;
	} catch (const std::string &str) {
#ifdef _CONSOLE
		fprintf(stderr, "*** error: %s\n", str.c_str());
#else
		MessageBox(NULL, e.what(), NULL, MB_OK | MB_ICONERROR | MB_SETFOREGROUND);
#endif
		ret = -1;
	}

	return ret;
}
Beispiel #21
0
int __stdcall WinMain(HINSTANCE, HINSTANCE, LPSTR, int){
	Application app("Okienko");

	// Inicjalizacja Direct3D
	IDirect3D9* d3d = Direct3DCreate9(D3D_SDK_VERSION);

	// Parametry urzadzenia
	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory(&d3dpp, sizeof(d3dpp));
	d3dpp.Windowed = true;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.BackBufferCount = 1;
	d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
	d3dpp.BackBufferHeight = app.get_height();
	d3dpp.BackBufferWidth = app.get_width();
	d3dpp.EnableAutoDepthStencil = true;
	d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8;

	// Tworzenie urzadzenia
	IDirect3DDevice9* dev;
	d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, app.window_handle(),
		D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &dev);

	app.init_font(dev, "Courier New");

	dev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);	// Brak obcinania scian
    dev->SetRenderState(D3DRS_LIGHTING, false);			// Brak swiatla

	// Inicjalizacja kamery
//	D3DXVECTOR3 eye(0, 5, -10);
    D3DXVECTOR3 target(0, 0, 0);
    D3DXVECTOR3 up(0, 1, 0);
    D3DXMATRIXA16 view;

    D3DXMATRIX mProjection;
	D3DXMatrixPerspectiveFovLH(&mProjection, D3DX_PI * 0.5f,  app.get_width()/(float)app.get_height(), 1, 50);
    dev->SetTransform(D3DTS_PROJECTION, &mProjection);

	// Model pudelka
	Vertex box[] = {
	//	  X   Y   Z  Color
		{ 1,  1,  1, D3DCOLOR_XRGB(255, 255, 255)},
		{-1,  1,  1, D3DCOLOR_XRGB(0, 255, 255)},
		{-1,  1, -1, D3DCOLOR_XRGB(0, 255, 0)},
		{ 1,  1, -1, D3DCOLOR_XRGB(255, 255, 0)},

		{ 1, -1,  1, D3DCOLOR_XRGB(255, 0, 255)},
		{-1, -1,  1, D3DCOLOR_XRGB(0, 0, 255)},
		{-1, -1, -1, D3DCOLOR_XRGB(0, 0, 0)},
		{ 1, -1, -1, D3DCOLOR_XRGB(255, 0, 0)},

		box[0], box[4], box[1], box[5], box[2], box[6], box[3], box[7], box[0], box[4]
	};

	int box_size = (16 + 2) * sizeof(Vertex);

	// Tworzenie bufora wierzcholkow
	IDirect3DVertexBuffer9* box_buffer;
	dev->CreateVertexBuffer(box_size, 0, Vertex_Format, D3DPOOL_MANAGED, &box_buffer, NULL);

	VOID* pVoid;
	box_buffer->Lock(0, box_size, (void**)&pVoid, 0);
	memcpy(pVoid, box, box_size);
	box_buffer->Unlock();

	dev->SetFVF(Vertex_Format);
	dev->SetStreamSource(0, box_buffer, 0, sizeof(Vertex));

	float radius = 3;
	while(app.running()){
		float alfa = app.get_alfa();
		float beta = app.get_beta();
		// Aktualizujemy kamere
		D3DXVECTOR3 eye(
			radius * cos(alfa) * sin(beta),
			radius * cos(beta),
			radius * sin(alfa) * sin(beta)
		);

		D3DXMatrixLookAtLH(&view, &eye, &target, &up);
		dev->SetTransform(D3DTS_VIEW, &view);

		// Rysujemy pudeleczko
		dev->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
		dev->BeginScene();

		for(int i = 0; i < 2; i++) dev->DrawPrimitive(D3DPT_TRIANGLEFAN, i*4, 2);
		dev->DrawPrimitive(D3DPT_TRIANGLESTRIP, 8, 8);

		app.print(10, 10, "Mysz X = %d", app.get_mouse_x());
		app.print(10, 24, "Mysz Y = %d", app.get_mouse_y());

		dev->EndScene();
		dev->Present(NULL, NULL, NULL, NULL);
	}

	// Zwalniamy zasoby
	box_buffer->Release();
	dev->Release();
	d3d->Release();
	return 0;
}
Beispiel #22
0
static HRESULT __stdcall myCreateDevice(IDirect3D9 * id3d, UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS *pPresentationParameters, IDirect3DDevice9 **ppReturnedDeviceInterface) {
	ods("D3D9: Chaining CreateDevice");
	Mutex m;

//	BehaviorFlags &= ~D3DCREATE_PUREDEVICE;

	CreateDeviceType oCreateDevice = (CreateDeviceType) hhCreateDevice.call;

	hhCreateDevice.restore();
	HRESULT hr=oCreateDevice(id3d, Adapter,DeviceType,hFocusWindow,BehaviorFlags,pPresentationParameters,ppReturnedDeviceInterface);
	hhCreateDevice.inject();

	if (FAILED(hr))
		return hr;

	IDirect3DDevice9 *idd = *ppReturnedDeviceInterface;
	IDirect3DSwapChain9 *pSwap = NULL;

	// Get real interface, please.
	bool bfound;
	do {
		bfound = false;
		idd->GetSwapChain(0, &pSwap);
		if (pSwap) {
			IDirect3DDevice9 *idorig = NULL;
			if (SUCCEEDED(pSwap->GetDevice(&idorig))) {
				if (idorig != idd) {
					ods("Prepatched device, using original. %p => %p", idorig, idd);
					if (idd != *ppReturnedDeviceInterface)
						idd->Release();
					idd = idorig;
					bfound = true;
				} else {
					idorig->Release();
				}
			}
			pSwap->Release();
		}
	} while (bfound);

	DevState *ds = new DevState;
	ds->dev = idd;

	idd->AddRef();
	ds->initRefCount = idd->Release();

	devMap[idd] = ds;

	if (bIsWin8) {
		hhAddRef.setupInterface(idd, 1, reinterpret_cast<voidFunc>(myWin8AddRef));
		hhRelease.setupInterface(idd, 2, reinterpret_cast<voidFunc>(myWin8Release));
	} else {
		hhAddRef.setupInterface(idd, 1, reinterpret_cast<voidFunc>(myAddRef));
		hhRelease.setupInterface(idd, 2, reinterpret_cast<voidFunc>(myRelease));
	}
	hhReset.setupInterface(idd, 16, reinterpret_cast<voidFunc>(myReset));
	hhPresent.setupInterface(idd, 17, reinterpret_cast<voidFunc>(myPresent));

	pSwap = NULL;
	idd->GetSwapChain(0, &pSwap);
	if (pSwap) {
		hhSwapPresent.setupInterface(pSwap, 3, reinterpret_cast<voidFunc>(mySwapPresent));
		pSwap->Release();
	} else {
		ods("D3D9: Failed to get swapchain");
	}

	ds->createCleanState();

	return hr;
}