Esempio n. 1
0
BOOL dx9vid_init()
{
	d3d = Direct3DCreate9(D3D_SDK_VERSION);    // create the Direct3D interface
	D3DCAPS9 d3dCaps;
	d3d->GetDeviceCaps( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &d3dCaps );
	d3d->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm );

	ZeroMemory( &d3dpp, sizeof(d3dpp) );
	d3dpp.Windowed               = TRUE;
	d3dpp.SwapEffect             = D3DSWAPEFFECT_DISCARD;
	d3dpp.BackBufferFormat       = d3ddm.Format;
	d3dpp.EnableAutoDepthStencil = TRUE;
	d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
	d3dpp.PresentationInterval   = D3DPRESENT_INTERVAL_IMMEDIATE;

	d3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, g_hwnd,
						D3DCREATE_SOFTWARE_VERTEXPROCESSING,
						&d3dpp, &d3ddev );

	// Create the screen texture
	D3DXCreateTexture( d3ddev, 256, 256, D3DX_FILTER_NONE, D3DUSAGE_DYNAMIC, D3DFMT_X8R8G8B8, D3DPOOL_DEFAULT, &g_screenTex);

	// Create the screen sprite (ignores 3d perspective)
	D3DXCreateSprite( d3ddev, &g_screenSprite );

	// Scale our matrix to match the screen
	D3DXMatrixIdentity( &pTransform );
	spritePos = D3DXVECTOR2( 0.f, 0.f );
	rotCenter = D3DXVECTOR2( 0.f, 0.f);
	D3DXVECTOR2 vscale = D3DXVECTOR2( float(3.0f), float(3.0f));
	D3DXMatrixTransformation2D( &pTransform, NULL, 0.0f, &vscale, &rotCenter, 0.f, &spritePos );
	g_screenSprite->SetTransform(&pTransform);

	return TRUE;
}
Esempio n. 2
0
LRESULT InitD3D(HWND hWnd)
{
	if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
		return E_FAIL;
	D3DDISPLAYMODE d3ddm;
	if( FAILED( g_pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm ) ) )
		return E_FAIL;
	D3DPRESENT_PARAMETERS d3dpp; 
	ZeroMemory( &d3dpp, sizeof(d3dpp) );
	d3dpp.Windowed   = TRUE;

	d3dpp.BackBufferCount        = 2;
	d3dpp.MultiSampleType        = D3DMULTISAMPLE_NONE;
	d3dpp.MultiSampleQuality     =0;

	d3dpp.SwapEffect = D3DSWAPEFFECT_FLIP;
	d3dpp.BackBufferFormat = d3ddm.Format;
    d3dpp.EnableAutoDepthStencil = TRUE;
    d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
	d3dpp.Flags              = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;
	d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

	if(theViewer.getFullscreen())
	{
		d3dpp.Windowed   = FALSE;
		d3dpp.BackBufferWidth=theViewer.getWidth();
		d3dpp.BackBufferHeight=theViewer.getHeight();

	}

	D3DCAPS9 Caps;
	g_pD3D->GetDeviceCaps(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,&Caps);

	if((Caps.TextureOpCaps & D3DTEXOPCAPS_DOTPRODUCT3) == 0)
	{
		MessageBox(hWnd,
              "Your 3D Card don't support DOT3 operation, bumpmapping is disabled",
		      "Warning",MB_OK);

		g_bCanDot3=false;
	}

	if(Caps.VertexShaderVersion >= D3DVS_VERSION(1,1))
	{
        if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                  D3DCREATE_HARDWARE_VERTEXPROCESSING,
                                  &d3dpp, &g_pD3DDevice ) ) )
			return E_FAIL;
	}
	else
	{
		if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                  D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                  &d3dpp, &g_pD3DDevice ) ) )
			return E_FAIL;
	}

	
	return S_OK;
}
Esempio n. 3
0
RString RageDisplay_D3D::Init( const VideoModeParams &p, bool /* bAllowUnacceleratedRenderer */ )
{
	GraphicsWindow::Initialize( true );

	LOG->Trace( "RageDisplay_D3D::RageDisplay_D3D()" );
	LOG->MapLog("renderer", "Current renderer: Direct3D");

	g_pd3d = Direct3DCreate9(D3D_SDK_VERSION);
	if(!g_pd3d)
	{
		LOG->Trace( "Direct3DCreate9 failed" );
		return D3D_NOT_INSTALLED.GetValue();
	}

	if( FAILED( g_pd3d->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &g_DeviceCaps) ) )
		return HARDWARE_ACCELERATION_NOT_AVAILABLE.GetValue();
			

	D3DADAPTER_IDENTIFIER9	identifier;
	g_pd3d->GetAdapterIdentifier( D3DADAPTER_DEFAULT, 0, &identifier );

	LOG->Trace( 
		"Driver: %s\n"
		"Description: %s\n"
		"Max texture size: %d\n"
		"Alpha in palette: %s\n",
		identifier.Driver, 
		identifier.Description,
		g_DeviceCaps.MaxTextureWidth,
		(g_DeviceCaps.TextureCaps & D3DPTEXTURECAPS_ALPHAPALETTE) ? "yes" : "no" );

	LOG->Trace( "This display adaptor supports the following modes:" );
	D3DDISPLAYMODE mode;

	UINT modeCount = g_pd3d->GetAdapterModeCount(D3DADAPTER_DEFAULT, g_DefaultAdapterFormat);

	for( UINT u=0; u < modeCount; u++ )
		if( SUCCEEDED( g_pd3d->EnumAdapterModes( D3DADAPTER_DEFAULT, g_DefaultAdapterFormat, u, &mode ) ) )
			LOG->Trace( "  %ux%u %uHz, format %d", mode.Width, mode.Height, mode.RefreshRate, mode.Format );

	g_PaletteIndex.clear();
	for( int i = 0; i < 256; ++i )
		g_PaletteIndex.push_back(i);

	// Save the original desktop format.
	g_pd3d->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &g_DesktopMode );

	/* Up until now, all we've done is set up g_pd3d and do some queries. Now,
	 * actually initialize the window. Do this after as many error conditions as
	 * possible, because if we have to shut it down again we'll flash a window briefly. */
	bool bIgnore = false;
	return SetVideoMode( p, bIgnore );
}
Esempio n. 4
0
LRESULT InitD3D(HWND hWnd)
{
	if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
		return E_FAIL;
	D3DDISPLAYMODE d3ddm;
	if( FAILED( g_pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm ) ) )
		return E_FAIL;
	D3DPRESENT_PARAMETERS d3dpp; 
	ZeroMemory( &d3dpp, sizeof(d3dpp) );
	d3dpp.Windowed   = TRUE;

	d3dpp.BackBufferCount        = 2;
	d3dpp.MultiSampleType        = D3DMULTISAMPLE_NONE;
	d3dpp.MultiSampleQuality     =0;

	d3dpp.SwapEffect = D3DSWAPEFFECT_FLIP;
	d3dpp.BackBufferFormat = d3ddm.Format;
    d3dpp.EnableAutoDepthStencil = TRUE;
    d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
	d3dpp.Flags              = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;
	d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

	if(theViewer.getFullscreen())
	{
		d3dpp.Windowed   = FALSE;
		d3dpp.BackBufferWidth=theViewer.getWidth();
		d3dpp.BackBufferHeight=theViewer.getHeight();

	}

	D3DCAPS9 Caps;
	g_pD3D->GetDeviceCaps(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,&Caps);

	if(Caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
	{
        if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                  D3DCREATE_HARDWARE_VERTEXPROCESSING,
                                  &d3dpp, &g_pD3DDevice ) ) )
			return E_FAIL;
	}
	else
	{
		if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                  D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                  &d3dpp, &g_pD3DDevice ) ) )
			return E_FAIL;
	}

	
	return S_OK;
}
/**-----------------------------------------------------------------------------
 * Direct3D 초기화
 *------------------------------------------------------------------------------
 */
