Tech News
← Back to articles

An Experimental Approach to Printf in HLSL

read original related products more articles

There are a million reasons why having printf support in HLSL would be super valuable. It even used to exist in older shader models. Other shader languages like the Metal Shading language have their own logging mechanisms, and shader programming gurus like MJP have rolled their own.

Disclaimer: having an officially supported way to print strings would be super useful for HLSL… Although this isn’t official, this is just me playing around on my holiday break. It is likely we could make something like this supported in Clang, however there are some challenges to supporting this in DXC and when targeting SPIRV or Metal (more on that later).

Before I go any further, let me show you want it looks like to use this. Given the HLSL code here:

#include "dx/printf.h" [ numthreads ( 16 , 1 , 1 )] void main ( uint3 TID : SV_GroupThreadID ) { // Required to initialize the debug output stream. dx :: InitializeDebugStream (); uint idx = TID . x ; uint value = idx + 1 ; if ( value % 3 == 0 && value % 5 == 0 ) dx :: printf ( "FizzBuzz(%u)

" , value ); else if ( value % 3 == 0 ) dx :: printf ( "Fizz(%u)

" , value ); else if ( value % 5 == 0 ) dx :: printf ( "Buzz(%u)

" , value ); else dx :: printf ( "Baz(%u)

" , value ); }

This results in producing a buffer, that when interpreted by the CPU prints (note ordering of messages can be dependent on compiler optimizations and hardware constraints, but more on that later):

FizzBuzz(15) Fizz(3) Fizz(6) Fizz(9) Fizz(12) Buzz(5) Buzz(10) Baz(1) Baz(2) Baz(4) Baz(7) Baz(8) Baz(11) Baz(13) Baz(14) Baz(16)

... continue reading