Related
I wanted to draw a 3D cube, but it doesn't display correctly. That is, the Z buffer (depth buffer) does not work.
The initialization of the depth buffer occurs in the InitDepthBuffer method, which I copied from the manual from Microsoft. The InitDepthBuffer method is called in the InitD3D method below.
Why "cube" is not displayed correctly and how to fix the program?
My Game.cpp
// include the basic windows header files and the Direct3D header files
#include <windows.h>
#include <windowsx.h>
#include <d3d11.h>
#include <d3dx11.h>
#include <d3dx10.h>
#include <xnamath.h>
// include the Direct3D Library file
#pragma comment (lib, "d3d11.lib")
#pragma comment (lib, "d3dx11.lib")
#pragma comment (lib, "d3dx10.lib")
// define the screen resolution
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
// global declarations
IDXGISwapChain* swapchain; // the pointer to the swap chain interface
ID3D11Device* dev; // the pointer to our Direct3D device interface
ID3D11DeviceContext* devcon; // the pointer to our Direct3D device context
ID3D11RenderTargetView* backbuffer; // the pointer to our back buffer
ID3D11InputLayout* pLayout; // the pointer to the input layout
ID3D11VertexShader* pVS; // the pointer to the vertex shader
ID3D11PixelShader* pPS; // the pointer to the pixel shader
ID3D11Buffer* pVBuffer; // the pointer to the vertex buffer
ID3D11Buffer* pIBuffer;
ID3D11Buffer* wvpConstBuffer;
ID3D11ShaderResourceView* pTexture; // the texture
ID3D11SamplerState* pSamplerState;
ID3D11RasterizerState* pRasterState;
ID3D11Texture2D* pDepthStencil = NULL;
ID3D11DepthStencilState* pDSState;
ID3D11DepthStencilView* pDSV;
// a struct to define a single vertex
struct VERTEX { FLOAT X, Y, Z, texX, texY; };
struct ConstantBuffer
{
XMMATRIX mWorld;
XMMATRIX mView;
XMMATRIX mProjection;
};
XMMATRIX g_World;
XMMATRIX g_View;
XMMATRIX g_Projection;
// function prototypes
void InitD3D(HWND hWnd); // sets up and initializes Direct3D
void RenderFrame(void); // renders a single frame
void CleanD3D(void); // closes Direct3D and releases memory
void InitGraphics(void); // creates the shape to render
void InitPipeline(void); // loads and prepares the shaders
// the WindowProc function prototype
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
// the entry point for any Windows program
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
HWND hWnd;
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpszClassName = L"WindowClass";
RegisterClassEx(&wc);
RECT wr = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT };
AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
hWnd = CreateWindowEx(NULL,
L"WindowClass",
L"My Game",
WS_OVERLAPPEDWINDOW,
300,
300,
wr.right - wr.left,
wr.bottom - wr.top,
NULL,
NULL,
hInstance,
NULL);
ShowWindow(hWnd, nCmdShow);
// set up and initialize Direct3D
InitD3D(hWnd);
// enter the main loop:
MSG msg;
while (TRUE)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if (msg.message == WM_QUIT)
break;
}
RenderFrame();
}
// clean up DirectX and COM
CleanD3D();
return msg.wParam;
}
// this is the main message handler for the program
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
} break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
void InitDepthBuffer()
{
D3D11_TEXTURE2D_DESC descDepth;
descDepth.Width = SCREEN_WIDTH;
descDepth.Height = SCREEN_HEIGHT;
descDepth.MipLevels = 1;
descDepth.ArraySize = 1;
descDepth.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
descDepth.SampleDesc.Count = 1;
descDepth.SampleDesc.Quality = 0;
descDepth.Usage = D3D11_USAGE_DEFAULT;
descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
descDepth.CPUAccessFlags = 0;
descDepth.MiscFlags = 0;
dev->CreateTexture2D(&descDepth, NULL, &pDepthStencil);
D3D11_DEPTH_STENCIL_DESC dsDesc;
// Depth test parameters
dsDesc.DepthEnable = true;
dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
dsDesc.DepthFunc = D3D11_COMPARISON_LESS;
// Stencil test parameters
dsDesc.StencilEnable = true;
dsDesc.StencilReadMask = 0xFF;
dsDesc.StencilWriteMask = 0xFF;
// Stencil operations if pixel is front-facing
dsDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
dsDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
dsDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
dsDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Stencil operations if pixel is back-facing
dsDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
dsDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
dsDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
dsDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
dev->CreateDepthStencilState(&dsDesc, &pDSState);
D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
descDSV.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
descDSV.Texture2D.MipSlice = 0;
dev->CreateDepthStencilView(pDepthStencil, // Depth stencil texture
&descDSV, // Depth stencil desc
&pDSV); // [out] Depth stencil view
}
// this function initializes and prepares Direct3D for use
void InitD3D(HWND hWnd)
{
// create a struct to hold information about the swap chain
DXGI_SWAP_CHAIN_DESC scd;
// clear out the struct for use
ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));
// fill the swap chain description struct
scd.BufferCount = 1; // one back buffer
scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // use 32-bit color
scd.BufferDesc.Width = SCREEN_WIDTH; // set the back buffer width
scd.BufferDesc.Height = SCREEN_HEIGHT; // set the back buffer height
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // how swap chain is to be used
scd.OutputWindow = hWnd; // the window to be used
scd.SampleDesc.Count = 4; // how many multisamples
scd.Windowed = TRUE; // windowed/full-screen mode
scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; // allow full-screen switching
// create a device, device context and swap chain using the information in the scd struct
D3D11CreateDeviceAndSwapChain(NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
NULL,
NULL,
NULL,
D3D11_SDK_VERSION,
&scd,
&swapchain,
&dev,
NULL,
&devcon);
// get the address of the back buffer
ID3D11Texture2D* pBackBuffer;
swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
// use the back buffer address to create the render target
dev->CreateRenderTargetView(pBackBuffer, NULL, &backbuffer);
pBackBuffer->Release();
InitDepthBuffer();
// set the render target as the back buffer
devcon->OMSetRenderTargets(1, &backbuffer, pDSV);
devcon->OMSetDepthStencilState(pDSState, 1);
// Set the viewport
D3D11_VIEWPORT viewport;
ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
viewport.Width = SCREEN_WIDTH;
viewport.Height = SCREEN_HEIGHT;
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
devcon->RSSetViewports(1, &viewport);
InitPipeline();
InitGraphics();
}
// this is the function used to render a single frame
void RenderFrame(void)
{
// update WVP matrices
ConstantBuffer cb;
cb.mWorld = XMMatrixTranspose(g_World);
cb.mView = XMMatrixTranspose(g_View);
cb.mProjection = XMMatrixTranspose(g_Projection);
devcon->UpdateSubresource(wvpConstBuffer, 0, NULL, &cb, 0, 0);
// clear the back buffer to a deep blue and the depth buffer
devcon->ClearRenderTargetView(backbuffer, D3DXCOLOR(0.0f, 0.0f, 0.0f, 1.0f));
devcon->ClearDepthStencilView(pDSV, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
// select which vertex buffer to display
UINT stride = sizeof(VERTEX);
UINT offset = 0;
devcon->IASetVertexBuffers(0, 1, &pVBuffer, &stride, &offset);
devcon->IASetIndexBuffer(pIBuffer, DXGI_FORMAT_R32_UINT, 0);
devcon->VSSetConstantBuffers(0, 1, &wvpConstBuffer);
// select which primtive type we are using
devcon->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// draw the vertex buffer to the back buffer
devcon->DrawIndexed(24, 0, 0);
// switch the back buffer and the front buffer
swapchain->Present(0, 0);
g_World *= XMMatrixRotationY(XM_PI / 12);
Sleep(100);
}
// this is the function that cleans up Direct3D and COM
void CleanD3D(void)
{
swapchain->SetFullscreenState(FALSE, NULL); // switch to windowed mode
// close and release all existing COM objects
pLayout->Release();
pVS->Release();
pPS->Release();
pVBuffer->Release();
swapchain->Release();
backbuffer->Release();
dev->Release();
devcon->Release();
}
void InitTextures()
{
D3DX11CreateShaderResourceViewFromFile(dev, L"texture.png", NULL, NULL, &pTexture, NULL);
D3D11_SAMPLER_DESC sampDesc;
ZeroMemory(&sampDesc, sizeof(D3D11_SAMPLER_DESC));
sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
sampDesc.MinLOD = 0;
sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
dev->CreateSamplerState(&sampDesc, &pSamplerState);
}
// this is the function that creates the shape to render
void InitGraphics()
{
// create a triangle using the VERTEX struct
VERTEX OurVertices[] =
{ // CUBE
{-0.5f, 0.5f, 0.5f, 0.0f, 0.0f}, // Front
{0.5f, 0.5f, 0.5f, 1.0f, 0.0f},
{0.5f, -0.5f, 0.5f, 1.0f, 1.0f},
{-0.5f, -0.5f, 0.5f, 0.0f, 1.0f},
{-0.5f, 0.5f, -0.5f, 1.0f, 0.0f}, // Back
{0.5f, 0.5f, -0.5f, 0.0f, 0.0f},
{0.5f, -0.5f, -0.5f, 0.0f, 1.0f},
{-0.5f, -0.5f, -0.5f, 1.0f, 1.0f},
};
// create the vertex buffer
D3D11_BUFFER_DESC bd;
ZeroMemory(&bd, sizeof(bd));
bd.Usage = D3D11_USAGE_DYNAMIC; // write access access by CPU and GPU
bd.ByteWidth = sizeof(OurVertices); // size is the VERTEX struct * 3
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; // use as a vertex buffer
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // allow CPU to write in buffer
dev->CreateBuffer(&bd, NULL, &pVBuffer); // create the buffer
// copy the vertices into the buffer
D3D11_MAPPED_SUBRESOURCE ms;
devcon->Map(pVBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms); // map the buffer
memcpy(ms.pData, OurVertices, sizeof(OurVertices)); // copy the data
devcon->Unmap(pVBuffer, NULL); // unmap the buffer
unsigned int indices[] =
{
0, 1, 2, // front
0, 2, 3,
4, 0, 3, // left
4, 3, 7,
//4, 5, 6, // back
//4, 6, 7,
6, 5, 1, // right
6, 1, 2,
};
// indices
D3D11_BUFFER_DESC bdIndices;
bdIndices.Usage = D3D11_USAGE_DEFAULT;
bdIndices.ByteWidth = sizeof(indices);
bdIndices.BindFlags = D3D11_BIND_INDEX_BUFFER;
bdIndices.CPUAccessFlags = 0;
bdIndices.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA InitData;
InitData.pSysMem = indices;
InitData.SysMemPitch = 0;
InitData.SysMemSlicePitch = 0;
dev->CreateBuffer(&bdIndices, &InitData, &pIBuffer);
D3D11_BUFFER_DESC bdWVP;
ZeroMemory(&bdWVP, sizeof(D3D11_BUFFER_DESC));
bdWVP.Usage = D3D11_USAGE_DEFAULT;
bdWVP.ByteWidth = sizeof(ConstantBuffer);
bdWVP.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bdWVP.CPUAccessFlags = 0;
dev->CreateBuffer(&bdWVP, NULL, &wvpConstBuffer);
g_World = XMMatrixIdentity();
XMVECTOR Eye = XMVectorSet(0.0f, 1.0f, -3.0f, 0.0f);
XMVECTOR At = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
XMVECTOR Up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
g_View = XMMatrixLookAtLH(Eye, At, Up);
g_Projection = XMMatrixPerspectiveFovLH(XM_PIDIV2, SCREEN_WIDTH / (FLOAT)SCREEN_HEIGHT, 0.01f, 100.0f);
}
void InitRasterizer()
{
D3D11_RASTERIZER_DESC raster_desc;
raster_desc.FillMode = D3D11_FILL_SOLID;
raster_desc.CullMode = D3D11_CULL_NONE;
raster_desc.FrontCounterClockwise = false;
raster_desc.DepthBias = 0;
raster_desc.DepthBiasClamp = 0.0f;
raster_desc.SlopeScaledDepthBias = 0.0f;
raster_desc.DepthClipEnable = true;
raster_desc.ScissorEnable = false;
raster_desc.MultisampleEnable = false;
raster_desc.AntialiasedLineEnable = false;
dev->CreateRasterizerState(&raster_desc, &pRasterState);
}
// this function loads and prepares the shaders
void InitPipeline()
{
InitRasterizer();
InitTextures();
// load and compile the two shaders
ID3D10Blob* VS, * PS;
D3DX11CompileFromFile(L"shaders.shader", 0, 0, "VShader", "vs_4_0", 0, 0, 0, &VS, 0, 0);
D3DX11CompileFromFile(L"shaders.shader", 0, 0, "PShader", "ps_4_0", 0, 0, 0, &PS, 0, 0);
// encapsulate both shaders into shader objects
dev->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &pVS);
dev->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &pPS);
// set the shader objects
devcon->VSSetShader(pVS, 0, 0);
devcon->PSSetShader(pPS, 0, 0);
// set the texture
devcon->PSSetShaderResources(0, 1, &pTexture);
devcon->PSSetSamplers(0, 1, &pSamplerState);
// off cull mode
devcon->RSSetState(pRasterState);
// create the input layout object
D3D11_INPUT_ELEMENT_DESC ied[] =
{
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0},
};
dev->CreateInputLayout(ied, 2, VS->GetBufferPointer(), VS->GetBufferSize(), &pLayout);
devcon->IASetInputLayout(pLayout);
}
shaders.shader
cbuffer ConstantBuffer : register(b0)
{
matrix World;
matrix View;
matrix Projection;
}
Texture2D ObjTexture;
SamplerState ObjSamplerState;
struct VS_OUTPUT
{
float4 Pos : SV_POSITION;
float2 TexCoord : TEXCOORD;
};
VS_OUTPUT VShader(float4 Pos : POSITION, float4 inTexCoord : TEXCOORD)
{
VS_OUTPUT output = (VS_OUTPUT)0;
output.Pos = mul(Pos, World);
output.Pos = mul(output.Pos, View);
output.Pos = mul(output.Pos, Projection);
output.TexCoord = inTexCoord;
return output;
}
float4 PShader(VS_OUTPUT input) : SV_Target
{
return ObjTexture.Sample(ObjSamplerState, input.TexCoord);
}
the "cube"
I've looked all over but couldn't solve the problem.
With a fresh eye today i've noticed that besides things i've mentioned earlier render target view and depth stencil view are using different multisampling settings: render target use 4 samples while depth stencil only 1. In order for them to work together their dimensions and multisampling settings must be exactly the same.
I'm displaying the fps of my application. When I change the size or position of the text, it sometimes isn't rendered properly and the layout rect is big enough.
Anyone know how to fix this?
Example code, only snippets:
Variables:
IDWriteTextFormat* textFormat;
WCHAR* text = L"Example0101";
int textSize = (int)wcslen(text);
D2D1_RECT_F rect = {};
ID2D1SolidColorBrush* brush;
Constructor:
Game::Game(ID2D1HwndRenderTarget* D2DRenderTarget) {
this->D2DRenderTarget = D2DRenderTarget;
CoInitialize(NULL);
CoCreateInstance(
CLSID_WICImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
IID_IWICImagingFactory,
(LPVOID*)&WICImagingFactory);
DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), (IUnknown**)&writeFactory);
writeFactory->CreateTextFormat(
L"Arial",
NULL,
DWRITE_FONT_WEIGHT_REGULAR,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
16.0f,
L"en-us",
&textFormat
);
rect.left = 480.0f;
rect.top = 275.0f;
rect.right = 1000.0f;
rect.bottom = 1000.0f;
D2DRenderTarget->CreateSolidColorBrush(D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f), &brush);
}
Drawing:
void Game::draw() {
D2DRenderTarget->Clear(D2D1::ColorF(0.5f, 0.5f, 0.9f, 1.0f));
D2DRenderTarget->DrawTextW(text, textSize, textFormat, rect, brush, D2D1_DRAW_TEXT_OPTIONS_NO_SNAP, DWRITE_MEASURING_MODE_GDI_CLASSIC);
}
RenderTarget:
D2DFactory->CreateHwndRenderTarget(
D2D1::RenderTargetProperties(),
D2D1::HwndRenderTargetProperties(
window,
D2D1::SizeU(960, 540),
D2D1_PRESENT_OPTIONS_IMMEDIATELY),
&D2DRenderTarget
);
Everything is very normal. I guess this is solved with some kind of smoothing or maybe I just forgot something.
I'm using the SpriteFont/SpriteBatch classes to render text onto my game because quite frankly, i am tired of using Direct2D and DirectWrite... But everytime I draw text using SpriteFont, I get the text written on the screen, but it is written on a black background... The black background blocks the entire scene of my game.. is there any way to remove the black background and only keep the text?
Down below is my implementation of SpriteFont..
void RenderText(int FPS)
{
std::unique_ptr<DirectX::SpriteFont> Sprite_Font(new DirectX::SpriteFont(device, L"myfile.spritefont"));
std::unique_ptr<DirectX::SpriteBatch> Sprite_Batch(new DirectX::SpriteBatch(DevContext));
Sprite_Batch->Begin();
Sprite_Font->DrawString(Sprite_Batch.get(), L"FPS: ", DirectX::XMFLOAT2(200,200));
Sprite_Batch->End();
}
It seems to me that the black background is drawn because of the values that I specified in the function ClearRenderTargetView().
float BackgroundColor[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
DevContext->ClearRenderTargetView(RenderTarget, BackgroundColor); //This is where the black background gets drawn over my entire scene
Everytime i change BackgroundColor[4] to different values, the background color changes as well, respectably. How can I remove the black background from my game and only include the text?
Here is my entire code.
#include <Windows.h>
#include <SpriteFont.h>
#include <SpriteBatch.h>
#include <d3dcompiler.h>
#include <SimpleMath.h>
#pragma comment (lib, "dinput8.lib")
#pragma comment (lib, "D3D11.lib")
#pragma comment (lib, "d3dcompiler.lib")
LRESULT CALLBACK WindowProcedure(HWND, unsigned int, WPARAM, LPARAM);
void Create_Window(HINSTANCE&);
void Initialize_Direct3D11(HINSTANCE);
void Initialize_Rendering_Pipeline();
void Initialize_Sprites();
void Render_Frame();
void Render_Text();
void Create_Vertex_Buffer_for_triangle();
HWND MainWindow;
IDXGISwapChain * SwapChain;
ID3D11Device * device;
ID3D11DeviceContext * DevContext;
ID3D11RenderTargetView * RenderTarget;
ID3D11Buffer * VertexBuffer;
ID3D10Blob * VertexShader;
ID3D10Blob * PixelShader;
ID3D11VertexShader * VS;
ID3D11PixelShader * PS;
ID3D11InputLayout * inputLayout;
std::unique_ptr<DirectX::SpriteFont> Sprite_Font;
std::unique_ptr<DirectX::SpriteBatch> Sprite_Batch;
DirectX::SimpleMath::Vector2 m_fontPos;
const wchar_t* output = L"Hello World";
struct Vertex_Buffer
{
float Positions[3];
Vertex_Buffer(float x, float y, float z)
{
Positions[0] = x;
Positions[1] = y;
Positions[2] = z;
};
};
int WINAPI WinMain(HINSTANCE CurrentInstance, HINSTANCE PrevInstance, LPSTR ignore, int WindowShow)
{
MSG message;
HRESULT status;
Create_Window(CurrentInstance);
Initialize_Direct3D11(CurrentInstance);
Initialize_Sprites();
Initialize_Rendering_Pipeline();
Create_Vertex_Buffer_for_triangle();
while (true)
{
if (PeekMessage(&message, MainWindow, 0, 0, PM_REMOVE))
{
TranslateMessage(&message);
DispatchMessage(&message);
}
else
{
Render_Frame();
Render_Text();
SwapChain->Present(0, 0);
}
}
}
void Initialize_Sprites()
{
Sprite_Font.reset(new DirectX::SpriteFont(device, L"myfile.spritefont"));
Sprite_Batch.reset(new DirectX::SpriteBatch(DevContext));
m_fontPos.x = 200;
m_fontPos.y = 200;
}
void Create_Window(HINSTANCE &CurrentInstance)
{
WNDCLASSEX windowclass;
ZeroMemory(&windowclass, sizeof(WNDCLASSEX));
windowclass.cbSize = sizeof(WNDCLASSEX);
windowclass.lpszClassName = L"Window Class";
windowclass.hInstance = CurrentInstance;
windowclass.lpfnWndProc = WindowProcedure;
windowclass.hIcon = LoadIcon(NULL, IDI_WINLOGO);
windowclass.hCursor = LoadCursor(NULL, IDC_ARROW);
RegisterClassEx(&windowclass);
MainWindow = CreateWindowEx(
0,
L"Window Class",
L"The Empire of Anatoria",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
800,
600,
NULL,
NULL,
CurrentInstance,
NULL
);
ShowWindow(MainWindow, SW_SHOW);
}
void Render_Text()
{
DirectX::SimpleMath::Vector2 origin = Sprite_Font->MeasureString(output);
Sprite_Batch->Begin();
Sprite_Font->DrawString(Sprite_Batch.get(), output,
m_fontPos, DirectX::Colors::White, 0.f, origin);
Sprite_Batch->End();
}
void Initialize_Direct3D11(HINSTANCE instance)
{
DXGI_MODE_DESC BackBufferDesc;
DXGI_SWAP_CHAIN_DESC SwapChainDesc;
ZeroMemory(&BackBufferDesc, sizeof(DXGI_MODE_DESC));
BackBufferDesc.Width = 400;
BackBufferDesc.Height = 400;
BackBufferDesc.RefreshRate.Numerator = 60;
BackBufferDesc.RefreshRate.Denominator = 1;
BackBufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
ZeroMemory(&SwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
SwapChainDesc.BufferDesc = BackBufferDesc;
SwapChainDesc.BufferCount = 1;
SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
SwapChainDesc.SampleDesc.Count = 1;
SwapChainDesc.SampleDesc.Quality = 0;
SwapChainDesc.OutputWindow = MainWindow;
SwapChainDesc.Windowed = TRUE;
SwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
D3D11CreateDeviceAndSwapChain(NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
NULL,
NULL,
NULL,
D3D11_SDK_VERSION,
&SwapChainDesc,
&SwapChain,
&device,
NULL,
&DevContext
);
ID3D11Texture2D * BackBuffer;
SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&BackBuffer);
device->CreateRenderTargetView(BackBuffer, NULL, &RenderTarget);
DevContext->OMSetRenderTargets(
1,
&RenderTarget,
NULL
);
BackBuffer->Release();
DevContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}
void Initialize_Rendering_Pipeline()
{
D3DCompileFromFile(L"VertexShader.hlsl", 0, 0, "main", "vs_5_0", 0, 0, &VertexShader, 0);
D3DCompileFromFile(L"VertexShader.hlsl", 0, 0, "Pixel_Shader", "ps_5_0", 0, 0, &PixelShader, 0);
device->CreateVertexShader(VertexShader->GetBufferPointer(), VertexShader->GetBufferSize(), NULL, &VS);
device->CreatePixelShader(PixelShader->GetBufferPointer(), PixelShader->GetBufferSize(), NULL, &PS);
DevContext->VSSetShader(VS, 0, 0);
DevContext->PSSetShader(PS, 0, 0);
D3D11_VIEWPORT Raster;
ZeroMemory(&Raster, sizeof(D3D11_VIEWPORT));
Raster.MinDepth = 0.0f;
Raster.MaxDepth = 1.0f;
Raster.Width = 400;
Raster.Height = 400;
DevContext->RSSetViewports(1, &Raster);
D3D11_INPUT_ELEMENT_DESC InputLayout[1];
ZeroMemory(&InputLayout[0], sizeof(D3D11_INPUT_ELEMENT_DESC));
InputLayout[0].SemanticName = "POSITION";
InputLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
InputLayout[0].InputSlot = 0;
InputLayout[0].AlignedByteOffset = 0;
InputLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
device->CreateInputLayout(
InputLayout,
1,
VertexShader->GetBufferPointer(),
VertexShader->GetBufferSize(),
&inputLayout
);
DevContext->IASetInputLayout(inputLayout);
}
void Render_Frame()
{
float BackgroundColor[4] = {0.0f, 0.0f, 0.0f, 1.0f};
DevContext->ClearRenderTargetView(RenderTarget, BackgroundColor);
DevContext->Draw(3, 0);
}
void Create_Vertex_Buffer_for_triangle()
{
D3D11_BUFFER_DESC VertexBufferDesc;
D3D11_SUBRESOURCE_DATA VertexData;
UINT stride = sizeof(Vertex_Buffer);
UINT offset = 0;
ZeroMemory(&VertexBufferDesc, sizeof(D3D11_BUFFER_DESC));
VertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
VertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
VertexBufferDesc.CPUAccessFlags = 0;
VertexBufferDesc.ByteWidth = sizeof(Vertex_Buffer) * 3;
Vertex_Buffer VerticesData[] =
{
Vertex_Buffer(0.0f, 0.5f, 0.5f),
Vertex_Buffer(0.5f, -0.5f, 0.5f),
Vertex_Buffer(-0.5f, -0.5f, 0.5f)
};
ZeroMemory(&VertexData, sizeof(D3D11_SUBRESOURCE_DATA));
VertexData.pSysMem = VerticesData;
device->CreateBuffer(
&VertexBufferDesc,
&VertexData,
&VertexBuffer);
DevContext->IASetVertexBuffers(
0,
1,
&VertexBuffer,
&stride,
&offset
);
}
LRESULT CALLBACK WindowProcedure(HWND handle, unsigned int message, WPARAM ignore1, LPARAM ignore2)
{
switch (message)
{
case WM_CREATE:
return 0;
case WM_CLOSE:
DestroyWindow(handle);
return 0;
default:
return DefWindowProc(handle, message, ignore1, ignore2);
}
}
Here is the VertexShader.hlsl file
float4 main( float4 pos : POSITION ) : SV_POSITION
{
return pos;
}
float4 Pixel_Shader() : SV_TARGET
{
return float4(1.0f, 0.0f, 0.0f, 1.0f);
}
First, if your code snippet is accurate, you should not be creating the SpriteFont and SpriteBatch instance every frame. You only have to create them when the device changes.
By default, SpriteFont is drawing using pre-multiplied alpha blending modes, so if you are getting a fully "background color" image then something else is amiss in your pipeline state. It is likely that you are leaving some state in effect in the rendering between the clear and RenderText that is affecting the SpriteBatch renderer that you should reset.
It might also be the color you are using for the background clear which has the alpha set to 0 rather than 1. Try using:
float BackgroundColor[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
Try working through a few of the DirectX Tool Kit tutorials to make sure things are working in isolation and so you understand how the classes work, specifically Drawing text.
You and me have the same problem with SpriteFont. We forgot to reset the VertexBuffers and all other rendering states after the call to SpriteFont. See my post and the solution from Chuck Walbourn: DirectX::SpriteFont/SpriteBatch prevents 3D scene from drawing.
To quote Chuck:
You set the render state up for your scene in InitScene, but drawing anything else changes the state which is exactly what SpriteBatch does. I document which render states each object in DirectX Toolkit manipulates on the wiki. You need to set all the state your Draw requires each frame, not assume it is set forever, if you do more than a single draw.
See my question for additional links providing more information.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Looking for the right general approach for making a UI really snappy.
I'm thinking of developing a UI tool that might go beyond just some "in house" tool. It would involve elaborate and custom 2d elements and would need to support fast scrolling of a big virtual surface, which would likely entail redrawing tons of custom things really quickly.
I've done some GDI programming back when XP was new, and I ran into some perf issues with lots of full screen blitting (it was a slow computer anyway). I understand GDI has some degree of acceleration, but I have difficulty ascertaining what exactly I can expect to be accelerated here.
I've only used Direct3D in games. Is it reasonable to make D3D to power a windowed GUI application? Also, if I use D3D, do I have to do everything from scratch, or can I make some kind of GDI/D3D hybrid, for example, using Direct3D calls inside WM_PAINT or something, in order to leverage some Win32 stuff like menu bars or listboxes side-by-side with a panel full of D3D rendered stuff? Does anyone have an example of mixing D3D with Win32 gui junk? Or is this not really the right approach?
What do programs like AutoCad or 3ds Max or Photoshop, or other major Win32 applications with similarly elaborate UI's do?
If your GUI involves 3D manipulation of 3D scenes, Direct3D or OpenGL would probably be a win. If you are just trying to give your GUI a "non-boring" look where the controls are stylized and drawn with alpha blended bitmaps and so-on, then you're best sticking to the traditional windowing system (i.e. GDI) as the bottom-most rendering layer. However, the easiest way to achieve such a "look and feel" is to use a higher-level toolkit like wxWidgets or Qt in order to achieve the theming and customization that will make your GUI look "modern" and not like a boring corporate application.
Another option is to use XAML/WPF from a native application and use the tools that are available for creating XAML-based GUIs like Microsoft's Expression. I haven't explored that myself, but it should be feasible using the technique from this article in the March, 2013 issue of MSDN Magazine.
Simple C style D3D9 app code (display mesh).
////////////////////////////////////////////////////////////////
// Defines main Direct3D rendering funcions
#include <windows.h>
#include <mmsystem.h>
#include <d3d9.h>
#include "d3dx9.h"
#include "cube_prim.h"
#ifndef __D3D_RENDERER_H__
#define __D3D_RENDERER_H__
#pragma comment(lib,"d3d9.lib")
#pragma comment(lib,"d3dx9.lib")
#pragma comment(lib,"winmm.lib")
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1)
LPDIRECT3D9 pDirect3D = NULL;
LPDIRECT3DDEVICE9 pDirect3DDevice = NULL;
LPDIRECT3DVERTEXBUFFER9 pDirect3DVertexBuffer = NULL;
LPDIRECT3DINDEXBUFFER9 pDirect3DIndexBuffer = NULL;
LPDIRECT3DTEXTURE9 pDirect3DTexture01 = NULL;
LPDIRECT3DTEXTURE9 pDirect3DTexture02 = NULL;
LPD3DXMESH pD3DXMesh = NULL;
D3DMATERIAL9* pDirect3DMaterial = NULL;
LPDIRECT3DTEXTURE9* pDirect3DTexture = NULL;
DWORD Subsets = 0;
FLOAT XRot = 0.0f;
FLOAT YRot = 0.0f;
HRESULT InitializeD3D(HWND hWnd)
{
D3DDISPLAYMODE dispMode;
D3DPRESENT_PARAMETERS parameters;
pDirect3D = Direct3DCreate9(D3D_SDK_VERSION);
if (pDirect3D == NULL)
return E_FAIL;
if (FAILED(pDirect3D->GetAdapterDisplayMode(
D3DADAPTER_DEFAULT,&dispMode)))
return E_FAIL;
ZeroMemory(¶meters,sizeof(D3DPRESENT_PARAMETERS));
parameters.Windowed = FALSE;
parameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
parameters.BackBufferFormat = dispMode.Format;
parameters.BackBufferWidth = dispMode.Width;
parameters.BackBufferHeight = dispMode.Height;
parameters.BackBufferCount = 2;
parameters.EnableAutoDepthStencil = TRUE;
parameters.AutoDepthStencilFormat = D3DFMT_D24S8;
if (FAILED(pDirect3D->CreateDevice(D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,hWnd,D3DCREATE_HARDWARE_VERTEXPROCESSING,
¶meters,&pDirect3DDevice)))
return E_FAIL;
pDirect3DDevice->SetRenderState(D3DRS_LIGHTING,TRUE);
pDirect3DDevice->SetRenderState(D3DRS_AMBIENT,RGB(180,180,180));
pDirect3DDevice->SetRenderState(D3DRS_CULLMODE,D3DCULL_CCW);
pDirect3DDevice->SetRenderState(D3DRS_ZENABLE,TRUE);
//pDirect3DDevice->SetRenderState(D3DRS_AMBIENTMATERIALSOURCE,D3DMCS_COLOR2);
//pDirect3DDevice->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE,D3DMCS_COLOR2);
pDirect3DDevice->SetRenderState(D3DRS_SPECULARENABLE,TRUE);
return S_OK;
}
HRESULT InitializeD3DBufferObject(void)
{
VOID* pVertices = NULL;
VOID* pIndicies = NULL;
if (pDirect3DDevice != NULL)
{
if (FAILED(pDirect3DDevice->CreateVertexBuffer(
sizeof(vertices),0,D3DFVF_CUSTOMVERTEX,
D3DPOOL_DEFAULT,&pDirect3DVertexBuffer,NULL)))
return E_FAIL;
if (FAILED(pDirect3DVertexBuffer->Lock(0,
sizeof(vertices),(void**)&pVertices,NULL)))
return E_FAIL;
memcpy(pVertices,vertices,sizeof(vertices));
pDirect3DVertexBuffer->Unlock();
if (FAILED(pDirect3DDevice->CreateIndexBuffer(
sizeof(indices),0,D3DFMT_INDEX32,D3DPOOL_DEFAULT,
&pDirect3DIndexBuffer,NULL)))
return E_FAIL;
if (FAILED(pDirect3DIndexBuffer->Lock(0,
sizeof(indices),(void**)&pIndicies,NULL)))
return E_FAIL;
memcpy(pIndicies,indices,sizeof(indices));
pDirect3DIndexBuffer->Unlock();
if (FAILED(D3DXCreateTextureFromFile(pDirect3DDevice,
_T("wood.tga"),&pDirect3DTexture01)))
return E_FAIL;
if (FAILED(D3DXCreateTextureFromFile(pDirect3DDevice,
_T("stripes.tga"),&pDirect3DTexture02)))
return E_FAIL;
return S_OK;
}
else
return E_FAIL;
}
HRESULT InitialMesh(void)
{
LPD3DXBUFFER pMeshObj = NULL;
LPD3DXMATERIAL pMaterial = NULL;
char buffer[255];
if (pDirect3DDevice != NULL)
{
if (FAILED(D3DXLoadMeshFromX(_T("Dwarf\\Dwarf.x"),
D3DXMESH_SYSTEMMEM,
pDirect3DDevice,
NULL,
&pMeshObj,
NULL,
&Subsets,
&pD3DXMesh)))
return E_FAIL;
pMaterial = (D3DXMATERIAL*)pMeshObj->GetBufferPointer();
pDirect3DMaterial = new D3DMATERIAL9[Subsets];
pDirect3DTexture = new LPDIRECT3DTEXTURE9[Subsets];
for (INT i = 0; i < Subsets; i++)
{
pDirect3DMaterial[i] = pMaterial[i].MatD3D;
sprintf(buffer,"Dwarf\\");
strcat(buffer,pMaterial[i].pTextureFilename);
if (FAILED(D3DXCreateTextureFromFileA(
pDirect3DDevice,buffer,&pDirect3DTexture[i])))
return E_FAIL;
}
pMeshObj->Release();
return S_OK;
}
else
return E_FAIL;
}
VOID ChangeSize(INT cx,INT cy)
{
D3DXMATRIX projMatrix;
if (pDirect3DDevice != NULL)
{
if (cy == 0)
cy = 1;
FLOAT aspectRatio = static_cast<FLOAT>(cx) /
static_cast<FLOAT>(cy);
D3DXMatrixPerspectiveFovLH(&projMatrix,45.0f,
aspectRatio,1.0f,150.0f);
pDirect3DDevice->SetTransform(D3DTS_PROJECTION,&projMatrix);
}
}
VOID RotateScene(void)
{
if (GetAsyncKeyState(VK_ESCAPE))
exit(0);
if (GetAsyncKeyState(VK_UP))
XRot -= 0.1f;
if (GetAsyncKeyState(VK_DOWN))
XRot += 0.1f;
if (GetAsyncKeyState(VK_LEFT))
YRot -= 0.1f;
if (GetAsyncKeyState(VK_RIGHT))
YRot += 0.1f;
}
VOID RenderScene(void)
{
D3DXMATRIX worldMatrix;
D3DMATERIAL9 material;
D3DLIGHT9 light;
D3DCAPS9 caps;
D3DCOLORVALUE ambientLight = { 0.0f, 0.0f, 0.0f, 1.0f };
D3DCOLORVALUE diffuseLight = { 0.7f, 0.7f, 0.7f, 1.0f };
D3DCOLORVALUE specularLight = { 1.0f, 1.0f, 1.0f, 1.0f };
D3DCOLORVALUE materialColor = { 1.0f, 1.0f, 1.0f, 1.0f };
ZeroMemory(&material,sizeof(D3DMATERIAL9));
material.Ambient = materialColor;
material.Diffuse = materialColor;
material.Specular = specularLight;
material.Power = 20.0f;
ZeroMemory(&light,sizeof(D3DLIGHT9));
light.Ambient = ambientLight;
light.Diffuse = diffuseLight;
light.Specular = specularLight;
light.Range = 300.0f;
light.Position = D3DXVECTOR3(-30,150,-10);
light.Type = D3DLIGHT_POINT;
light.Attenuation0 = 1.0f;
if (pDirect3DDevice != NULL)
{
D3DXMatrixIdentity(&worldMatrix);
pDirect3DDevice->SetTransform(D3DTS_WORLD,&worldMatrix);
D3DXMatrixTranslation(&worldMatrix,0.0f,0.0f,4.0f);
pDirect3DDevice->MultiplyTransform(D3DTS_WORLD,&worldMatrix);
D3DXMatrixRotationX(&worldMatrix,XRot);
pDirect3DDevice->MultiplyTransform(D3DTS_WORLD,&worldMatrix);
D3DXMatrixRotationY(&worldMatrix,YRot);
pDirect3DDevice->MultiplyTransform(D3DTS_WORLD,&worldMatrix);
pDirect3DDevice->Clear(0,0,D3DCLEAR_TARGET |
D3DCLEAR_ZBUFFER,D3DCOLOR_ARGB(255,0,0,0),1.0f,0);
pDirect3DDevice->SetMaterial(&material);
pDirect3DDevice->SetLight(0,&light);
pDirect3DDevice->LightEnable(0,TRUE);
pDirect3DDevice->SetTexture(0,pDirect3DTexture01);
//pDirect3DDevice->SetTexture(1,pDirect3DTexture02);
pDirect3DDevice->SetTextureStageState(0,
D3DTSS_COLORARG1,D3DTA_TEXTURE);
pDirect3DDevice->SetTextureStageState(0,
D3DTSS_COLORARG2,D3DTA_DIFFUSE);
pDirect3DDevice->SetTextureStageState(0,
D3DTSS_COLOROP,D3DTOP_MODULATE);
pDirect3DDevice->SetTextureStageState(1,
D3DTSS_TEXCOORDINDEX,0);
pDirect3DDevice->SetTextureStageState(1,
D3DTSS_COLORARG1,D3DTA_TEXTURE);
pDirect3DDevice->SetTextureStageState(1,
D3DTSS_COLORARG1,D3DTA_TEXTURE);
pDirect3DDevice->SetTextureStageState(1,
D3DTSS_COLOROP,D3DTOP_MODULATE);
pDirect3DDevice->GetDeviceCaps(&caps);
pDirect3DDevice->SetSamplerState(0,D3DSAMP_MAXANISOTROPY,caps.MaxAnisotropy);
pDirect3DDevice->SetSamplerState(0,D3DSAMP_MINFILTER,D3DTEXF_ANISOTROPIC);
pDirect3DDevice->SetSamplerState(0,D3DSAMP_MAGFILTER,D3DTEXF_ANISOTROPIC);
pDirect3DDevice->SetSamplerState(0,D3DSAMP_MIPFILTER,D3DTEXF_ANISOTROPIC);
pDirect3DDevice->SetSamplerState(1,D3DSAMP_MAXANISOTROPY,caps.MaxAnisotropy);
pDirect3DDevice->SetSamplerState(1,D3DSAMP_MINFILTER,D3DTEXF_ANISOTROPIC);
pDirect3DDevice->SetSamplerState(1,D3DSAMP_MAGFILTER,D3DTEXF_ANISOTROPIC);
pDirect3DDevice->SetSamplerState(1,D3DSAMP_MIPFILTER,D3DTEXF_ANISOTROPIC);
pDirect3DDevice->BeginScene();
{
pDirect3DDevice->SetStreamSource(0,pDirect3DVertexBuffer,0,
sizeof(CUSTOMVERTEX));
pDirect3DDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
pDirect3DDevice->SetIndices(pDirect3DIndexBuffer);
/*pDirect3DDevice->DrawIndexedPrimitive(
D3DPT_TRIANGLELIST,0,0,36,0,12);*/
for (int i = 0; i < Subsets; i++)
{
pDirect3DDevice->SetMaterial(&pDirect3DMaterial[i]);
pDirect3DDevice->SetTexture(0,pDirect3DTexture[i]);
pD3DXMesh->DrawSubset(i);
}
}
pDirect3DDevice->EndScene();
pDirect3DDevice->Present(NULL,NULL,NULL,NULL);
}
}
VOID ReleaseD3D(void)
{
if (pDirect3DTexture)
{
for (int i = 0; i < 0; i++)
pDirect3DTexture[i]->Release();
}
if (pDirect3DMaterial)
{
delete [] pDirect3DMaterial;
}
if (pD3DXMesh)
pD3DXMesh->Release();
if (pDirect3DTexture02)
pDirect3DTexture02->Release();
if (pDirect3DTexture01)
pDirect3DTexture01->Release();
if (pDirect3DIndexBuffer)
pDirect3DIndexBuffer->Release();
if (pDirect3DVertexBuffer)
pDirect3DVertexBuffer->Release();
if (pDirect3DDevice)
pDirect3DDevice->Release();
if (pDirect3D)
pDirect3D->Release();
}
#endif
App use simple Win32 framework with WinMain etc...
Sample code in MFC classes
#include "MainWnd.h"
#include "d3d_renderer.h"
CMainWnd::CMainWnd(void)
{
}
CMainWnd::~CMainWnd(void)
{
}
BEGIN_MESSAGE_MAP(CMainWnd, CWnd)
ON_WM_CREATE()
ON_WM_DESTROY()
ON_WM_SIZE()
ON_WM_TIMER()
ON_WM_PAINT()
END_MESSAGE_MAP()
// WM_CREATE
int CMainWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (FAILED(InitializeD3D(m_hWnd)))
exit(0);
if (FAILED(InitializeD3DBufferObject()))
exit(0);
if (FAILED(InitialMesh()))
exit(0);
SetTimer(33,1,NULL);
return 0;
}
// WM_DESTROY
void CMainWnd::OnDestroy()
{
CWnd::OnDestroy();
KillTimer(101);
ReleaseD3D();
}
// WM_SIZE
void CMainWnd::OnSize(UINT nType, int cx, int cy)
{
CWnd::OnSize(nType, cx, cy);
ChangeSize(cx,cy);
}
// WM_TIMER
void CMainWnd::OnTimer(UINT_PTR nIDEvent)
{
InvalidateRect(NULL,FALSE);
CWnd::OnTimer(nIDEvent);
}
// WM_PAINT
void CMainWnd::OnPaint()
{
RotateScene();
RenderScene();
ValidateRect(NULL);
}
so decide what you want to use (D3D is significaly faster than GDI)
you can also use OpenGL to draw accelerated graphics (little bit slower than D3D) with less code amount.
Displaying 3D text with OpenGL and pure Win32 UI
#include <windows.h>
#include <gl\gl.h>
#include <gl\glu.h>
// Palette Handle
HPALETTE hPalette = NULL;
static LPCTSTR lpszAppName = "Text3D";
GLint nFontList;
// Light values and coordinates
GLfloat whiteLight[] = { 0.4f, 0.4f, 0.4f, 1.0f };
GLfloat diffuseLight[] = { 0.8f, 0.8f, 0.8f, 1.0f };
GLfloat specular[] = { 0.9f, 0.9f, 0.9f, 1.0f};
GLfloat lightPos[] = { -100.0f, 200.0f, 50.0f, 1.0f };
// Declaration for Window procedure
LRESULT CALLBACK WndProc( HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam);
// Set Pixel Format function - forward declaration
void SetDCPixelFormat(HDC hDC);
void ChangeSize(GLsizei w, GLsizei h)
{
GLfloat nRange = 100.0f;
GLfloat fAspect;
// Prevent a divide by zero
if(h == 0)
h = 1;
fAspect = (GLfloat)w/(GLfloat)h;
// Set Viewport to window dimensions
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
// Reset coordinate system
glLoadIdentity();
// Setup perspective for viewing
gluPerspective(17.5f,fAspect,1,300);
// Viewing transformation
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(-1.8f, 0.0f, -15.0f);
glRotatef(-20.0f, 0.0f, 1.0f,0.0f);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
}
void RenderScene(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Blue 3D Text
glColor3ub(0, 0, 255);
glPushMatrix();
glListBase(nFontList);
glCallLists (6, GL_UNSIGNED_BYTE, "OpenGL");
glPopMatrix();
}
void SetupRC(HDC hDC)
{
// Setup the Font characteristics
HFONT hFont;
GLYPHMETRICSFLOAT agmf[128]; // Throw away
LOGFONT logfont;
logfont.lfHeight = -10;
logfont.lfWidth = 0;
logfont.lfEscapement = 0;
logfont.lfOrientation = 0;
logfont.lfWeight = FW_BOLD;
logfont.lfItalic = FALSE;
logfont.lfUnderline = FALSE;
logfont.lfStrikeOut = FALSE;
logfont.lfCharSet = ANSI_CHARSET;
logfont.lfOutPrecision = OUT_DEFAULT_PRECIS;
logfont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
logfont.lfQuality = DEFAULT_QUALITY;
logfont.lfPitchAndFamily = DEFAULT_PITCH;
strcpy(logfont.lfFaceName,"Arial");
// Create the font and display list
hFont = CreateFontIndirect(&logfont);
SelectObject (hDC, hFont);
//create display lists for glyphs 0 through 128 with 0.1 extrusion
// and default deviation.
nFontList = glGenLists(128);
wglUseFontOutlines(hDC, 0, 128, nFontList, 0.0f, 0.5f,
WGL_FONT_POLYGONS, agmf);
DeleteObject(hFont);
glEnable(GL_DEPTH_TEST); // Hidden surface removal
glEnable(GL_COLOR_MATERIAL);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0,GL_AMBIENT,whiteLight);
glLightfv(GL_LIGHT0,GL_DIFFUSE,diffuseLight);
glLightfv(GL_LIGHT0,GL_SPECULAR,specular);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glEnable(GL_LIGHT0);
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
glMaterialfv(GL_FRONT, GL_SPECULAR,specular);
glMateriali(GL_FRONT,GL_SHININESS,128);
}
// If necessary, creates a 3-3-2 palette for the device context listed.
HPALETTE GetOpenGLPalette(HDC hDC)
{
HPALETTE hRetPal = NULL; // Handle to palette to be created
PIXELFORMATDESCRIPTOR pfd; // Pixel Format Descriptor
LOGPALETTE *pPal; // Pointer to memory for logical palette
int nPixelFormat; // Pixel format index
int nColors; // Number of entries in palette
int i; // Counting variable
BYTE RedRange,GreenRange,BlueRange;
// Range for each color entry (7,7,and 3)
// Get the pixel format index and retrieve the pixel format description
nPixelFormat = GetPixelFormat(hDC);
DescribePixelFormat(hDC, nPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
// Does this pixel format require a palette? If not, do not create a
// palette and just return NULL
if(!(pfd.dwFlags & PFD_NEED_PALETTE))
return NULL;
// Number of entries in palette. 8 bits yeilds 256 entries
nColors = 1 << pfd.cColorBits;
// Allocate space for a logical palette structure plus all the palette entries
pPal = (LOGPALETTE*)malloc(sizeof(LOGPALETTE) +nColors*sizeof(PALETTEENTRY));
// Fill in palette header
pPal->palVersion = 0x300; // Windows 3.0
pPal->palNumEntries = nColors; // table size
// Build mask of all 1's. This creates a number represented by having
// the low order x bits set, where x = pfd.cRedBits, pfd.cGreenBits, and
// pfd.cBlueBits.
RedRange = (1 << pfd.cRedBits) -1;
GreenRange = (1 << pfd.cGreenBits) - 1;
BlueRange = (1 << pfd.cBlueBits) -1;
// Loop through all the palette entries
for(i = 0; i < nColors; i++)
{
// Fill in the 8-bit equivalents for each component
pPal->palPalEntry[i].peRed = (i >> pfd.cRedShift) & RedRange;
pPal->palPalEntry[i].peRed = (unsigned char)(
(double) pPal->palPalEntry[i].peRed * 255.0 / RedRange);
pPal->palPalEntry[i].peGreen = (i >> pfd.cGreenShift) & GreenRange;
pPal->palPalEntry[i].peGreen = (unsigned char)(
(double)pPal->palPalEntry[i].peGreen * 255.0 / GreenRange);
pPal->palPalEntry[i].peBlue = (i >> pfd.cBlueShift) & BlueRange;
pPal->palPalEntry[i].peBlue = (unsigned char)(
(double)pPal->palPalEntry[i].peBlue * 255.0 / BlueRange);
pPal->palPalEntry[i].peFlags = (unsigned char) NULL;
}
// Create the palette
hRetPal = CreatePalette(pPal);
// Go ahead and select and realize the palette for this device context
SelectPalette(hDC,hRetPal,FALSE);
RealizePalette(hDC);
// Free the memory used for the logical palette structure
free(pPal);
// Return the handle to the new palette
return hRetPal;
}
// Select the pixel format for a given device context
void SetDCPixelFormat(HDC hDC)
{
int nPixelFormat;
static PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR), // Size of this structure
1, // Version of this structure
PFD_DRAW_TO_WINDOW | // Draw to Window (not to bitmap)
PFD_SUPPORT_OPENGL | // Support OpenGL calls in window
PFD_DOUBLEBUFFER, // Double buffered mode
PFD_TYPE_RGBA, // RGBA Color mode
32, // Want 32 bit color
0,0,0,0,0,0, // Not used to select mode
0,0, // Not used to select mode
0,0,0,0,0, // Not used to select mode
16, // Size of depth buffer
0, // Not used to select mode
0, // Not used to select mode
0, // Draw in main plane
0, // Not used to select mode
0,0,0 }; // Not used to select mode
// Choose a pixel format that best matches that described in pfd
nPixelFormat = ChoosePixelFormat(hDC, &pfd);
// Set the pixel format for the device context
SetPixelFormat(hDC, nPixelFormat, &pfd);
}
// Entry point of all Windows programs
int APIENTRY WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
MSG msg; // Windows message structure
WNDCLASS wc; // Windows class structure
HWND hWnd; // Storeage for window handle
// Register Window style
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = (WNDPROC) WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
// No need for background brush for OpenGL window
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = lpszAppName;
// Register the window class
if(RegisterClass(&wc) == 0)
return FALSE;
// Create the main application window
hWnd = CreateWindow(
lpszAppName,
lpszAppName,
// OpenGL requires WS_CLIPCHILDREN and WS_CLIPSIBLINGS
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
// Window position and size
100, 100,
250, 250,
NULL,
NULL,
hInstance,
NULL);
// If window was not created, quit
if(hWnd == NULL)
return FALSE;
// Display the window
ShowWindow(hWnd,SW_SHOW);
UpdateWindow(hWnd);
// Process application messages until the application closes
while( GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
// Window procedure, handles all messages for this program
LRESULT CALLBACK WndProc( HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam)
{
static HGLRC hRC; // Permenant Rendering context
static HDC hDC; // Private GDI Device context
switch (message)
{
// Window creation, setup for OpenGL
case WM_CREATE:
// Store the device context
hDC = GetDC(hWnd);
// Select the pixel format
SetDCPixelFormat(hDC);
// Create the rendering context and make it current
hRC = wglCreateContext(hDC);
wglMakeCurrent(hDC, hRC);
// Create the palette
hPalette = GetOpenGLPalette(hDC);
SetupRC(hDC);
break;
// Window is being destroyed, cleanup
case WM_DESTROY:
// Kill the timer that we created
KillTimer(hWnd,101);
glDeleteLists(nFontList, 128);
// Deselect the current rendering context and delete it
wglMakeCurrent(hDC,NULL);
wglDeleteContext(hRC);
// Delete the palette
if(hPalette != NULL)
DeleteObject(hPalette);
// Tell the application to terminate after the window
// is gone.
PostQuitMessage(0);
break;
// Window is resized.
case WM_SIZE:
// Call our function which modifies the clipping
// volume and viewport
ChangeSize(LOWORD(lParam), HIWORD(lParam));
break;
// The painting function. This message sent by Windows
// whenever the screen needs updating.
case WM_PAINT:
{
// Call OpenGL drawing code
RenderScene();
// Call function to swap the buffers
SwapBuffers(hDC);
ValidateRect(hWnd,NULL);
}
break;
// Windows is telling the application that it may modify
// the system palette. This message in essance asks the
// application for a new palette.
case WM_QUERYNEWPALETTE:
// If the palette was created.
if(hPalette)
{
int nRet;
// Selects the palette into the current device context
SelectPalette(hDC, hPalette, FALSE);
// Map entries from the currently selected palette to
// the system palette. The return value is the number
// of palette entries modified.
nRet = RealizePalette(hDC);
// Repaint, forces remap of palette in current window
InvalidateRect(hWnd,NULL,FALSE);
return nRet;
}
break;
// This window may set the palette, even though it is not the
// currently active window.
case WM_PALETTECHANGED:
// Don't do anything if the palette does not exist, or if
// this is the window that changed the palette.
if((hPalette != NULL) && ((HWND)wParam != hWnd))
{
// Select the palette into the device context
SelectPalette(hDC,hPalette,FALSE);
// Map entries to system palette
RealizePalette(hDC);
// Remap the current colors to the newly realized palette
UpdateColors(hDC);
return 0;
}
break;
default: // Passes it on if unproccessed
return (DefWindowProc(hWnd, message, wParam, lParam));
}
return (0L);
}
can work without reseting palette
AS window handle you may use every legal window handles (panel, listbox, buttons etc...) so you can display 3d content almost everywhere
Photoshop use OpenGL, 3DS Max optional (OpenGL, Direct3D), AutoCad it is hard to say: GDI older versions, newest using .NET too.
Im trying to create a popup window with half transparency that renders stuff on itself with DirectX.
The problem is that background does not redraw itself only if rendering is enabled. Redraw happens only when updating (ie when I select a line in a text editor behind my popup window).
Magic begins when my window gets moved to the secondary monitor. Its all ok there. Transparency works perfectly, background redraws constantly. Also if popup steps out of display borders transparency begins to work. (Screenshots below.)
The OS is windows xp SP3 with DirectX 9.0c and NVIDIA graphics card with lastest drivers.
I also tested the program on Win Vista and Win 7 with several different videocards. Works perfectly.
Creating window
m_popup = new popup(__("pew!"), wxPoint(600, 330), wxSize(250, 250));
m_popup->Show(true);
m_popup->SetWindowStyle(wxSTAY_ON_TOP);
m_popup->SetTransparent(150);
SetTopWindow(m_popup);
Transparency code from wxWidgets (2.8.12)
bool wxTopLevelWindowMSW::SetTransparent(wxByte alpha)
{
typedef DWORD (WINAPI *PSETLAYEREDWINDOWATTR)(HWND, DWORD, BYTE, DWORD);
static PSETLAYEREDWINDOWATTR pSetLayeredWindowAttributes = NULL;
if ( pSetLayeredWindowAttributes == NULL )
{
wxDynamicLibrary dllUser32(_T("user32.dll"));
pSetLayeredWindowAttributes = (PSETLAYEREDWINDOWATTR)
dllUser32.GetSymbol(wxT("SetLayeredWindowAttributes"));
}
if ( pSetLayeredWindowAttributes == NULL )
return false;
LONG exstyle = GetWindowLong(GetHwnd(), GWL_EXSTYLE);
// if setting alpha to fully opaque then turn off the layered style
if (alpha == 255)
{
SetWindowLong(GetHwnd(), GWL_EXSTYLE, exstyle & ~WS_EX_LAYERED);
Refresh();
return true;
}
// Otherwise, set the layered style if needed and set the alpha value
if ((exstyle & WS_EX_LAYERED) == 0 )
SetWindowLong(GetHwnd(), GWL_EXSTYLE, exstyle | WS_EX_LAYERED);
// ^ this line seems to cause the problem
// (tried to make the window transparent manually without wxWidgets' help)
return pSetLayeredWindowAttributes(GetHwnd(), 0, (BYTE)alpha, LWA_ALPHA) != 0;
}
DirectX Init
m_d3d = Direct3DCreate9(D3D_SDK_VERSION);
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.hDeviceWindow = hWnd;
d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
d3dpp.BackBufferWidth = g_size;
d3dpp.BackBufferHeight = g_size;
m_d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &m_d3ddev);
CUSTOMVERTEX vertices[] =
{
{ 320.0f, 50.0f, 0.5f, 1.0f, D3DCOLOR_ARGB(150, 255, 150, 150), },
{ 520.0f, 400.0f, 0.5f, 1.0f, D3DCOLOR_ARGB(150, 150, 255, 150), },
{ 120.0f, 400.0f, 0.5f, 1.0f, D3DCOLOR_ARGB(150, 150, 150, 255), },
};
m_d3ddev->CreateVertexBuffer(3*sizeof(CUSTOMVERTEX),
0,
CUSTOMFVF,
D3DPOOL_MANAGED,
&v_buffer,
NULL);
VOID* pVoid;
v_buffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, vertices, sizeof(vertices));
v_buffer->Unlock();
Rendering
if (m_render)
{
m_d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_ARGB(150, 150, 150, 200), 1.0f, 0);
m_d3ddev->BeginScene();
m_d3ddev->SetFVF(CUSTOMFVF);
m_d3ddev->SetStreamSource(0, v_buffer, 0, sizeof(CUSTOMVERTEX));
m_d3ddev->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);
m_d3ddev->EndScene();
m_d3ddev->Present(NULL, NULL, NULL, NULL);
}
Screenshots
Transparency fail: http://clip2net.com/s/5IHAyQ
Transparency is ok when popup is out of display borders: http://clip2net.com/s/5IHCI3
I also wanted to post a screenshot of how it works on the secondary monitor but I cant neither I can post images directly to SO because of rep. Just imagine that its just ok on it like it is on the secondary screenshot.
Thank you.
PARTIALLY SOLVED, see comments.