3Dの物体の前後関係を正しく表示するためには「深度ステンシル(デプスステンシル)」というものを使う。
これはCG検定に出てきた「Zバッファ」のこと。
(陰面消去の代表的な手法として「Zバッファ法」「レイトレーシング法」「スキャンライン法」を習ったはず)
描画した個所の深度情報を書き込むバッファ(テクスチャ)と、そのバッファにアクセスするための深度ステンシルビューを作成する。
namespace Direct3D
{
ID3D11Device* pDevice = nullptr; //デバイス
ID3D11DeviceContext* pContext = nullptr; //デバイスコンテキスト
IDXGISwapChain* pSwapChain = nullptr; //スワップチェイン
ID3D11RenderTargetView* pRenderTargetView = nullptr; //レンダーターゲットビュー
ID3D11Texture2D* pDepthStencil; //深度ステンシル
ID3D11DepthStencilView* pDepthStencilView; //深度ステンシルビュー
int scrWidth = 0;
int scrHeight = 0;
void Direct3D::Initialize(int winW, int winH, HWND hWnd)
{
:
:
:
//深度ステンシルビューの作成
D3D11_TEXTURE2D_DESC descDepth;
descDepth.Width = winW;
descDepth.Height = winH;
descDepth.MipLevels = 1;
descDepth.ArraySize = 1;
descDepth.Format = DXGI_FORMAT_D32_FLOAT;
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;
pDevice->CreateTexture2D(&descDepth, NULL, &pDepthStencil);
pDevice->CreateDepthStencilView(pDepthStencil, NULL, &pDepthStencilView);
//データを画面に描画するための一通りの設定(パイプライン)
pContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // データの入力種類を指定
pContext->OMSetRenderTargets(1, &pRenderTargetView, pDepthStencilView); // 描画先を設定
pContext->RSSetViewports(1, &vp);
//シェーダー準備
InitShader();
//カメラ準備
Camera::Initialize();
scrWidth = winW;
scrHeight = winH;
}
画面をクリアすると同時に深度バッファもクリアする。
void Direct3D::BeginDraw()
{
//背景の色
float clearColor[4] = { 0.0f, 0.5f, 0.5f, 1.0f };//R,G,B,A
//画面をクリア
pContext->ClearRenderTargetView(pRenderTargetView, clearColor);
Camera::Update();
//深度バッファクリア
pContext->ClearDepthStencilView(pDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
}