bool initializeD3D(HWND hwnd) {
	//创建一个d3d管理器
	d3dManager = Direct3DCreate9(D3D_SDK_VERSION);
	if (d3dManager == NULL)
		return false;

	//创建一份d3d配置
	D3DPRESENT_PARAMETERS d3dCfg = {};
	d3dCfg.Windowed = TRUE;
	d3dCfg.BackBufferWidth = 1024;
	d3dCfg.BackBufferHeight = 768;
	d3dCfg.SwapEffect = D3DSWAPEFFECT_DISCARD;
	D3DDISPLAYMODE displayMode;//用d3d管理器读取显示器显示模式
	if (FAILED(d3dManager->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &displayMode)))
		return false;
	d3dCfg.BackBufferFormat = displayMode.Format;

	//用d3d管理器根据d3d配置创建一个d3d设备
	if (FAILED(d3dManager->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,
										hwnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING,
										&d3dCfg, &d3dDevice)))
		return false;

	if (!initializeObj())
		return false;

	return true;
}
Beispiel #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;
}
Beispiel #3
0
HRESULT InitializeD3D(HWND hWnd)
{
	g_pD3D=Direct3DCreate9(D3D_SDK_VERSION);
	if(g_pD3D==NULL) return E_FAIL;

	//Get the currnet display mode
	D3DDISPLAYMODE d3ddm;
	if(FAILED(g_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm))) return E_FAIL;

	//Create a structure to hold the settings for our device
	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory(&d3dpp, sizeof(d3dpp));

	//Fill the structure
	//We want our program to be windowed and set the back buffer to a format that matches the current display mode
	d3dpp.Windowed=TRUE;
	d3dpp.SwapEffect=D3DSWAPEFFECT_COPY;
	d3dpp.BackBufferFormat=d3ddm.Format;

	//Create a Direct3D device
	if(FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &g_pD3DDevice)))
		return E_FAIL;

	//Hide the back
	g_pD3DDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
	//Turn off the light
	g_pD3DDevice->SetRenderState(D3DRS_LIGHTING, FALSE);

	return S_OK;
}
Beispiel #4
0
void setup( void )
{
	// ---- direct3d initialisation ----
  g_pD3D = Direct3DCreate9( D3D_SDK_VERSION );

	// ---- display mode ----
  D3DDISPLAYMODE d3ddm;
  g_pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm );
  ZeroMemory( &g_d3dpp, sizeof(g_d3dpp) );

	// ---- set present parameters ----
  g_d3dpp.Windowed = TRUE;
  g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
  g_d3dpp.BackBufferFormat = d3ddm.Format;
  g_d3dpp.EnableAutoDepthStencil = TRUE;
  g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
  g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;


	// ---- create the d3d device ----
  g_pD3D->CreateDevice( D3DADAPTER_DEFAULT,
	  D3DDEVTYPE_HAL,
	  g_hWnd,
	  D3DCREATE_SOFTWARE_VERTEXPROCESSING,
	  &g_d3dpp,
	  &g_pd3dDevice
  );
}
Beispiel #5
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;
}
Beispiel #6
0
//-----------------------------------------------------------------------------
// Name: InitD3D()
// Desc: Initializes Direct3D
//-----------------------------------------------------------------------------
HRESULT InitD3D( HWND hWnd )
{
	int nOutputWindowID;

	g_pD3D = Direct3DCreate9( D3D_SDK_VERSION );

	D3DDISPLAYMODE d3ddm;

	g_pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm );

	D3DPRESENT_PARAMETERS d3dpp;
	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;

	g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
		D3DCREATE_SOFTWARE_VERTEXPROCESSING,
		&d3dpp, &g_pd3dDevice );


	g_cEngineMemStack.Initialize( KG3DMEM_LEQUAL_32M );
	g_hWnd = hWnd;


	return S_OK;
}
HRESULT InitD3D( HWND hWnd ) 
{ 
	HRESULT hr ;

	// Create the D3D object, which is needed to create the D3DDevice. 
	if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) ) 
	{ 
		MessageBox(NULL, "Create D3D9 object failed!", "Error", 0) ; 
		return E_FAIL; 
	} 

	D3DDISPLAYMODE	ddm;
	hr = g_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT,&ddm) ;
	if(FAILED(hr))
	{
		MessageBox(NULL, "Unable to Get Adapter Display Mode", "Error", 0) ; 
		return E_FAIL;
	}

	ZeroMemory( &d3dpp, sizeof(d3dpp) ); 

	d3dpp.Windowed = TRUE;  
	d3dpp.BackBufferCount = 1 ;
	d3dpp.BackBufferWidth = ddm.Width ;
	d3dpp.BackBufferHeight = ddm.Height ;
	d3dpp.SwapEffect = D3DSWAPEFFECT_FLIP; 
	d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8; 

	// Create device 
	if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, 
		D3DCREATE_SOFTWARE_VERTEXPROCESSING, 
		&d3dpp, &g_pd3dDevice ) ) ) 
	{ 
		MessageBoxA(NULL, "Create D3D9 device failed!", "Error", 0) ; 
		return E_FAIL; 
	} 

	// Create Semaphore variable
	g_hMutex = CreateMutex(NULL,FALSE,NULL);
	g_hFullSemaphore = CreateSemaphore(NULL, g_PoolSize - 1, g_PoolSize - 1, NULL);
	g_hEmptySemaphore = CreateSemaphore(NULL, 0, g_PoolSize - 1, NULL);

	// Get back buffer
	g_pd3dDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &g_pBackBuffer) ;

	// Create surface
	for (int i = 0; i < g_PoolSize; ++i)
	{
		g_SurfPool[i] = NULL ;
		if (FAILED(hr = g_pd3dDevice->CreateOffscreenPlainSurface(d3dpp.BackBufferWidth, 
			d3dpp.BackBufferHeight, d3dpp.BackBufferFormat, D3DPOOL_SYSTEMMEM, &g_SurfPool[i], NULL)))
		{
			return hr;
		}
	}

	return S_OK; 
} 
Beispiel #8
0
BOOL InitD3D(HWND hwnd)
{
	HRESULT hr;
	D3DDISPLAYMODE disp_mode;
	D3DPRESENT_PARAMETERS pp;

	if (g_bSetupOK) return TRUE;

	if (g_pD3D) return FALSE;

	g_pD3D = Direct3DCreate9(D3D_SDK_VERSION);
	if (!g_pD3D) return FALSE;
	
	hr = g_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &disp_mode);
	if (FAILED(hr)) 
	{
		g_pD3D->Release();
		g_pD3D = NULL;
		return FALSE;
	}
	
	ZeroMemory(&pp, sizeof(D3DPRESENT_PARAMETERS));
	pp.Windowed = true;
	pp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	pp.BackBufferFormat = disp_mode.Format;
	pp.EnableAutoDepthStencil = TRUE;
	pp.AutoDepthStencilFormat = D3DFMT_D16;
    pp.BackBufferCount = 1;

	BOOL flgSoft = GetPrivateProfileInt("GENERIC","LEVEL",1,".\\TDWGame.ini");

	char buff[256];
	wsprintf(buff,"%d",flgSoft);
	WritePrivateProfileString("GENERIC","LEVEL",buff,".\\TDWGame.ini");

	hr = g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hwnd,D3DCREATE_HARDWARE_VERTEXPROCESSING,&pp,&g_pD3DDevice);
	if (FAILED(hr))
	{
		hr = g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hwnd,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&pp,&g_pD3DDevice);
		if (FAILED(hr)) 
		{
			hr = g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_REF,hwnd,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&pp,&g_pD3DDevice);
			if (FAILED(hr)) 
			{
				g_pD3D->Release();
				g_pD3D = NULL;
				return FALSE;
			}
		}
	}

	D3DCAPS9 DX9DCaps;
	g_pD3DDevice->GetDeviceCaps(&DX9DCaps);
	g_bSetupOK = TRUE;
	return TRUE;	
}
Beispiel #9
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 );
}
Beispiel #10
0
D3DDevice::D3DDevice(HWND hwnd, LPDIRECT3D9 d3d, size_t width, size_t height,
        bool fullscreen)
{
    HRESULT ret = 0;
    D3DPRESENT_PARAMETERS settings;
    D3DDISPLAYMODE dmode;

    ZeroMemory(&settings, sizeof(D3DPRESENT_PARAMETERS));

    ret = d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &dmode);
    if(FAILED(ret))
    {
        return;
    }

    settings.BackBufferWidth = width;
    settings.BackBufferHeight = height;
    settings.BackBufferFormat = fullscreen ? dmode.Format : D3DFMT_UNKNOWN;
    settings.BackBufferCount = 1;
    //settings.hDeviceWindow = hwnd;
    settings.Windowed = !fullscreen;
    settings.SwapEffect = D3DSWAPEFFECT_DISCARD;

    if(SUCCEEDED(d3d->CheckDeviceMultiSampleType(D3DADAPTER_DEFAULT, 
                    D3DDEVTYPE_HAL, settings.BackBufferFormat, !fullscreen,
                    D3DMULTISAMPLE_2_SAMPLES, NULL)))
    {
        settings.MultiSampleQuality = D3DMULTISAMPLE_2_SAMPLES;
    }
    else
    {
        settings.MultiSampleQuality = D3DMULTISAMPLE_NONE;
    }

    settings.EnableAutoDepthStencil = false;
    settings.AutoDepthStencilFormat = D3DFMT_D16;
    settings.FullScreen_RefreshRateInHz = 0;
    settings.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; //0;
    settings.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;

    ret = d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd,
            D3DCREATE_SOFTWARE_VERTEXPROCESSING, &settings, &m_device);

    if(FAILED(ret))
    {
        m_device = NULL;
        /* TODO */
        return;
    }

    /* copy settings */
    memcpy(&m_settings, &settings, sizeof(settings));
}
Beispiel #11
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;
}
Beispiel #12
0
bool InitDX(HWND hwnd)
{
	g_pD3D=Direct3DCreate9(D3D_SDK_VERSION);
	if(g_pD3D==NULL){
		OutputDebugString("failed -Direct3DCreate9()");
	}

	HRESULT hr;
	D3DDISPLAYMODE d3ddm;
	hr=g_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT,&d3ddm);
	if(FAILED(hr)){
		OutputDebugString("InitD3D failed -GetAdapterDisplayMode() failed");
		return false;
	}

	//プレゼンテーションパラメータの設定
	D3DPRESENT_PARAMETERS D3DPP;
	ZeroMemory(&D3DPP,sizeof(D3DPRESENT_PARAMETERS));
	D3DPP.BackBufferCount=1;
	if(ISFULLSCREENED){
		D3DPP.Windowed			 = false;
		D3DPP.BackBufferWidth	 = DEFAULT_CLIANT_WIDTH;
		D3DPP.BackBufferHeight	 = DEFAULT_CLIANT_HEIGHT;
	}
	else{
		D3DPP.Windowed=true;
	}
	D3DPP.BackBufferFormat		 = d3ddm.Format;
	D3DPP.SwapEffect			 = D3DSWAPEFFECT_DISCARD;
	D3DPP.EnableAutoDepthStencil = true;
	D3DPP.AutoDepthStencilFormat = D3DFMT_D16;
	D3DPP.Flags					 = true;
	D3DPP.PresentationInterval	 = D3DPRESENT_INTERVAL_ONE;
   
