Beispiel #1
0
void StateManager9::setDepthFunc(bool depthTest, GLenum depthFunc)
{
    if (depthTest)
    {
        IDirect3DDevice9 *device = mRenderer9->getDevice();
        device->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
        device->SetRenderState(D3DRS_ZFUNC, gl_d3d9::ConvertComparison(depthFunc));
    }
    else
    {
        mRenderer9->getDevice()->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
    }

    mCurDepthStencilState.depthTest = depthTest;
    mCurDepthStencilState.depthFunc = depthFunc;
}
Beispiel #2
0
  bool GPUContextDX9::initialize()
  {
    _window = DX9Window::create();
    if( _window == NULL )
    {
      DX9WARN << "Could not create offscreen window.";
      return false;
    }

    HWND windowHandle = _window->getWindowHandle();

    _direct3D = Direct3DCreate9( D3D_SDK_VERSION );
    if( _direct3D == NULL )
    {
      DX9WARN << "Could not create Direct3D interface.";
      return false;
    }

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

    deviceDesc.Windowed = TRUE;
    deviceDesc.SwapEffect = D3DSWAPEFFECT_DISCARD;
    deviceDesc.BackBufferFormat = D3DFMT_UNKNOWN;
    deviceDesc.EnableAutoDepthStencil = FALSE;
    deviceDesc.AutoDepthStencilFormat = D3DFMT_D24S8;

    HRESULT result = _direct3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, windowHandle,
      D3DCREATE_HARDWARE_VERTEXPROCESSING, &deviceDesc, &_device );
    if( FAILED(result) )
    {
      DX9WARN << "Could not create Direct3D device.";
      return false;
    }

    // create vertex buffer
    static const int kMaxVertexCount = 64;

    result = _device->CreateVertexBuffer(
      kMaxVertexCount*sizeof(DX9Vertex), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, 0, D3DPOOL_DEFAULT, &_vertexBuffer, NULL );
    DX9AssertResult( result, "CreateVertexBuffer failed" );

    result = _device->CreateVertexDeclaration( kDX9VertexElements, &_vertexDecl );
    DX9AssertResult( result, "CreateVertexDeclaration failed" );


    // TIM: set up initial state
    result = _device->SetRenderState( D3DRS_ZENABLE, D3DZB_FALSE );
    GPUAssert( !FAILED(result), "SetRenderState failed" );

    _passthroughVertexShader = createVertexShader( kPassthroughVertexShaderSource );
    _passthroughPixelShader = createPixelShader( kPassthroughPixelShaderSource );

    for( size_t i = 0; i < kMaximumOutputCount; i++ )
      _boundOutputs[i] = NULL;
    for( size_t t = 0; t < kMaximumSamplerCount; t++ )
      _boundTextures[t] = NULL;

    return true;
  }
