upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/descriptor_table.h252
-rw-r--r--runtime/src/root_signature.cpp456
-rw-r--r--runtime/src/root_signature.h150
3 files changed, 858 insertions, 0 deletions
diff --git a/runtime/src/descriptor_table.h b/runtime/src/descriptor_table.h
new file mode 100644
index 000000000..2fc9e99cb
--- /dev/null
+++ b/runtime/src/descriptor_table.h
@@ -0,0 +1,252 @@
1#pragma once
2
3// The descriptor hash table for set 0, binding 2 (docs/d3d12_vulkan.md section 5.1 and docs/design.md):
4// Shaders look up bindless resource/sampler indices by FNV-1a hashing the 8-dword descriptor key (T# or padded S#)
5// and probing up to 8 slots in this table. Miss or fallback yields index 0.
6
7#include <algorithm>
8#include <array>
9#include <cstdint>
10#include <cstring>
11#include <mutex>
12#include <span>
13#include <vector>
14
15namespace leonida {
16
17// FNV-1a constants for 32-bit dwords
18inline constexpr std::uint32_t kFnvOffsetBasis = 2166136261u;
19inline constexpr std::uint32_t kFnvPrime = 16777619u;
20inline constexpr std::uint32_t kDescriptorProbes = 8;
21inline constexpr std::uint32_t kSlotOccupiedMarker = 0xA11CA7EDu;
22
23// Key types:
24// T# key is 8 dwords.
25// S# key is 4 dwords followed by 4x 0xFFFFFFFF.
26using DescriptorKey = std::array<std::uint32_t, 8>;
27
28inline std::uint32_t hash_descriptor_key(const std::uint32_t key[8]) {
29 std::uint32_t h = kFnvOffsetBasis;
30 for (int i = 0; i < 8; ++i) {
31 h = (h ^ key[i]) * kFnvPrime;
32 }
33 return h;
34}
35
36inline std::uint32_t hash_descriptor_key(const DescriptorKey& key) {
37 return hash_descriptor_key(key.data());
38}
39
40inline DescriptorKey make_tsharp_key(const std::uint32_t tsharp[8]) {
41 DescriptorKey k{};
42 std::memcpy(k.data(), tsharp, sizeof(DescriptorKey));
43 return k;
44}
45
46inline DescriptorKey make_ssharp_key(const std::uint32_t ssharp[4]) {
47 DescriptorKey k{};
48 k[0] = ssharp[0];
49 k[1] = ssharp[1];
50 k[2] = ssharp[2];
51 k[3] = ssharp[3];
52 k[4] = 0xFFFFFFFFu;
53 k[5] = 0xFFFFFFFFu;
54 k[6] = 0xFFFFFFFFu;
55 k[7] = 0xFFFFFFFFu;
56 return k;
57}
58
59// Memory layout of each entry in the table: 10 uint32s = 40 bytes.
60struct DescriptorEntry {
61 std::uint32_t key[8] = {};
62 std::uint32_t index = 0;
63 std::uint32_t pad = 0; // 0 when empty, kSlotOccupiedMarker when occupied
64};
65static_assert(sizeof(DescriptorEntry) == 40);
66
67class DescriptorTable {
68public:
69 explicit DescriptorTable(std::uint32_t initial_capacity = 16) {
70 std::uint32_t cap = 16;
71 while (cap < initial_capacity) cap <<= 1;
72 mask_ = cap - 1;
73 entries_.resize(cap);
74 }
75
76 // Inserts or updates a key -> index mapping.
77 // If the key already exists in one of the 8 probe slots, its index is updated.
78 // If insertion would exceed 8 probes or 50% load, the table grows and re-hashes.
79 bool insert(const std::uint32_t key[8], std::uint32_t index) {
80 std::lock_guard lock(mutex_);
81 return insert_locked(key, index);
82 }
83
84 bool insert(const DescriptorKey& key, std::uint32_t index) {
85 return insert(key.data(), index);
86 }
87
88 // Queries the index associated with key. Returns 0 if not found.
89 std::uint32_t lookup(const std::uint32_t key[8]) const {
90 std::lock_guard lock(mutex_);
91 const std::uint32_t h = hash_descriptor_key(key);
92 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
93 const std::uint32_t slot = (h + k) & mask_;
94 const auto& entry = entries_[slot];
95 if (entry.pad == kSlotOccupiedMarker && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) {
96 return entry.index;
97 }
98 if (entry.pad != kSlotOccupiedMarker) {
99 return 0; // Empty slot encountered: key is definitely absent
100 }
101 }
102 return 0; // Exceeded 8 probes without a match
103 }
104
105 std::uint32_t lookup(const DescriptorKey& key) const {
106 return lookup(key.data());
107 }
108
109 bool contains(const std::uint32_t key[8]) const {
110 std::lock_guard lock(mutex_);
111 const std::uint32_t h = hash_descriptor_key(key);
112 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
113 const std::uint32_t slot = (h + k) & mask_;
114 const auto& entry = entries_[slot];
115 if (entry.pad == kSlotOccupiedMarker && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) {
116 return true;
117 }
118 if (entry.pad != kSlotOccupiedMarker) return false;
119 }
120 return false;
121 }
122
123 bool contains(const DescriptorKey& key) const {
124 return contains(key.data());
125 }
126
127 void clear() {
128 std::lock_guard lock(mutex_);
129 std::fill(entries_.begin(), entries_.end(), DescriptorEntry{});
130 occupied_count_ = 0;
131 }
132
133 std::size_t size() const {
134 std::lock_guard lock(mutex_);
135 return occupied_count_;
136 }
137
138 std::size_t capacity() const {
139 std::lock_guard lock(mutex_);
140 return entries_.size();
141 }
142
143 std::uint32_t mask() const {
144 std::lock_guard lock(mutex_);
145 return mask_;
146 }
147
148 std::size_t size_dwords() const {
149 std::lock_guard lock(mutex_);
150 return 1 + entries_.size() * 10;
151 }
152
153 std::size_t size_bytes() const {
154 return size_dwords() * sizeof(std::uint32_t);
155 }
156
157 // Exports the table buffer format consumed by SPIR-V set 0, binding 2.
158 // Word 0 is mask; followed by entries[mask + 1] of 10 dwords: key[8], index, pad.
159 std::vector<std::uint32_t> build_gpu_buffer(bool clear_pad = false) const {
160 std::lock_guard lock(mutex_);
161 std::vector<std::uint32_t> out(1 + entries_.size() * 10, 0);
162 out[0] = mask_;
163 for (std::size_t s = 0; s < entries_.size(); ++s) {
164 const std::size_t base = 1 + s * 10;
165 std::memcpy(&out[base], entries_[s].key, sizeof(entries_[s].key));
166 out[base + 8] = entries_[s].index;
167 out[base + 9] = clear_pad ? 0 : entries_[s].pad;
168 }
169 return out;
170 }
171
172 void write_to_buffer(void* dest, bool clear_pad = false) const {
173 if (!dest) return;
174 const auto buf = build_gpu_buffer(clear_pad);
175 std::memcpy(dest, buf.data(), buf.size() * sizeof(std::uint32_t));
176 }
177
178private:
179 bool insert_locked(const std::uint32_t key[8], std::uint32_t index) {
180 while (true) {
181 const std::uint32_t h = hash_descriptor_key(key);
182 int empty_slot = -1;
183
184 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
185 const std::uint32_t slot = (h + k) & mask_;
186 auto& entry = entries_[slot];
187 if (entry.pad == kSlotOccupiedMarker) {
188 if (std::memcmp(entry.key, key, sizeof(entry.key)) == 0) {
189 entry.index = index;
190 return true;
191 }
192 } else if (empty_slot < 0) {
193 empty_slot = static_cast<int>(slot);
194 }
195 }
196
197 // Check if we can place in an empty slot without exceeding 50% load
198 if (empty_slot >= 0 && (occupied_count_ + 1) * 2 <= entries_.size()) {
199 auto& entry = entries_[empty_slot];
200 std::memcpy(entry.key, key, sizeof(entry.key));
201 entry.index = index;
202 entry.pad = kSlotOccupiedMarker;
203 ++occupied_count_;
204 return true;
205 }
206
207 // Table is full (>50% load) or no slot found in 8 probes: grow and retry
208 grow_locked();
209 }
210 }
211
212 void grow_locked() {
213 std::uint32_t new_cap = static_cast<std::uint32_t>(entries_.size() * 2);
214 while (true) {
215 std::vector<DescriptorEntry> new_entries(new_cap);
216 const std::uint32_t new_mask = new_cap - 1;
217 bool rehash_ok = true;
218
219 for (const auto& old : entries_) {
220 if (old.pad != kSlotOccupiedMarker) continue;
221 const std::uint32_t h = hash_descriptor_key(old.key);
222 bool placed = false;
223 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
224 const std::uint32_t s = (h + k) & new_mask;
225 if (new_entries[s].pad != kSlotOccupiedMarker) {
226 new_entries[s] = old;
227 placed = true;
228 break;
229 }
230 }
231 if (!placed) {
232 rehash_ok = false;
233 break;
234 }
235 }
236
237 if (rehash_ok) {
238 entries_ = std::move(new_entries);
239 mask_ = new_mask;
240 break;
241 }
242 new_cap *= 2;
243 }
244 }
245
246 mutable std::mutex mutex_;
247 std::uint32_t mask_ = 15;
248 std::vector<DescriptorEntry> entries_;
249 std::size_t occupied_count_ = 0;
250};
251
252} // namespace leonida
diff --git a/runtime/src/root_signature.cpp b/runtime/src/root_signature.cpp
new file mode 100644
index 000000000..79a633b61
--- /dev/null
+++ b/runtime/src/root_signature.cpp
@@ -0,0 +1,456 @@
1// Portable root-signature packer, see root_signature.h.
2#include "root_signature.h"
3
4#include <cstring>
5
6namespace rt::rootsig {
7
8PackResult pack(const RootSignature& sig) {
9 PackResult out;
10 if (sig.params.size() > 64) {
11 out.error = "root signature has more than 64 root parameters";
12 return out;
13 }
14 uint32_t cost = 0;
15 for (const RootParameter& p : sig.params) {
16 if (p.type == ParamType::Constants && p.num_values == 0) {
17 out.error = "root constant parameter needs at least 1 dword";
18 return out;
19 }
20 const uint32_t dwords = p.type == ParamType::Table ? 2
21 : p.type == ParamType::Descriptor ? 2
22 : p.num_values;
23 cost += param_cost(p.type, p.num_values);
24 if (cost > kMaxD3d12Cost) {
25 out.error = "root signature exceeds the 64-dword D3D12 cost limit";
26 return out;
27 }
28 if (out.dword_count + dwords > kMaxUserSgprs) {
29 // Spill layout is unknown (see __XB_GetRootSignatureSpillPointer):
30 // refuse loudly instead of silently truncating every draw.
31 out.error = "root signature needs more than 32 user SGPRs (spill unsupported)";
32 return out;
33 }
34 const uint32_t param_index =
35 static_cast<uint32_t>(&p - sig.params.data());
36 for (uint32_t i = 0; i < dwords; ++i) {
37 out.dwords[out.dword_count] = 0; // filled at bind time
38 out.provenance.push_back({param_index, i});
39 ++out.dword_count;
40 }
41 }
42 out.d3d12_cost = cost;
43 out.ok = true;
44 return out;
45}
46
47namespace {
48
49void put_u32(std::vector<uint8_t>& out, uint32_t v) {
50 out.push_back(static_cast<uint8_t>(v));
51 out.push_back(static_cast<uint8_t>(v >> 8));
52 out.push_back(static_cast<uint8_t>(v >> 16));
53 out.push_back(static_cast<uint8_t>(v >> 24));
54}
55
56void put_f32(std::vector<uint8_t>& out, float v) {
57 uint32_t bits = 0;
58 static_assert(sizeof(bits) == sizeof(v));
59 std::memcpy(&bits, &v, sizeof(bits));
60 put_u32(out, bits);
61}
62
63class Reader {
64public:
65 Reader(const uint8_t* data, size_t size) : data_(data), size_(size) {}
66
67 [[nodiscard]] bool u32(uint32_t& v) {
68 if (pos_ + 4 > size_) return false;
69 v = static_cast<uint32_t>(data_[pos_]) |
70 (static_cast<uint32_t>(data_[pos_ + 1]) << 8) |
71 (static_cast<uint32_t>(data_[pos_ + 2]) << 16) |
72 (static_cast<uint32_t>(data_[pos_ + 3]) << 24);
73 pos_ += 4;
74 return true;
75 }
76
77 [[nodiscard]] bool f32(float& v) {
78 uint32_t bits = 0;
79 if (!u32(bits)) return false;
80 std::memcpy(&v, &bits, sizeof(v));
81 return true;
82 }
83
84 [[nodiscard]] bool at_end() const { return pos_ == size_; }
85
86private:
87 const uint8_t* data_ = nullptr;
88 size_t size_ = 0;
89 size_t pos_ = 0;
90};
91
92constexpr uint32_t kCanonicalMagic = 0x3153524Cu; // "LRS1" little-endian
93constexpr uint32_t kCanonicalVersion = 1;
94
95} // namespace
96
97std::vector<uint8_t> encode_canonical(const RootSignature& sig) {
98 std::vector<uint8_t> out;
99 put_u32(out, kCanonicalMagic);
100 put_u32(out, kCanonicalVersion);
101 put_u32(out, static_cast<uint32_t>(sig.version));
102 put_u32(out, static_cast<uint32_t>(sig.params.size()));
103 put_u32(out, static_cast<uint32_t>(sig.static_samplers.size()));
104 put_u32(out, sig.flags);
105 for (const RootParameter& p : sig.params) {
106 put_u32(out, static_cast<uint32_t>(p.type));
107 put_u32(out, static_cast<uint32_t>(p.visibility));
108 put_u32(out, p.num_values);
109 put_u32(out, p.shader_register);
110 put_u32(out, p.register_space);
111 put_u32(out, p.descriptor_register);
112 put_u32(out, p.descriptor_space);
113 put_u32(out, static_cast<uint32_t>(p.ranges.size()));
114 for (const DescriptorRange& r : p.ranges) {
115 put_u32(out, r.range_type);
116 put_u32(out, r.num_descriptors);
117 }
118 }
119 for (const StaticSampler& s : sig.static_samplers) {
120 put_u32(out, s.filter);
121 put_u32(out, s.address_u);
122 put_u32(out, s.address_v);
123 put_u32(out, s.address_w);
124 put_f32(out, s.mip_lod_bias);
125 put_u32(out, s.max_anisotropy);
126 put_u32(out, s.comparison_func);
127 put_u32(out, s.border_color);
128 put_f32(out, s.min_lod);
129 put_f32(out, s.max_lod);
130 put_u32(out, s.shader_register);
131 put_u32(out, s.register_space);
132 put_u32(out, static_cast<uint32_t>(s.visibility));
133 }
134 return out;
135}
136
137DecodeResult decode_canonical(const uint8_t* data, size_t size) {
138 DecodeResult out;
139 if (data == nullptr && size != 0) {
140 out.error = "null data with nonzero size";
141 return out;
142 }
143 Reader r(data == nullptr ? reinterpret_cast<const uint8_t*>("") : data, size);
144 uint32_t magic = 0, version = 0, nparams = 0, nsamplers = 0;
145 if (!r.u32(magic) || magic != kCanonicalMagic) {
146 out.error = "bad canonical magic";
147 return out;
148 }
149 if (!r.u32(version) || version != kCanonicalVersion) {
150 out.error = "unsupported canonical version";
151 return out;
152 }
153 uint32_t ver = 0;
154 if (!r.u32(ver) || !r.u32(nparams) || !r.u32(nsamplers) || !r.u32(out.sig.flags)) {
155 out.error = "truncated canonical header";
156 return out;
157 }
158 if (ver != 1 && ver != 2) {
159 out.error = "unknown root-signature version";
160 return out;
161 }
162 if (nparams > 64) {
163 out.error = "more than 64 root parameters";
164 return out;
165 }
166 if (nsamplers > 4096) {
167 out.error = "absurd sampler count";
168 return out;
169 }
170 out.sig.version = ver == 1 ? Version::V1_0 : Version::V1_1;
171 out.sig.params.reserve(nparams);
172 for (uint32_t i = 0; i < nparams; ++i) {
173 RootParameter p;
174 uint32_t type = 0, vis = 0, nranges = 0;
175 if (!r.u32(type) || !r.u32(vis) || !r.u32(p.num_values) || !r.u32(p.shader_register) ||
176 !r.u32(p.register_space) || !r.u32(p.descriptor_register) ||
177 !r.u32(p.descriptor_space) || !r.u32(nranges)) {
178 out.error = "truncated canonical parameter";
179 return out;
180 }
181 if (type > 2) {
182 out.error = "unknown parameter type";
183 return out;
184 }
185 p.type = static_cast<ParamType>(type);
186 p.visibility = static_cast<Visibility>(vis);
187 if (nranges > 1024) {
188 out.error = "absurd range count";
189 return out;
190 }
191 p.ranges.reserve(nranges);
192 for (uint32_t j = 0; j < nranges; ++j) {
193 DescriptorRange range;
194 if (!r.u32(range.range_type) || !r.u32(range.num_descriptors)) {
195 out.error = "truncated canonical range";
196 return out;
197 }
198 p.ranges.push_back(range);
199 }
200 out.sig.params.push_back(std::move(p));
201 }
202 out.sig.static_samplers.reserve(nsamplers);
203 for (uint32_t i = 0; i < nsamplers; ++i) {
204 StaticSampler s;
205 uint32_t vis = 0;
206 if (!r.u32(s.filter) || !r.u32(s.address_u) || !r.u32(s.address_v) || !r.u32(s.address_w) ||
207 !r.f32(s.mip_lod_bias) || !r.u32(s.max_anisotropy) || !r.u32(s.comparison_func) ||
208 !r.u32(s.border_color) || !r.f32(s.min_lod) || !r.f32(s.max_lod) ||
209 !r.u32(s.shader_register) || !r.u32(s.register_space) || !r.u32(vis)) {
210 out.error = "truncated canonical sampler";
211 return out;
212 }
213 s.visibility = static_cast<Visibility>(vis);
214 out.sig.static_samplers.push_back(s);
215 }
216 if (!r.at_end()) {
217 out.error = "trailing bytes after canonical root signature";
218 return out;
219 }
220 out.ok = true;
221 return out;
222}
223
224// RTS0 payload hypothesis: u32 version (1 = 1.0, 2 = 1.1), u32 num_params,
225// u32 num_static_samplers, u32 flags, then per-parameter fields in d3d12.h
226// order. Static samplers follow the same field order as D3D12_STATIC_SAMPLER_DESC.
227// Anything else (v1.2 blobs, extra dwords, truncation) is a hard error.
228// Payload decoder: the RTS0 chunk contents (see header for the hypothesis).
229static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) {
230 DecodeResult out;
231 if (data == nullptr && size != 0) {
232 out.error = "null data with nonzero size";
233 return out;
234 }
235 if (data == nullptr) {
236 out.error = "null RTS0 payload";
237 return out;
238 }
239 // Random access into the payload: every (offset, byte-count) pair is
240 // validated before any byte is touched. Offsets count from payload start.
241 auto at = [&](size_t off, size_t bytes) -> const uint8_t* {
242 if (bytes > size || off > size - bytes) return nullptr;
243 return data + off;
244 };
245 auto u32_at = [&](size_t off, uint32_t& v) {
246 const uint8_t* p = at(off, 4);
247 if (p == nullptr) return false;
248 v = static_cast<uint32_t>(p[0]) | (static_cast<uint32_t>(p[1]) << 8) |
249 (static_cast<uint32_t>(p[2]) << 16) | (static_cast<uint32_t>(p[3]) << 24);
250 return true;
251 };
252 auto f32_at = [&](size_t off, float& v) {
253 uint32_t bits = 0;
254 if (!u32_at(off, bits)) return false;
255 static_assert(sizeof(bits) == sizeof(v));
256 std::memcpy(&v, &bits, sizeof(v));
257 return true;
258 };
259 // Header: version, num_params, params_offset, num_samplers,
260 // samplers_offset, flags.
261 uint32_t ver = 0, nparams = 0, params_off = 0, nsamplers = 0, samplers_off = 0, flags = 0;
262 if (!u32_at(0, ver) || !u32_at(4, nparams) || !u32_at(8, params_off) ||
263 !u32_at(12, nsamplers) || !u32_at(16, samplers_off) || !u32_at(20, flags)) {
264 out.error = "truncated RTS0 header";
265 return out;
266 }
267 if (ver != 1 && ver != 2) {
268 out.error = "unknown RTS0 version (not 1.0/1.1)";
269 return out;
270 }
271 if (nparams > 64) {
272 out.error = "RTS0 with more than 64 root parameters";
273 return out;
274 }
275 if (nsamplers > 4096) {
276 out.error = "RTS0 with absurd sampler count";
277 return out;
278 }
279 out.sig.version = ver == 1 ? Version::V1_0 : Version::V1_1;
280 out.sig.flags = flags;
281 // Parameter table at params_off: num_params x {u32 d3d_type, u32
282 // visibility, u32 offset}. d3d_type follows D3D12_ROOT_PARAMETER_TYPE
283 // (0 table, 1 constants, 2/3/4 CBV/SRV/UAV root descriptors).
284 constexpr size_t kEntryBytes = 12;
285 if (nparams > 0 &&
286 (params_off > size || nparams > (size - params_off) / kEntryBytes)) {
287 out.error = "RTS0 parameter table overruns its payload";
288 return out;
289 }
290 out.sig.params.reserve(nparams);
291 for (uint32_t i = 0; i < nparams; ++i) {
292 const size_t eoff = static_cast<size_t>(params_off) + i * kEntryBytes;
293 uint32_t dtype = 0, vis = 0, poff = 0;
294 if (!u32_at(eoff, dtype) || !u32_at(eoff + 4, vis) || !u32_at(eoff + 8, poff)) {
295 out.error = "truncated RTS0 parameter entry";
296 return out;
297 }
298 RootParameter p;
299 p.visibility = static_cast<Visibility>(vis);
300 if (dtype == 1) {
301 p.type = ParamType::Constants;
302 if (!u32_at(poff, p.shader_register) || !u32_at(poff + 4, p.register_space) ||
303 !u32_at(poff + 8, p.num_values)) {
304 out.error = "truncated RTS0 constants payload";
305 return out;
306 }
307 } else if (dtype == 2 || dtype == 3 || dtype == 4) {
308 p.type = ParamType::Descriptor;
309 uint32_t dflags = 0;
310 const size_t need = ver == 2 ? 12 : 8;
311 if (poff > size || need > size - static_cast<size_t>(poff)) {
312 out.error = "truncated RTS0 descriptor payload";
313 return out;
314 }
315 if (!u32_at(poff, p.descriptor_register) || !u32_at(poff + 4, p.descriptor_space)) {
316 out.error = "truncated RTS0 descriptor payload";
317 return out;
318 }
319 if (ver == 2 && !u32_at(poff + 8, dflags)) {
320 out.error = "truncated RTS0 descriptor flags";
321 return out;
322 }
323 (void)dflags; // descriptor flags do not affect the user-SGPR map
324 } else if (dtype == 0) {
325 p.type = ParamType::Table;
326 uint32_t nranges = 0;
327 if (!u32_at(poff, nranges)) {
328 out.error = "truncated RTS0 table payload";
329 return out;
330 }
331 if (nranges > 1024) {
332 out.error = "absurd RTS0 range count";
333 return out;
334 }
335 // Range record: {type, num, base_reg, space, offset} (+ flags on 1.1).
336 const size_t stride = ver == 2 ? 24 : 20;
337 if (nranges > 0 &&
338 (poff + 4 > size || nranges > (size - (poff + 4)) / stride)) {
339 out.error = "RTS0 ranges overrun their payload";
340 return out;
341 }
342 p.ranges.reserve(nranges);
343 for (uint32_t j = 0; j < nranges; ++j) {
344 const size_t roff = static_cast<size_t>(poff) + 4 + j * stride;
345 DescriptorRange range;
346 uint32_t base_reg = 0, space = 0, disp_off = 0, rflags = 0;
347 if (!u32_at(roff, range.range_type) || !u32_at(roff + 4, range.num_descriptors) ||
348 !u32_at(roff + 8, base_reg) || !u32_at(roff + 12, space) ||
349 !u32_at(roff + 16, disp_off) ||
350 (ver == 2 && !u32_at(roff + 20, rflags))) {
351 out.error = "truncated RTS0 range";
352 return out;
353 }
354 (void)base_reg;
355 (void)space;
356 (void)disp_off;
357 (void)rflags;
358 p.ranges.push_back(range);
359 }
360 } else {
361 out.error = "unknown RTS0 parameter type";
362 return out;
363 }
364 out.sig.params.push_back(std::move(p));
365 }
366 // Sampler records mirror D3D12_STATIC_SAMPLER_DESC field order.
367 constexpr size_t kSamplerBytes = 13 * 4;
368 if (nsamplers > 0 &&
369 (samplers_off > size || nsamplers > (size - samplers_off) / kSamplerBytes)) {
370 out.error = "RTS0 samplers overrun their payload";
371 return out;
372 }
373 out.sig.static_samplers.reserve(nsamplers);
374 for (uint32_t i = 0; i < nsamplers; ++i) {
375 const size_t soff = static_cast<size_t>(samplers_off) + i * kSamplerBytes;
376 StaticSampler s;
377 uint32_t vis = 0;
378 if (!u32_at(soff, s.filter) || !u32_at(soff + 4, s.address_u) ||
379 !u32_at(soff + 8, s.address_v) || !u32_at(soff + 12, s.address_w) ||
380 !f32_at(soff + 16, s.mip_lod_bias) || !u32_at(soff + 20, s.max_anisotropy) ||
381 !u32_at(soff + 24, s.comparison_func) || !u32_at(soff + 28, s.border_color) ||
382 !f32_at(soff + 32, s.min_lod) || !f32_at(soff + 36, s.max_lod) ||
383 !u32_at(soff + 40, s.shader_register) || !u32_at(soff + 44, s.register_space) ||
384 !u32_at(soff + 48, vis)) {
385 out.error = "truncated RTS0 sampler";
386 return out;
387 }
388 s.visibility = static_cast<Visibility>(vis);
389 out.sig.static_samplers.push_back(s);
390 }
391 out.ok = true;
392 return out;
393}
394
395DecodeResult parse_rts0(const uint8_t* data, size_t size) {
396 DecodeResult out;
397 if ((data == nullptr && size != 0) || (data != nullptr && size < 4)) {
398 out.error = "blob too small for a DXBC container";
399 return out;
400 }
401 if (data == nullptr) {
402 out.error = "null blob";
403 return out;
404 }
405 // A bare payload (unit-test path) has no DXBC magic: decode directly.
406 if (!(data[0] == 'D' && data[1] == 'X' && data[2] == 'B' && data[3] == 'C')) {
407 return parse_rts0_payload(data, size);
408 }
409 // DXBC container walk (mirrors input_signature in tools/rdna2spirv.py):
410 // +28: chunk count, +32: chunk offsets, each chunk is FourCC + u32 size.
411 auto at = [&](size_t off, uint32_t& v) {
412 if (off + 4 > size) return false;
413 v = static_cast<uint32_t>(data[off]) | (static_cast<uint32_t>(data[off + 1]) << 8) |
414 (static_cast<uint32_t>(data[off + 2]) << 16) | (static_cast<uint32_t>(data[off + 3]) << 24);
415 return true;
416 };
417 uint32_t nchunks = 0;
418 if (!at(28, nchunks)) {
419 out.error = "truncated DXBC header";
420 return out;
421 }
422 if (nchunks > 1024) {
423 out.error = "absurd DXBC chunk count";
424 return out;
425 }
426 for (uint32_t k = 0; k < nchunks; ++k) {
427 uint32_t off = 0;
428 // NOTE: off and payload_size are u32; promote to size_t BEFORE adding
429 // or a hostile container wraps the check and turns it into an OOB read.
430 if (!at(32 + 4 * static_cast<size_t>(k), off) ||
431 static_cast<size_t>(off) + 8 > size) {
432 out.error = "truncated DXBC chunk table";
433 return out;
434 }
435 if (data[off] == 'R' && data[off + 1] == 'T' && data[off + 2] == 'S' && data[off + 3] == '0') {
436 uint32_t payload_size = 0;
437 if (static_cast<size_t>(off) + 8 > size) {
438 out.error = "truncated RTS0 chunk header";
439 return out;
440 }
441 payload_size = static_cast<uint32_t>(data[off + 4]) |
442 (static_cast<uint32_t>(data[off + 5]) << 8) |
443 (static_cast<uint32_t>(data[off + 6]) << 16) |
444 (static_cast<uint32_t>(data[off + 7]) << 24);
445 if (static_cast<size_t>(off) + 8 + payload_size > size) {
446 out.error = "RTS0 chunk overruns its container";
447 return out;
448 }
449 return parse_rts0_payload(data + off + 8, payload_size);
450 }
451 }
452 out.error = "no RTS0 chunk in DXBC container";
453 return out;
454}
455
456} // namespace rt::rootsig
diff --git a/runtime/src/root_signature.h b/runtime/src/root_signature.h
new file mode 100644
index 000000000..4c19cf72d
--- /dev/null
+++ b/runtime/src/root_signature.h
@@ -0,0 +1,150 @@
1// Portable D3D12 root-signature model + packer to user SGPRs (s0..s31).
2//
3// No d3d12.h, no windows.h: this compiles on Linux CI and in the Windows
4// runtime alike. It models exactly what docs/d3d12_vulkan.md section 3.5
5// needs: root parameters in order, static samplers (no dwords), the 64-dword
6// D3D12 cost limit, and the 32-dword console user-SGPR budget. Anything that
7// does not fit is refused loudly, never guessed (see pack()).
8//
9// Numbering follows D3D12 docs: descriptor tables cost 1 dword of the 64-dword
10// limit, root views (CBV/SRV/UAV) cost 2, 32-bit constants cost their count.
11#pragma once
12
13#include <array>
14#include <cstdint>
15#include <string>
16#include <vector>
17
18namespace rt::rootsig {
19
20// D3D12_ROOT_SIGNATURE_VERSION subset the layer handles.
21enum class Version : uint32_t { V1_0 = 1, V1_1 = 2 };
22
23// D3D12_ROOT_PARAMETER_TYPE subset (order matches D3D12 docs).
24enum class ParamType : uint32_t {
25 Constants = 0, // 32BIT_CONSTANTS: NumValues dwords
26 Descriptor = 1, // CBV/SRV/UAV root descriptor: 2 dwords (64-bit VA)
27 Table = 2, // DESCRIPTOR_TABLE: 2 dwords (table GPU VA)
28};
29
30// D3D12_SHADER_VISIBILITY (ALL 0, VERTEX 1, HULL 2, DOMAIN 3,
31// GEOMETRY 4, PIXEL 5, AMPLIFICATION 6, MESH 7).
32enum class Visibility : uint32_t {
33 All = 0,
34 Vertex = 1,
35 Geometry = 4,
36 Pixel = 5,
37 Amplification = 6,
38 Mesh = 7,
39};
40
41// One descriptor range inside a table (SRV/CBV/UAV/sampler + count).
42struct DescriptorRange {
43 uint32_t range_type = 0; // 0 SRV, 1 UAV, 2 CBV, 3 sampler (D3D12 order)
44 uint32_t num_descriptors = 0;
45};
46
47// Static sampler: no user-SGPR dwords; registered in the hash table instead.
48struct StaticSampler {
49 uint32_t filter = 0;
50 uint32_t address_u = 0;
51 uint32_t address_v = 0;
52 uint32_t address_w = 0;
53 float mip_lod_bias = 0.0f;
54 uint32_t max_anisotropy = 0;
55 uint32_t comparison_func = 0;
56 uint32_t border_color = 0; // 0 transparent-black .. 4 opaque-white
57 float min_lod = 0.0f;
58 float max_lod = 0.0f;
59 uint32_t shader_register = 0;
60 uint32_t register_space = 0;
61 Visibility visibility = Visibility::All;
62};
63
64struct RootParameter {
65 ParamType type = ParamType::Constants;
66 Visibility visibility = Visibility::All;
67 // Constants:
68 uint32_t num_values = 0; // shader register + space describe the slot
69 uint32_t shader_register = 0;
70 uint32_t register_space = 0;
71 // Root descriptor:
72 uint32_t descriptor_register = 0;
73 uint32_t descriptor_space = 0;
74 // Descriptor table:
75 std::vector<DescriptorRange> ranges;
76};
77
78struct RootSignature {
79 Version version = Version::V1_1;
80 std::vector<RootParameter> params; // at most 64 root parameters (D3D12)
81 std::vector<StaticSampler> static_samplers;
82 uint32_t flags = 0; // low 16 bits: PC meaning; high byte: Xbox type bits
83};
84
85// Where one packed dword came from (provenance for diagnostics).
86struct DwordProvenance {
87 uint32_t param_index = 0; // index into RootSignature::params
88 uint32_t sub_index = 0; // constant index, or 0 = VA lo, 1 = VA hi
89};
90
91struct PackResult {
92 bool ok = false;
93 std::string error; // set when !ok; names the refusing parameter
94 std::array<uint32_t, 32> dwords{}; // valid dwords [0, dword_count)
95 uint32_t dword_count = 0;
96 std::vector<DwordProvenance> provenance; // same length as dword_count
97 uint32_t d3d12_cost = 0; // cost against the 64-dword D3D12 limit
98};
99
100constexpr uint32_t kMaxUserSgprs = 32;
101constexpr uint32_t kMaxD3d12Cost = 64;
102
103// Packs root parameters in order. Static samplers consume no dwords.
104// Fails (ok == false) when the signature needs more than 32 user SGPRs
105// (spill layout unknown: refuse, do not guess) or exceeds the 64-dword
106// D3D12 cost limit, or holds more than 64 root parameters.
107[[nodiscard]] PackResult pack(const RootSignature& sig);
108
109// D3D12 cost of one parameter against the 64-dword limit.
110[[nodiscard]] constexpr uint32_t param_cost(ParamType type, uint32_t num_values) noexcept {
111 switch (type) {
112 case ParamType::Constants:
113 return num_values;
114 case ParamType::Descriptor:
115 return 2;
116 case ParamType::Table:
117 return 1;
118 }
119 return 0;
120}
121
122// Canonical binary codec for caching root signatures (magic "LRS1",
123// little-endian). This is Leonida's own layout, NOT the Microsoft RTS0
124// format: it round-trips pack() inputs byte-exactly and is fully tested on
125// every CI leg. Never write game blobs in this format and claim otherwise.
126[[nodiscard]] std::vector<uint8_t> encode_canonical(const RootSignature& sig);
127
128struct DecodeResult {
129 bool ok = false;
130 std::string error;
131 RootSignature sig;
132};
133
134[[nodiscard]] DecodeResult decode_canonical(const uint8_t* data, size_t size);
135
136// RTS0 chunk parser (payload layout per the maintainer: offset table).
137//
138// The input is a whole DXBC container (what D3D12SerializeVersionedRootSignature
139// returns: "DXBC" magic, hash, size, chunk table). The parser walks the chunk
140// table exactly like tools/rdna2spirv.py:input_signature does, finds the
141// "RTS0" chunk and decodes its payload: version, counts and table offsets,
142// then a parameter table of {d3d_type, visibility, offset} entries with
143// payloads at their offsets (d3d types follow D3D12_ROOT_PARAMETER_TYPE
144// numbering). A bare payload without the DXBC header is also accepted
145// (unit-test path). Every deviation the oracle test finds is a hard failure
146// to investigate, not a quirk to absorb.
147// Returns ok == false with a reason for unknown versions or truncation.
148[[nodiscard]] DecodeResult parse_rts0(const uint8_t* data, size_t size);
149
150} // namespace rt::rootsig