HRESULT InitD3D( HWND hWnd )
{

    // 디바이스를 생성하기위한 D3D객체 생성
    if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
        return E_FAIL;

    // 디바이스를 생성할 구조체
    // 복잡한 오브젝트를 그릴것이기때문에, 이번에는 Z버퍼가 필요하다.
    D3DPRESENT_PARAMETERS d3dpp;
    ZeroMemory( &d3dpp, sizeof(d3dpp) );
    d3dpp.Windowed = TRUE;
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
    d3dpp.EnableAutoDepthStencil = TRUE;
    d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

	D3DCAPS9 caps;
	DWORD dwPSProcess;
	// 디바이스의 능력값(caps)을 읽어온다
	g_pD3D->GetDeviceCaps( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps );

	// 지원하는 픽셀쉐이더 버전이 1.0이하라면 REF드라이버를, 1.0이상이면 HW드라이버를 생성한다.
	dwPSProcess = ( caps.PixelShaderVersion < D3DPS_VERSION(1,0) ) ? 0 : 1;

	if( dwPSProcess )
	{
		if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
										  D3DCREATE_HARDWARE_VERTEXPROCESSING, 
										  &d3dpp, &g_pd3dDevice ) ) )
			return E_FAIL;
	}
	else
	{
		if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_REF, hWnd,
										  D3DCREATE_SOFTWARE_VERTEXPROCESSING, 
										  &d3dpp, &g_pd3dDevice ) ) )
			return E_FAIL;
	}

    // 기본컬링, CCW
	g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW );

    // Z버퍼기능을 켠다.
    g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );

    return S_OK;
}
Esempio n. 6
0
HRESULT InitD3D( HWND hWnd, LPDIRECT3D9 &d3d9, LPDIRECT3DDEVICE9 &device)
{
    // Create the D3D object, which is needed to create the D3DDevice.
    if( NULL == ( d3d9 = Direct3DCreate9( D3D_SDK_VERSION ) ) )
        return E_FAIL;

	D3DCAPS9 Caps;
	d3d9->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &Caps);

    D3DPRESENT_PARAMETERS d3dpp;
    ZeroMemory( &d3dpp, sizeof( d3dpp ) );
    d3dpp.Windowed = TRUE;
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;

    // depth 버퍼 설정
	d3dpp.EnableAutoDepthStencil = TRUE;
    d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

    if( FAILED( d3d9->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                      D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                      &d3dpp, &device ) ) )
        return E_FAIL;

	// device의 alpha blending 기능 설정
	device->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
	device->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
	device->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );

	// 빛 처리는 일단 나중에
	device->SetRenderState( D3DRS_LIGHTING, FALSE );
	device->SetRenderState( D3DRS_AMBIENT, 0x00606060 );

	// 일단 다 그리도록
	device->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );

    // z-buffer 사용
	device->SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE );
	device->SetRenderState( D3DRS_ALPHATESTENABLE, TRUE );
	device->SetRenderState( D3DRS_ALPHAREF, 0x00000080 );
	device->SetRenderState( D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL );

	//device->SetRenderState( D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_COLOR1 );

	return S_OK;
}
Esempio n. 7
0
HRESULT HookIDirect3D9::GetDeviceCaps(LPVOID _this, UINT Adapter,D3DDEVTYPE DeviceType,D3DCAPS9* pCaps)
{
	LOG_API();
	return pD3D->GetDeviceCaps(Adapter, DeviceType, pCaps);
}
Esempio n. 8
0
CString RageDisplay_D3D::Init( VideoModeParams p )
{
	GraphicsWindow::Initialize();

	LOG->Trace( "RageDisplay_D3D::RageDisplay_D3D()" );
	LOG->MapLog("renderer", "Current renderer: Direct3D");

	typedef IDirect3D9 * (WINAPI * Direct3DCreate9_t) (UINT SDKVersion);
	Direct3DCreate9_t pDirect3DCreate9;
#if defined(XBOX)
	pDirect3DCreate8 = Direct3DCreate8;
#else
	g_D3D9_Module = LoadLibrary("D3D9.dll");
	if(!g_D3D9_Module)
		return D3D_NOT_INSTALLED;

	pDirect3DCreate9 = (Direct3DCreate9_t) GetProcAddress(g_D3D9_Module, "Direct3DCreate9");
	if(!pDirect3DCreate9)
	{
		LOG->Trace( "Direct3DCreate9 not found" );
		return D3D_NOT_INSTALLED;
	}
#endif

	g_pd3d = pDirect3DCreate9( D3D_SDK_VERSION );
	if(!g_pd3d)
	{
		LOG->Trace( "Direct3DCreate9 failed" );
		return D3D_NOT_INSTALLED;
	}

	if( FAILED( g_pd3d->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &g_DeviceCaps) ) )
		return
			"Your system is reporting that Direct3D hardware acceleration is not available.  "
			"Please obtain an updated driver from your video card manufacturer.\n\n";

	D3DADAPTER_IDENTIFIER9	identifier;
	g_pd3d->GetAdapterIdentifier( D3DADAPTER_DEFAULT, 0, &identifier );

	LOG->Trace( 
		"Driver: %s\n"
		"Description: %s\n"
		"Max texture size: %d\n"
		"Alpha in palette: %s\n",
		identifier.Driver, 
		identifier.Description,
		g_DeviceCaps.MaxTextureWidth,
		(g_DeviceCaps.TextureCaps & D3DPTEXTURECAPS_ALPHAPALETTE) ? "yes" : "no" );

	LOG->Trace( "This display adaptor supports the following modes:" );
	D3DDISPLAYMODE mode;
	UINT modeCount = g_pd3d->GetAdapterModeCount(D3DADAPTER_DEFAULT, g_DefaultAdapterFormat);
	
	for( UINT u=0; u<modeCount; u++ )
		if( SUCCEEDED( g_pd3d->EnumAdapterModes( D3DADAPTER_DEFAULT, g_DefaultAdapterFormat, u, &mode ) ) )
			LOG->Trace( "  %ux%u %uHz, format %d", mode.Width, mode.Height, mode.RefreshRate, mode.Format );

	g_PaletteIndex.clear();
	for( int i = 0; i < 256; ++i )
		g_PaletteIndex.push_back(i);

	// Save the original desktop format.
	g_pd3d->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &g_DesktopMode );

	/* Up until now, all we've done is set up g_pd3d and do some queries.  Now,
	 * actually initialize the window.  Do this after as many error conditions
	 * as possible, because if we have to shut it down again we'll flash a window
	 * briefly. */
	bool bIgnore = false;
	return SetVideoMode( p, bIgnore );
}
Esempio n. 9
0
HRESULT InitD3D(HINSTANCE hInstance)
{
	// 先创建DInput和DSound
	if(FAILED(DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&g_pDI, NULL)))
		return E_FAIL;
	if(FAILED(g_pDI->CreateDevice(GUID_SysKeyboard, &g_pDIKey, NULL)))
		return E_FAIL;
	if(FAILED(g_pDI->CreateDevice(GUID_SysMouse, &g_pDIMouse, NULL)))
		return E_FAIL;
		// 设置参数
	if(FAILED(g_pDIKey->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE)))
		return E_FAIL;
	if(FAILED(g_pDIKey->SetDataFormat(&c_dfDIKeyboard)))
		return E_FAIL;
	if(FAILED(g_pDIMouse->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE)))
		return E_FAIL;
	if(FAILED(g_pDIMouse->SetDataFormat(&c_dfDIMouse)))
		return E_FAIL;
		
		// 缓冲输入,设置数据格式和属性
	DIPROPDWORD dipdw;
	dipdw.diph.dwSize       = sizeof(DIPROPDWORD);
	dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
	dipdw.diph.dwObj        = 0;
	dipdw.diph.dwHow        = DIPH_DEVICE;
	dipdw.dwData            = SAMPLE_BUFFER_SIZE; // Arbitary buffer size