void StateManager9::setStencilOpsBack(GLenum stencilBackFail,
                                      GLenum stencilBackPassDepthFail,
                                      GLenum stencilBackPassDepthPass,
                                      bool frontFaceCCW)
{
    IDirect3DDevice9 *device = mRenderer9->getDevice();
    device->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
                           gl_d3d9::ConvertStencilOp(stencilBackFail));
    device->SetRenderState(!frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
                           gl_d3d9::ConvertStencilOp(stencilBackPassDepthFail));
    device->SetRenderState(!frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
                           gl_d3d9::ConvertStencilOp(stencilBackPassDepthPass));

    mCurDepthStencilState.stencilBackFail          = stencilBackFail;
    mCurDepthStencilState.stencilBackPassDepthFail = stencilBackPassDepthFail;
    mCurDepthStencilState.stencilBackPassDepthPass = stencilBackPassDepthPass;
}
void StateManager9::setStencilFuncsFront(GLenum stencilFunc,
                                         GLuint stencilMask,
                                         GLint stencilRef,
                                         bool frontFaceCCW,
                                         unsigned int maxStencil)
{
    IDirect3DDevice9 *device = mRenderer9->getDevice();
    device->SetRenderState(frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
                           gl_d3d9::ConvertComparison(stencilFunc));
    device->SetRenderState(frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
                           (stencilRef < static_cast<int>(maxStencil)) ? stencilRef : maxStencil);
    device->SetRenderState(frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK, stencilMask);

    mCurDepthStencilState.stencilFunc = stencilFunc;
    mCurStencilRef                    = stencilRef;
    mCurDepthStencilState.stencilMask = stencilMask;
}
void StateManager9::setBlendFuncsEquations(const gl::BlendState &blendState)
{
    if (!blendState.blend)
        return;

    IDirect3DDevice9 *device = mRenderer9->getDevice();

    device->SetRenderState(D3DRS_SRCBLEND, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendRGB));
    device->SetRenderState(D3DRS_DESTBLEND, gl_d3d9::ConvertBlendFunc(blendState.destBlendRGB));
    device->SetRenderState(D3DRS_BLENDOP, gl_d3d9::ConvertBlendOp(blendState.blendEquationRGB));

    if (blendState.sourceBlendRGB != blendState.sourceBlendAlpha ||
        blendState.destBlendRGB != blendState.destBlendAlpha ||
        blendState.blendEquationRGB != blendState.blendEquationAlpha)
    {
        device->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);

        device->SetRenderState(D3DRS_SRCBLENDALPHA,
                               gl_d3d9::ConvertBlendFunc(blendState.sourceBlendAlpha));
        device->SetRenderState(D3DRS_DESTBLENDALPHA,
                               gl_d3d9::ConvertBlendFunc(blendState.destBlendAlpha));
        device->SetRenderState(D3DRS_BLENDOPALPHA,
                               gl_d3d9::ConvertBlendOp(blendState.blendEquationAlpha));
    }
    else
    {
        device->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
    }

    mCurBlendState.sourceBlendRGB     = blendState.sourceBlendRGB;
    mCurBlendState.destBlendRGB       = blendState.destBlendRGB;
    mCurBlendState.blendEquationRGB   = blendState.blendEquationRGB;
    mCurBlendState.blendEquationAlpha = blendState.blendEquationAlpha;
}
Beispiel #6
0
static void SetUpLights(){
	IDirect3DDevice9 *pDevice = _pGraphics->GetD3DDevice();
	D3DXVECTOR3 dir(1.0f, -1.0f, 1.0f);
	D3DXCOLOR col(1.0f, 1.0f, 1.0f, 1.0f);
	D3DLIGHT9 light;
	light.Type      = D3DLIGHT_DIRECTIONAL;
	light.Ambient   = col * 0.4f;
	light.Diffuse   = col;
	light.Specular  = col * 0.6f;
	light.Direction = dir;
	pDevice->SetLight(0, &light);
	pDevice->LightEnable(0, true);
	//pDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE );
	pDevice->SetRenderState(D3DRS_LIGHTING, TRUE);
	//pDevice->SetRenderState(D3DRS_AMBIENT, 0xFFFFFFFF);
	pDevice->SetRenderState(D3DRS_NORMALIZENORMALS, true);
	pDevice->SetRenderState(D3DRS_SPECULARENABLE, true);
}
// TODO(dianx) one bit for color mask
void StateManager9::setColorMask(const gl::Framebuffer *framebuffer,
                                 bool red,
                                 bool blue,
                                 bool green,
                                 bool alpha)
{
    // Set the color mask
    bool zeroColorMaskAllowed = mRenderer9->getVendorId() != VENDOR_ID_AMD;
    // Apparently some ATI cards have a bug where a draw with a zero color
    // write mask can cause later draws to have incorrect results. Instead,
    // set a nonzero color write mask but modify the blend state so that no
    // drawing is done.
    // http://code.google.com/p/angleproject/issues/detail?id=169

    const gl::FramebufferAttachment *attachment = framebuffer->getFirstColorbuffer();
    GLenum internalFormat                       = attachment ? attachment->getInternalFormat() : GL_NONE;

    const gl::InternalFormat &formatInfo = gl::GetInternalFormatInfo(internalFormat);

    DWORD colorMask = gl_d3d9::ConvertColorMask(
        formatInfo.redBits > 0 && red, formatInfo.greenBits > 0 && green,
        formatInfo.blueBits > 0 && blue, formatInfo.alphaBits > 0 && alpha);

    if (colorMask == 0 && !zeroColorMaskAllowed)
    {
        IDirect3DDevice9 *device = mRenderer9->getDevice();
        // Enable green channel, but set blending so nothing will be drawn.
        device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
        device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);

        device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
        device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
        device->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
    }
    else
    {
        mRenderer9->getDevice()->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
    }

    mCurBlendState.colorMaskRed   = red;
    mCurBlendState.colorMaskGreen = green;
    mCurBlendState.colorMaskBlue  = blue;
    mCurBlendState.colorMaskAlpha = alpha;
}
void StateManager9::setStencilOpsFront(GLenum stencilFail,
                                       GLenum stencilPassDepthFail,
                                       GLenum stencilPassDepthPass,
                                       bool frontFaceCCW)
{
    // TODO(dianx) It may be slightly more efficient todo these and other similar areas
    // with separate dirty bits.
    IDirect3DDevice9 *device = mRenderer9->getDevice();
    device->SetRenderState(frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
                           gl_d3d9::ConvertStencilOp(stencilFail));
    device->SetRenderState(frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
                           gl_d3d9::ConvertStencilOp(stencilPassDepthFail));
    device->SetRenderState(frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
                           gl_d3d9::ConvertStencilOp(stencilPassDepthPass));

    mCurDepthStencilState.stencilFail          = stencilFail;
    mCurDepthStencilState.stencilPassDepthFail = stencilPassDepthFail;
    mCurDepthStencilState.stencilPassDepthPass = stencilPassDepthPass;
}
Beispiel #9
0
HRESULT APPLICATION::Render()
{
    // Clear the viewport
    m_pDevice->Clear(0L, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0L );

    // Begin the scene 
    if(SUCCEEDED(m_pDevice->BeginScene()))
    {
		//Set camera
		D3DXMATRIX view, proj;
		D3DXMatrixLookAtLH(&view, &D3DXVECTOR3(0.0f, 10.0f, -50.0f), &D3DXVECTOR3(0.0f, 3.0f, 0.0f), &D3DXVECTOR3(0.0f, 1.0f, 0.0f));
		D3DXMatrixOrthoLH(&proj, 10.0f, 9.0f, 0.1f, 1000.0f);
		m_pDevice->SetTransform(D3DTS_VIEW, &view);
		m_pDevice->SetTransform(D3DTS_PROJECTION, &proj);

		if(m_wireframe)m_pDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);	
		else m_pDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);

		m_farmer1.Render();
		m_farmer2.RenderProgressive();

		//Number of polygons
		char number[50];
		std::string text = itoa(m_farmer2.GetNumProgressiveFaces(), number, 10);
		text += " polygons (UP/DOWN Arrow)";
		
		RECT r[] = {{170, 520, 0, 0}, {530, 520, 0, 0}, {470, 540, 0, 0}, {130, 540, 0, 0}};
		m_pFont->DrawText(NULL, "Original", -1, &r[0], DT_LEFT| DT_TOP | DT_NOCLIP, 0xff000000);
		m_pFont->DrawText(NULL, "Progressive Mesh", -1, &r[1], DT_LEFT| DT_TOP | DT_NOCLIP, 0xff000000);
		m_pFont->DrawText(NULL, text.c_str(), -1, &r[2], DT_LEFT| DT_TOP | DT_NOCLIP, 0xff000000);
		m_pFont->DrawText(NULL, "(W)ireframe On/Off", -1, &r[3], DT_LEFT| DT_TOP | DT_NOCLIP, 0xff000000);		

        // End the scene.
		m_pDevice->EndScene();
		m_pDevice->Present(0, 0, 0, 0);
    }

	return S_OK;
}
Beispiel #10
0
    void CubeMesh::DrawRay(const D3DXVECTOR2& screenPos,
        const D3DXMATRIX& matWorld, const D3DXMATRIX& matView, const D3DXMATRIX& matProj)
    {
        HRESULT hr = S_FALSE;
        GraphicsDevice* pGDevice = GraphicsDevice::getInstance();
        IDirect3DDevice9* pDevice = pGDevice->m_pD3DDevice;
        Ray ray = CalcPickingRay((int)screenPos.x, (int)screenPos.y,
            pGDevice->mCubeViewport, matView, matProj );
        PCVertex rayLine[] = {
            {D3DXVECTOR3(0.0f,0.0f,0.0f), D3DCOLOR_ARGB(255,255,0,0)},
            {ray.Origin + 1000*ray.Direction, D3DCOLOR_ARGB(255,255,0,0)},
        };

        PCVertex intersectPoint[] = {
            {p, D3DCOLOR_ARGB(255,0,0,255)},
            {p+D3DXVECTOR3(0.5f,0.0f,0.0f),  D3DCOLOR_ARGB(255,0,0,255)},
            {p+D3DXVECTOR3(0.0f,0.5f,0.0f),  D3DCOLOR_ARGB(255,0,0,255)},
            {p+D3DXVECTOR3(0.0f,0.0f,0.5f),  D3DCOLOR_ARGB(255,0,0,255)},
            {p+D3DXVECTOR3(-0.5f,0.0f,0.0f), D3DCOLOR_ARGB(255,0,0,255)},
            {p+D3DXVECTOR3(0.0f,-0.5f,0.0f), D3DCOLOR_ARGB(255,0,0,255)},
            {p+D3DXVECTOR3(0.0f,0.0f,-0.5f), D3DCOLOR_ARGB(255,0,0,255)},
        };

        pGDevice->SetViewport(pGDevice->mCubeViewport);
        pDevice->SetVertexShader(NULL);
        pDevice->SetPixelShader(NULL);
        V(pDevice->SetTransform(D3DTS_WORLD, &matWorld));
        V(pDevice->SetTransform(D3DTS_VIEW, &matView));
        V(pDevice->SetTransform(D3DTS_PROJECTION, &matProj));
        V(pDevice->SetRenderState(D3DRS_LIGHTING, FALSE));
        V(pDevice->SetRenderState(D3DRS_ZENABLE, FALSE));
        V(pDevice->SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE));
        V(pDevice->DrawPrimitiveUP(D3DPT_LINELIST, 1, rayLine, sizeof(PCVertex)));
        V(pDevice->DrawPrimitiveUP(D3DPT_POINTLIST, 7, intersectPoint, sizeof(PCVertex)));
        V(pDevice->SetFVF(NULL));
        V(pDevice->SetRenderState(D3DRS_ZENABLE, TRUE));
        V(pDevice->SetRenderState(D3DRS_LIGHTING, TRUE));
        pGDevice->ResetViewport();
    }
