Recursive AI

HLSL ByteAddressBuffer: load and store a matrix struct

OneShader is a free, open-source HLSL compiler library for .NET from Recursive AI. MIT or Apache-2.0.

Use Load<Record> and Store<Record> at a byte offset. The example runs on Vulkan 1.2.

Terminal
dotnet add package RecursiveAI.OneShader

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

HLSL
// Inside CSMain in Matrix.hlsl (below).
Record item = Source.Load<Record>(0);
item.matrix[0][1] += 10.0;
item.tag += 1u;
Target.Store<Record>(0, item);

The matrix travels as consecutive, unpadded columns, but the struct’s layout puts the tag at byte 32.

Run the program from the zip: it includes VulkanHost.cs, which binds the buffers and isn’t shown on this page. The program prints the bytes before and after the dispatch.

The example is the full program below: unzip it and dotnet run.

The full program

Matrix.hlsl (included in the zip):

HLSL
struct Record {
    row_major float2x3 matrix;
    uint tag;
};
 
ByteAddressBuffer Source : register(t0);
RWByteAddressBuffer Target : register(u1);
 
[shader("compute")]
[numthreads(1, 1, 1)]
void CSMain()
{
    Record item = Source.Load<Record>(0);
    item.matrix[0][1] += 10.0;
    item.tag += 1u;
    Target.Store<Record>(0, item);
}

The host in the zip also uses Silk.NET.Vulkan:

Terminal
dotnet add package Silk.NET.Vulkan

The input is built in C#: two logical rows [1, 2, 3] and [4, 5, 6], followed by a tag of 7. VulkanHost.cs in the zip binds the input and output buffers at set 0, bindings 0 and 1. It dispatches one workgroup, waits for the GPU, and reads the output buffer back. The project enables unsafe code for the Vulkan calls.

C#
using OneShader;
 
var result = ShaderCompiler.CompileFile("Matrix.hlsl",
    new CompileOptions { Targets = [CompileTarget.SpirV] });
if (!result.Success)
    throw new Exception(string.Join("\n", result.Diagnostics));
byte[] shader = result.Find("CSMain", CompileTarget.SpirV)!.ToArray();
 
// The logical rows are [1, 2, 3] and [4, 5, 6]. Pack columns.
uint[] input = [.. new float[] { 1, 4, 2, 5, 3, 6 }
    .Select(BitConverter.SingleToUInt32Bits), 0u, 0u, 7u, 0u, 0u, 0u];
uint[] output = VulkanHost.Run(shader, [0, 1], [input, new uint[12]])[1];
uint[] expected = (uint[])input.Clone();
expected[2] = BitConverter.SingleToUInt32Bits(12f);
expected[8] = 8u;
if (!output.SequenceEqual(expected))
    throw new InvalidOperationException("Unexpected matrix record bytes.");
 
Console.WriteLine("Offset  Input bytes  Output bytes");
for (int i = 0; i < output.Length; i++)
    Console.WriteLine($"{i * 4,6}  {Bytes(input[i])}  {Bytes(output[i])}");
 
static string Bytes(uint word) => string.Join(" ",
    Enumerable.Range(0, 4).Select(i => ((byte)(word >> (8 * i))).ToString("X2")));
Text
Vulkan device: NVIDIA GeForce RTX 4070
Offset  Input bytes  Output bytes
     0  00 00 80 3F  00 00 80 3F
     4  00 00 80 40  00 00 80 40
     8  00 00 00 40  00 00 40 41
    12  00 00 A0 40  00 00 A0 40
    16  00 00 40 40  00 00 40 40
    20  00 00 C0 40  00 00 C0 40
    24  00 00 00 00  00 00 00 00
    28  00 00 00 00  00 00 00 00
    32  07 00 00 00  08 00 00 00
    36  00 00 00 00  00 00 00 00
    40  00 00 00 00  00 00 00 00
    44  00 00 00 00  00 00 00 00

A shader compile error stops the program before dispatch and prints OneShader’s diagnostics in the exception message.

Variations

To change the bottom-right matrix entry instead, replace the matrix update in Matrix.hlsl with:

HLSL
item.matrix[1][2] += 10.0;

Replace the expected[2] line in Program.cs to check the new result:

C#
expected[5] = BitConverter.SingleToUInt32Bits(16f);

The changed matrix word is now at byte 20: 00 00 C0 40 becomes 00 00 80 41 (6 to 16).

The short answer

Use Source.Load<Record>(byteOffset) to fetch the struct and Target.Store<Record>(byteOffset, item) to write it. Starting with OneShader 1.7.3, the templated operations accept a struct containing a matrix. The struct’s fields start at their structured-buffer offsets, but the matrix payload itself travels as consecutive, unpadded columns. Those are two separate layout rules: don’t use the end of the matrix payload to guess where the next field starts.

How do you index a ByteAddressBuffer in HLSL?

The argument to Load<T> is a byte offset, not an index into an array of T. Offset 0 loads the record at the start of Source. If a record starts 48 bytes into the buffer, the argument is 48, not 1 or 12. ByteAddressBuffer is read-only; use RWByteAddressBuffer for the destination. Use a four-byte-aligned base offset for the example’s 32-bit fields and leave room for the whole record in both buffers.

Once loaded, the matrix uses row-then-column subscripts: item.matrix[0][1] is the second entry in the first row. That convention doesn’t dictate how the raw bytes are ordered. Here the input word order is 1, 4, 2, 5, 3, 6, so the 2 is the third word, at byte 8. Changing it to 12 and seeing it change at byte 8 checks more than a copy: the shader read the intended logical entry and wrote it back to the same byte position.

What’s the difference between ByteAddressBuffer and StructuredBuffer?

A StructuredBuffer<Record> lets you address the first element as records[0]. Use it when the buffer is an array with one fixed record layout. A ByteAddressBuffer lets you give each access its own type and byte offset; it fits a buffer where records live at explicit offsets or share space with other kinds of data. Templated loads and stores remove the manual word-by-word decoding, not the need to agree on the layout with the producer of the bytes.

For this example’s exact declaration and compiler options, the matrix payload occupies bytes 0 through 23; the tag starts at byte 32, not 24. The host leaves the gap at bytes 24 through 31 and sets the tag separately. The row_major modifier does not make a templated byte-address access transfer the matrix in row order. When porting a layout from a constant buffer, or changing the member types or layout options, recheck the field offsets instead of copying this example’s numbers.

All oneshader recipes