从字符串创建 DX11 着色器
Creating DX11 shaders from string
我还没有找到任何关于这个的东西,我不确定它是否真的可行,但是这里是:
我希望能够为我的 DX11 游戏提供一个着色器,该着色器不是从文件加载的(从那时起,每个使用我的框架的项目都必须包含该文件)。我想直接使用HLSL文件的内容。我确实试过了,但它给了我 E_INVALIDARG 回报。
代码如下:
auto pixelShaderByteCode = std::string("struct PixelShaderInput" \
"{" \
"float4 pos : SV_POSITION;" \
"float3 color : COLOR0;" \
"};" \
"float4 main(PixelShaderInput input) : SV_TARGET" \
"{" \
"return float4(input.color, 1.0f);" \
"}");
Microsoft::WRL::ComPtr<ID3D11PixelShader> ps;
auto hr = m_deviceResources->GetD3DDevice()->CreatePixelShader(
pixelShaderByteCode.c_str(),
pixelShaderByteCode.length(),
nullptr,
&ps);
if (FAILED(hr))
{
// that did not work... hr = E_INVALIDARG
}
是不是我需要一个已编译的着色器才能工作?如果是这样,将 "baking" 着色器引入引擎的最佳实践是什么?
您不能使用 HLSL 源调用 CreatePixelShader
方法。您必须先将其编译为二进制着色器 blob .
Microsoft::WRL::ComPtr<ID3DBlob> blob;
HRESULT hr = D3DCompile(
pixelShaderByteCode.c_str(),
pixelShaderByteCode.length(),
nullptr,
nullptr,
nullptr,
"main", "ps_4_0",
D3DCOMPILE_ENABLE_STRICTNESS, 0,
&blob;
nullptr);
if (FAILED(hr))
...
Microsoft::WRL::ComPtr<ID3D11PixelShader> ps;
hr = m_deviceResources->GetD3DDevice()->CreatePixelShader(
blob.GetBufferPointer(),
blob.GetBufferSize(),
nullptr,
&ps);
if (FAILED(hr))
...
Note a better answer is compile your shaders offline and have the binary blob generated as a C array in a C source header file using fxc and the /Fh
parameter. You then include that header which puts the shader data into your program directly. See DirectX Tool Kit which uses this approach.
我还没有找到任何关于这个的东西,我不确定它是否真的可行,但是这里是:
我希望能够为我的 DX11 游戏提供一个着色器,该着色器不是从文件加载的(从那时起,每个使用我的框架的项目都必须包含该文件)。我想直接使用HLSL文件的内容。我确实试过了,但它给了我 E_INVALIDARG 回报。
代码如下:
auto pixelShaderByteCode = std::string("struct PixelShaderInput" \
"{" \
"float4 pos : SV_POSITION;" \
"float3 color : COLOR0;" \
"};" \
"float4 main(PixelShaderInput input) : SV_TARGET" \
"{" \
"return float4(input.color, 1.0f);" \
"}");
Microsoft::WRL::ComPtr<ID3D11PixelShader> ps;
auto hr = m_deviceResources->GetD3DDevice()->CreatePixelShader(
pixelShaderByteCode.c_str(),
pixelShaderByteCode.length(),
nullptr,
&ps);
if (FAILED(hr))
{
// that did not work... hr = E_INVALIDARG
}
是不是我需要一个已编译的着色器才能工作?如果是这样,将 "baking" 着色器引入引擎的最佳实践是什么?
您不能使用 HLSL 源调用 CreatePixelShader
方法。您必须先将其编译为二进制着色器 blob .
Microsoft::WRL::ComPtr<ID3DBlob> blob;
HRESULT hr = D3DCompile(
pixelShaderByteCode.c_str(),
pixelShaderByteCode.length(),
nullptr,
nullptr,
nullptr,
"main", "ps_4_0",
D3DCOMPILE_ENABLE_STRICTNESS, 0,
&blob;
nullptr);
if (FAILED(hr))
...
Microsoft::WRL::ComPtr<ID3D11PixelShader> ps;
hr = m_deviceResources->GetD3DDevice()->CreatePixelShader(
blob.GetBufferPointer(),
blob.GetBufferSize(),
nullptr,
&ps);
if (FAILED(hr))
...
Note a better answer is compile your shaders offline and have the binary blob generated as a C array in a C source header file using fxc and the
/Fh
parameter. You then include that header which puts the shader data into your program directly. See DirectX Tool Kit which uses this approach.