Debian Codegraph @

Sources/nCine/Graphics/RHI/D3D11/D3D11ShaderProgram.cpp

raw
1 #include "D3D11ShaderProgram.h"
2 #include "D3D11Device.h"
3 #include "D3D11BufferObject.h"
4 #include "../../RenderResources.h"
5 #include "../../../Application.h"
6 #include "../../../Base/HashFunctions.h"
7
8 #include "../../../../Shaders/Generated/ShaderCompilerTypes.h"
9
10 #include <cstring>
11 #include <memory>
12
13 #include <d3d11.h>
14 #include <d3d11shader.h>
15 #include <d3dcompiler.h>
16
17 #include <Asserts.h>
18 #include <IO/FileSystem.h>
19 #include <IO/Stream.h>
20
21 using namespace Death::Containers::Literals;
22 using namespace Death::IO;
23
24 namespace nCine::RHI::D3D11
25 {
26 namespace
27 {
28 template<class T>
29 void SafeRelease(T*& p)
30 {
31 if (p != nullptr) {
32 p->Release();
33 p = nullptr;
34 }
35 }
36
37 // On-disk DXBC blob cache for the runtime-compile FALLBACK path (headers generated without embedded
38 // DXBC). Compiling ~120 HLSL stages with D3DCompile at startup takes many seconds; caching the compiled
39 // bytecode keyed by a hash of the HLSL source means a warm run only recompiles shaders whose source
40 // actually changed. Format: magic, version, VS size, PS size, then the two raw DXBC blobs. Stored under
41 // <shaderCachePath>/D3D11. Shaders with offline-precompiled DXBC embedded in the generated headers (the
42 // normal case) never touch this cache.
43 constexpr std::uint32_t kBlobCacheMagic = 0x31314458u; // 'XD11'
44 constexpr std::uint32_t kBlobCacheVersion = 1u;
45
46 String BlobCachePath(const char* vsSource, const char* fsSource)
47 {
48 const String& base = theApplication().GetAppConfiguration().shaderCachePath;
49 if (base.empty()) {
50 return {};
51 }
52 const std::uint64_t h = xxHash3(fsSource, std::strlen(fsSource), xxHash3(vsSource, std::strlen(vsSource)));
53 char name[24];
54 for (std::int32_t i = 0; i < 16; i++) {
55 name[i] = "0123456789abcdef"[(h >> ((15 - i) * 4)) & 0xFu];
56 }
57 name[16] = '.'; name[17] = 'd'; name[18] = 'x'; name[19] = 'b'; name[20] = 'c';
58 return fs::CombinePath(fs::CombinePath(base, "D3D11"_s), StringView(name, 21));
59 }
60
61 bool LoadBlobCache(const String& path, ShaderByteCode& vs, ShaderByteCode& ps)
62 {
63 std::unique_ptr<Stream> s = fs::Open(path, FileAccess::Read);
64 if (s == nullptr || !s->IsValid() || s->GetSize() < 16) {
65 return false;
66 }
67 if (s->ReadValueAsLE<std::uint32_t>() != kBlobCacheMagic || s->ReadValueAsLE<std::uint32_t>() != kBlobCacheVersion) {
68 return false;
69 }
70 const std::uint32_t vsSize = s->ReadValueAsLE<std::uint32_t>();
71 const std::uint32_t psSize = s->ReadValueAsLE<std::uint32_t>();
72 if (vsSize == 0 || psSize == 0 || vsSize > 8u * 1024 * 1024 || psSize > 8u * 1024 * 1024) {
73 return false;
74 }
75 vs.resize(vsSize);
76 ps.resize(psSize);
77 return (s->Read(vs.data(), std::int64_t(vsSize)) == std::int64_t(vsSize) &&
78 s->Read(ps.data(), std::int64_t(psSize)) == std::int64_t(psSize));
79 }
80
81 void SaveBlobCache(const String& path, const ShaderByteCode& vs, const ShaderByteCode& ps)
82 {
83 fs::CreateDirectories(fs::GetDirectoryName(path));
84 std::unique_ptr<Stream> s = fs::Open(path, FileAccess::Write);
85 if (s == nullptr || !s->IsValid()) {
86 return;
87 }
88 s->WriteValueAsLE<std::uint32_t>(kBlobCacheMagic);
89 s->WriteValueAsLE<std::uint32_t>(kBlobCacheVersion);
90 s->WriteValueAsLE<std::uint32_t>(std::uint32_t(vs.size()));
91 s->WriteValueAsLE<std::uint32_t>(std::uint32_t(ps.size()));
92 s->Write(vs.data(), std::int64_t(vs.size()));
93 s->Write(ps.data(), std::int64_t(ps.size()));
94 }
95
96 // DXGI format + byte size for a reflected vertex attribute type (used by the input layout builder)
97 DXGI_FORMAT AttributeFormat(ShaderCompiler::UniformType type)
98 {
99 switch (type) {
100 case ShaderCompiler::UniformType::Float: return DXGI_FORMAT_R32_FLOAT;
101 case ShaderCompiler::UniformType::Vec2: return DXGI_FORMAT_R32G32_FLOAT;
102 case ShaderCompiler::UniformType::Vec3: return DXGI_FORMAT_R32G32B32_FLOAT;
103 case ShaderCompiler::UniformType::Vec4: return DXGI_FORMAT_R32G32B32A32_FLOAT;
104 case ShaderCompiler::UniformType::Int: return DXGI_FORMAT_R32_SINT;
105 case ShaderCompiler::UniformType::IVec2: return DXGI_FORMAT_R32G32_SINT;
106 case ShaderCompiler::UniformType::IVec4: return DXGI_FORMAT_R32G32B32A32_SINT;
107 case ShaderCompiler::UniformType::UInt: return DXGI_FORMAT_R32_UINT;
108 case ShaderCompiler::UniformType::UVec2: return DXGI_FORMAT_R32G32_UINT;
109 default: return DXGI_FORMAT_R32G32B32A32_FLOAT;
110 }
111 }
112 }
113
114 std::uint32_t D3D11ShaderProgram::_nextHandle = 1;
115
116 D3D11ShaderProgram::D3D11ShaderProgram()
117 : D3D11ShaderProgram(QueryPhase::Immediate)
118 {
119 }
120
121 D3D11ShaderProgram::D3D11ShaderProgram(QueryPhase queryPhase)
122 : _handle(_nextHandle++), _status(Status::NotLinked), _introspection(Introspection::Disabled), _queryPhase(queryPhase),
123 _batchSize(DefaultBatchSize), _shouldLogOnErrors(true), _uniformsSize(0), _uniformBlocksSize(0),
124 _reflection(nullptr), _boundVbo(nullptr), _boundIbo(nullptr),
125 _vertexShader(nullptr), _pixelShader(nullptr), _inputLayout(nullptr), _inputLayoutFingerprint(~std::uint64_t(0))
126 {
127 }
128
129 D3D11ShaderProgram::D3D11ShaderProgram(StringView vertexFile, StringView fragmentFile, Introspection introspection, QueryPhase queryPhase)
130 : D3D11ShaderProgram(queryPhase)
131 {
132 static_cast<void>(vertexFile);
133 static_cast<void>(fragmentFile);
134 static_cast<void>(introspection);
135 }
136
137 D3D11ShaderProgram::D3D11ShaderProgram(StringView vertexFile, StringView fragmentFile, Introspection introspection)
138 : D3D11ShaderProgram(vertexFile, fragmentFile, introspection, QueryPhase::Immediate)
139 {
140 }
141
142 D3D11ShaderProgram::D3D11ShaderProgram(StringView vertexFile, StringView fragmentFile)
143 : D3D11ShaderProgram(vertexFile, fragmentFile, Introspection::Enabled, QueryPhase::Immediate)
144 {
145 }
146
147 D3D11ShaderProgram::~D3D11ShaderProgram()
148 {
149 // Clear this program from the device's current-program and last-bound-shader tracking before the
150 // shader objects are released, so a recycled pointer can't be mistaken for a still-bound shader
151 D3D11Device::OnProgramDestroyed(this);
152 SafeRelease(_inputLayout);
153 SafeRelease(_pixelShader);
154 SafeRelease(_vertexShader);
155 // The pipeline keys per-shader camera uniform data on the program pointer; drop this program's
156 // entry so RenderResources::Dispose() finds the map empty (mirrors GLShaderProgram's destructor)
157 RenderResources::RemoveCameraUniformData(this);
158 }
159
160 bool D3D11ShaderProgram::IsLinked() const
161 {
162 return (_status == Status::Linked || _status == Status::LinkedWithDeferredQueries || _status == Status::LinkedWithIntrospection);
163 }
164
165 bool D3D11ShaderProgram::AttachShaderFromFile(ShaderStage stage, StringView filename)
166 {
167 static_cast<void>(stage);
168 static_cast<void>(filename);
169 return true;
170 }
171
172 bool D3D11ShaderProgram::AttachShaderFromString(ShaderStage stage, StringView string)
173 {
174 static_cast<void>(stage);
175 static_cast<void>(string);
176 return true;
177 }
178
179 bool D3D11ShaderProgram::AttachShaderFromStrings(ShaderStage stage, ArrayView<const StringView> strings)
180 {
181 static_cast<void>(stage);
182 static_cast<void>(strings);
183 return true;
184 }
185
186 bool D3D11ShaderProgram::AttachShaderFromStringsAndFile(ShaderStage stage, ArrayView<const StringView> strings, StringView filename)
187 {
188 static_cast<void>(stage);
189 static_cast<void>(strings);
190 static_cast<void>(filename);
191 return true;
192 }
193
194 bool D3D11ShaderProgram::Link(Introspection introspection)
195 {
196 return FinalizeAfterLinking(introspection);
197 }
198
199 bool D3D11ShaderProgram::FinalizeAfterLinking(Introspection introspection)
200 {
201 _introspection = introspection;
202 PerformIntrospection();
203 return true;
204 }
205
206 void D3D11ShaderProgram::Use()
207 {
208 D3D11Device::BindProgram(this);
209 }
210
211 void D3D11ShaderProgram::PerformIntrospection()
212 {
213 if (_introspection != Introspection::Disabled && _status != Status::LinkedWithIntrospection) {
214 _uniformsSize = 0;
215 _uniformBlocksSize = 0;
216
217 if (_reflection != nullptr) {
218 ImportReflection();
219 // Compile the HLSL stage sources while the reflection is still available. Attribute/block
220 // imports above populate the data the cbuffer reflection maps block cbuffers against.
221 CompileHlsl();
222 }
223 _status = Status::LinkedWithIntrospection;
224 }
225 // The reflection is consumed by introspection (its layout is imported into the members above)
226 _reflection = nullptr;
227 }
228
229 void D3D11ShaderProgram::ImportReflection()
230 {
231 const ShaderCompiler::ProgramVariant& reflection = *_reflection;
232 std::int32_t nextLocation = 0;
233
234 // Loose uniforms - samplers are kept in a separate reflection list but treated as loose uniforms here
235 for (std::size_t i = 0; i < reflection.UniformCount; i++) {
236 const ShaderCompiler::Uniform& u = reflection.Uniforms[i];
237 _uniforms.emplace_back(this, u.Name, u.Type, std::int32_t(u.ArraySize), nextLocation++);
238 _uniformsSize += _uniforms.back().GetMemorySize();
239 }
240 for (std::size_t i = 0; i < reflection.TextureCount; i++) {
241 const ShaderCompiler::TextureBinding& t = reflection.Textures[i];
242 _uniforms.emplace_back(this, t.Name, ShaderCompiler::UniformType::Sampler2D, 1, nextLocation++);
243 _uniformsSize += _uniforms.back().GetMemorySize();
244 }
245
246 _uniformBlocks.reserve(reflection.BlockCount);
247 for (std::size_t i = 0; i < reflection.BlockCount; i++) {
248 const ShaderCompiler::UniformBlock& b = reflection.Blocks[i];
249
250 // A BATCH_SIZE-sized instance array uses the explicitly set batch size, or the same 64 KB-based
251 // fallback the in-shader "#ifndef BATCH_SIZE" defaults assume when no size is injected
252 std::uint32_t effectiveBatchSize = 0;
253 std::uint32_t dataSize = b.BaseSize;
254 if (b.InstanceStride > 0) {
255 effectiveBatchSize = (_batchSize != std::uint32_t(DefaultBatchSize) && _batchSize > 0)
256 ? _batchSize : (64u * 1024u) / b.InstanceStride;
257 dataSize += b.InstanceStride * effectiveBatchSize;
258 }
259
260 const std::uint32_t blockIndex = std::uint32_t(_uniformBlocks.size());
261 _uniformBlocks.emplace_back(blockIndex, b.Name, std::int32_t(dataSize));
262 D3D11UniformBlock& block = _uniformBlocks.back();
263 _uniformBlocksSize += block.GetSize();
264
265 if (_introspection != Introspection::NoUniformsInBlocks) {
266 block._members.reserve(b.MemberCount);
267 for (std::size_t j = 0; j < b.MemberCount; j++) {
268 const ShaderCompiler::BlockMember& m = b.Members[j];
269 if (m.Type == ShaderCompiler::UniformType::Struct) {
270 // Struct aggregates are never read by name; only flat leaf members matter
271 continue;
272 }
273 D3D11Uniform member;
274 member.SetName(m.Name);
275 member._type = m.Type;
276 member._size = (m.ArraySize == ShaderCompiler::SymbolicArraySize)
277 ? std::int32_t(effectiveBatchSize)
278 : (m.ArraySize > 0 ? std::int32_t(m.ArraySize) : 1);
279 member._blockIndex = std::int32_t(blockIndex);
280 member._offset = std::int32_t(m.Offset);
281 member._owner = this;
282 block._members.push_back(member);
283 }
284 }
285 }
286
287 for (std::size_t i = 0; i < reflection.AttributeCount; i++) {
288 const ShaderCompiler::Attribute& a = reflection.Attributes[i];
289 const std::int32_t location = (a.Location >= 0 ? a.Location : std::int32_t(i));
290 _attributes.emplace_back(a.Name, a.Type, location);
291 _vertexFormat[std::uint32_t(location)].Init(std::uint32_t(location), std::int32_t(UniformTypeInfo::ComponentCount(a.Type)), 0);
292 }
293 }
294
295 void D3D11ShaderProgram::CompileHlsl()
296 {
297 ID3D11Device* device = D3D11Device::GetD3DDevice();
298 if (device == nullptr) {
299 LOGE("Cannot create shaders: Direct3D 11 device is not created yet");
300 return;
301 }
302
303 ShaderByteCode vsBytes;
304 ShaderByteCode psBytes;
305
306 const char* vsSource = _reflection->HlslVsSource;
307 const char* fsSource = _reflection->HlslFsSource;
308 if (_reflection->HlslVsDxbc != nullptr && _reflection->HlslFsDxbc != nullptr &&
309 _reflection->HlslVsDxbcSize > 0 && _reflection->HlslFsDxbcSize > 0) {
310 // Precompiled path: ShaderCompiler embedded offline-compiled DXBC (same entry points/targets and
311 // column-major packing as the runtime compile below, but fully optimized) - no D3DCompile at
312 // startup and no on-disk cache needed. This is also what UWP/Xbox builds run.
313 vsBytes.assign(_reflection->HlslVsDxbc, _reflection->HlslVsDxbc + _reflection->HlslVsDxbcSize);
314 psBytes.assign(_reflection->HlslFsDxbc, _reflection->HlslFsDxbc + _reflection->HlslFsDxbcSize);
315 } else if (vsSource != nullptr && fsSource != nullptr) {
316 // Runtime-compile fallback for variants that carry only HLSL text (headers generated without
317 // d3dcompiler_47 or with --no-dxbc)
318
319 // Warm path: load the precompiled DXBC from the on-disk cache (keyed by the HLSL source hash)
320 const String cachePath = BlobCachePath(vsSource, fsSource);
321 bool loaded = (!cachePath.empty() && LoadBlobCache(cachePath, vsBytes, psBytes));
322
323 if (!loaded) {
324 // Force column-major cbuffer matrix packing so the emitter's mul(M, v) column-vector algebra reads
325 // the engine's column-major (OpenGL-convention) uniform data verbatim - no per-matrix transpose
326 // needed. Skip optimization to keep the cold-start compile fast (this is a fallback path).
327 const UINT compileFlags = D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_SKIP_OPTIMIZATION;
328
329 auto compileStage = [&](const char* source, const char* entry, const char* target, ShaderByteCode& out) -> bool {
330 ID3DBlob* blob = nullptr;
331 ID3DBlob* errorBlob = nullptr;
332 const HRESULT hr = D3DCompile(source, std::strlen(source), nullptr, nullptr, nullptr,
333 entry, target, compileFlags, 0, &blob, &errorBlob);
334 if (FAILED(hr)) {
335 if (errorBlob != nullptr) {
336 LOGE("HLSL {} compile failed: {}", entry, reinterpret_cast<const char*>(errorBlob->GetBufferPointer()));
337 errorBlob->Release();
338 } else {
339 LOGE("HLSL {} compile failed: 0x{:.8x}", entry, static_cast<std::uint32_t>(hr));
340 }
341 if (blob != nullptr) {
342 blob->Release();
343 }
344 return false;
345 }
346 if (errorBlob != nullptr) {
347 errorBlob->Release();
348 }
349 out.assign(reinterpret_cast<const std::uint8_t*>(blob->GetBufferPointer()),
350 reinterpret_cast<const std::uint8_t*>(blob->GetBufferPointer()) + blob->GetBufferSize());
351 blob->Release();
352 return true;
353 };
354
355 if (!compileStage(vsSource, "VSMain", "vs_4_0", vsBytes) || !compileStage(fsSource, "PSMain", "ps_4_0", psBytes)) {
356 _status = Status::CompilationFailed;
357 return;
358 }
359 if (!cachePath.empty()) {
360 SaveBlobCache(cachePath, vsBytes, psBytes);
361 }
362 }
363 } else {
364 // No HLSL lowering available (e.g. a runtime-compiled shader outside the emitter's subset)
365 if (_shouldLogOnErrors) {
366 LOGW("Program {} has no HLSL bytecode or sources; draws with it are skipped", _handle);
367 }
368 return;
369 }
370
371 HRESULT hr = device->CreateVertexShader(vsBytes.data(), vsBytes.size(), nullptr, &_vertexShader);
372 if (SUCCEEDED(hr)) {
373 hr = device->CreatePixelShader(psBytes.data(), psBytes.size(), nullptr, &_pixelShader);
374 }
375 if (FAILED(hr)) {
376 LOGE("Failed to create Direct3D 11 shader objects: 0x{:.8x}", static_cast<std::uint32_t>(hr));
377 SafeRelease(_vertexShader);
378 SafeRelease(_pixelShader);
379 _status = Status::CompilationFailed;
380 return;
381 }
382
383 // Keep the VS bytecode so input layouts can be validated/created against it later
384 _vsByteCode = vsBytes;
385
386 ReflectStageCBuffers(vsBytes.data(), vsBytes.size(), _vsCBuffers, _vsTextureMask);
387 ReflectStageCBuffers(psBytes.data(), psBytes.size(), _psCBuffers, _psTextureMask);
388 }
389
390 void D3D11ShaderProgram::ReflectStageCBuffers(const void* byteCode, std::size_t byteCodeSize, CBufferSlotList& slots, std::uint32_t& textureMask)
391 {
392 ID3D11ShaderReflection* refl = nullptr;
393 if (FAILED(D3DReflect(byteCode, byteCodeSize, __uuidof(ID3D11ShaderReflection), reinterpret_cast<void**>(&refl))) || refl == nullptr) {
394 return;
395 }
396
397 D3D11_SHADER_DESC shaderDesc;
398 refl->GetDesc(&shaderDesc);
399
400 // Record which texture/sampler registers the stage actually binds, so the device only touches those
401 // slots at draw time instead of re-binding all units to both stages every draw
402 textureMask = 0;
403 for (UINT r = 0; r < shaderDesc.BoundResources; r++) {
404 D3D11_SHADER_INPUT_BIND_DESC bindDesc;
405 if (SUCCEEDED(refl->GetResourceBindingDesc(r, &bindDesc)) &&
406 (bindDesc.Type == D3D_SIT_TEXTURE || bindDesc.Type == D3D_SIT_SAMPLER) && bindDesc.BindPoint < 32) {
407 textureMask |= (1u << bindDesc.BindPoint);
408 }
409 }
410
411 for (UINT i = 0; i < shaderDesc.ConstantBuffers; i++) {
412 ID3D11ShaderReflectionConstantBuffer* cb = refl->GetConstantBufferByIndex(i);
413 D3D11_SHADER_BUFFER_DESC cbDesc;
414 if (FAILED(cb->GetDesc(&cbDesc))) {
415 continue;
416 }
417
418 // Resolve the cbuffer's register (bN) from the resource bindings
419 std::uint32_t reg = 0;
420 for (UINT r = 0; r < shaderDesc.BoundResources; r++) {
421 D3D11_SHADER_INPUT_BIND_DESC bindDesc;
422 if (SUCCEEDED(refl->GetResourceBindingDesc(r, &bindDesc)) &&
423 bindDesc.Type == D3D_SIT_CBUFFER && std::strcmp(bindDesc.Name, cbDesc.Name) == 0) {
424 reg = bindDesc.BindPoint;
425 break;
426 }
427 }
428
429 D3D11CBufferSlot slot;
430 slot.Register = reg;
431 slot.ByteSize = (cbDesc.Size + 15u) & ~15u;
432
433 if (std::strcmp(cbDesc.Name, "_Globals") == 0) {
434 slot.IsGlobals = true;
435 for (UINT v = 0; v < cbDesc.Variables; v++) {
436 ID3D11ShaderReflectionVariable* var = cb->GetVariableByIndex(v);
437 D3D11_SHADER_VARIABLE_DESC varDesc;
438 if (SUCCEEDED(var->GetDesc(&varDesc))) {
439 slot.Globals.push_back({ std::string(varDesc.Name), varDesc.StartOffset, varDesc.Size });
440 }
441 }
442 } else {
443 slot.IsGlobals = false;
444 slot.BlockIndex = -1;
445 for (std::size_t b = 0; b < _uniformBlocks.size(); b++) {
446 if (std::strcmp(_uniformBlocks[b].GetName(), cbDesc.Name) == 0) {
447 slot.BlockIndex = std::int32_t(b);
448 break;
449 }
450 }
451 }
452
453 slots.push_back(std::move(slot));
454 }
455
456 refl->Release();
457 }
458
459 ID3D11InputLayout* D3D11ShaderProgram::GetInputLayout()
460 {
461 if (_attributes.empty() || _vsByteCode.empty()) {
462 return nullptr;
463 }
464 // The attribute set is fixed per program, so the layout is built once and cached (the per-vertex byte
465 // offsets/stride the pipeline set on the vertex format are stable for this program's geometry).
466 if (_inputLayout != nullptr) {
467 return _inputLayout;
468 }
469
470 ID3D11Device* device = D3D11Device::GetD3DDevice();
471 if (device == nullptr) {
472 return nullptr;
473 }
474
475 // One input element per reflected attribute. The HLSL emitter assigns each attribute the semantic
476 // TEXCOORD<location>, so the semantic index is the attribute location; the within-vertex byte offset
477 // comes from the vertex format the pipeline defined (its `_pointer`), matching the GL backend which
478 // feeds that same value to glVertexAttribPointer.
479 // One element per attribute; the shipped attribute-based shaders stay well inside the inline capacity
480 SmallVector<D3D11_INPUT_ELEMENT_DESC, D3D11VertexFormat::MaxAttributes> elements;
481 elements.reserve(_attributes.size());
482 for (const D3D11Attribute& a : _attributes) {
483 const std::int32_t loc = a.GetLocation();
484 if (loc < 0) {
485 continue;
486 }
487 const D3D11VertexFormat::Attribute& fa = _vertexFormat[std::uint32_t(loc)];
488 D3D11_INPUT_ELEMENT_DESC desc = {};
489 desc.SemanticName = "TEXCOORD";
490 desc.SemanticIndex = static_cast<UINT>(loc);
491 desc.Format = AttributeFormat(a.GetType());
492 // A vertex format may override the component type to unsigned byte (SetType/SetNormalized - e.g.
493 // the ImGui vertex color, 4 x u8 normalized read as float4); honor it like glVertexAttribPointer does
494 if (fa.GetType() == std::uint32_t(VertexAttribType::UnsignedByte)) {
495 switch (fa.GetSize()) {
496 case 1: desc.Format = (fa.IsNormalized() ? DXGI_FORMAT_R8_UNORM : DXGI_FORMAT_R8_UINT); break;
497 case 2: desc.Format = (fa.IsNormalized() ? DXGI_FORMAT_R8G8_UNORM : DXGI_FORMAT_R8G8_UINT); break;
498 default: desc.Format = (fa.IsNormalized() ? DXGI_FORMAT_R8G8B8A8_UNORM : DXGI_FORMAT_R8G8B8A8_UINT); break;
499 }
500 }
501 desc.InputSlot = 0;
502 desc.AlignedByteOffset = static_cast<UINT>(reinterpret_cast<std::uintptr_t>(fa.GetPointer()));
503 desc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
504 desc.InstanceDataStepRate = 0;
505 elements.push_back(desc);
506 }
507
508 if (elements.empty()) {
509 return nullptr;
510 }
511
512 ID3D11InputLayout* layout = nullptr;
513 const HRESULT hr = device->CreateInputLayout(elements.data(), static_cast<UINT>(elements.size()),
514 _vsByteCode.data(), _vsByteCode.size(), &layout);
515 if (FAILED(hr)) {
516 LOGE("CreateInputLayout failed for program {}: 0x{:.8x}", _handle, static_cast<std::uint32_t>(hr));
517 return nullptr;
518 }
519
520 _inputLayout = layout;
521 return _inputLayout;
522 }
523
524 std::uint32_t D3D11ShaderProgram::GetVertexStride() const
525 {
526 for (const D3D11Attribute& a : _attributes) {
527 if (a.GetLocation() >= 0) {
528 const D3D11VertexFormat::Attribute& fa = _vertexFormat[std::uint32_t(a.GetLocation())];
529 if (fa.IsEnabled() && fa.GetStride() > 0) {
530 return static_cast<std::uint32_t>(fa.GetStride());
531 }
532 }
533 }
534 return 0;
535 }
536
537 bool D3D11ShaderProgram::HasAttribute(const char* name) const
538 {
539 for (const D3D11Attribute& a : _attributes) {
540 if (std::strcmp(a.GetName(), name) == 0) {
541 return true;
542 }
543 }
544 return false;
545 }
546
547 D3D11VertexFormat::Attribute* D3D11ShaderProgram::GetAttribute(const char* name)
548 {
549 for (const D3D11Attribute& a : _attributes) {
550 if (std::strcmp(a.GetName(), name) == 0 && a.GetLocation() >= 0) {
551 return &_vertexFormat[std::uint32_t(a.GetLocation())];
552 }
553 }
554 return nullptr;
555 }
556
557 void D3D11ShaderProgram::DefineVertexFormat(const D3D11BufferObject* vbo, const D3D11BufferObject* ibo, std::uint32_t vboOffset)
558 {
559 _boundVbo = vbo;
560 _boundIbo = ibo;
561 if (vbo != nullptr) {
562 for (const D3D11Attribute& a : _attributes) {
563 if (a.GetLocation() >= 0) {
564 D3D11VertexFormat::Attribute& attr = _vertexFormat[std::uint32_t(a.GetLocation())];
565 attr.setVbo(vbo);
566 attr.SetBaseOffset(vboOffset);
567 }
568 }
569 _vertexFormat.SetIbo(ibo);
570 }
571 }
572
573 void D3D11ShaderProgram::Reset()
574 {
575 D3D11Device::OnProgramDestroyed(this);
576 _uniforms.clear();
577 _uniformBlocks.clear();
578 _attributes.clear();
579 _resolvedUniforms.clear();
580 _vertexFormat.Reset();
581 _vsCBuffers.clear();
582 _psCBuffers.clear();
583 _vsByteCode.clear();
584 _vsTextureMask = 0;
585 _psTextureMask = 0;
586 SafeRelease(_inputLayout);
587 SafeRelease(_pixelShader);
588 SafeRelease(_vertexShader);
589 _inputLayoutFingerprint = ~std::uint64_t(0);
590 _status = Status::NotLinked;
591 _batchSize = DefaultBatchSize;
592 _reflection = nullptr;
593 }
594
595 void D3D11ShaderProgram::SetObjectLabel(StringView label)
596 {
597 // The backend selects the HLSL variant from the reflection, not the label, so this is informational only
598 static_cast<void>(label);
599 }
600
601 void D3D11ShaderProgram::SetResolvedUniform(const char* name, const std::uint8_t* data)
602 {
603 for (ResolvedUniform& r : _resolvedUniforms) {
604 if (r.Name == name) {
605 r.Data = data;
606 return;
607 }
608 }
609 _resolvedUniforms.push_back({name, data});
610 }
611
612 const std::uint8_t* D3D11ShaderProgram::ResolveUniform(const char* name) const
613 {
614 for (const ResolvedUniform& r : _resolvedUniforms) {
615 if (r.Name == name) {
616 return r.Data;
617 }
618 }
619 return nullptr;
620 }
621 }