//デバイスオブジェクトの作成
	if(FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hwnd,D3DCREATE_HARDWARE_VERTEXPROCESSING,&D3DPP,&g_pD3DDev))){
		if(FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hwnd,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&D3DPP,&g_pD3DDev))){
			if(FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_REF,hwnd,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&D3DPP,&g_pD3DDev))){
				OutputDebugString("InitD3D failed -デバイスオブジェクトの作成に失敗 \n");
				return false;
			}
		}
	}

	g_pD3DDev->CreateTexture(SCREEN_WIDTH, SCREEN_HEIGHT, 1,D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8,D3DPOOL_DEFAULT,&g_tex, NULL);

	return true;
}
Beispiel #13
0
bool InitializeD3D(HWND hWnd, bool fullscreen)
{
    D3DDISPLAYMODE displayMode;

    g_D3D = Direct3DCreate9(D3D_SDK_VERSION);
    if(g_D3D == NULL) return false;

    if(FAILED(g_D3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT,
        &displayMode)))
    {
        return false;
    }

    D3DPRESENT_PARAMETERS d3dpp;
    ZeroMemory(&d3dpp, sizeof(d3dpp));

    if(fullscreen)
    {
        d3dpp.Windowed = FALSE;
        d3dpp.BackBufferWidth = 640;
        d3dpp.BackBufferHeight = 480;
    }
    else
    {
        d3dpp.Windowed = TRUE;
        d3dpp.BackBufferWidth = 640;
        d3dpp.BackBufferHeight = 480;
    }

    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.BackBufferFormat = displayMode.Format;

    if(FAILED(g_D3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
        D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &g_D3DDevice)))
    {
        return false;
    }

    return true;
}
Beispiel #14
0
//--------------------------------------------------------------------------------------
DepthTexture::DepthTexture(const LPDIRECT3D9 d3d) {
	D3DDISPLAYMODE currentDisplayMode;
	d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &currentDisplayMode);

	// determine if RESZ is supported
	m_isRESZ = d3d->CheckDeviceFormat(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,
		currentDisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, FOURCC_RESZ) == D3D_OK;
	SDLOG(-1, "[DepthTexture] RESZ: %s\n", m_isRESZ?"true":"false");

	// determine if INTZ is supported
	m_isINTZ = d3d->CheckDeviceFormat(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,
		currentDisplayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, FOURCC_INTZ) == D3D_OK;
	SDLOG(-1, "[DepthTexture] INTZ: %s\n", m_isINTZ ? "true" : "false");

	// determine if RAWZ is supported, used in GeForce 6-7 series.
	m_isRAWZ = d3d->CheckDeviceFormat(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,
		currentDisplayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, FOURCC_RAWZ) == D3D_OK;
	SDLOG(-1, "[DepthTexture] RAWZ: %s\n", m_isRAWZ ? "true" : "false");

	// determine if RESZ or NVAPI supported
	m_isSupported = (NvAPI_Initialize() == NVAPI_OK || m_isRESZ) && (m_isRAWZ || m_isINTZ);
}
Beispiel #15
0
/**-----------------------------------------------------------------------------
* Direct3D 초기화
*------------------------------------------------------------------------------
*/
HRESULT InitD3D( HWND hWnd )
{
	/// 디바이스를 생성하기위한 D3D객체 생성
	if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
		return E_FAIL;

	/// 디바이스를 생성할 구조체
	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory( &d3dpp, sizeof(d3dpp) );

	D3DDISPLAYMODE d3ddm;
	if(FAILED(g_pD3D->GetAdapterDisplayMode(0, &d3ddm))) {
		MessageBox(NULL, "GetAdapterDisplayMode failed", "Error", MB_OK);
		return false;
	}

	d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
	d3dpp.BackBufferCount		 = 1;
	d3dpp.BackBufferFormat		 = d3ddm.Format;
	d3dpp.BackBufferHeight		 = HEIGHT;
	d3dpp.BackBufferWidth		 = WIDTH;
	d3dpp.EnableAutoDepthStencil = TRUE;
	d3dpp.hDeviceWindow			 = hWnd;
	d3dpp.PresentationInterval	 = D3DPRESENT_INTERVAL_IMMEDIATE;
	d3dpp.SwapEffect			 = D3DSWAPEFFECT_DISCARD;
	d3dpp.Windowed				 = TRUE;


	/// 디바이스 생성
	if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
		D3DCREATE_SOFTWARE_VERTEXPROCESSING,
		&d3dpp, &g_pd3dDevice ) ) )
	{
		return E_FAIL;
	}

	return S_OK;
}
Beispiel #16
0
//-----------------------------------------------------------------------------
// Direct X Graphics 초기화
//-----------------------------------------------------------------------------
HRESULT InitD3D( HWND hWnd )
{
    // Direct 3D 사용
    if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ))) return E_FAIL;

    // 디스플레이 모드 조사
    D3DDISPLAYMODE d3ddm;
    if( FAILED( g_pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm )))
        return E_FAIL;

    // Direct 3D 디바이스 생성
    D3DPRESENT_PARAMETERS d3dpp; 
    ZeroMemory( &d3dpp, sizeof(d3dpp) );        // 몽땅 0으로
    d3dpp.Windowed = TRUE;                      // 윈도우모드
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;   // 화면전환 방법
    d3dpp.BackBufferFormat = d3ddm.Format;      // 현재 화면 포맷 사용

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

    return S_OK;
}
Beispiel #17
0
int Renderer::InitDirect3DDevice(HWND hWndTarget, int Width, int Height, BOOL bWindowed, D3DFORMAT FullScreenFormat, LPDIRECT3D9 pD3D, LPDIRECT3DDEVICE9* ppDevice) {
	D3DPRESENT_PARAMETERS d3dpp;//rendering info
	D3DDISPLAYMODE d3ddm;//current display mode info
	HRESULT r = 0;

	if (*ppDevice)
		(*ppDevice)->Release();

	ZeroMemory(&d3dpp, sizeof(D3DPRESENT_PARAMETERS));
	r = pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm);
	if (FAILED(r)) {
		Errors::SetError(TEXT("Could not get display adapter information"));
		return E_FAIL;
	}

	d3dpp.BackBufferWidth = Width;
	d3dpp.BackBufferHeight = Height;
	d3dpp.BackBufferFormat = bWindowed ? d3ddm.Format : FullScreenFormat;
	d3dpp.BackBufferCount = 1;
	d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;//D3DSWAPEFFECT_COPY;
	d3dpp.hDeviceWindow = hWndTarget;
	d3dpp.Windowed = bWindowed;
	d3dpp.EnableAutoDepthStencil = TRUE;
	d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
	d3dpp.FullScreen_RefreshRateInHz = 0;//default refresh rate
	d3dpp.PresentationInterval = bWindowed ? 0 : D3DPRESENT_INTERVAL_IMMEDIATE;
	d3dpp.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;

	r = pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWndTarget, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, ppDevice);
	if (FAILED(r)) {
		Errors::SetError(TEXT("Could not create the render device"));
		return E_FAIL;
	}

	return S_OK;
}
Beispiel #18
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 );
}
Beispiel #19
0
HRESULT HookIDirect3D9::GetAdapterDisplayMode(LPVOID _this, UINT Adapter,D3DDISPLAYMODE* pMode)
{
	LOG_API();
	return pD3D->GetAdapterDisplayMode(Adapter, pMode);
}
Beispiel #20
0
//-----------------------------------------------------------------------------
// Name: InitD3D()
// Desc: Initializes Direct3D
//-----------------------------------------------------------------------------
HRESULT InitD3D( HWND hWnd )
{
    HRESULT hr;

    // Create the D3D object.
    if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
        return E_FAIL;

    // Get the current desktop display mode, so we can set up a back
    // buffer of the same format
    D3DDISPLAYMODE d3ddm;
    if ( FAILED( hr = g_pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm ) ) )
    {
        Msg(TEXT("Could not read adapter display mode!  hr=0x%x"), hr);
        return hr;
    }

    // Set up the structure used to create the D3DDevice. Since we are now
    // using more complex geometry, we will create a device with a zbuffer.
    D3DPRESENT_PARAMETERS d3dpp;
    ZeroMemory( &d3dpp, sizeof(d3dpp) );
    d3dpp.Windowed               = TRUE;
    d3dpp.SwapEffect             = D3DSWAPEFFECT_COPY;
    d3dpp.BackBufferFormat       = d3ddm.Format;
    d3dpp.EnableAutoDepthStencil = TRUE;
    d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

    // Create the D3DDevice
    hr = g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                               D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED,
                               &d3dpp, &g_pd3dDevice );                                     
    if (FAILED(hr))                                      
    {
        Msg(TEXT("Could not create the D3D9 device!  hr=0x%x\r\n\r\n")
            TEXT("This sample is attempting to create a buffer that might not\r\n")
            TEXT("be supported by your video card in its current mode.\r\n\r\n")
            TEXT("You may want to reduce your screen resolution or bit depth\r\n")
            TEXT("and try to run this sample again."), hr);
        return hr;
    }

    hr = g_pd3dDevice->SetSamplerState( 0, D3DSAMP_ADDRESSU,  D3DTADDRESS_CLAMP );
    hr = g_pd3dDevice->SetSamplerState( 0, D3DSAMP_ADDRESSV,  D3DTADDRESS_CLAMP );

    // Add filtering
    hr = g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
    hr = g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );

    // set maximum ambient light
    hr = g_pd3dDevice->SetRenderState(D3DRS_AMBIENT,RGB(255,255,255));

    // Turn off culling
    hr = g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );

    // Turn off D3D lighting
    hr = g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );

    // Turn on the zbuffer
    hr = g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );

    // Set texture states
    hr = g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_MODULATE );
    hr = g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
    hr = g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
    hr = g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP,   D3DTOP_DISABLE );

    g_pFont = new CD3DFont(TEXT("Trebuchet MS"), 10);
    if( g_pFont )
    {
        hr = g_pFont->InitDeviceObjects( g_pd3dDevice );
        if( FAILED(hr))
        {
            delete g_pFont;
            g_pFont = NULL;
        }
        else
        {
            hr = g_pFont->RestoreDeviceObjects();
            if( FAILED(hr))
            {
                delete g_pFont;
                g_pFont = NULL;
            }
        }
    }

    return hr;
}
Beispiel #21
0
HRESULT InitD3D(HWND hwnd)
{
    HRESULT hr;

    // Create the D3D object.
    if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
        return E_FAIL;

    // Get the current desktop display mode, so we can set up a back
    // buffer of the same format
    D3DDISPLAYMODE d3ddm;

    if ( FAILED( hr = g_pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm ) ) )
    {
        Msg(TEXT("Could not read adapter display mode!  hr=0x%x"), hr);
        return hr;
    }

    // Set up the structure used to create the D3DDevice. Since we are now
    // using more complex geometry, we will create a device with a zbuffer.
    D3DPRESENT_PARAMETERS d3dpp;
    ZeroMemory( &d3dpp, sizeof(d3dpp) );
    d3dpp.Windowed               = TRUE;
    d3dpp.SwapEffect             = D3DSWAPEFFECT_COPY;
    d3dpp.BackBufferFormat       = d3ddm.Format;
    d3dpp.EnableAutoDepthStencil = TRUE;
    d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

    // Create the D3DDevice
    hr = g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd,
                               D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED,
                               &d3dpp, &g_pd3dDevice );                                     


    hr = g_pd3dDevice->SetSamplerState( 0, D3DSAMP_ADDRESSU,  D3DTADDRESS_CLAMP );
    hr = g_pd3dDevice->SetSamplerState( 0, D3DSAMP_ADDRESSV,  D3DTADDRESS_CLAMP );

    // Add filtering
    hr = g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
    hr = g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );

    // set maximum ambient light
    hr = g_pd3dDevice->SetRenderState(D3DRS_AMBIENT,RGB(255,255,255));

    // Turn off culling
    hr = g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );

    // Turn off D3D lighting
    hr = g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );

    // Turn on the zbuffer
    hr = g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );

    // Set texture states
    hr = g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_MODULATE );
    hr = g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
    hr = g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
    hr = g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP,   D3DTOP_DISABLE );


    return hr;
}
Beispiel #22
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;
}
Beispiel #23
0
	bool InitGraphics(HWND hWnd, int width, int height, bool fullscreen,
										int colordepth) {
		ambientcolor = D3DCOLOR_RGBA(255, 255, 255, 0);
		clearColor = D3DCOLOR_RGBA(0, 0, 0, 255);
		d3d = Direct3DCreate9(D3D_SDK_VERSION);
		if(d3d == NULL) {
			return false;
		}

		//get default display-adapter
		D3DDISPLAYMODE dm;
		d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &dm);

		//setup present-parameters
		D3DPRESENT_PARAMETERS d3dpp;
		ZeroMemory(&d3dpp, sizeof(d3dpp));
		d3dpp.Windowed = !fullscreen;
		d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
		d3dpp.EnableAutoDepthStencil = TRUE;
		d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
		d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
		d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
		d3dpp.BackBufferCount = 1;
		d3dpp.BackBufferWidth = width;
		d3dpp.BackBufferHeight = height;
		d3dpp.hDeviceWindow = hWnd;

		//create device
		HRESULT result = d3d->CreateDevice(
			D3DADAPTER_DEFAULT,
			D3DDEVTYPE_HAL,
			hWnd,
			D3DCREATE_SOFTWARE_VERTEXPROCESSING,
			&d3dpp,
			&device);

		if(result != D3D_OK) {
			return false;
		}

		device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backbuffer);
		device->Clear(0, NULL, D3DCLEAR_TARGET, 0xFAFF, 1.0f, 0);

		//create font (arial)
		D3DXFONT_DESC FontDesc = { 24,
			0,
			400,
			0,
			false,
			DEFAULT_CHARSET,
			OUT_TT_PRECIS,
			CLIP_DEFAULT_PRECIS,
			DEFAULT_PITCH,
			"Arial"
		};

		D3DXCreateFontIndirect(device, &FontDesc, &font);

		//Create sprite-handler
		D3DXCreateSprite(device, &spriteHandler);
		if(result != D3D_OK) {
			return false;
		}

		return true;
	}