#ifdef USE_BUFFERED_KEYBOARD_INPUT
	if( FAILED( g_pDIKey->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph ) ) )
		return E_FAIL;
#endif
#ifdef USE_BUFFERED_MOUSE_INPUT
	if( FAILED( g_pDIMouse->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph ) ) )
		return E_FAIL;
#endif

		// 开始
	g_pDIKey->Acquire();
	g_pDIMouse->Acquire();



	// 初始化D3D
	if(NULL==(d3d=Direct3DCreate9(D3D_SDK_VERSION)))
		  return E_FAIL;

	//查询当前显卡模式,Desktop是目前桌面设置,d3ddm总是当前使用全屏模式的设置,即使是窗口模式,颜色数值也总和当前的一样
	if(FAILED(d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &DesktopDisplayMode)))
		  return E_FAIL;
	if(FAILED(d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm)))
		return E_FAIL;

	//全屏的话默认是32位色
	if(!WindowMode) d3ddm.Format = D3DFMT_X8R8G8B8;

	//查询设备能力,并设置顶点处理器模式
	DWORD UserVertexShaderProcessing;

	d3d->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &d3dcaps);

	if(FAILED(DetectDeviceCaps())) return E_FAIL;

	if(d3dcaps.VertexShaderVersion < D3DVS_VERSION(1, 0))
		UserVertexShaderProcessing=D3DCREATE_HARDWARE_VERTEXPROCESSING;
	else
		UserVertexShaderProcessing=D3DCREATE_SOFTWARE_VERTEXPROCESSING;

//创建D3D设备
	ZeroMemory(&d3dpp,sizeof(d3dpp));

	d3dpp.Windowed = WindowMode;
	d3dpp.SwapEffect = D3DSWAPEFFECT_COPY;
	d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
	d3dpp.hDeviceWindow = hWnd;
	d3dpp.BackBufferCount = 1;
	d3dpp.BackBufferWidth = d3ddm.Width;
	d3dpp.BackBufferHeight = d3ddm.Height;
	d3dpp.EnableAutoDepthStencil = TRUE;
	
	if(WindowMode)
	{
		d3ddm.Format = DesktopDisplayMode.Format;
		d3dpp.BackBufferWidth = WindowWidth;
		d3dpp.BackBufferHeight = WindowHeight;
	}

	d3dpp.BackBufferFormat = d3ddm.Format;

	if(d3ddm.Format == D3DFMT_X8R8G8B8)
	{
		d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8;
		TextureFormat = D3DFMT_A8R8G8B8;
	}
	else
	{
		d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
		TextureFormat = D3DFMT_A4R4G4B4;
	}


	// 先强制以硬件顶点方式创建设备(为了不漏掉MX440这种不支持VS但支持T&L的显卡,XIXI)
	UserVertexShaderProcessing = D3DCREATE_HARDWARE_VERTEXPROCESSING;
	HRESULT hr = d3d->CreateDevice( D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL, hWnd, UserVertexShaderProcessing, &d3dpp, &d3ddevice);
	// 这种错误表示顶点处理方式不被硬件支持,强制以软件方式创建设备(为了兼容不支持T&L的DX7显卡,比如某些集成显卡)
	if(hr == D3DERR_INVALIDCALL)
	{
		mymessage("警告:显卡不支持硬件顶点处理,强制以软件方式创建设备,性能会急剧下降!!!");
		UserVertexShaderProcessing = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
		hr = d3d->CreateDevice( D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL, hWnd, UserVertexShaderProcessing, &d3dpp, &d3ddevice);
	}
	// 全部失败?有问题吧?
	if(FAILED(hr))
	{
		char szErrorInfo[512] = "";
		sprintf(szErrorInfo, "创建D3D设备失败!请检查系统或硬件设置!比如显卡驱动程序或DirectX是否安装正确!错误号%x", hr);
		mymessage(szErrorInfo);
		return E_FAIL;
	}

	// Shader版本检测
	char pVSVersion[7] = "", pPSVersion[7] = "";
	char pNeedVSVersion[7] = USE_VSVERSION, pNeedPSVersion[7] = USE_PSVERSION;
	char szErrorInfo[100] = "";