//Function to check if the renderer is Direct 3D (If not, it's OpenGL)
bool GameDebugger::IsD3D(ALLEGRO_DISPLAY* mydisplay)
{
    IDirect3DDevice9 * whatisthis = al_get_d3d_device(mydisplay);
    if(!whatisthis)
        return false;


    HRESULT isDirect3D = NULL;
    isDirect3D = whatisthis->SetRenderState(D3DRS_LIGHTING,false);

    if(isDirect3D == D3D_OK)
        return true;
    return false;
}
void Blit::setCommonBlitState()
{
    IDirect3DDevice9 *device = getDevice();

    device->SetDepthStencilSurface(NULL);

    device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
    device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
    device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
    device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
    device->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
    device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED);
    device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE);
    device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);

    device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
    device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
    device->SetSamplerState(0, D3DSAMP_SRGBTEXTURE, FALSE);
    device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
    device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);

    RECT scissorRect = {0};   // Scissoring is disabled for flipping, but we need this to capture and restore the old rectangle
    device->SetScissorRect(&scissorRect);
}
Beispiel #13
0
void UIRender::InitRenderEffect()
{
	IDirect3DDevice9* pIDevice = UIDXInit::GetSingleton()->_pIDevice;

	// 关闭灯光
	pIDevice->SetRenderState( D3DRS_LIGHTING, false );

	// 开启颜色alpha透明
	pIDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, true );
	pIDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
	pIDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );

	// 高斯光栅 会产生颜色渐变效果
	pIDevice->SetRenderState( D3DRS_SHADEMODE, D3DSHADE_GOURAUD );

	// 不采用反面拣选
	pIDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );

	// 确定可视柱体
	// 设置摄像头位置
	UICamera::GetSingleton()->SetCameraView();
	// 设置剪裁面宽高比、摄像头上下视角、前后剪裁面与摄像头距离
	UICamera::GetSingleton()->SetPerspective( (float)( UIDXInit::GetSingleton()->GetPresentWidth() )/UIDXInit::GetSingleton()->GetPresentHeight() );
}
Beispiel #14
0
bool CScreen::SetDefaultGraphicsSettings3D()
{
	HRESULT hr;

	D3DXMATRIX identityTransform, projTransform;
	D3DXMatrixIdentity(&identityTransform);
	D3DXMatrixPerspectiveFovLH(&projTransform, D3DX_PI / 4, 1.0f, 1.0f, 100.0f);

    D3DXVECTOR3 vEyePt(-10.0f, -10.0f, 10.0f);
    D3DXVECTOR3 vLookatPt(0.0f, 0.0f, 0.0f);
    D3DXVECTOR3 vUpVec(0.0f, 0.0f, 1.0f);
    D3DXMATRIXA16 matView;
    D3DXMatrixLookAtLH(&matView, &vEyePt, &vLookatPt, &vUpVec);

	D3DCOLORVALUE lightColor = {1.0f, 1.0f, 1.0f, 1.0f};
	D3DXVECTOR3 lightDir(-1.0f, 0.7f, -0.2f);

	D3DLIGHT9 light;
	setupDirectionalLight(light, lightColor, lightDir);

	D3DMATERIAL9 mtrl;
	ZeroMemory( &mtrl, sizeof( D3DMATERIAL9 ) );
	mtrl.Diffuse = lightColor;
	mtrl.Ambient = lightColor;
	mtrl.Ambient.g = 0.0f;

	CGraphicsManager *pGraphicsManager = CGraphicsManager::GetInstance();
	IDirect3DDevice9 *pDevice = pGraphicsManager->GetDevice();
	CCamera * pCamera = CCamera::GetInstance();

	hr = pDevice->SetTransform(D3DTS_WORLD, &identityTransform);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set world transform", hr);
		return false;
	}
		
	D3DXMATRIX camViewMat = pCamera->GetViewMatrix();
	hr = pDevice->SetTransform(D3DTS_VIEW, &camViewMat);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set view transform", hr);
		return false;
	}

	D3DXMATRIX camProjMat = pCamera->GetProjectionMatrix();
	hr = pDevice->SetTransform(D3DTS_PROJECTION, &camProjMat);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set projection transform", hr);
		return false;
	}

	hr = pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set cull mode render state", hr);
		return false;
	}

	hr = pDevice->SetLight(0, &light);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set light 0", hr);
		return false;
	}

	hr = pDevice->SetMaterial(&mtrl);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set material", hr);
		return false;
	}

	hr = pDevice->LightEnable(0, TRUE);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to enable light", hr);
		return false;
	}

	hr = pDevice->SetRenderState(D3DRS_AMBIENT, 0x00202020);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set ambient color", hr);
		return false;
	}

	hr = pDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to enable z", hr);
		return false;
	}

	hr = pDevice->SetRenderState(D3DRS_ZWRITEENABLE , TRUE);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set z write enabled", hr);
		return false;
	}

	hr = pDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set sampler state - MINFILTER", hr);
		return false;
	}

	hr = pDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set sampler state - MAGFILTER", hr);
		return false;
	}

	hr = pDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set sampler state - MIPFILTER", hr);
		return false;
	}

	return true;
}
Beispiel #15
0
void CState::Restore()
{
	// viewport
	m_D3DDev->SetViewport(&m_Vp);

	// render states
	m_D3DDev->SetRenderState(D3DRS_ZENABLE, m_Z);
	m_D3DDev->SetRenderState(D3DRS_CULLMODE, m_CullMode);
	m_D3DDev->SetRenderState(D3DRS_ALPHATESTENABLE, m_AlphaTest);
	m_D3DDev->SetRenderState(D3DRS_ALPHABLENDENABLE, m_AlphaBlend);
	m_D3DDev->SetRenderState(D3DRS_BLENDOP, m_BlendOp);
	m_D3DDev->SetRenderState(D3DRS_SRCBLEND, m_SrcBlend);
	m_D3DDev->SetRenderState(D3DRS_DESTBLEND, m_DstBlend);
	m_D3DDev->SetRenderState(D3DRS_CLIPPLANEENABLE, m_ClipPlane);
	m_D3DDev->SetRenderState(D3DRS_FILLMODE, m_FillMode);
	m_D3DDev->SetRenderState(D3DRS_LASTPIXEL, m_LastPixel);
	m_D3DDev->SetRenderState(D3DRS_FOGENABLE, m_Fog);
	m_D3DDev->SetRenderState(D3DRS_STENCILENABLE, m_Stencil);
	m_D3DDev->SetRenderState(D3DRS_COLORWRITEENABLE, m_ColorWrite);
	m_D3DDev->SetRenderState(D3DRS_SCISSORTESTENABLE, m_Scissor);
	if( m_Caps.PrimitiveMiscCaps & D3DPMISCCAPS_SEPARATEALPHABLEND )
		m_D3DDev->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, m_SeparateAlphaBlend);
	//if( m_Caps.LineCaps & D3DLINECAPS_ANTIALIAS )
		m_D3DDev->SetRenderState(D3DRS_ANTIALIASEDLINEENABLE, m_AntiAliasedLine);

	// primitive
	m_D3DDev->SetFVF(m_FVF);
	m_D3DDev->SetStreamSource(0, m_StreamData, m_StreamOffset, m_StreamStride);
	if( m_StreamData )
		m_StreamData->Release();
	m_D3DDev->SetVertexShader(m_VertexShader);
	if( m_VertexShader )
		m_VertexShader->Release();

	// texture
	m_D3DDev->SetTexture(0, m_Tex);
	if( m_Tex )
		m_Tex->Release();
	m_D3DDev->SetPixelShader(m_PixelShader);
	if( m_PixelShader )
		m_PixelShader->Release();

	// texture stage states
	m_D3DDev->SetTextureStageState(0, D3DTSS_COLOROP, m_ColorOp);
	m_D3DDev->SetTextureStageState(0, D3DTSS_COLORARG1, m_ColorArg1);
	m_D3DDev->SetTextureStageState(0, D3DTSS_COLORARG2, m_ColorArg2);
	m_D3DDev->SetTextureStageState(0, D3DTSS_ALPHAOP, m_AlphaOp);
	m_D3DDev->SetTextureStageState(0, D3DTSS_ALPHAARG1, m_AlphaArg1);
	m_D3DDev->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, m_TexCoordIndex);
	m_D3DDev->SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, m_TexTransfFlags);
	m_D3DDev->SetSamplerState(0, D3DSAMP_ADDRESSU, m_AddressU);
	m_D3DDev->SetSamplerState(0, D3DSAMP_ADDRESSV, m_AddressV);
	m_D3DDev->SetSamplerState(0, D3DSAMP_MAGFILTER, m_MagFilter);
	m_D3DDev->SetSamplerState(0, D3DSAMP_MINFILTER, m_MinFilter);
	m_D3DDev->SetSamplerState(0, D3DSAMP_MIPFILTER, m_MipFilter);
}
Beispiel #16
0
bool CScreen::SetDefaultGraphicsSettings2D()
{
	HRESULT hr;
	CGraphicsManager *pGraphicsManager = CGraphicsManager::GetInstance();
	IDirect3DDevice9 *pDevice = pGraphicsManager->GetDevice();

	D3DXMATRIX identityTransform, projTransform;
	D3DXMatrixIdentity(&identityTransform);
	D3DXMatrixOrthoLH(&projTransform, 100.0f * pGraphicsManager->GetAspectRatio(), 100.0f, -1.0f, 1.0f);

	hr = pDevice->SetTransform(D3DTS_WORLD, &identityTransform);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set world transform", hr);
		return false;
	}
		
	hr = pDevice->SetTransform(D3DTS_VIEW, &identityTransform);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set view transform", hr);
		return false;
	}

	hr = pDevice->SetTransform(D3DTS_PROJECTION, &projTransform);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set projection transform", hr);
		return false;
	}

	hr = pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set cull mode render state", hr);
		return false;
	}

	hr = pDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to enable z", hr);
		return false;
	}

	hr = pDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set z write enabled", hr);
		return false;
	}

	hr = pDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set lighting to false", hr);
		return false;
	}

	hr = pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set alpha blending to true", hr);
		return false;
	}

	hr = pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set alpha source render state", hr);
		return false;
	}

	hr = pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
	if(FAILED(hr))
	{
		LogErrorHr("Failed to set alpha dest render state", hr);
		return false;
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	// Zwalniamy zasoby
	box_buffer->Release();
	dev->Release();
	d3d->Release();
	return 0;
}
Beispiel #18
0
void DevState::createCleanState() {
	if (dwMyThread != 0) {
		ods("D3D9: CreateCleanState from other thread.");
	}
	Stash<DWORD> stashThread(&dwMyThread, GetCurrentThreadId());

	if (pSB)
		pSB->Release();
	pSB = NULL;

	IDirect3DStateBlock9* pStateBlock = NULL;
	dev->CreateStateBlock(D3DSBT_ALL, &pStateBlock);
	if (! pStateBlock)
		return;

	pStateBlock->Capture();

	dev->CreateStateBlock(D3DSBT_ALL, &pSB);
	if (! pSB) {
		pStateBlock->Release();
		return;
	}

	D3DVIEWPORT9 vp;
	dev->GetViewport(&vp);

	dev->SetVertexShader(NULL);
	dev->SetPixelShader(NULL);
	dev->SetFVF(D3DFVF_TLVERTEX);

	dev->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
	dev->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
	dev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); // 0x16
	dev->SetRenderState(D3DRS_WRAP0, FALSE); // 0x80

	dev->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
	dev->SetRenderState(D3DRS_SRCBLEND,  D3DBLEND_ONE);
	dev->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);

	dev->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
	dev->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER);

	dev->SetRenderState(D3DRS_ZENABLE, FALSE);
	dev->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
	dev->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
	dev->SetRenderState(D3DRS_COLORVERTEX, FALSE);

	dev->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
	dev->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
	dev->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);

	dev->SetRenderState(D3DRS_LIGHTING, FALSE);

	pSB->Capture();

	pStateBlock->Apply();
	pStateBlock->Release();
}
Beispiel #19
0
// parameters should be validated/clamped by caller
EGLint SwapChain9::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
{
    if (!mSwapChain)
    {
        return EGL_SUCCESS;
    }

    IDirect3DDevice9 *device = mRenderer->getDevice();

    // Disable all pipeline operations
    device->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
    device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
    device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
    device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
    device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
    device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
    device->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
    device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED);
    device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE);
    device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
    device->SetPixelShader(NULL);
    device->SetVertexShader(NULL);

    device->SetRenderTarget(0, mBackBuffer);
    device->SetDepthStencilSurface(NULL);

    device->SetTexture(0, mOffscreenTexture);
    device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
    device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
    device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
    device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
    device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
    device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
    device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
    device->SetFVF(D3DFVF_XYZRHW | D3DFVF_TEX1);

    D3DVIEWPORT9 viewport = {0, 0, mWidth, mHeight, 0.0f, 1.0f};
    device->SetViewport(&viewport);

    float x1 = x - 0.5f;
    float y1 = (mHeight - y - height) - 0.5f;
    float x2 = (x + width) - 0.5f;
    float y2 = (mHeight - y) - 0.5f;

    float u1 = x / float(mWidth);
    float v1 = y / float(mHeight);
    float u2 = (x + width) / float(mWidth);
    float v2 = (y + height) / float(mHeight);

    float quad[4][6] = {{x1, y1, 0.0f, 1.0f, u1, v2},
                        {x2, y1, 0.0f, 1.0f, u2, v2},
                        {x2, y2, 0.0f, 1.0f, u2, v1},
                        {x1, y2, 0.0f, 1.0f, u1, v1}};   // x, y, z, rhw, u, v

    mRenderer->startScene();
    device->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, quad, 6 * sizeof(float));
    mRenderer->endScene();

    device->SetTexture(0, NULL);

    RECT rect =
    {
        x, mHeight - y - height,
        x + width, mHeight - y
    };

    HRESULT result = mSwapChain->Present(&rect, &rect, NULL, NULL, 0);

    mRenderer->markAllStateDirty();

    if (d3d9::isDeviceLostError(result))
    {
        return EGL_CONTEXT_LOST;
    }

    if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DRIVERINTERNALERROR)
    {
        return EGL_BAD_ALLOC;
    }

    ASSERT(SUCCEEDED(result));

    return EGL_SUCCESS;
}
Beispiel #20
0
HRESULT _stdcall MGEProxyD3D::CreateDevice(UINT a, D3DDEVTYPE b, HWND c, DWORD d, D3DPRESENT_PARAMETERS8 *e, IDirect3DDevice8 **f)
{
    LOG::logline(">> D3D Proxy CreateDevice");

    if(e->Windowed)
    {
        HWND hMainWnd = GetParent(c);
        int wx = std::max(0, (GetSystemMetrics(SM_CXSCREEN) - (int)e->BackBufferWidth) / 2);
        int wy = std::max(0, (GetSystemMetrics(SM_CYSCREEN) - (int)e->BackBufferHeight) / 2);

        if(Configuration.Borderless)
        {
            // Remove non-client window parts and move window flush to screen edge / centre if smaller than display
            SetWindowLong(hMainWnd, GWL_STYLE, WS_VISIBLE);
            SetWindowPos(hMainWnd, NULL, wx, wy, e->BackBufferWidth, e->BackBufferHeight, SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOZORDER);
        }
        else
        {
            // Move window to top, with client area centred on one axis
            RECT rect = { wx, wy, e->BackBufferWidth, e->BackBufferHeight };
            AdjustWindowRect(&rect, GetWindowLong(hMainWnd, GWL_STYLE), FALSE);
            SetWindowPos(hMainWnd, NULL, rect.left, 0, 0, 0, SWP_NOSIZE|SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOZORDER);
        }
    }

    // Map 16x antialiasing to equivalent CSAA
    D3DMULTISAMPLE_TYPE msaaSamples = (Configuration.AALevel == 16) ? D3DMULTISAMPLE_8_SAMPLES : (D3DMULTISAMPLE_TYPE)Configuration.AALevel;
    DWORD msaaQuality = (Configuration.AALevel == 16) ? 2 : 0;

    // Override device parameters
    // Note that Morrowind will look at the modified parameters
    if(e->Flags & D3DPRESENTFLAG_LOCKABLE_BACKBUFFER)
        e->Flags ^= D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;

    e->MultiSampleType = msaaSamples;
    e->AutoDepthStencilFormat = (D3DFORMAT)Configuration.ZBufFormat;
    e->FullScreen_RefreshRateInHz = (!e->Windowed) ? Configuration.RefreshRate : 0;
    e->FullScreen_PresentationInterval = (Configuration.VWait == 255) ? D3DPRESENT_INTERVAL_IMMEDIATE : Configuration.VWait;

    // Convert presentation parameters to DX9
    D3DPRESENT_PARAMETERS9 pp;

    pp.BackBufferWidth = e->BackBufferWidth;
    pp.BackBufferHeight = e->BackBufferHeight;
    pp.BackBufferFormat = e->BackBufferFormat;
    pp.BackBufferCount = e->BackBufferCount;
    pp.MultiSampleType = e->MultiSampleType;
    pp.MultiSampleQuality = msaaQuality;
    pp.SwapEffect = e->SwapEffect;
    pp.hDeviceWindow = e->hDeviceWindow;
    pp.Windowed = e->Windowed;
    pp.Flags = e->Flags;
    pp.EnableAutoDepthStencil = e->EnableAutoDepthStencil;
    pp.AutoDepthStencilFormat = e->AutoDepthStencilFormat;
    pp.FullScreen_RefreshRateInHz = e->FullScreen_RefreshRateInHz;
    pp.PresentationInterval = e->FullScreen_PresentationInterval;

    // Create device in the same manner as the proxy
    IDirect3DDevice9 *realDevice = NULL;
    HRESULT hr = realD3D->CreateDevice(a, b, c, d, &pp, &realDevice);

    if(hr != D3D_OK)
    {
        LOG::logline("!! D3D Proxy CreateDevice failure");
        return hr;
    }

    *f = factoryProxyDevice(realDevice);

    // Set up default render states
    Configuration.ScaleFilter = (Configuration.AnisoLevel > 0) ? D3DTEXF_ANISOTROPIC : D3DTEXF_LINEAR;
    Configuration.MipFilter = D3DTEXF_LINEAR;

    for(int i = 0; i != 4; ++i)
    {
        realDevice->SetSamplerState(i, D3DSAMP_MAXANISOTROPY, Configuration.AnisoLevel);
        realDevice->SetSamplerState(i, D3DSAMP_MINFILTER, Configuration.ScaleFilter);
        realDevice->SetSamplerState(i, D3DSAMP_MIPMAPLODBIAS, *(DWORD *)&Configuration.LODBias);
    }

    // Set variables dependent on configuration
    DWORD FogPixelMode, FogVertexMode, RangedFog;
    if(Configuration.FogMode == 2)
    {
            FogVertexMode = D3DFOG_LINEAR;
            FogPixelMode = D3DFOG_NONE;
            RangedFog = 1;
    }
    else if(Configuration.FogMode == 1)
    {
            FogVertexMode = D3DFOG_LINEAR;
            FogPixelMode = D3DFOG_NONE;
            RangedFog = 0;
    }
    else
    {
            FogVertexMode = D3DFOG_NONE;
            FogPixelMode = D3DFOG_LINEAR;
            RangedFog = 0;
    }

    realDevice->SetRenderState(D3DRS_FOGVERTEXMODE, FogVertexMode);
    realDevice->SetRenderState(D3DRS_FOGTABLEMODE, FogPixelMode);
    realDevice->SetRenderState(D3DRS_RANGEFOGENABLE, RangedFog);
    realDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, (Configuration.AALevel > 0));

    LOG::logline("<< D3D Proxy CreateDevice");
    return D3D_OK;
}
Beispiel #21
0
// parameters should be validated/clamped by caller
EGLint SwapChain9::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
{
    if (!mSwapChain)
    {
        return EGL_SUCCESS;
    }

    IDirect3DDevice9 *device = mRenderer->getDevice();

    // Disable all pipeline operations
    device->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
    device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
    device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
    device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
    device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
    device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
    device->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
    device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED);
    device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE);
    device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
    device->SetPixelShader(NULL);
    device->SetVertexShader(NULL);

    device->SetRenderTarget(0, mBackBuffer);
    device->SetDepthStencilSurface(NULL);

    device->SetTexture(0, mOffscreenTexture);
    device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
    device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
    device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
    device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
    device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
    device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
    device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
    device->SetFVF(D3DFVF_XYZRHW | D3DFVF_TEX1);

    for (UINT streamIndex = 0; streamIndex < gl::MAX_VERTEX_ATTRIBS; streamIndex++)
    {
        device->SetStreamSourceFreq(streamIndex, 1);
    }

    D3DVIEWPORT9 viewport = {0, 0, mWidth, mHeight, 0.0f, 1.0f};
    device->SetViewport(&viewport);

    float x1 = x - 0.5f;
    float y1 = (mHeight - y - height) - 0.5f;
    float x2 = (x + width) - 0.5f;
    float y2 = (mHeight - y) - 0.5f;

    float u1 = x / float(mWidth);
    float v1 = y / float(mHeight);
    float u2 = (x + width) / float(mWidth);
    float v2 = (y + height) / float(mHeight);

    float quad[4][6] = {{x1, y1, 0.0f, 1.0f, u1, v2},
                        {x2, y1, 0.0f, 1.0f, u2, v2},
                        {x2, y2, 0.0f, 1.0f, u2, v1},
                        {x1, y2, 0.0f, 1.0f, u1, v1}};   // x, y, z, rhw, u, v

    mRenderer->startScene();
    device->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, quad, 6 * sizeof(float));
    mRenderer->endScene();

    device->SetTexture(0, NULL);

    RECT rect =
    {
        x, mHeight - y - height,
        x + width, mHeight - y
    };

    HRESULT result = mSwapChain->Present(&rect, &rect, NULL, NULL, 0);

    mRenderer->markAllStateDirty();

    if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DRIVERINTERNALERROR)
    {
        return EGL_BAD_ALLOC;
    }

    // On Windows 8 systems, IDirect3DSwapChain9::Present sometimes returns 0x88760873 when the windows is
    // in the process of entering/exiting fullscreen. This code doesn't seem to have any documentation.  The
    // device appears to be ok after emitting this error so simply return a failure to swap.
    if (result == 0x88760873)
    {
        return EGL_BAD_NATIVE_WINDOW;
    }

    // http://crbug.com/313210
    // If our swap failed, trigger a device lost event. Resetting will work around an AMD-specific
    // device removed bug with lost contexts when reinstalling drivers.
    if (FAILED(result))
    {
        mRenderer->notifyDeviceLost();
        return EGL_CONTEXT_LOST;
    }

    return EGL_SUCCESS;
}
void MenuHandler::render()
{
	if (!enabled)
		return;
	
	sprite->Begin(D3DXSPRITE_ALPHABLEND);

	IDirect3DDevice9* device;
	sprite->GetDevice(&device);
	device->SetRenderState(D3DRS_ZENABLE, FALSE);

	if (selectedMode == MAIN_MENU)
	{
		int jitter = std::rand() % 100;
		
		if (jitter < 95)
			jitter = 0;
		else
			jitter = std::rand() % 100 - 50;

		// Draw main menu
		D3DXVECTOR3 currentPos;
		currentPos.x = (float) screenWidth / 2.0f - 192 + jitter;
		currentPos.y = (float) screenHeight / 2.0f + jitter;
		currentPos.z = 0;

		float scaleFactorX = screenWidth / 1024.0f;
		float scaleFactorY = screenHeight / 819.0f;

		D3DXMATRIX origTrans, newTrans;
		sprite->GetTransform(&origTrans);
		D3DXMatrixScaling(&newTrans, scaleFactorX, scaleFactorY, 1.0f);
		sprite->SetTransform(&newTrans);

		RECT area;
		area.top = 0;
		area.bottom = 819;
		area.left = 0;
		area.right = 1024;

		sprite->Draw(mainMenuTexture, &area, &D3DXVECTOR3(512, 409.5f, 0),
			&D3DXVECTOR3(512, 409.5f, 0), 0xFFFFFFFF);

		sprite->SetTransform(&origTrans);


		// Draw menu options
		sprite->Draw(uiTexture, startGameRect, NULL, &currentPos, 0xFFFFFFFF);
		currentPos.y += 128;
		sprite->Draw(uiTexture, quitRect, NULL, &currentPos, 0xFFFFFFFF);
		
		// Draw arrow next to appropriate selection
		currentPos.x -= 128.0f;
		currentPos.y = (float) screenHeight / 2.0f;

		if (selectedOption == QUIT)
		{
			currentPos.y += 128;
		}

		sprite->Draw(uiTexture, arrowRect, NULL, &currentPos, 0xFFFF0000);
	}
	else if (selectedMode == PAUSE_MENU)
	{
		int jitter = std::rand() % 100;
		
		if (jitter < 95)
			jitter = 0;
		else
			jitter = std::rand() % 100 - 50;

		// Draw pause menu
		D3DXVECTOR3 currentPos;
		currentPos.x = (float) screenWidth / 2 - 128 + jitter;
		currentPos.y = (float) screenHeight / 2 - 128 + jitter;
		currentPos.z = 0;

		// Draw menu options
		sprite->Draw(uiTexture, continueRect, NULL, &currentPos, 0xFFFFFFFF);
		currentPos.y += 128;
		sprite->Draw(uiTexture, quitRect, NULL, &currentPos, 0xFFFFFFFF);
		
		// Draw arrow next to appropriate selection
		currentPos.x -= 128.0f;
		currentPos.y = (float) screenHeight / 2 - 128;

		if (selectedOption == CONTINUE)
		{
			// Do nothing
		}
		else if (selectedOption == QUIT)
		{
			currentPos.y += 128;
		}

		sprite->Draw(uiTexture, arrowRect, NULL, &currentPos, 0xFFFF0000);
	}
	else if (selectedMode == LOADING)
	{
		// Show loading screen, then wait for player to hit A or Start
		sprite->Draw(loadingbgTexture, NULL, &D3DXVECTOR3(512, 0, 0),
			&D3DXVECTOR3((float) screenWidth / 2.0f, 0, 0), 0xFFFFFFFF);
		
		
		if (loadingComplete)
		{
			RECT doneLoading;
			doneLoading.top = 128;
			doneLoading.bottom = 256;
			doneLoading.left = 0;
			doneLoading.right = 512;

			sprite->Draw(loadingTextTexture, &doneLoading, &D3DXVECTOR3(256, 0, 0),
				&D3DXVECTOR3((float) screenWidth / 2.0f, (float) screenHeight - 128.0f, 0), 0xFFFFFFFF);
		}
		else
		{
			RECT loading;
			loading.top = 0;
			loading.bottom = 128;
			loading.left = 0;
			loading.right = 512;

			sprite->Draw(loadingTextTexture, &loading, &D3DXVECTOR3(256, 0, 0),
				&D3DXVECTOR3((float) screenWidth / 2.0f, (float) screenHeight - 128.0f, 0), 0xFFFFFFFF);
		}
	}


	sprite->End();
}