Beispiel #24
0
//! creates the hardware texture
bool CD3D9Texture::createTexture(u32 flags, IImage * image)
{
	ImageSize = image->getDimension();

	core::dimension2d<u32> optSize = ImageSize.getOptimalSize(!Driver->queryFeature(EVDF_TEXTURE_NPOT), !Driver->queryFeature(EVDF_TEXTURE_NSQUARE), true, Driver->Caps.MaxTextureWidth);

	D3DFORMAT format = D3DFMT_A1R5G5B5;

	switch(getTextureFormatFromFlags(flags))
	{
	case ETCF_ALWAYS_16_BIT:
		format = D3DFMT_A1R5G5B5; break;
	case ETCF_ALWAYS_32_BIT:
		format = D3DFMT_A8R8G8B8; break;
	case ETCF_OPTIMIZED_FOR_QUALITY:
		{
			switch(image->getColorFormat())
			{
			case ECF_R8G8B8:
			case ECF_A8R8G8B8:
				format = D3DFMT_A8R8G8B8; break;
			case ECF_A1R5G5B5:
			case ECF_R5G6B5:
				format = D3DFMT_A1R5G5B5; break;
			}
		}
		break;
	case ETCF_OPTIMIZED_FOR_SPEED:
		format = D3DFMT_A1R5G5B5;
		break;
	default:
		break;
	}
	if (Driver->getTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL))
	{
		if (format == D3DFMT_A8R8G8B8)
			format = D3DFMT_R8G8B8;
		else if (format == D3DFMT_A1R5G5B5)
			format = D3DFMT_R5G6B5;
	}

	const bool mipmaps = Driver->getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS);

	DWORD usage = 0;

	// This enables hardware mip map generation.
	if (mipmaps && Driver->queryFeature(EVDF_MIP_MAP_AUTO_UPDATE))
	{
		LPDIRECT3D9 intf = Driver->getExposedVideoData().D3D9.D3D9;
		D3DDISPLAYMODE d3ddm;
		intf->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm);

		if (D3D_OK==intf->CheckDeviceFormat(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,d3ddm.Format,D3DUSAGE_AUTOGENMIPMAP,D3DRTYPE_TEXTURE,format))
		{
			usage = D3DUSAGE_AUTOGENMIPMAP;
			HardwareMipMaps = true;
		}
	}

	HRESULT hr = Device->CreateTexture(optSize.Width, optSize.Height,
		mipmaps ? 0 : 1, // number of mipmaplevels (0 = automatic all)
		usage, // usage
		format, D3DPOOL_MANAGED , &Texture, NULL);

	if (FAILED(hr))
	{
		// try brute force 16 bit
		HardwareMipMaps = false;
		if (format == D3DFMT_A8R8G8B8)
			format = D3DFMT_A1R5G5B5;
		else if (format == D3DFMT_R8G8B8)
			format = D3DFMT_R5G6B5;
		else
			return false;

		hr = Device->CreateTexture(optSize.Width, optSize.Height,
			mipmaps ? 0 : 1, // number of mipmaplevels (0 = automatic all)
			0, format, D3DPOOL_MANAGED, &Texture, NULL);
	}

	ColorFormat = Driver->getColorFormatFromD3DFormat(format);
	setPitch(format);
	return (SUCCEEDED(hr));
}
Beispiel #25
0
//Инициализаци DirectX
HRESULT init( HWND g_hWnd)
{
	/*-----------------------------------------------------------------------------------------------*/

	/*
	Вся работа начинается с создания главного объекта. 
	Именно создание главного объекта Direct3D позволит осуществить доступ ко всем возможностям, 
	предоставляемым его интерфейсами. Создание главного объекта – это вызов предусмотренной функции (Direct3DCreate9)
	с единственным параметром (D3D_SDK_VERSION). D3D_SDK_VERSION – это предопределенная константа, описанная в заголовочном модуле
	(d3d9.h или Direct3D9.pas) и указывающая номер версии библиотеки DirectX. В этом можно убедиться, заглянув в справку помощи по DirectX.
	*/
    g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ); 
	if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION )))
		return E_FAIL;	

	/*-----------------------------------------------------------------------------------------------*/

	/*
	Следующим шагом является получение текущих установок рабочего стола,
	а именно, какой формат пикселя (сколько битов отведено под каждую составляющую цвета) присутствует в данный момент.
	Для этого можно воспользоваться, вызвав метод GetAdapterDisplayMode главного объекта Direct3D.
	1. константа, определяющая номер (индекс) видеоадаптера, для которого запрашиваются параметры;
    2. указатель на переменную, в которую помещается результат выполнения команды.
	*/
    D3DDISPLAYMODE d3ddm;
    if( FAILED( g_pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm ) ) )  
		return E_FAIL;


	/*-----------------------------------------------------------------------------------------------*/

	/*
	Следующий шаг – заполнение структуры D3DPRESENT_PARAMETERS,
	которая будет задавать параметры поверхности вывода (рендеринга)
	*/
	D3DPRESENT_PARAMETERS d3dpp;
	memset(&d3dpp, 0, sizeof(d3dpp));	                    //заполняем нулями
    d3dpp.BackBufferFormat       = d3ddm.Format;            //формат видеорежима заднего буфера устанавливаем равным текущему видеорежиму.
	d3dpp.SwapEffect             = D3DSWAPEFFECT_DISCARD;  // задаем режим двойно буферизации
	d3dpp.Windowed               = TRUE;                   // что вывод будет производится в некоторое окно


	/*-----------------------------------------------------------------------------------------------*/

	/*
	.В результате вызова метода CreateDevice получаем ссылку на интерфейс IDirect3DDevice9,
	с помощью которого мы будем производить рендеринг сцены. 
	1. номер адаптера, установленного в системе
	2. тип устройства, в нашем случае, позволяет использовать аппаратное ускорение на 100%,
	   D3DDEVTYPE_REF – указывает использовать только программные действия (ресурсы центрального процессора)
	3. куда будет производиться вывод сцены
	4. обработка вершин сцены будет производиться по фиксированным заданным правилам 
	   (этот параметр следует указывать, если видеоадаптер не поддерживает архитектуру шейдеров)
    5. хранит параметры создаваемого устройства вывода
	6. это имя переменной, в которую при успешном вызове будет помещен результат работы метода
	*/
    if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT,
		                              D3DDEVTYPE_HAL, 
									  g_hWnd,
									  D3DCREATE_SOFTWARE_VERTEXPROCESSING ,
                                      &d3dpp,
									  &g_pd3dDevice)))
       return E_FAIL;
       return S_OK;
} 
Beispiel #26
0
//*******
// this function initializes Direct3D...
bool init3D(HWND hWnd)
{
    D3DDISPLAYMODE d3ddm;   // Direct3D Display Mode..
    D3DPRESENT_PARAMETERS d3dpp;    // d3d present parameters..details on how it should present
    // a scene.. such as swap effect.. size.. windowed or full screen..
    HFONT fnt;

    // create D3D9.. if error (like that ever happens..) return false..
    if (NULL == (lpD3D9 = Direct3DCreate9(D3D_SDK_VERSION)))
        return false;
    // get display adapter mode.. if error return false..
    if (FAILED(lpD3D9->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm)))
        return false;

    // NOTE:  it's possible that this example will not work as is
    //        in windowed mode due to display format and depth buffer format
    ZeroMemory(&d3dpp, sizeof(d3dpp));            // blank the memory for good measure..
    //   d3dpp.Windowed = true;                   // use this for window mode..
    d3dpp.Windowed = false;                       // use this for full screen... it's that easy!
    d3dpp.BackBufferWidth = 1024;                 // rather useless for windowed version
    d3dpp.BackBufferHeight = 768;                 // ditto..but left it in anyway for full screen
    d3dpp.SwapEffect = D3DSWAPEFFECT_FLIP;        // flip using a back buffer...easy performance
    d3dpp.BackBufferFormat = D3DFMT_R5G6B5;       // just set back buffer format from display mode
    d3dpp.EnableAutoDepthStencil = true;
    d3dpp.AutoDepthStencilFormat =  D3DFMT_D16;   // 16 bit depth buffer..

    // Create the D3DDevice
    if (FAILED(lpD3D9->CreateDevice(D3DADAPTER_DEFAULT,   // which display adapter..
                                    D3DDEVTYPE_HAL,
                                    hWnd, D3DCREATE_MIXED_VERTEXPROCESSING,   // mixed, software, or hardware..
                                    &d3dpp, &lpD3DDevice9)))             // sends stuff.. and to receive
    {   // if it fails to create with HAL, then try (usually succeeds) to create
        // with ref (software) using a much lower screen res
        d3dpp.BackBufferWidth = 320;
        d3dpp.BackBufferHeight = 240;
        d3dpp.Windowed = false;
        if (FAILED(lpD3D9->CreateDevice(D3DADAPTER_DEFAULT,
                                        D3DDEVTYPE_REF,
                                        hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                        &d3dpp, &lpD3DDevice9)))
        {
            return false;
        }
        else
        {   // create smaller font for software... lower res..
            fnt = CreateFont(20, 10, 2, 0, 500, 0, 0, 0, ANSI_CHARSET, OUT_DEFAULT_PRECIS,
                             CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FF_MODERN, 0);
            // disable dithering for software..
            lpD3DDevice9->SetRenderState( D3DRS_DITHERENABLE, false);
        }
    }
    else
    {   // create larger font for hardware.. higher res
        fnt = CreateFont(50, 22, 2, 0, 500, 0, 0, 0, ANSI_CHARSET, OUT_DEFAULT_PRECIS,
                         CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FF_MODERN, 0);
        // enable dithering for hardware...
        lpD3DDevice9->SetRenderState( D3DRS_DITHERENABLE, true);
    }

    // cull counter clockwise.. triangles drawn counterclockwise from the
    // view will not be rendered.. this is rather normal culling
    lpD3DDevice9->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW );
    // turn off lighting since we have color values..
    // and no light sources exist..
    lpD3DDevice9->SetRenderState( D3DRS_LIGHTING, false );

    // create a D3DXFont from a windows font created above...
    // for use in drawing text with D3D
    D3DXCreateFont(lpD3DDevice9,
                   50,               //Font height
                   0,                //Font width
                   FW_NORMAL,        //Font Weight
                   1,                //MipLevels
                   false,            //Italic
                   DEFAULT_CHARSET,  //CharSet
                   OUT_DEFAULT_PRECIS, //OutputPrecision
                   ANTIALIASED_QUALITY, //Quality
                   DEFAULT_PITCH|FF_DONTCARE, //PitchAndFamily
                   "Arial",          //pFacename
                   &lpD3DXFont);

    return true;
}
	virtual const char* open( unsigned buffer_width, unsigned buffer_height, HWND hWnd )
	{
		if ( this->hWnd )
			return "Display already open";

		this->hWnd = hWnd;

		lpd3d = Direct3DCreate9( D3D_SDK_VERSION );
		if ( ! lpd3d )
			return "Creating Direct3D 9 object";

		D3DDISPLAYMODE mode;
		lpd3d->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, & mode );

		ZeroMemory(&dpp, sizeof(dpp));
		dpp.Flags                  = D3DPRESENTFLAG_VIDEO;
		dpp.SwapEffect             = D3DSWAPEFFECT_FLIP;
		dpp.hDeviceWindow          = hWnd;
		dpp.BackBufferCount        = 1;
		dpp.MultiSampleType        = D3DMULTISAMPLE_NONE;
		dpp.MultiSampleQuality     = 0;
		dpp.EnableAutoDepthStencil = false;
		dpp.AutoDepthStencilFormat = D3DFMT_UNKNOWN;
		dpp.PresentationInterval   = D3DPRESENT_INTERVAL_IMMEDIATE;
		dpp.Windowed               = TRUE;
		dpp.BackBufferFormat       = D3DFMT_UNKNOWN;
		dpp.BackBufferWidth        = 640;
		dpp.BackBufferHeight       = 480;

		if ( lpd3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, & dpp, & lpdev ) != D3D_OK )
			return "Creating Direct3D 9 device object";

		lpdev->GetDeviceCaps(&d3dcaps);

		bool dynamic = !!(d3dcaps.Caps2 & D3DCAPS2_DYNAMICTEXTURES);

		if(dynamic)
		{
			flags.t_usage = D3DUSAGE_DYNAMIC;
			flags.v_usage = D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC;
			flags.t_pool  = D3DPOOL_DEFAULT;
			flags.v_pool  = D3DPOOL_DEFAULT;
			flags.lock    = D3DLOCK_NOSYSLOCK | D3DLOCK_DISCARD;
		}
		else
		{
			flags.t_usage = 0;
			flags.v_usage = D3DUSAGE_WRITEONLY;
			flags.t_pool  = D3DPOOL_MANAGED;
			flags.v_pool  = D3DPOOL_MANAGED;
			flags.lock    = D3DLOCK_NOSYSLOCK | D3DLOCK_DISCARD;
		}

		input_width = buffer_width;
		input_height = buffer_height;

		surface_width = rounded_power_of_two( buffer_width );
		surface_height = rounded_power_of_two( buffer_height );

		if ( surface_width > d3dcaps.MaxTextureWidth || surface_height > d3dcaps.MaxTextureHeight )
			return "Device texture size limit is too small";

		restore_objects();

		update_position();

		clear();

		retry_count = 0;

		return 0;
	}