#ifdef USE_PIXELSHADER
	// 判断PS版本
	memcpy(pPSVersion, D3DXGetPixelShaderProfile(d3ddevice), 7);
	// 2.x中'b'虽然字母数值大于'a',但它从支持度上来看是小于a的,所以这里强制把它置为小于'a',以便后面比较
	if(pPSVersion[3] == '2' && pPSVersion[5] == 'b')
		pPSVersion[5] = 'a'-1;
	if(pNeedPSVersion[3] == '2' && pNeedPSVersion[5] == 'b')
		pNeedPSVersion[5] = 'a'-1;
	if(pPSVersion[3]<pNeedPSVersion[3] || pPSVersion[3]==pNeedPSVersion[3]&&pPSVersion[5]<pNeedPSVersion[5])
	{
		sprintf(szErrorInfo, "不支持Pixel Shader %c.%c!", pNeedPSVersion[3], pNeedPSVersion[5]);
		mymessage(szErrorInfo);	return E_FAIL;
	}
	
	// 判断PS2.0x的条件是否符合程序的最小需求
	if(!strcmp(USE_PSVERSION, "ps_2_a") || !strcmp(USE_PSVERSION, "ps_2_b") || !strcmp(USE_PSVERSION, "ps_2_x"))
	{
		BOOL bFlowControl = FALSE;
#ifdef PS2x_USE_FLOWCONTROL
		bFlowControl = TRUE;
#endif

		if(!CheckPS2xSupport(PS2x_USE_MAXNUM_TEMP, bFlowControl))
		{
			sprintf(szErrorInfo, "不完整支持Pixel Shader 2.x,无法执行程序!");
			mymessage(szErrorInfo);	return E_FAIL;
		}
	}


#endif USE_PIXELSHADER

#ifdef USE_VERTEXSHADER
	BOOL bSoftwareVertexProcessing = FALSE;
	// 完全不支持的,要跳过版本检测,否则D3DXGetVertexShaderProfile会返回空指针造成非法操作
	if((d3dcaps.VertexShaderVersion&0xffff) == 0) 
	{
		bSoftwareVertexProcessing = TRUE;
	}
	else
	{
		// 判断VS版本
		memcpy(pVSVersion, D3DXGetVertexShaderProfile(d3ddevice), 7);
		if(pVSVersion[3]<pNeedVSVersion[3] || pVSVersion[3]==pNeedVSVersion[3]&&pVSVersion[5]<pNeedVSVersion[5])
		{
			bSoftwareVertexProcessing = TRUE;
		}
		// 判断VS2.0x的条件是否符合程序的最小需求
		if(!strcmp(USE_VSVERSION, "vs_2_a") || !strcmp(USE_VSVERSION, "vs_2_b") || !strcmp(USE_VSVERSION, "vs_2_x"))
		{
#ifdef VS2a_USE_MAXNUM_TEMP
			if(d3dcaps.VS20Caps.NumTemps < VS2x_USE_MAXNUM_TEMP)
			{
				bSoftwareVertexProcessing = TRUE;
			}
#endif
		}
	}

	// 如果刚才是以硬件顶点创建设备的,而现在又需要强制软顶点以运行硬件不支持的VS,那么释放设备,重新创建
	if(bSoftwareVertexProcessing && UserVertexShaderProcessing == D3DCREATE_HARDWARE_VERTEXPROCESSING)
	{
		// 如果不支持指定版本的Vertex Shader,就强制创建软顶点处理设备
		sprintf(szErrorInfo, "警告:显卡不支持Vertex Shader %c.%c!强制以软件方式创建设备,性能会急剧下降!!!", pNeedVSVersion[3], pNeedVSVersion[5]);
		mymessage(szErrorInfo);
		SAFE_RELEASE(d3ddevice);
		hr = d3d->CreateDevice( D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL, hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddevice);
		if(FAILED(hr))
		{
			char szErrorInfo[512] = "";
			sprintf(szErrorInfo, "创建D3D设备失败!请检查系统或硬件设置!比如显卡驱动程序或DirectX是否安装正确!错误号%x", hr);
			mymessage(szErrorInfo);
			return E_FAIL;
		}
	}

