第一节,hlsl的结构
一般情况下需要写的Shader分为VertexShader,PixelShader两种,可以单独写到不同的hlsl文件中,也可以写到一个fx文件里面
单独的hlsl文件
以hlsl为后缀,添加到VS工程后,默认就会进行编译,如果不想每次编译工程的时候都编译生成,可以右击属性配置,在常规中选择 从生成中排除
注意,选择对应的着色器类型和入口点名称,否则编译会报错
其次在输出文件一栏可以选择输出头文件,也就是编译后的二进制字节码,可以直接载入
一般选择设置成 $(IntDir)shaders%(Filename).h
fx 文件
另一种方法就是选择编写fx文件,可以把所有的着色器写入这一个文件里面
编译选项需要修改 在生成中排除 ,否则会报错
然后在hlsl文件中 直接
#include "Tutorial07.fx"
除了预编译,也可以在运行时进行加载编译
#include <d3d11_1.h>
#include <d3dcompiler.h>
static inline HRESULT CompileShaderFromFile(const WCHAR * szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob ** ppBlobOut)
{
HRESULT hr = S_OK;
DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#ifdef _DEBUG
// Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags |= D3DCOMPILE_DEBUG;
// Disable optimizations to further improve shader debugging
dwShaderFlags |= D3DCOMPILE_SKIP_OPTIMIZATION;
#endif
ID3DBlob* pErrorBlob = nullptr;
hr = D3DCompileFromFile(szFileName, nullptr, nullptr, szEntryPoint, szShaderModel,
dwShaderFlags, 0, ppBlobOut, &pErrorBlob);
if (FAILED(hr))
{
if (pErrorBlob)
{
OutputDebugStringA(reinterpret_cast<const char*>(pErrorBlob->GetBufferPointer()));
pErrorBlob->Release();
}
return hr;
}
if (pErrorBlob) pErrorBlob->Release();
return S_OK;
};
获取到的是二进制字节流 pPSBlob,输入入口和ShaderModel即可
#define SM_PS_5 "ps_5_0"
ID3DBlob* pPSBlob = nullptr;
hr = ShaderUtil::CompileShaderFromFile(L"Shader/Tutorial02.fx", "PS", SM_PS_5, &pPSBlob);
if (FAILED(hr))
{
MessageBox(nullptr,
L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
return hr;
}
// Create the pixel shader
hr = g_pd3dDevice->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), nullptr, &g_pPixelSolidShader);
pPSBlob->Release();
```