Beispiel #28
0
int main(int argc, char* argv[])
{
	if (argc < 3)
	{
		puts("Usage: MeshConv meshfile rdffile");
		return 1;
	}

	// Initialize DirectDraw
	pD3D = Direct3DCreate9(D3D_SDK_VERSION);
	if (pD3D == NULL)
	{
		puts("Cannot init D3D");
		return 1;
	}

	MeshMender mender;
	std::vector<MeshMender::Vertex> MendVerts;
	std::vector<unsigned int> MendIndices;
	std::vector<unsigned int> mappingNewToOld;

	HRESULT hr;
	D3DDISPLAYMODE dispMode;
	D3DPRESENT_PARAMETERS presentParams;

	pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &dispMode);

	ZeroMemory(&presentParams, sizeof(presentParams));
	presentParams.Windowed = TRUE;
	presentParams.hDeviceWindow = GetConsoleWindow();
	presentParams.SwapEffect = D3DSWAPEFFECT_COPY;
	presentParams.BackBufferWidth = 8;
	presentParams.BackBufferHeight = 8;
	presentParams.BackBufferFormat = dispMode.Format;

	hr = pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, NULL, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &presentParams, &pD3DDevice);
	if (FAILED(hr))
	{
		printf("Cannot init D3D device: %08x\n", hr);
		pD3D->Release();
		return 1;
	}

	printf("Loading mesh %s: ", argv[1]);

	LPD3DXBUFFER pAdjacency, pMaterials, pEffects;
	DWORD n;
	LPD3DXMESH pLoadMesh;
	hr = D3DXLoadMeshFromX(argv[1], D3DXMESH_SYSTEMMEM, pD3DDevice, &pAdjacency, &pMaterials, &pEffects, &n, &pLoadMesh);
	if (FAILED(hr))
	{
		printf("ERROR: %08x\n", hr);
		goto mesherror;
	}
	pEffects->Release();
	pMaterials->Release();
	printf("%d faces, %d verts\n", pLoadMesh->GetNumFaces(), pLoadMesh->GetNumVertices());

	LPD3DXMESH pMesh;
	if (pLoadMesh->GetFVF() != MESHFVF)
	{
		hr = pLoadMesh->CloneMeshFVF(D3DXMESH_SYSTEMMEM, MESHFVF, pD3DDevice, &pMesh);
		pLoadMesh->Release();
		if (FAILED(hr))
		{
			printf("CloneMesh error: %08x\n", hr);
			goto mesherror;
		}
	}
	else
		pMesh = pLoadMesh;

	printf("Welding verts: ");

	DWORD* pAdj = new DWORD[pAdjacency->GetBufferSize() / 4];

	D3DXWELDEPSILONS Eps;
	memset(&Eps, 0, sizeof(Eps));
	hr = D3DXWeldVertices(pMesh, D3DXWELDEPSILONS_WELDPARTIALMATCHES, &Eps, (DWORD*)pAdjacency->GetBufferPointer(), pAdj, NULL, NULL);
	if (FAILED(hr))
	{
		printf("ERROR: %08x\n", hr);
		goto mesherror;
	}
	
	hr = pMesh->OptimizeInplace(D3DXMESHOPT_VERTEXCACHE, pAdj, (DWORD*)pAdjacency->GetBufferPointer(), NULL, NULL);
	if (FAILED(hr))
	{
		printf("ERROR: %08x\n", hr);
		goto mesherror;
	}
	
	pAdjacency->Release();
	delete [] pAdj;

	printf("%d faces, %d verts\n", pMesh->GetNumFaces(), pMesh->GetNumVertices());

	printf("Mending mesh: ");

	DWORD NumVerts = pMesh->GetNumVertices();
	DWORD NumFaces = pMesh->GetNumFaces();

	MESHVERT* MeshVert;
	pMesh->LockVertexBuffer(0, (LPVOID*)&MeshVert);

	//fill up Mend vectors with your mesh's data
	MendVerts.reserve(NumVerts);
	for(DWORD i = 0; i < NumVerts; ++i)
	{
		MeshMender::Vertex v;
		v.pos = MeshVert[i].pos;
		v.s = MeshVert[i].s;
		v.t = MeshVert[i].t;
		v.normal = MeshVert[i].norm;
		MendVerts.push_back(v);
	}
	pMesh->UnlockVertexBuffer();

	WORD* MeshIdx;
	pMesh->LockIndexBuffer(0, (LPVOID*)&MeshIdx);

	MendIndices.reserve(NumFaces * 3);
	for(DWORD i = 0; i < NumFaces * 3; ++i)
	{
		MendIndices.push_back(MeshIdx[i]);
	}
	pMesh->UnlockIndexBuffer();

	pMesh->Release();
	pMesh = 0;

	//pass it in to Mend mender to do it's stuff
	mender.Mend(MendVerts, MendIndices, mappingNewToOld, 0.9f, 0.9f, 0.9f, 1.0f, MeshMender::DONT_CALCULATE_NORMALS, MeshMender::RESPECT_SPLITS);
	
	mappingNewToOld.clear();

	printf("%d faces, %d verts\n", MendIndices.size() / 3, MendVerts.size());

	printf("Saving data: ");

	FILE* fp = fopen("meshdata.bin", "wb");
	n = MendIndices.size() / 3;
	fwrite(&n, 4, 1, fp);
	n = MendVerts.size();
	fwrite(&n, 4, 1, fp);
	fclose(fp);

	// Load existing file
	HANDLE hFile = CreateFile(argv[2], GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		printf("ERROR: %08x\n", GetLastError());
		goto mesherror;
	}
	DWORD Size = GetFileSize(hFile, 0);
	char* FileData = (char*)VirtualAlloc(0, 64*1024*1024, MEM_RESERVE, PAGE_NOACCESS);
	VirtualAlloc(FileData, Size, MEM_COMMIT, PAGE_READWRITE);
	ReadFile(hFile, FileData, Size, &n, 0);
	FileData[n] = 0;
	Size = n;

	char *p, *q;
	// Find vertex data
	p = strstr(FileData, "VertexBuffer");
	if (!p)
	{
		printf("ERROR: Invalid output file\n");
		goto mesherror;
	}
	p = strchr(p, '{');
	q = p+1;
	int depth = 1;
	do {
		if (*q == '}')
			--depth;
		else if (*q == '{')
			++depth;
		++q;
	} while (depth > 0);

	// move post-vertex data to temp buffer
	Size = (FileData + Size) - q;
	char* TempData = (char*)VirtualAlloc(0, Size, MEM_COMMIT, PAGE_READWRITE);
	memcpy(TempData, q, Size);

	// write vertex data
	strcpy(p, "{\r\n    VertexFormat {D3DVSDT_FLOAT3 D3DVSDT_NORMPACKED3 D3DVSDT_FLOAT2 D3DVSDT_NORMPACKED3 D3DVSDT_NORMPACKED3}\r\n    VertexData\r\n    {\r\n");
	p += strlen(p);

	for (std::vector<MeshMender::Vertex>::iterator i = MendVerts.begin(); i != MendVerts.end(); ++i)
	{
		VirtualAlloc(p, 500, MEM_COMMIT, PAGE_READWRITE);
		p += sprintf(p, "        %12f %12f %12f  %12f %12f %12f  %12f %12f  %12f %12f %12f  %12f %12f %12f\r\n",
			i->pos.x, i->pos.y, i->pos.z, i->normal.x, i->normal.y, i->normal.z,
			i->s, i->t,
			i->tangent.x, i->tangent.y, i->tangent.z, i->binormal.x, i->binormal.y, i->binormal.z);
	}

	strcpy(p, "    }\r\n}");
	p += strlen(p);

	VirtualAlloc(p, Size, MEM_COMMIT, PAGE_READWRITE);
	memcpy(p, TempData, Size);
	Size += p - FileData;
	VirtualFree(TempData, 0, MEM_RELEASE);

	// Find index data
	p = strstr(FileData, "IndexBuffer");
	if (!p)
	{
		printf("ERROR: Invalid output file\n");
		goto mesherror;
	}
	p = strchr(p, '{');
	q = p+1;
	depth = 1;
	do {
		if (*q == '}')
			--depth;
		else if (*q == '{')
			++depth;
		++q;
	} while (depth > 0);

	// move post-index data to temp buffer
	Size = (FileData + Size) - q;
	TempData = (char*)VirtualAlloc(0, Size, MEM_COMMIT, PAGE_READWRITE);
	memcpy(TempData, q, Size);

	// write index data
	strcpy(p, "{\r\n    IndexData\r\n    {\r\n        ");
	p += strlen(p);

	n = 0;
	for (std::vector<unsigned>::iterator i = MendIndices.begin(); i != MendIndices.end(); ++i)
	{
		VirtualAlloc(p, 20, MEM_COMMIT, PAGE_READWRITE);
		p += sprintf(p, " %5hu", *i);
		if (n++ == 2)
		{
			p += sprintf(p, "\r\n       ");
			n = 0;
		}
	}

	strcpy(p-3, "}\r\n}");
	p += strlen(p);

	VirtualAlloc(p, Size, MEM_COMMIT, PAGE_READWRITE);
	memcpy(p, TempData, Size);
	Size += p - FileData;
	VirtualFree(TempData, 0, MEM_RELEASE);

	SetFilePointer(hFile, 0, 0, FILE_BEGIN);
	WriteFile(hFile, FileData, Size, &n, 0);
	SetEndOfFile(hFile);

	CloseHandle(hFile);
	VirtualFree(FileData, 0, MEM_RELEASE);

	printf("Done\n");

	pD3D->Release();
	pD3DDevice->Release();

	return 0;

mesherror:
	pD3D->Release();
	pD3DDevice->Release();
	
	return 1;
}
Beispiel #29
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;
}
Beispiel #30
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;
}