#endif



	//初始化摄像机,之所以放在这里,是为了设备丢失后不会又重置到初始位置
	D3DXVECTOR3 PtLookAt = g_PtCameraInitPos + g_VecCameraInitDir;
	CameraChange.InitCamera(g_PtCameraInitPos.x, g_PtCameraInitPos.y, g_PtCameraInitPos.z,  PtLookAt.x, PtLookAt.y, PtLookAt.z,  0.0f,1.0f,0.0f, 7,7,90);

	//得到硬件精确计时器的频率
	QueryPerformanceFrequency(&PerformanceFrequency);

	return S_OK;
}
Esempio n. 10
0
bool D3D9_Init(HWND wnd, bool windowed, std::string *error_message) {
    hWnd = wnd;

    DIRECT3DCREATE9EX g_pfnCreate9ex;

    hD3D9 = LoadLibrary(TEXT("d3d9.dll"));
    if (!hD3D9) {
        ELOG("Missing d3d9.dll");
        *error_message = "D3D9.dll missing - try reinstalling DirectX.";
        return false;
    }

    int d3dx_version = LoadD3DX9Dynamic();
    if (!d3dx_version) {
        *error_message = "D3DX DLL not found! Try reinstalling DirectX.";
        return false;
    }

    g_pfnCreate9ex = (DIRECT3DCREATE9EX)GetProcAddress(hD3D9, "Direct3DCreate9Ex");
    has9Ex = (g_pfnCreate9ex != NULL) && IsVistaOrHigher();

    if (has9Ex) {
        HRESULT result = g_pfnCreate9ex(D3D_SDK_VERSION, &d3dEx);
        d3d = d3dEx;
        if (FAILED(result)) {
            FreeLibrary(hD3D9);
            *error_message = "D3D9Ex available but context creation failed. Try reinstalling DirectX.";
            return false;
        }
    } else {
        d3d = Direct3DCreate9(D3D_SDK_VERSION);
        if (!d3d) {
            FreeLibrary(hD3D9);
            *error_message = "Failed to create D3D9 context. Try reinstalling DirectX.";
            return false;
        }
    }

    D3DCAPS9 d3dCaps;

    D3DDISPLAYMODE d3ddm;
    if (FAILED(d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm))) {
        *error_message = "GetAdapterDisplayMode failed";
        d3d->Release();
        return false;
    }

    adapterId = D3DADAPTER_DEFAULT;
    if (FAILED(d3d->GetDeviceCaps(adapterId, D3DDEVTYPE_HAL, &d3dCaps))) {
        *error_message = "GetDeviceCaps failed (???)";
        d3d->Release();
        return false;
    }

    HRESULT hr;
    if (FAILED(hr = d3d->CheckDeviceFormat(D3DADAPTER_DEFAULT,
                                           D3DDEVTYPE_HAL,
                                           d3ddm.Format,
                                           D3DUSAGE_DEPTHSTENCIL,
                                           D3DRTYPE_SURFACE,
                                           D3DFMT_D24S8))) {
        if (hr == D3DERR_NOTAVAILABLE) {
            *error_message = "D24S8 depth/stencil not available";
            d3d->Release();
            return false;
        }
    }

    DWORD dwBehaviorFlags = D3DCREATE_MULTITHREADED | D3DCREATE_FPU_PRESERVE;
    if (d3dCaps.VertexProcessingCaps != 0)
        dwBehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
    else
        dwBehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;

    int xres, yres;
    GetRes(xres, yres);

    memset(&pp, 0, sizeof(pp));
    pp.BackBufferWidth = xres;
    pp.BackBufferHeight = yres;
    pp.BackBufferFormat = d3ddm.Format;
    pp.MultiSampleType = D3DMULTISAMPLE_NONE;
    pp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    pp.Windowed = windowed;
    pp.hDeviceWindow = wnd;
    pp.EnableAutoDepthStencil = true;
    pp.AutoDepthStencilFormat = D3DFMT_D24S8;
    pp.PresentationInterval = (g_Config.bVSync) ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;

    if (has9Ex) {
        if (windowed && IsWin7OrLater()) {
            // This new flip mode gives higher performance.
            // TODO: This makes it slower?
            //pp.BackBufferCount = 2;
            //pp.SwapEffect = D3DSWAPEFFECT_FLIPEX;
        }
        hr = d3dEx->CreateDeviceEx(adapterId, D3DDEVTYPE_HAL, wnd, dwBehaviorFlags, &pp, NULL, &deviceEx);
        device = deviceEx;
    } else {
        hr = d3d->CreateDevice(adapterId, D3DDEVTYPE_HAL, wnd, dwBehaviorFlags, &pp, &device);
    }

    if (FAILED(hr)) {
        *error_message = "Failed to create D3D device";
        d3d->Release();
        return false;
    }

    device->BeginScene();
    DX9::pD3Ddevice = device;
    DX9::pD3DdeviceEx = deviceEx;

    if (!DX9::CompileShaders(*error_message)) {
        *error_message = "Unable to compile shaders: " + *error_message;
        device->EndScene();
        device->Release();
        d3d->Release();
        DX9::pD3Ddevice = nullptr;
        DX9::pD3DdeviceEx = nullptr;
        device = nullptr;
        UnloadD3DXDynamic();
        return false;
    }

    DX9::fbo_init(d3d);

    if (deviceEx && IsWin7OrLater()) {
        // TODO: This makes it slower?
        //deviceEx->SetMaximumFrameLatency(1);
    }

    return true;
}
Esempio n. 11
0
	//< d3d초기화
	HRESULT			Init3D( HWND hWnd , HINSTANCE hInst, BOOL bWindowMode, INT nWidth, INT nHeight )
	{
		m_hWnd	= hWnd;
		m_hInst	= hInst;

		//< d3d객체 인터페이스 생성
		m_pd3d = Direct3DCreate9( D3D_SDK_VERSION );

		//< 예외 처리 
		if( m_pd3d == NULL )
		{
			//< 에러 
			return E_FAIL;
		}

		//< 하드웨어 가속 여부 확인 (Caps)
		D3DCAPS9		caps;	//< 장치 정보 
		DWORD			dwVp;	//< 버텍스 프로세싱
		D3DDEVTYPE		sDevType;

		m_pd3d->GetDeviceCaps(D3DADAPTER_DEFAULT , D3DDEVTYPE_HAL, &caps);

		if( caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT )
		{
			dwVp = D3DCREATE_HARDWARE_VERTEXPROCESSING;
			sDevType = D3DDEVTYPE_HAL;
		}
		else
		{
			dwVp = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
			sDevType = D3DDEVTYPE_SW;
		}

		//< D3D파라메터 설정 
		D3DPRESENT_PARAMETERS		d3dpp;
		ZeroMemory(&d3dpp,sizeof(D3DPRESENT_PARAMETERS));

		d3dpp.BackBufferWidth			= nWidth;
		d3dpp.BackBufferHeight			= nHeight;
		d3dpp.BackBufferCount			= 1;
		d3dpp.SwapEffect				= D3DSWAPEFFECT_DISCARD;
		d3dpp.BackBufferFormat			= D3DFMT_X8R8G8B8;
		d3dpp.AutoDepthStencilFormat	= D3DFMT_D24S8;	
		d3dpp.EnableAutoDepthStencil	= TRUE;	
		d3dpp.Windowed					= bWindowMode;

		//< 디바이스 생성
		if( FAILED(m_pd3d->CreateDevice(
			D3DADAPTER_DEFAULT,
			sDevType,
			m_hWnd,
			dwVp,
			&d3dpp,
			&m_pd3dDevice)))
		{
			//< 디바이스 예외 처리 
			return E_FAIL;
		}

		//< 끝~~
		return S_OK;
	}
Esempio n. 12
0
//==================================
//  函数:InitD3D( HWND )
//  目的:初始化Direct3D设备对象
//
bool InitD3D()
{
	//创建Direct3D对象    [用于获取硬件信息]
	g_pD3D = Direct3DCreate9(D3D_SDK_VERSION);
	if(g_pD3D==NULL) return false;

	//检查是否支持硬件顶点处理
	D3DCAPS9 caps;
	g_pD3D->GetDeviceCaps(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,&caps);
	int vp=0;
	if(caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
		vp=D3DCREATE_HARDWARE_VERTEXPROCESSING;  //硬件处理
	else
		vp=D3DCREATE_SOFTWARE_VERTEXPROCESSING;  //软件处理

	//检查硬件支持的shader的版本
/*	if(caps.VertexShaderVersion < D3DVS_VERSION(2,0))
		deviceType = D3DDEVTYPE_REF;
	else
		deviceType = D3DDEVTYPE_HAL;*/

	//设置D3DPRESENT_PARAMETERS结构
	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory(&d3dpp,sizeof(d3dpp));
	d3dpp.Windowed = TRUE;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
//	d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;  //实时模式,默认是根据屏幕刷新频率

	//创建Direct3D设备对象     [用于渲染图形]
	if( FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hwnd,vp,&d3dpp,&g_pd3dD)) )
		return false;

	//设置观察和投影矩阵
	setupViewAndProjMat();

	//设置线性过滤
	g_pd3dD->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
	g_pd3dD->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_ANISOTROPIC);
	g_pd3dD->SetSamplerState(1, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
	g_pd3dD->SetSamplerState(1, D3DSAMP_MINFILTER, D3DTEXF_ANISOTROPIC);

	//设置纹理寻址模式
	g_pd3dD->SetSamplerState(0, D3DSAMP_BORDERCOLOR, 0x00000000);
	g_pd3dD->SetSamplerState(0, D3DSAMP_ADDRESSU,    D3DTADDRESS_BORDER);
	g_pd3dD->SetSamplerState(0, D3DSAMP_ADDRESSV,    D3DTADDRESS_BORDER);
	g_pd3dD->SetSamplerState(1, D3DSAMP_BORDERCOLOR, 0x00000000);
	g_pd3dD->SetSamplerState(1, D3DSAMP_ADDRESSU,    D3DTADDRESS_BORDER);
	g_pd3dD->SetSamplerState(1, D3DSAMP_ADDRESSV,    D3DTADDRESS_BORDER);
	g_pd3dD->SetSamplerState(2, D3DSAMP_BORDERCOLOR, 0x00000000);
	g_pd3dD->SetSamplerState(2, D3DSAMP_ADDRESSU,    D3DTADDRESS_BORDER);
	g_pd3dD->SetSamplerState(2, D3DSAMP_ADDRESSV,    D3DTADDRESS_BORDER);

	//正反面都绘制
	g_pd3dD->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
    //关闭光照
	g_pd3dD->SetRenderState( D3DRS_LIGHTING, FALSE );

	//激活alpha混合
	g_pd3dD->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
	g_pd3dD->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
	g_pd3dD->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
	g_pd3dD->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);


	InitVertex();      //初始化顶点缓存,用于装载贴图

	return true;
}
Esempio n. 13
0
int EnumerateDriver(D3DDEVICEINFO **tabdev)
{
   typedef char devDesc[4];
   unsigned int i, j, k;
   const DWORD dwNumDeviceTypes = 1;
   devDesc strDeviceDescs[2] = { "HAL", "REF" };
   const D3DDEVTYPE DeviceTypes[] = { D3DDEVTYPE_HAL, D3DDEVTYPE_REF };
   BOOL bHALExists = FALSE;
   BOOL bHALIsWindowedCompatible = FALSE;
   BOOL bHALIsDesktopCompatible = FALSE;
   BOOL bHALIsSampleCompatible = FALSE;

   g_pD3D = Direct3DCreate9(D3D_SDK_VERSION);
   D3DDISPLAYMODE modes[100];
   D3DFORMAT      formats[20];
   DWORD dwNumFormats      = 0;
   DWORD dwNumModes        = 0;
   DWORD dwNumAdapterModes = g_pD3D->GetAdapterModeCount(0, D3DFMT_A8R8G8B8);
   DWORD dwNumDevices;

   for(i=0; i < dwNumAdapterModes; i++)
   {
      // Get the display mode attributes
      D3DDISPLAYMODE DisplayMode;
      g_pD3D->EnumAdapterModes(0, D3DFMT_A8R8G8B8, i, &DisplayMode);

      // Check if the mode already exists (to filter out refresh rates)
      for(j=0; j<dwNumModes; j++)
      {
         if(( modes[j].Width  == DisplayMode.Width  ) &&
            ( modes[j].Height == DisplayMode.Height ) &&
            ( modes[j].Format == DisplayMode.Format ))
                    break;
	  }
      // If we found a new mode, add it to the list of modes
      if (j == dwNumModes)
      {
         modes[dwNumModes].Width       = DisplayMode.Width;
         modes[dwNumModes].Height      = DisplayMode.Height;
         modes[dwNumModes].Format      = DisplayMode.Format;
         modes[dwNumModes].RefreshRate = 0;
         dwNumModes++;

         // Check if the mode's format already exists
         for(k=0; k<dwNumFormats; k++)
         {
            if (DisplayMode.Format == formats[k]) break;
		 }
         // If the format is new, add it to the list
         if(k==dwNumFormats) formats[dwNumFormats++] = DisplayMode.Format;
	  }
   }
   // Sort the list of display modes (by format, then width, then height)
   qsort(modes, dwNumModes, sizeof(D3DDISPLAYMODE), SortModesCallback);

   // Add devices to adapter
   dwNumDevices=0;
   for(i=0; i<dwNumDeviceTypes; i++)
   {
     // Fill in device info
     D3DDEVICEINFO *pDevice;
     pDevice  = &g_Devices[dwNumDevices];
	 pDevice->DeviceType = DeviceTypes[i];
	 // se non ci sono devices HAL o T&L ritorna errore
	 if (g_pD3D->GetDeviceCaps(0, D3DDEVTYPE_HAL, &pDevice->d3dCaps)!=D3D_OK)
	    return(-1);

     strcpy(pDevice->strDesc, strDeviceDescs[i]);
     pDevice->dwNumModes     = 0;
     pDevice->bCanDoWindowed = FALSE;
     pDevice->MultiSampleType = D3DMULTISAMPLE_NONE;

     // Examine each format supported by the adapter to see if it will
     // work with this device and meets the needs of the application.
     BOOL  bFormatConfirmed[20];
     DWORD dwBehavior[20];
     D3DFORMAT fmtDepthStencil[20];

     for(DWORD f=0; f<dwNumFormats; f++)
     {
        bFormatConfirmed[f] = FALSE;
        fmtDepthStencil[f] = D3DFMT_UNKNOWN;
        // Skip formats that cannot be used as render targets on this device
        if( FAILED(g_pD3D->CheckDeviceType(0, pDevice->DeviceType,
                                            formats[f], formats[f], FALSE )))
        continue;

        if(pDevice->DeviceType == D3DDEVTYPE_HAL )
        {
           // This system has a HAL device
           bHALExists = TRUE;
           if(pDevice->d3dCaps.Caps2)
           {
               // HAL can run in a window for some mode
               bHALIsWindowedCompatible = TRUE;
			   /*
               if(f == 0)
               {
                   // HAL can run in a window for the current desktop mode
                   bHALIsDesktopCompatible = TRUE;
               }
			   */
           }
		}

       // Confirm the device/format for HW vertex processing
       if (pDevice->d3dCaps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
       {
          if (pDevice->d3dCaps.DevCaps & D3DDEVCAPS_PUREDEVICE)
          {
              dwBehavior[f] = D3DCREATE_HARDWARE_VERTEXPROCESSING |
                              D3DCREATE_PUREDEVICE;
              bFormatConfirmed[f] = TRUE;
          }
          if (FALSE == bFormatConfirmed[f])
          {
             dwBehavior[f] = D3DCREATE_HARDWARE_VERTEXPROCESSING;
             bFormatConfirmed[f] = TRUE;
          }
          if (FALSE == bFormatConfirmed[f])
          {
             dwBehavior[f] = D3DCREATE_MIXED_VERTEXPROCESSING;
             bFormatConfirmed[f] = TRUE;
          }
	   }
       // Confirm the device/format for SW vertex processing
       if(bFormatConfirmed[f]==FALSE)
       {
         dwBehavior[f] = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
         bFormatConfirmed[f] = TRUE;
       }

       // Find a suitable depth/stencil buffer format for this device/format
       if(bFormatConfirmed[f])
       {
           if(!FindDepthStencilFormat(0, pDevice->DeviceType,
                         formats[f], &fmtDepthStencil[f]))
           {
              bFormatConfirmed[f] = FALSE;
		   }
       }
	 }

     // Add all enumerated display modes with confirmed formats to the
     // device's list of valid modes
     for(DWORD m=0L; m<dwNumModes; m++)
     {
         for( DWORD f=0; f<dwNumFormats; f++)
         {
             if (modes[m].Format == formats[f])
             {
                 if(bFormatConfirmed[f] == TRUE)
                 {
                   // Add this mode to the device's list of valid modes
                   pDevice->SupportedModes[pDevice->dwNumModes].Width      = modes[m].Width;
                   pDevice->SupportedModes[pDevice->dwNumModes].Height     = modes[m].Height;
                   pDevice->SupportedModes[pDevice->dwNumModes].Format     = modes[m].Format;
                   pDevice->SupportedModes[pDevice->dwNumModes].Bpp        = D3DFormat2Bpp(modes[m].Format);
                   pDevice->SupportedModes[pDevice->dwNumModes].dwBehavior = dwBehavior[f];
                   pDevice->SupportedModes[pDevice->dwNumModes].DepthStencilFormat = fmtDepthStencil[f];
                   pDevice->dwNumModes++;

                   if(pDevice->DeviceType == D3DDEVTYPE_HAL)
                                bHALIsSampleCompatible = TRUE;
                 }
              }
         }
	 }
     if (pDevice->d3dCaps.Caps2) pDevice->bCanDoWindowed = TRUE;
     if (pDevice->dwNumModes > 0) dwNumDevices++;
   }

   if(0 == dwNumDevices)
   {
	  *tabdev=NULL;
      return -1;
   }
   else
   {
	 *tabdev=g_Devices;
	 return(dwNumDevices);
   }
}
Esempio n. 14
0
HRESULT KGraphicsEngine::InitializeWindowed(HWND hBaseWindow, HWND hRenderWindow)
{
	// Create the D3D object.
    if ( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
	{
		MessageBox(hBaseWindow,"Failed Create the D3D object!.","Failed Create the D3D object!",0);
        return E_FAIL;
	}
    // Get the current desktop display mode, so we can set up a back
    // buffer of the same format
	g_pD3D->GetDeviceCaps(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,&g_D3DCaps);

    if ( FAILED( g_pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &m_DisplayMode ) ) )
	{
		MessageBox(hBaseWindow,"Failed GetAdapterDisplayMode !.","Failed Create the D3D object!",0);
		return E_FAIL;
	}
     
    // Set up the structure used to create the D3DDevice
	D3DFORMAT  DepFormat;
	if (SUCCEEDED(g_pD3D->CheckDepthStencilMatch(D3DADAPTER_DEFAULT,
		D3DDEVTYPE_HAL,
		m_DisplayMode.Format,
		m_DisplayMode.Format,
		D3DFMT_D24S8)))
	{
		DepFormat = D3DFMT_D24S8;
	}
	else
	{
		DepFormat = D3DFMT_D16;
	}

    memset( &m_PresentParam, 0, sizeof(D3DPRESENT_PARAMETERS) );

    memset(&m_RenderWindowRect, 0, sizeof(m_RenderWindowRect));	

	if(hRenderWindow)
		::GetWindowRect(hRenderWindow,&m_RenderWindowRect);
	else
	{
		::GetWindowRect(hBaseWindow,&m_RenderWindowRect);
		hRenderWindow = hBaseWindow;
	}
		
	//m_PresentParam.BackBufferWidth = m_RenderWindowRect.right-m_RenderWindowRect.left ;
    //m_PresentParam.BackBufferHeight= m_RenderWindowRect.bottom - m_RenderWindowRect.top;
	m_PresentParam.BackBufferWidth = m_DisplayMode.Width ;
	m_PresentParam.BackBufferHeight= m_DisplayMode.Height;

    m_PresentParam.Windowed = TRUE ;
    m_PresentParam.SwapEffect = D3DSWAPEFFECT_DISCARD;
    m_PresentParam.BackBufferFormat = m_DisplayMode.Format;
	m_PresentParam.EnableAutoDepthStencil = TRUE;
    m_PresentParam.AutoDepthStencilFormat = DepFormat;
    m_PresentParam.MultiSampleType = D3DMULTISAMPLE_NONE;
    m_PresentParam.hDeviceWindow = hBaseWindow;
    m_PresentParam.Flags = 0;
    m_PresentParam.FullScreen_RefreshRateInHz = 0;
    m_PresentParam.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

	//just set camera's aspect
	m_cCamera.Aspect = m_PresentParam.BackBufferWidth*1.0f/m_PresentParam.BackBufferHeight; 

	HRESULT hr;

	// Set default settings
	UINT AdapterToUse=D3DADAPTER_DEFAULT;
	D3DDEVTYPE DeviceType=D3DDEVTYPE_HAL;
//#if SHIPPING_VERSION
	// When building a shipping version, disable NVPerfHUD (opt-out)
//#else
	// Look for 'NVIDIA NVPerfHUD' adapter
	// If it is present, override default settings
	for (UINT Adapter=0;Adapter<g_pD3D->GetAdapterCount();Adapter++)
	{
		D3DADAPTER_IDENTIFIER9 Identifier;
		HRESULT Res=g_pD3D->GetAdapterIdentifier(Adapter,0,&Identifier);
		if (strcmp(Identifier.Description,"NVIDIA NVPerfHUD")==0)
		{
			AdapterToUse=Adapter;
			DeviceType=D3DDEVTYPE_REF;
			break;
		}
	}
//#endif

    // Create the D3DDevice
    /*if ( FAILED(hr = g_pD3D->CreateDevice( AdapterToUse, DeviceType, hBaseWindow,
                                      D3DCREATE_HARDWARE_VERTEXPROCESSING,
                                      &m_PresentParam, &g_pd3dDevice ) ) )
    {*/
		if ( FAILED(hr = g_pD3D->CreateDevice( AdapterToUse, DeviceType, hBaseWindow,
                                      D3DCREATE_MIXED_VERTEXPROCESSING,
                                      &m_PresentParam, &g_pd3dDevice ) ) )
		{
			if ( FAILED(hr = g_pD3D->CreateDevice( AdapterToUse, DeviceType, hBaseWindow,
                                      D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                      &m_PresentParam, &g_pd3dDevice ) ) )
			{
				
				if (hr == D3DERR_INVALIDCALL)
					MessageBox(hBaseWindow,"The method call is invalid. For example, a method's parameter may have an invalid value.","Failed Create Device!",0);
				else if (hr == E_OUTOFMEMORY )
					MessageBox(hBaseWindow,"Direct3D could not allocate sufficient memory to complete the call.","Failed Create Device!",0);
				else if (hr == D3DERR_OUTOFVIDEOMEMORY)
					MessageBox(hBaseWindow,"Direct3D does not have enough display memory to perform the operation. ","Failed Create Device!",0);
				return E_FAIL;
			}
		}
	
  /*  }*/
    
//	D3DMULTISAMPLE_TYPE Mul = D3DMULTISAMPLE_4_SAMPLES;
//
//	if( FAILED(g_pD3D->CheckDeviceMultiSampleType( D3DADAPTER_DEFAULT, 
//			D3DDEVTYPE_HAL, m_PresentParam.BackBufferFormat, 
//			FALSE, Mul, NULL ) ) &&
//			SUCCEEDED(g_pD3D->CheckDeviceMultiSampleType( D3DADAPTER_DEFAULT, 
//			D3DDEVTYPE_HAL, m_PresentParam.AutoDepthStencilFormat, 
//			FALSE, Mul, NULL ) ) )
//	{
//		Mul = D3DMULTISAMPLE_3_SAMPLES; 
//
//		if( FAILED(g_pD3D->CheckDeviceMultiSampleType( D3DADAPTER_DEFAULT, 
//			D3DDEVTYPE_HAL, m_PresentParam.BackBufferFormat, 
//			FALSE, Mul, NULL ) ) &&
//			SUCCEEDED(g_pD3D->CheckDeviceMultiSampleType( D3DADAPTER_DEFAULT, 
//			D3DDEVTYPE_HAL, m_PresentParam.AutoDepthStencilFormat, 
//			FALSE, Mul, NULL ) ) )
//		{
//			Mul = D3DMULTISAMPLE_2_SAMPLES; 
//
//			if( FAILED(g_pD3D->CheckDeviceMultiSampleType( D3DADAPTER_DEFAULT, 
//				D3DDEVTYPE_HAL, m_PresentParam.BackBufferFormat, 
//				FALSE, Mul, NULL ) ) &&
//				SUCCEEDED(g_pD3D->CheckDeviceMultiSampleType( D3DADAPTER_DEFAULT, 
//				D3DDEVTYPE_HAL, m_PresentParam.AutoDepthStencilFormat, 
//				FALSE, Mul, NULL ) ) )
//			{
//				Mul = D3DMULTISAMPLE_NONE; 
//			}
//		}
//	}
//	if (Mul != D3DMULTISAMPLE_NONE)
//	{
//		m_PresentParam.MultiSampleType = Mul;
//		g_pd3dDevice->Reset( &m_PresentParam );
//	}
    
    // Device state would normally be set here
	// Turn off culling, so we see the front and back of the triangle
     g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW  );

    // Turn off D3D lighting, since we are providing our own vertex colors

    // Turn on the zbuffer
    g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );
    //g_pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE , TRUE );
    g_pd3dDevice->SetRenderState( D3DRS_ZFUNC, D3DCMP_LESSEQUAL  );

	g_cGraphicsTool.SetCurCamera(&m_cCamera);
	
	PreRender(); 
	m_bWindowed = TRUE;
    
	if (m_bUseMotionBlur)
	{
		BackBufferCreate();
		
		g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,
			0xff666666, 1.0f, 0 );
	}

	return S_OK;
}
Esempio n. 15
0
//==================================
//  函数:InitD3D( HWND )
//  目的:初始化Direct3D设备对象
//
bool _InitD3D(HWND hwnd,RECT* Rect,const char* font_lib)
{
	dhwnd = hwnd;
	if(Rect)
	{
		drect.bottom = Rect->bottom-Rect->top;
		drect.right  = Rect->right-Rect->left;
	}
	else
	{
		GetClientRect(dhwnd, &drect);
	}

	imgbase* **&map = full_map.full_map;
	//初始化窗口map(用于检测btn)
	map = new imgbase* *[drect.right];
	for(int i=0;i<drect.right;i++)
		map[i] = new imgbase*[drect.bottom];

	for(int x=0;x<drect.right;x++)
	{
		for(int y=0;y<drect.bottom;y++)
			map[x][y] = 0;
	}
	full_map.width = drect.right; full_map.height = drect.bottom;

	//创建Direct3D对象    [用于获取硬件信息]
	g_pD3D = Direct3DCreate9(D3D_SDK_VERSION);
	if(g_pD3D==NULL) return false;

	//检查是否支持硬件顶点处理
	D3DCAPS9 caps;
	g_pD3D->GetDeviceCaps(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,&caps);
	int vp=0;
	if(caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
		vp=D3DCREATE_HARDWARE_VERTEXPROCESSING;  //硬件处理
	else
		vp=D3DCREATE_SOFTWARE_VERTEXPROCESSING;  //软件处理


	//设置D3DPRESENT_PARAMETERS结构
	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory(&d3dpp,sizeof(d3dpp));
	d3dpp.Windowed = TRUE;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;

	//创建Direct3D设备对象     [用于渲染图形]
	if( FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,dhwnd,vp,&d3dpp,&g_pd3dD)) )
		return false;


	setupViewAndProjMat();		//设置观察和投影矩阵
	for(int i=0; i<=2; i++)
	{
		//设置线性过滤
		g_pd3dD->SetSamplerState(i, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
		g_pd3dD->SetSamplerState(i, D3DSAMP_MINFILTER, D3DTEXF_ANISOTROPIC);

		//设置纹理寻址模式
		g_pd3dD->SetSamplerState(i, D3DSAMP_BORDERCOLOR, 0x00000000);
		g_pd3dD->SetSamplerState(i, D3DSAMP_ADDRESSU,    D3DTADDRESS_BORDER);
		g_pd3dD->SetSamplerState(i, D3DSAMP_ADDRESSV,    D3DTADDRESS_BORDER);
	}

	g_pd3dD->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );	//正反面都绘制
	g_pd3dD->SetRenderState( D3DRS_LIGHTING, FALSE );			//关闭光照

	//激活alpha混合
	g_pd3dD->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
	g_pd3dD->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
	g_pd3dD->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
	g_pd3dD->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);


	if(!InitImg())		//初始化图片模块
		return false;
	if(!initText(font_lib))		//初始化字体模块
		return false;
	return true;
}