Documentation
¶
Overview ¶
Package oneshader compiles modern HLSL (Shader Model 6 style) to SPIR-V, Metal Shading Language, WGSL and DXIL, with reflection, and does it in pure Go.
The happy path is Compile (CompileFile and CompileFS for files, and a CompileContext twin of each for cancellation), configured with options. WithTargets picks the outputs; each entry point gives one Blob per target, and Result.Reflection describes the shader's interface:
res, err := oneshader.Compile(src,
oneshader.WithName("sprite.hlsl"),
oneshader.WithIncludeFS(shaderFiles, "common"),
oneshader.WithTargets(oneshader.TargetSPIRV, oneshader.TargetMSL))
if err != nil {
for _, d := range res.Diagnostics {
fmt.Println(d) // sprite.hlsl(12,5): error OSH0201: expected an expression here, found ';'
}
return err
}
spirv, _ := res.Find("PSMain", oneshader.TargetSPIRV)
Diagnostics carry a stable OSHnnnn code, a location and advice on the fix. Output is deterministic: the same source and options give the same bytes. Compile keeps no state between calls and may run on many goroutines at once; a Cache remembers results for tools that recompile on every file change, and Compatible tells whether a recompiled shader still fits code built against the old one (hot reload).
HLSL source is untrusted input. Include depth and count, macro expansion, nesting, template instantiations, array and struct sizes, the size of the lowered program and the number of errors are all bounded by Limits (WithLimits), and a compile that crosses a bound is an error, never a crash or an unbounded allocation; errors.Is(err, ErrLimit) matches it.
For Go programs the usual route is the oneshader command, run from go:generate: it compiles *.hlsl at build time and writes Go structs laid out to the shader's byte layout, binding values and the compiled blobs (package gen, and shader for the types the generated code uses). The packages below this one are the low level the happy path is built on: preprocess and syntax (the preprocessor, lexer, parser and syntax tree), layout (HLSL types and the one byte layout every target shares), ir and ir/opt (the intermediate representation, its verifier and the optimizer), spirv, msl, wgsl and dxil (the backends), and pipeline (descriptor, argument and bind group layouts for a renderer).
Index ¶
- Constants
- Variables
- func Compatible(old, updated *Reflection) error
- func MSLFunctionName(entry string) string
- func Version() string
- type Blob
- type BuiltIn
- type Cache
- func (c *Cache) Clear()
- func (c *Cache) Compile(ctx context.Context, src []byte, opts ...Option) (*Result, error)
- func (c *Cache) CompileFS(ctx context.Context, fsys fs.FS, name string, opts ...Option) (*Result, error)
- func (c *Cache) CompileFile(ctx context.Context, path string, opts ...Option) (*Result, error)
- func (c *Cache) Len() int
- func (c *Cache) Stats() CacheStats
- type CacheStats
- type Code
- type DebugInfo
- type Define
- type Diagnostic
- type DiagnosticsError
- type Difference
- type DifferenceKind
- type EntryPoint
- type EntryRequest
- type Features
- type Heap
- type HeapBinding
- type IncludeFile
- type IncludeRequest
- type IncludeResolver
- type IncompatibleError
- type Interpolation
- type Limits
- type Option
- func WithDXILPixelPosition(on bool) Option
- func WithDXILShaderModel(minor int) Option
- func WithDebugInfo(level DebugInfo) Option
- func WithDebugSourceRoot(dir string) Option
- func WithDefine(name, value string) Option
- func WithDefines(defs ...Define) Option
- func WithEnable16BitTypes(on bool) Option
- func WithEntryPoints(eps ...EntryRequest) Option
- func WithHLSLVersion(v int) Option
- func WithIncludeDirs(dirs ...string) Option
- func WithIncludeFS(fsys fs.FS, dirs ...string) Option
- func WithIncludeResolver(r IncludeResolver) Option
- func WithKeepNames(on bool) Option
- func WithLimits(l Limits) Option
- func WithMatrixPacking(p layout.MatrixPacking) Option
- func WithName(name string) Option
- func WithOptimize(on bool) Option
- func WithResourceHeapBinding(binding, set int) Option
- func WithSPIRVVersion(minor int) Option
- func WithSamplerHeapBinding(binding, set int) Option
- func WithSpecConstant(name string, value float64) Option
- func WithTargetProfile(profile string) Option
- func WithTargets(targets ...Target) Option
- type PushConstant
- type ReflectedMember
- type ReflectedType
- type Reflection
- func (r *Reflection) AppendJSON(b []byte) []byte
- func (r *Reflection) AppendText(b []byte) []byte
- func (r *Reflection) EntryLayout(entry string) (*pipeline.EntryLayout, error)
- func (r *Reflection) Equal(o *Reflection) bool
- func (r *Reflection) MarshalJSON() ([]byte, error)
- func (r *Reflection) MarshalText() ([]byte, error)
- func (r *Reflection) SpecLayouts() []pipeline.SpecConstant
- func (r *Reflection) UnmarshalJSON(data []byte) error
- func (r *Reflection) UsesSubgroups() bool
- func (r *Reflection) WriteTo(w io.Writer) (int64, error)
- type ResolverFunc
- type Resource
- type ResourceKind
- type Result
- func Compile(src []byte, opts ...Option) (*Result, error)
- func CompileContext(ctx context.Context, src []byte, opts ...Option) (*Result, error)
- func CompileFS(fsys fs.FS, name string, opts ...Option) (*Result, error)
- func CompileFSContext(ctx context.Context, fsys fs.FS, name string, opts ...Option) (*Result, error)
- func CompileFile(path string, opts ...Option) (*Result, error)
- func CompileFileContext(ctx context.Context, path string, opts ...Option) (*Result, error)
- type Severity
- type Slot
- type Span
- type SpecConstant
- type SpecSlot
- type Stage
- type StageSet
- type StageVariable
- type SubgroupOps
- type Target
- type TypeKind
Examples ¶
- Cache
- Cache (HotReload)
- Compatible
- Compatible (NilReflection)
- Compile
- Compile (Errors)
- CompileContext
- ReflectedTypeFromLayout
- Reflection
- Reflection.AppendJSON
- Reflection.EntryLayout
- Reflection.WriteTo
- Result.Find
- WithDXILPixelPosition
- WithDefine
- WithEntryPoints
- WithIncludeFS
- WithLimits
- WithOptimize
- WithSpecConstant
- WithTargets (Dxil)
- WithTargets (Msl)
- WithTargets (Wgsl)
Constants ¶
const ( SeverityInfo = diag.Info SeverityWarning = diag.Warning SeverityError = diag.Error )
Severities. The values are stable.
const ( TargetSPIRV = shader.SPIRV TargetMSL = shader.MSL TargetWGSL = shader.WGSL // TargetIR is the verified intermediate representation in its binary form (see ir.Encode). It lets a // CPU executor run the same shader the GPU targets run. TargetIR = shader.IR // TargetDXIL is a DXIL container (shader model 6) for Direct3D 12, one per entry point. TargetDXIL = shader.DXIL )
Output formats.
const ( StageVertex = shader.Vertex StagePixel = shader.Pixel StageCompute = shader.Compute )
Pipeline stages, in the numbering reflection uses.
const ( StagesVertex = shader.StagesVertex StagesPixel = shader.StagesPixel StagesCompute = shader.StagesCompute )
Stage sets.
const ( KindConstantBuffer = shader.ConstantBuffer KindSampledTexture = shader.SampledTexture KindStorageTexture = shader.StorageTexture KindSampler = shader.Sampler KindReadOnlyStorageBuffer = shader.ReadOnlyStorageBuffer KindStorageBuffer = shader.StorageBuffer KindUniformTexelBuffer = shader.UniformTexelBuffer KindStorageTexelBuffer = shader.StorageTexelBuffer )
Resource kinds.
const ( HeapNone = shader.HeapNone HeapResource = shader.HeapResource HeapSampler = shader.HeapSampler )
Descriptor heaps.
const ( FeatureFloat16 = shader.FeatureFloat16 FeatureInt16 = shader.FeatureInt16 FeatureFloat64 = shader.FeatureFloat64 FeatureInt64 = shader.FeatureInt64 FeatureStorageBuffer16 = shader.FeatureStorageBuffer16 FeatureUniformBuffer16 = shader.FeatureUniformBuffer16 FeaturePushConstant16 = shader.FeaturePushConstant16 FeatureInputOutput16 = shader.FeatureInputOutput16 FeatureInt64Atomics = shader.FeatureInt64Atomics FeatureRuntimeDescriptorArray = shader.FeatureRuntimeDescriptorArray FeatureNonUniformIndexing = shader.FeatureNonUniformIndexing FeatureMutableDescriptorType = shader.FeatureMutableDescriptorType FeatureCooperativeMatrix = shader.FeatureCooperativeMatrix FeatureVulkanMemoryModel = shader.FeatureVulkanMemoryModel FeatureBFloat16 = shader.FeatureBFloat16 FeatureBFloat16CooperativeMatrix = shader.FeatureBFloat16CooperativeMatrix FeatureIntegerDotProduct = shader.FeatureIntegerDotProduct FeatureFullSubgroups = shader.FeatureFullSubgroups )
Device features; the values are the bits reflection writes.
const ( SubgroupBasic = shader.SubgroupBasic SubgroupVote = shader.SubgroupVote SubgroupArithmetic = shader.SubgroupArithmetic SubgroupBallot = shader.SubgroupBallot SubgroupShuffle = shader.SubgroupShuffle SubgroupQuad = shader.SubgroupQuad )
Subgroup operation classes.
const DefaultCacheEntries = 256
DefaultCacheEntries is the number of results a Cache keeps when the caller has no reason to choose another.
const ReflectionFormatVersion = 1
ReflectionFormatVersion is the version of the line-based reflection text that WriteTo writes and ParseReflection reads.
Variables ¶
var ErrIncompatible = errors.New("oneshader: the new shader's interface differs from the old one")
ErrIncompatible is matched by errors.Is for every *IncompatibleError.
var ErrLimit = errors.New("oneshader: input exceeds a limit")
ErrLimit is matched by errors.Is for a compile that stopped at one of the Limits: include depth, macro expansion, nesting or the error cap.
var ErrNilReflection = errors.New("oneshader: Compatible needs two reflections")
ErrNilReflection is what Compatible returns when either reflection is nil, for instance the Reflection of a compile that failed.
var ErrReflectionFormat = errors.New("oneshader: invalid reflection text")
ErrReflectionFormat is wrapped by every error ParseReflection returns for a document it rejects.
Functions ¶
func Compatible ¶
func Compatible(old, updated *Reflection) error
Compatible reports whether a program built against the old reflection can use the new one without recreating its pipeline layouts, buffers or vertex setups, which is the question hot reload asks after an edit. It returns nil when it can, and otherwise an *IncompatibleError (errors.Is ErrIncompatible) listing every difference. Edits that leave the interface alone, new entry points, new specialization constants, changed specialization defaults and resources visible to fewer stages are compatible. A nil argument is ErrNilReflection, which is not an *IncompatibleError.
Example ¶
package main
import (
"errors"
"fmt"
"recursiveai.org/go/oneshader"
)
func main() {
const base = `cbuffer Frame : register(b0) { float4 Tint; float Time; };
RWStructuredBuffer<float> Out : register(u1);
[shader("compute")] [numthreads(8, 1, 1)] void CSMain(uint3 id : SV_DispatchThreadID) { Out[id.x] = Time; }
`
edited := `cbuffer Frame : register(b0) { float4 Tint; float4 Extra; float Time; };
RWStructuredBuffer<float> Out : register(u1);
[shader("compute")] [numthreads(8, 1, 1)] void CSMain(uint3 id : SV_DispatchThreadID) { Out[id.x] = Time; }
`
compile := func(src string) *oneshader.Reflection {
res, _ := oneshader.Compile([]byte(src), oneshader.WithTargets(oneshader.TargetSPIRV))
return res.Reflection
}
old := compile(base)
fmt.Println(oneshader.Compatible(old, compile(base+"// a comment\n")))
err := oneshader.Compatible(old, compile(edited))
var inc *oneshader.IncompatibleError
if errors.As(err, &inc) {
fmt.Println(errors.Is(err, oneshader.ErrIncompatible), inc.Differences[0].Kind)
}
}
Output: <nil> true BufferLayout
Example (NilReflection) ¶
package main
import (
"errors"
"fmt"
"recursiveai.org/go/oneshader"
)
func main() {
res, _ := oneshader.Compile([]byte("void f( {"), oneshader.WithTargets(oneshader.TargetSPIRV))
fmt.Println(errors.Is(oneshader.Compatible(res.Reflection, res.Reflection), oneshader.ErrNilReflection))
}
Output: true
func MSLFunctionName ¶
MSLFunctionName returns the MSL function the entry point with the HLSL name gets: the name itself, or with a "0" appended when it is an MSL or C++ reserved word (main becomes main0).
Types ¶
type Blob ¶
type Blob struct {
// Entry is the entry point the blob was compiled for.
Entry string
// Stage is the entry point's pipeline stage.
Stage Stage
// Target is the target format of Data.
Target Target
// Data is the compiled bytes: a SPIR-V module, MSL or WGSL source text, or a DXIL container.
Data []byte
}
Blob is the compiled code of one entry point for one target.
type BuiltIn ¶
type BuiltIn uint8
BuiltIn names a stage built-in variable.
const ( BuiltInNone BuiltIn = iota BuiltInPosition BuiltInFragCoord BuiltInVertexIndex BuiltInInstanceIndex BuiltInFrontFacing BuiltInFragDepth BuiltInSampleIndex BuiltInSampleMask BuiltInPrimitiveIndex BuiltInLayer BuiltInViewportIndex BuiltInClipDistance BuiltInCullDistance BuiltInGlobalInvocationID BuiltInLocalInvocationID BuiltInWorkgroupID BuiltInLocalInvocationIndex BuiltInSubgroupLocalInvocationID BuiltInSubgroupSize )
Built-ins, in the numbering reflection uses.
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache remembers compile results so a tool that recompiles on every file change (hot reload, a watch loop, an editor) only pays for what changed. It is safe for concurrent use; callers asking for the same key at the same moment share one compile, and different keys compile in parallel.
A result is found again when the source, its name and every option that affects the output are equal and every file the compile read through #include still resolves to the same path with the same bytes, and every place an earlier compile searched without finding a file still lacks it. A changed include, a file appearing earlier on the search path or a removed include therefore compiles again, with no timestamps involved. Results, error results included, are kept up to the limit given to NewCache; the least recently used goes first.
The methods take a context first and have no separate context-free form: Cache.Compile is Compile and CompileContext in one, with context.Background() for a caller that never cancels.
The *Result a call returns is shared with other callers of the same key: treat it, its blobs and its reflection as read-only.
Example ¶
package main
import (
"context"
"fmt"
"testing/fstest"
"recursiveai.org/go/oneshader"
)
func main() {
files := fstest.MapFS{
"main.hlsl": {Data: []byte("#include \"a.hlsli\"\nRWStructuredBuffer<uint> Out : register(u0);\n[shader(\"compute\")] [numthreads(1, 1, 1)] void CSMain() { Out[0] = A; }\n")},
"a.hlsli": {Data: []byte("static const uint A = 1u;\n")},
}
cache := oneshader.NewCache(oneshader.DefaultCacheEntries)
ctx := context.Background()
compile := func() *oneshader.Result {
res, _ := cache.CompileFS(ctx, files, "main.hlsl", oneshader.WithTargets(oneshader.TargetSPIRV))
return res
}
first := compile()
fmt.Println("same result again:", compile() == first)
files["a.hlsli"] = &fstest.MapFile{Data: []byte("static const uint A = 2u;\n")} // an edit to an include
fmt.Println("after the include changed:", compile() == first)
fmt.Printf("%+v\n", cache.Stats())
}
Output: same result again: true after the include changed: false {Hits:1 Misses:2}
Example (HotReload) ¶
A hot-reload loop: recompile through a Cache when a file changes, and ask Compatible whether the program can keep its pipeline layouts and buffers or must recreate them.
package main
import (
"context"
"fmt"
"testing/fstest"
"recursiveai.org/go/oneshader"
)
func main() {
const shaderText = `cbuffer Frame : register(b0) { float4 Tint; %s };
RWStructuredBuffer<float> Out : register(u1);
[shader("compute")] [numthreads(8, 1, 1)] void CSMain(uint3 id : SV_DispatchThreadID) { Out[id.x] = Tint.x; }
`
files := fstest.MapFS{}
cache := oneshader.NewCache(0)
ctx := context.Background()
var current *oneshader.Reflection
for _, edit := range []string{"float Time;", "float Time; /* only a comment changed */", "float4 Extra; float Time;"} {
files["main.hlsl"] = &fstest.MapFile{Data: []byte(fmt.Sprintf(shaderText, edit))}
res, err := cache.CompileFS(ctx, files, "main.hlsl", oneshader.WithTargets(oneshader.TargetSPIRV))
if err != nil {
fmt.Println("keep running the old shader:", err)
continue
}
switch {
case current == nil:
fmt.Println("first load")
case oneshader.Compatible(current, res.Reflection) == nil:
fmt.Println("swap the code, keep the layouts")
default:
fmt.Println("recreate the layouts")
}
current = res.Reflection
}
}
Output: first load swap the code, keep the layouts recreate the layouts
func NewCache ¶
NewCache returns a Cache that keeps at most maxEntries results; a value below 1 means DefaultCacheEntries. The zero Cache is ready to use and keeps DefaultCacheEntries too.
func (*Cache) Clear ¶
func (c *Cache) Clear()
Clear drops every kept result. Compiles in progress finish and are kept.
func (*Cache) Compile ¶
Compile is oneshader.Compile through the cache. A cancelled ctx, before the call or while it waits for another caller's compile, returns ctx.Err() and caches nothing; a compile that ctx ends is abandoned at its next check (see CompileContext) and caches nothing either.
func (*Cache) CompileFS ¶
func (c *Cache) CompileFS(ctx context.Context, fsys fs.FS, name string, opts ...Option) (*Result, error)
CompileFS is oneshader.CompileFS through the cache. A file that cannot be read is the diagnostic OSH0003 and is not cached.
func (*Cache) CompileFile ¶
CompileFile is oneshader.CompileFile through the cache. A file that cannot be read is the diagnostic OSH0003 and is not cached.
func (*Cache) Stats ¶
func (c *Cache) Stats() CacheStats
Stats returns the hit and miss counts so far.
type CacheStats ¶
type CacheStats struct {
// Hits counts calls answered from memory, including callers that shared another caller's compile.
Hits uint64
// Misses counts compiles the cache started and finished or abandoned after the start; calls refused
// before any work (a cancelled context, an unreadable main file) count neither.
Misses uint64
}
CacheStats counts what a Cache answered.
type Code ¶
Code is a stable diagnostic code; see diag.Code. The published codes are the diag.Code constants.
type DebugInfo ¶
type DebugInfo uint8
DebugInfo says how much source information blobs carry: SPIR-V debug instructions, MSL #line directives.
type Define ¶
type Define = preprocess.Define
Define is a macro defined before the first line of the source; see the preprocess package.
type Diagnostic ¶
type Diagnostic = diag.Diagnostic
Diagnostic is one message from the compiler; see diag.Diagnostic. Its Code is a stable "OSHnnnn" value (the diag.Code constants).
type DiagnosticsError ¶
type DiagnosticsError struct {
// Diagnostics lists the errors, in the order they were found; Result.Errors returns the same list.
Diagnostics []Diagnostic
// contains filtered or unexported fields
}
DiagnosticsError is the error Compile returns when there are errors in the source. It lists the error diagnostics (not the warnings).
func (*DiagnosticsError) Error ¶
func (e *DiagnosticsError) Error() string
Error implements error: it describes what went wrong.
func (*DiagnosticsError) Is ¶
func (e *DiagnosticsError) Is(target error) bool
Is reports whether the error list holds a limit diagnostic and target is ErrLimit.
func (*DiagnosticsError) Unwrap ¶
func (e *DiagnosticsError) Unwrap() error
Unwrap returns the first I/O error behind the diagnostics: the error reading the main file, or the error an include resolver gave for a file it could not find. errors.Is(err, fs.ErrNotExist) therefore works on a missing file. It is nil when no diagnostic came from I/O.
type Difference ¶
type Difference struct {
// Kind is what differs.
Kind DifferenceKind
// Message names what changed with the old and new values, for example
// "Frame.Tint moved from offset 64 to 80".
Message string
}
Difference is one change that would break code built against the old interface.
func Differences ¶
func Differences(old, updated *Reflection) []Difference
Differences returns what Compatible would report, without wrapping it in an error.
type DifferenceKind ¶
type DifferenceKind uint8
DifferenceKind says which part of a shader's interface a Difference concerns.
const ( // DiffEntryPoint: an entry point of the old shader is gone or has another stage. DiffEntryPoint DifferenceKind = iota + 1 // DiffResource: a resource was added or removed, or its kind, array size, binding or stage visibility // (gaining a stage) changed. DiffResource // DiffBufferLayout: a buffer, push-constant block or texel type has another byte layout or type. DiffBufferLayout // DiffVertexInput: a vertex input of an old vertex entry point was added, removed or moved, or changed // format. DiffVertexInput // DiffWorkgroupSize: an entry point's thread-group size changed. DiffWorkgroupSize // DiffSpecConstant: a specialization constant was removed, or its id or type changed. DiffSpecConstant )
Kinds of interface difference.
func (DifferenceKind) String ¶
func (k DifferenceKind) String() string
String returns the kind's name, such as "BufferLayout".
type EntryPoint ¶
type EntryPoint struct {
// Name is the function name.
Name string
// Stage is the pipeline stage.
Stage Stage
// WorkgroupSize is the compute workgroup size; zero for other stages.
WorkgroupSize [3]uint32
// VertexStride is the byte size of one vertex for a vertex entry.
VertexStride uint32
// Outputs is the stage outputs in declaration order.
Inputs, Outputs []StageVariable
UsedResources []string // names of the resources it reads or writes, in declaration order
PushConstant string // name of the push-constant block it uses, "" when none
// UsedSpecConstants lists the names of the specialization constants it reads.
UsedSpecConstants []string
// RequiredFeatures is the device features it needs.
RequiredFeatures Features
// SubgroupOperations is the subgroup operations it uses.
SubgroupOperations SubgroupOps
// DescriptorHeaps is the descriptor heaps it indexes.
DescriptorHeaps Heap
}
EntryPoint is one shader entry point.
func (*EntryPoint) UsesSubgroups ¶
func (e *EntryPoint) UsesSubgroups() bool
UsesSubgroups reports whether the entry point uses any subgroup (wave) operation.
type EntryRequest ¶
type EntryRequest struct {
// Name is the function to compile.
Name string
// Stage is the pipeline stage. Its zero value is StageVertex, a valid stage, so an EntryRequest that
// leaves it unset asks for a vertex entry point; a value that is not a Stage constant is rejected.
Stage Stage
}
EntryRequest names a function to compile as an entry point of the given stage.
type Features ¶
Features lists device capabilities a compiled entry point needs; see shader.Features.
type Heap ¶
Heap says which descriptor heaps ResourceDescriptorHeap and SamplerDescriptorHeap an entry reads, or which one a bindless resource comes from; see shader.Heap.
type HeapBinding ¶
type HeapBinding struct {
// Binding is the descriptor binding and Set the descriptor set.
Binding, Set int
}
HeapBinding is the Vulkan descriptor set and binding of a descriptor heap array.
type IncludeFile ¶
type IncludeFile = preprocess.IncludeFile
IncludeFile is a file an IncludeResolver found; see the preprocess package.
type IncludeRequest ¶
type IncludeRequest = preprocess.IncludeRequest
IncludeRequest asks an IncludeResolver for a file; see the preprocess package.
type IncludeResolver ¶
type IncludeResolver = preprocess.IncludeResolver
IncludeResolver finds the files an #include names; see the preprocess package.
type IncompatibleError ¶
type IncompatibleError struct {
// Differences lists every difference found, in a stable order.
Differences []Difference
}
IncompatibleError lists the differences Compatible found, in the order of the old reflection's lists.
func (*IncompatibleError) Error ¶
func (e *IncompatibleError) Error() string
Error lists every difference, one per line after the first.
func (*IncompatibleError) Is ¶
func (e *IncompatibleError) Is(target error) bool
Is reports whether target is ErrIncompatible.
type Interpolation ¶
type Interpolation = layout.Interpolation
Interpolation is how a stage variable is interpolated.
type Limits ¶
type Limits struct {
// MaxIncludeDepth is the deepest chain of nested #include directives (default 64). The main file is
// depth 0; an include that would make the chain longer than the limit is OSH0122. A negative value allows
// no include at all (the first one is OSH0122).
MaxIncludeDepth int
// MaxIncludeCount is the most files one compile may open through #include, counting repeats
// (default 4096; a negative value allows none). Exceeding it is OSH0128.
MaxIncludeCount int
// MaxExpansionSteps bounds the tokens the macro expander handles in one compile (default 5,000,000).
// Exceeding it is OSH0128.
MaxExpansionSteps int
// MaxOutputTokens bounds the tokens the preprocessor returns (default 2,000,000). Exceeding it is
// OSH0128.
MaxOutputTokens int
// MaxMacroNesting bounds how deeply macro expansions nest, through replacement lists and
// arguments (default 128). Exceeding it is OSH0127.
MaxMacroNesting int
// MaxNesting bounds the nesting of blocks, parentheses, brackets, namespaces and template argument
// lists in the parser (default 256). Exceeding it is OSH0203.
MaxNesting int
// MaxErrors is the number of errors kept before the compiler adds OSH0004 and drops the rest
// (default 100).
MaxErrors int
// MaxIRInstructions bounds the instructions of the lowered program, all functions together (default
// 500,000). Exceeding it is OSH0353.
MaxIRInstructions int
// MaxTemplateInstantiations bounds the distinct template instantiations of one compile (default
// 100,000). Exceeding it is OSH0353.
MaxTemplateInstantiations int
// MaxArrayBytes bounds the size in bytes of one array, all dimensions together, and of one struct
// (default 1 GiB). Exceeding it is OSH0353.
MaxArrayBytes int64
}
Limits bounds what untrusted HLSL can make the compiler do. A zero field means its default, and limits cannot be switched off. A negative field also means the default, except MaxIncludeCount and MaxIncludeDepth where a negative value means no include is allowed.
func (Limits) WithDefaults ¶
WithDefaults returns l with every unset field replaced by its default. In the result MaxIncludeCount and MaxIncludeDepth are never negative (0 then means no includes).
type Option ¶
type Option func(*config)
Option configures Compile.
func WithDXILPixelPosition ¶
WithDXILPixelPosition makes the DXIL target list SV_Position as the first input of every pixel entry point whose shader does not declare it, so the interpolants sit in the registers after it, where a vertex shader that writes SV_Position leaves them. Direct3D 12 refuses a vertex and pixel pair whose registers for a semantic differ ("mismatched hardware registers"), which is what a pixel shader without SV_Position gets otherwise; DXC's output has the same problem. The default, false, writes what DXC does. A pixel shader that declares SV_Position, and the other targets, are unaffected.
Example ¶
A pixel shader that leaves out SV_Position gets different registers for its interpolants than the vertex shader writes them in, which Direct3D 12 refuses to link. WithDXILPixelPosition lists the position first in its input signature so the stages agree; the default writes what DXC does.
package main
import (
"bytes"
"fmt"
"recursiveai.org/go/oneshader"
)
func main() {
const src = `
struct VO { float4 pos : SV_Position; float4 color : COLOR0; };
[shader("vertex")] VO VSMain(float4 p : POSITION, float4 c : COLOR0) { VO o; o.pos = p; o.color = c; return o; }
[shader("pixel")] float4 PSMain(float4 color : COLOR0) : SV_Target { return color; }
`
pixel := func(opts ...oneshader.Option) []byte {
opts = append(opts, oneshader.WithName("link.hlsl"), oneshader.WithTargets(oneshader.TargetDXIL))
res, err := oneshader.Compile([]byte(src), opts...)
if err != nil {
panic(err)
}
b, _ := res.Find("PSMain", oneshader.TargetDXIL)
return b.Data
}
fmt.Println("same container:", bytes.Equal(pixel(), pixel(oneshader.WithDXILPixelPosition(true))))
}
Output: same container: false
func WithDXILShaderModel ¶
WithDXILShaderModel sets the minor version of shader model 6 the DXIL target writes (6.minor, 0 to 8). The default, 0, picks for each entry point the lowest model that has every feature it uses. A model too low for the shader is an error diagnostic naming the feature that needs more; a minor above 8 or below 0 is an error. Other targets ignore it.
func WithDebugInfo ¶
WithDebugInfo sets the source information carried by blobs (default DebugNone). For MSL, DebugLines and DebugFull both add #line directives.
func WithDebugSourceRoot ¶
WithDebugSourceRoot sets the folder file names in debug information are made relative to, written with '/' separators. A path under no root becomes its file name; with no root a relative path keeps its spelling and an absolute path becomes its file name, so no machine path reaches generated code.
func WithDefine ¶
WithDefine defines the macro name as value before the first line, like a -D option. An empty value defines it as empty. A name with a parameter list, "SQ(x)", defines a function-like macro. Defines apply in order and replace earlier ones and the predefined macros.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneshader"
)
func main() {
res, _ := oneshader.Compile([]byte("#ifdef FAST\nint fast;\n#else\nint = ;\n#endif\n"), oneshader.WithDefine("FAST", "1"))
fmt.Println(res.Success())
}
Output: true
func WithDefines ¶
WithDefines adds several defines at once.
func WithEnable16BitTypes ¶
WithEnable16BitTypes allows int16_t, uint16_t and float16_t and stores half and the min-precision types in 16 bits (DXC's -enable-16bit-types). Without it the 16-bit type names are error OSH0360 and half is a 32-bit type.
func WithEntryPoints ¶
func WithEntryPoints(eps ...EntryRequest) Option
WithEntryPoints replaces discovery by [shader(...)] attributes: exactly the listed functions are compiled, each with the given stage, whether or not they carry the attribute. A name the file does not define is the error OSH0320; a stage that is not one of the Stage constants, or an empty name, is OSH0005. Blobs and reflection list entry points in source order, not list order.
Example ¶
Name the entry points to compile instead of marking them with [shader(...)].
package main
import (
"fmt"
"recursiveai.org/go/oneshader"
)
func main() {
src := `
RWStructuredBuffer<uint> Out : register(u0);
[numthreads(8, 1, 1)]
void Fill(uint3 id : SV_DispatchThreadID) { Out[id.x] = 1; }
`
res, err := oneshader.Compile([]byte(src),
oneshader.WithTargets(oneshader.TargetSPIRV),
oneshader.WithEntryPoints(oneshader.EntryRequest{Name: "Fill", Stage: oneshader.StageCompute}))
if err != nil {
fmt.Println(err)
return
}
for _, e := range res.Reflection.EntryPoints {
fmt.Println(e.Name, e.Stage, e.WorkgroupSize)
}
}
Output: Fill Compute [8 1 1]
func WithHLSLVersion ¶
WithHLSLVersion sets the value of __HLSL_VERSION (default 2021; 0 means the default). A negative version is the error OSH0005.
func WithIncludeDirs ¶
WithIncludeDirs adds include directories to the lookup CompileFile and WithIncludeFS use.
func WithIncludeFS ¶
WithIncludeFS resolves #include through fsys: a quoted include looks in the including file's folder first, then in dirs in order (paths inside fsys); an angled include tries dirs first. WithIncludeFS replaces an earlier WithIncludeResolver and the reverse.
Example ¶
package main
import (
"fmt"
"testing/fstest"
"recursiveai.org/go/oneshader"
)
func main() {
fsys := fstest.MapFS{"lib/consts.hlsli": {Data: []byte("#define SIZE 8\n")}}
res, err := oneshader.Compile([]byte("#include \"consts.hlsli\"\nstatic const int n = SIZE;\n"),
oneshader.WithIncludeFS(fsys, "lib"))
fmt.Println(err, res.Files)
}
Output: <nil> [main.hlsl lib/consts.hlsli]
func WithIncludeResolver ¶
func WithIncludeResolver(r IncludeResolver) Option
WithIncludeResolver resolves #include through r, which replaces the standard lookup entirely.
func WithKeepNames ¶
WithKeepNames chooses whether blobs keep the shader's own names (the default, true) or replace them with generated ones: SPIR-V names types, variables, functions and members (OpName, OpMemberName), and the WGSL and MSL targets keep the names of structures, members, resources and local variables. Entry function names are always kept, except where WGSL reserves them (see the wgsl package). Reflection and behaviour do not depend on it. Other targets ignore it.
func WithLimits ¶
WithLimits sets the limits on untrusted input; zero fields keep their defaults.
Example ¶
package main
import (
"errors"
"fmt"
"recursiveai.org/go/oneshader"
)
func main() {
_, err := oneshader.Compile([]byte("int x = ((((((1))))));"), oneshader.WithLimits(oneshader.Limits{MaxNesting: 3}))
fmt.Println(errors.Is(err, oneshader.ErrLimit))
}
Output: true
func WithMatrixPacking ¶
func WithMatrixPacking(p layout.MatrixPacking) Option
WithMatrixPacking sets the packing of matrices that have no row_major or column_major qualifier. The default is layout.ColumnMajor, as in HLSL.
func WithName ¶
WithName sets the name of the main source, used in diagnostics and as the base folder of quoted includes. The default is "main.hlsl". CompileFile and CompileFS set it from the path.
func WithOptimize ¶
WithOptimize switches the IR optimizer on (the default) or off. Blobs from either setting behave the same.
Example ¶
Turn the optimizer off, for a shader that is easier to read next to its source.
package main
import (
"fmt"
"recursiveai.org/go/oneshader"
)
func main() {
src := `
RWStructuredBuffer<uint> Out : register(u0);
[shader("compute")] [numthreads(1, 1, 1)]
void CSMain() { uint a = 1; Out[0] = a + 2; }
`
size := func(on bool) int {
res, err := oneshader.Compile([]byte(src), oneshader.WithTargets(oneshader.TargetSPIRV), oneshader.WithOptimize(on))
if err != nil {
panic(err)
}
return len(res.Blobs[0].Data)
}
fmt.Println(size(true) < size(false))
}
Output: true
func WithResourceHeapBinding ¶
WithResourceHeapBinding places ResourceDescriptorHeap at the given Vulkan binding and set. Without it the heap takes the first free binding of set 0. A negative binding or set is the error OSH0005.
func WithSPIRVVersion ¶
WithSPIRVVersion marks the compile as a Vulkan SPIR-V compile of SPIR-V 1.minor, which defines __spirv__, __SPIRV_MAJOR_VERSION__ and __SPIRV_MINOR_VERSION__. A minor outside 0 to 6 is the error OSH0005.
func WithSamplerHeapBinding ¶
WithSamplerHeapBinding places SamplerDescriptorHeap at the given Vulkan binding and set, like WithResourceHeapBinding.
func WithSpecConstant ¶
WithSpecConstant fixes the specialization constant name to value, so the compiled shader has a plain constant in its place and reflection no longer lists it. value must fit the constant's type (a bool takes 0 or 1, an int or uint a whole number in range, a float a finite 32-bit value) or the compile fails with OSH0335; a name the file has no constant of is the warning OSH0335 (names are case-sensitive). Later calls for the same name win.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneshader"
)
func main() {
src := []byte(`[[vk::constant_id(1)]] const uint Tile = 8;
RWStructuredBuffer<uint> o;
[shader("compute")] [numthreads(1, 1, 1)] void CS() { o[0] = Tile; }`)
open, _ := oneshader.Compile(src, oneshader.WithTargets(oneshader.TargetSPIRV))
fixed, _ := oneshader.Compile(src, oneshader.WithTargets(oneshader.TargetSPIRV), oneshader.WithSpecConstant("Tile", 16))
fmt.Println(len(open.Reflection.SpecConstants), len(fixed.Reflection.SpecConstants))
}
Output: 1 0
func WithTargetProfile ¶
WithTargetProfile sets a shader profile such as "cs_6_6", which defines __SHADER_TARGET_STAGE, __SHADER_TARGET_MAJOR and __SHADER_TARGET_MINOR.
func WithTargets ¶
WithTargets selects the output formats: one blob per entry point and target, in Result.Blobs. A value that is not a Target is the error OSH0002. Without WithTargets the compile checks the source (parse and semantic analysis) and produces no blobs and no reflection.
Example (Dxil) ¶
Compile to DXIL: a container for Direct3D 12, one per entry point.
package main
import (
"fmt"
"recursiveai.org/go/oneshader"
)
func main() {
src := `
RWStructuredBuffer<uint> Out : register(u0);
[shader("compute")] [numthreads(64, 1, 1)]
void CSMain(uint3 id : SV_DispatchThreadID) { Out[id.x] = id.x * 2; }
`
res, err := oneshader.Compile([]byte(src), oneshader.WithTargets(oneshader.TargetDXIL), oneshader.WithDXILShaderModel(6))
if err != nil {
fmt.Println(err)
return
}
b := res.Blobs[0]
fmt.Println(b.Entry, b.Target, string(b.Data[:4]))
}
Output: CSMain dxil DXBC
Example (Msl) ¶
Compile HLSL to Metal Shading Language and read back the function Metal sees.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/oneshader"
)
func main() {
src := `
RWStructuredBuffer<uint> Out : register(u0);
[shader("compute")] [numthreads(64, 1, 1)]
void CSMain(uint3 id : SV_DispatchThreadID) { Out[id.x] = id.x * 2; }
`
res, err := oneshader.Compile([]byte(src), oneshader.WithTargets(oneshader.TargetMSL))
if err != nil {
fmt.Println(err)
return
}
for _, b := range res.Blobs {
text := string(b.Data)
fmt.Println(b.Entry, b.Stage, b.Target)
fmt.Println(strings.Contains(text, "kernel void "+oneshader.MSLFunctionName(b.Entry)+"("))
fmt.Println(strings.Contains(text, "device Out_buffer_mem& Out [[buffer(0)]]"))
}
}
Output: CSMain Compute msl true true
Example (Wgsl) ¶
Compile to WGSL: the text goes to a WebGPU shader module.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/oneshader"
)
func main() {
src := `
RWStructuredBuffer<uint> Out : register(u0);
[shader("compute")] [numthreads(64, 1, 1)]
void CSMain(uint3 id : SV_DispatchThreadID) { Out[id.x] = id.x * 2; }
`
res, err := oneshader.Compile([]byte(src), oneshader.WithTargets(oneshader.TargetWGSL))
if err != nil {
fmt.Println(err)
return
}
text := string(res.Blobs[0].Data)
fmt.Println(res.Blobs[0].Target)
fmt.Println(strings.Contains(text, "@compute @workgroup_size(64, 1, 1)"))
}
Output: wgsl true
type PushConstant ¶
type PushConstant struct {
// Name is the block name.
Name string
// Stages is the stages that use the block.
Stages StageSet
// Slots says where each selected target binds the block.
Slots []Slot
// Layout is the block's byte layout.
Layout *ReflectedType
}
PushConstant is the push-constant block of the shader.
type ReflectedMember ¶
type ReflectedMember struct {
// Name is the member name.
Name string
// Offset is the byte offset from the start of the struct.
Offset uint32
// Type is the member's type.
Type *ReflectedType
}
ReflectedMember is a struct member at a byte offset.
type ReflectedType ¶
type ReflectedType struct {
// Kind is the shape of the type.
Kind TypeKind
Scalar layout.ScalarKind // Scalar, Vector, Matrix: the element type
Components uint32 // Vector: the component count
Rows, Cols uint32 // Matrix: HLSL rows and columns
Name string // Struct
// Size is the size in bytes.
Size uint32
// Alignment is the alignment in bytes.
Alignment uint32
ArrayLength uint32 // Array; 0 for a runtime-sized array
// ArrayStride: Array: the byte distance between elements.
ArrayStride uint32
// MatrixStride: Matrix: the byte distance between rows or columns, as Packing says.
MatrixStride uint32
// ElementBytes: Matrix: the bytes one element takes when that is not 4 (2 for 16-bit types, 8 for 64-bit
// types); 0 means 4.
ElementBytes uint32
// Packing: Matrix: how the matrix is stored.
Packing layout.MatrixPacking
Element *ReflectedType // Array
// Members: Struct: the members in declaration order.
Members []ReflectedMember
}
ReflectedType is a buffer type with its byte layout, equal on every target.
func ReflectedTypeFromLayout ¶
func ReflectedTypeFromLayout(l *layout.Layout) *ReflectedType
ReflectedTypeFromLayout describes l, a layout computed with layout.Compute, the way reflection describes a buffer's element type: kind, size, alignment, member offsets, array and matrix strides. Whether half-precision types are 16 bits wide is the layout's own Enable16BitTypes.
Example ¶
ReflectedTypeFromLayout describes a type the way reflection describes a buffer element, for code that builds layouts itself.
package main
import (
"fmt"
"recursiveai.org/go/oneshader"
"recursiveai.org/go/oneshader/layout"
)
func main() {
t := layout.Array(layout.Vector(layout.Scalar(layout.Float), 3), 4)
l, err := layout.Compute(t, layout.RulesStorage, layout.Options{})
if err != nil {
fmt.Println(err)
return
}
r := oneshader.ReflectedTypeFromLayout(l)
fmt.Println(r.Kind, r.Size, r.ArrayLength, r.ArrayStride, r.Element.Kind, r.Element.Components)
}
Output: Array 64 4 16 Vector 3
type Reflection ¶
type Reflection struct {
// SourceName is the name the compile was given.
SourceName string
// Targets is the targets the compile selected.
Targets []Target
// Resources lists every texture, sampler and buffer binding.
Resources []Resource
// PushConstants is the push-constant blocks.
PushConstants []PushConstant
// SpecConstants is the specialization constants.
SpecConstants []SpecConstant
EntryPoints []EntryPoint
}
Reflection describes a compiled shader's interface. Every list is in source order; Targets is in the order the compile selected them.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneshader"
)
const flowShader = `
cbuffer Params : register(b0) { float4 Scale; };
RWStructuredBuffer<float4> Data : register(u1);
[shader("compute")] [numthreads(64, 1, 1)]
void Scale4(uint3 id : SV_DispatchThreadID) { Data[id.x] = Data[id.x] * Scale; }
`
func main() {
res, _ := oneshader.Compile([]byte(flowShader), oneshader.WithTargets(oneshader.TargetSPIRV))
r := res.Reflection
for _, rs := range r.Resources {
fmt.Println(rs.Name, rs.Kind, rs.Slots[0].Set, rs.Slots[0].Binding)
}
ep := r.EntryPoints[0]
fmt.Println(ep.Name, ep.WorkgroupSize, ep.UsedResources)
}
Output: Params ConstantBuffer 0 0 Data StorageBuffer 0 1 Scale4 [64 1 1] [Params Data]
func ParseReflection ¶
func ParseReflection(data []byte) (*Reflection, error)
ParseReflection reads the text WriteTo writes. It rejects a document with another version, a missing or malformed header, or a malformed known record, with an error that wraps ErrReflectionFormat; unknown records and unknown attributes are ignored so newer writers stay readable. Nesting is bounded.
func ReadReflection ¶
func ReadReflection(rd io.Reader) (*Reflection, error)
ReadReflection reads all of rd and parses it with ParseReflection.
func (*Reflection) AppendJSON ¶
func (r *Reflection) AppendJSON(b []byte) []byte
AppendJSON appends the schema-version-1 JSON document `oneshader --reflect` writes, indented and without a final newline, to b. The bytes depend only on the reflection, so equal reflections give equal documents.
Example ¶
The JSON document is the form `oneshader --reflect` writes; encoding/json reads it back.
package main
import (
"encoding/json"
"fmt"
"recursiveai.org/go/oneshader"
)
const flowShader = `
cbuffer Params : register(b0) { float4 Scale; };
RWStructuredBuffer<float4> Data : register(u1);
[shader("compute")] [numthreads(64, 1, 1)]
void Scale4(uint3 id : SV_DispatchThreadID) { Data[id.x] = Data[id.x] * Scale; }
`
func main() {
res, _ := oneshader.Compile([]byte(flowShader), oneshader.WithTargets(oneshader.TargetSPIRV))
doc := res.Reflection.AppendJSON(nil)
var back oneshader.Reflection
err := json.Unmarshal(doc, &back)
fmt.Println(err, back.Equal(res.Reflection))
}
Output: <nil> true
func (*Reflection) AppendText ¶
func (r *Reflection) AppendText(b []byte) []byte
AppendText appends the text WriteTo writes to b.
func (*Reflection) EntryLayout ¶
func (r *Reflection) EntryLayout(entry string) (*pipeline.EntryLayout, error)
EntryLayout returns the pipeline-layout description of an entry point: the resources it uses with their slots, texture dimensions and Metal indices, its push-constant block with the type of every member, its vertex input, workgroup size, required features and specialization constants. It fails with pipeline.UnknownEntryPoint when the shader has no such entry point and pipeline.IncompleteReflection when a used resource has no SPIR-V or WGSL slot.
Example ¶
A renderer needs descriptor set layouts, not reflection; the pipeline package converts.
package main
import (
"fmt"
"recursiveai.org/go/oneshader"
"recursiveai.org/go/oneshader/pipeline"
)
const flowShader = `
cbuffer Params : register(b0) { float4 Scale; };
RWStructuredBuffer<float4> Data : register(u1);
[shader("compute")] [numthreads(64, 1, 1)]
void Scale4(uint3 id : SV_DispatchThreadID) { Data[id.x] = Data[id.x] * Scale; }
`
func main() {
res, _ := oneshader.Compile([]byte(flowShader), oneshader.WithTargets(oneshader.TargetSPIRV))
entry, err := res.Reflection.EntryLayout("Scale4")
if err != nil {
fmt.Println(err)
return
}
l, err := pipeline.New(entry)
if err != nil {
fmt.Println(err)
return
}
vk := l.Vulkan(pipeline.VulkanOptions{})
for _, set := range vk.SetLayouts {
for _, b := range set.Bindings {
fmt.Println(set.Set, b.Binding, b.Name, b.DescriptorType)
}
}
}
Output: 0 0 Params 6 0 1 Data 7
func (*Reflection) Equal ¶
func (r *Reflection) Equal(o *Reflection) bool
Equal reports whether two reflections describe the same interface, that is whether they write the same text.
func (*Reflection) MarshalJSON ¶
func (r *Reflection) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler: the schema-version-1 JSON document in compact form, which is what encoding/json writes for a Reflection. AppendJSON gives the indented, byte-stable form.
func (*Reflection) MarshalText ¶
func (r *Reflection) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler with the same text WriteTo writes.
func (*Reflection) SpecLayouts ¶
func (r *Reflection) SpecLayouts() []pipeline.SpecConstant
SpecLayouts returns every specialization constant of the shader by increasing id, as a pipeline layout sees them.
func (*Reflection) UnmarshalJSON ¶
func (r *Reflection) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler for the schema-version-1 document AppendJSON writes. It rejects other schema versions, unknown enum names and layouts nested deeper than 64 levels with an error that wraps ErrReflectionFormat, and ignores unknown keys.
func (*Reflection) UsesSubgroups ¶
func (r *Reflection) UsesSubgroups() bool
UsesSubgroups reports whether any entry point uses a subgroup (wave) operation.
func (*Reflection) WriteTo ¶
func (r *Reflection) WriteTo(w io.Writer) (int64, error)
WriteTo writes the reflection in its line-based text form: UTF-8, "\n" line ends, one record per line, declaration order, nothing machine-specific. Equal reflections give identical bytes.
Example ¶
A reflection is plain text: write it next to the blobs, read it back later without the compiler.
package main
import (
"bytes"
"fmt"
"recursiveai.org/go/oneshader"
)
const flowShader = `
cbuffer Params : register(b0) { float4 Scale; };
RWStructuredBuffer<float4> Data : register(u1);
[shader("compute")] [numthreads(64, 1, 1)]
void Scale4(uint3 id : SV_DispatchThreadID) { Data[id.x] = Data[id.x] * Scale; }
`
func main() {
res, _ := oneshader.Compile([]byte(flowShader), oneshader.WithTargets(oneshader.TargetSPIRV))
var buf bytes.Buffer
if _, err := res.Reflection.WriteTo(&buf); err != nil {
fmt.Println(err)
return
}
back, err := oneshader.ReadReflection(&buf)
fmt.Println(err, back.Equal(res.Reflection))
}
Output: <nil> true
type ResolverFunc ¶
type ResolverFunc = preprocess.ResolverFunc
ResolverFunc adapts a function to IncludeResolver.
type Resource ¶
type Resource struct {
// Name is the resource name.
Name string
// Kind is the resource kind.
Kind ResourceKind
HLSLType string // the declared HLSL type, e.g. "Texture2D<float4>"
Count uint32 // array size; 0 for an unbounded array
// Stages is the stages that use the resource.
Stages StageSet
// Slots has one slot per selected target. The Dxil slot holds the register space (Set) and register (Binding) of
// the resource in the DXIL container. A descriptor heap that DXIL splits by element type has one Dxil slot per
// range, each in its own register space.
Slots []Slot
// CounterSlots are where the hidden counter of an Append/ConsumeStructuredBuffer binds.
CounterSlots []Slot
// ImageFormat is the declared storage-image format, "" when none.
ImageFormat string
// Heap is which descriptor heap the resource is indexed from, if any.
Heap Heap
HeapKinds []ResourceKind // for a heap: the kinds it was indexed as
Layout *ReflectedType // buffer element or constant-buffer block; nil for textures and samplers
}
Resource is a texture, sampler or buffer binding.
func (*Resource) ResourceType ¶
ResourceType returns the HLSL resource type without template arguments ("Texture2D" for "Texture2D<float4>"). A constant buffer declared with cbuffer has no HLSL type text and reports "ConstantBuffer".
type ResourceKind ¶
type ResourceKind = shader.ResourceKind
ResourceKind is the binding class of a resource, which is how a host creates its bind-group layout entry; see shader.ResourceKind.
type Result ¶
type Result struct {
// Diagnostics lists every error, warning and note in the order they were found.
Diagnostics []Diagnostic
// Files lists the files read: the main file first, then includes in the order first opened.
Files []string
// Blobs holds the compiled code, one per entry point and target, entry points in source order.
Blobs []Blob
// Reflection describes the shader's interface; nil unless a target was selected and the compile succeeded.
Reflection *Reflection
// contains filtered or unexported fields
}
Result is what a compile produced. It is never nil, also when the compile failed: Diagnostics says why.
func Compile ¶
Compile compiles HLSL source. The returned Result is never nil; the error is nil when the source has no errors and otherwise a *DiagnosticsError listing them (match limits with errors.Is(err, ErrLimit)).
Compile runs the preprocessor, the parser, semantic analysis and, for each target WithTargets selects, the optimizer and the code generator. #include needs WithIncludeFS or WithIncludeResolver; without either every include is an error. Compile is safe for concurrent use: it keeps no state between calls. CompileContext adds cancellation.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneshader"
)
func main() {
src := []byte("float4 main(float4 p : POSITION) : SV_Position { return p; }")
res, err := oneshader.Compile(src)
fmt.Println(err, res.Success())
}
Output: <nil> true
Example (Errors) ¶
package main
import (
"errors"
"fmt"
"recursiveai.org/go/oneshader"
)
func main() {
_, err := oneshader.Compile([]byte("void f() { int x = ; }"), oneshader.WithName("shader.hlsl"))
var de *oneshader.DiagnosticsError
if errors.As(err, &de) {
fmt.Println(de.Diagnostics[0])
}
}
Output: shader.hlsl(1,20): error OSH0201: expected an expression here, found ';'
func CompileContext ¶
CompileContext is Compile with a context: when ctx ends the compile stops at its next check (every few hundred tokens, statements or functions, and between phases and targets) and returns ctx.Err() with a Result that holds the files read so far and no blobs or reflection. Compile is CompileContext with context.Background().
Example ¶
package main
import (
"context"
"errors"
"fmt"
"recursiveai.org/go/oneshader"
)
const flowShader = `
cbuffer Params : register(b0) { float4 Scale; };
RWStructuredBuffer<float4> Data : register(u1);
[shader("compute")] [numthreads(64, 1, 1)]
void Scale4(uint3 id : SV_DispatchThreadID) { Data[id.x] = Data[id.x] * Scale; }
`
func main() {
ctx, cancel := context.WithCancel(context.Background())
cancel() // a build that was interrupted
_, err := oneshader.CompileContext(ctx, []byte(flowShader), oneshader.WithTargets(oneshader.TargetSPIRV))
fmt.Println(errors.Is(err, context.Canceled))
}
Output: true
func CompileFS ¶
CompileFS compiles the file name in fsys, resolving includes in the same file system.
func CompileFSContext ¶
func CompileFSContext(ctx context.Context, fsys fs.FS, name string, opts ...Option) (*Result, error)
CompileFSContext is CompileFS with a context; see CompileContext.
func CompileFile ¶
CompileFile compiles the file at path. Quoted includes resolve against the file's folder, then against the directories given by WithIncludeDirs; diagnostics name files by the paths used here, with '/'.
func CompileFileContext ¶
CompileFileContext is CompileFile with a context; see CompileContext.
func (*Result) Errors ¶
func (r *Result) Errors() []Diagnostic
Errors returns the error diagnostics of the compile, in the order they were found: the list a *DiagnosticsError carries. It is empty when the compile succeeded.
func (*Result) Find ¶
Find returns the blob of the entry point with exactly this name for target. Names are case-sensitive.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneshader"
)
const flowShader = `
cbuffer Params : register(b0) { float4 Scale; };
RWStructuredBuffer<float4> Data : register(u1);
[shader("compute")] [numthreads(64, 1, 1)]
void Scale4(uint3 id : SV_DispatchThreadID) { Data[id.x] = Data[id.x] * Scale; }
`
func main() {
res, err := oneshader.Compile([]byte(flowShader), oneshader.WithTargets(oneshader.TargetSPIRV, oneshader.TargetWGSL))
if err != nil {
fmt.Println(err)
return
}
spirv, _ := res.Find("Scale4", oneshader.TargetSPIRV)
_, hasMSL := res.Find("Scale4", oneshader.TargetMSL)
fmt.Println(spirv.Entry, spirv.Stage, spirv.Target, spirv.Data[0] == 0x03 && spirv.Data[3] == 0x07, hasMSL)
}
Output: Scale4 Compute spirv true false
type Severity ¶
Severity is how serious a diagnostic is; see diag.Severity.
type Slot ¶
type Slot struct {
// Target is the target the slot is for.
Target Target
// Set is the descriptor set, or WGSL group.
Set uint32
// Binding is the binding number or index.
Binding uint32
}
Slot is where a target binds a resource, push-constant block or specialization constant. For SPIR-V Set and Binding are the Vulkan descriptor set and binding; each other target documents its own use of the two numbers (MSL: Set 0 and Binding the argument index; WGSL: group and binding).
type SpecConstant ¶
type SpecConstant struct {
// Name is the constant name.
Name string
// ID is the [[vk::constant_id]] value.
ID uint32
// Scalar is the scalar type.
Scalar layout.ScalarKind
// DefaultBits is the default value as 32 bits.
DefaultBits uint32
// Slots says where each selected target takes the constant.
Slots []SpecSlot
}
SpecConstant is a specialization constant ([[vk::constant_id]]).
type SpecSlot ¶
type SpecSlot struct {
// Target is the target the slot is for.
Target Target
// Index is the constant id or index the target uses.
Index uint32
// Name is the name the target gives the constant.
Name string
}
SpecSlot is where a target takes a specialization constant.
type Stage ¶
Stage is a pipeline stage of an entry point; see shader.Stage. The zero Stage is StageVertex, a valid stage: leave no Stage field unset by accident.
type StageVariable ¶
type StageVariable struct {
// Name is the variable name.
Name string
// Semantic is the semantic without its index, upper case.
Semantic string
// SemanticIndex is the number at the end of the semantic, 0 when none.
SemanticIndex uint32
Location int // -1 when the variable has none (a built-in)
// BuiltIn is the built-in the variable is, if any.
BuiltIn BuiltIn
// Scalar is the component type.
Scalar layout.ScalarKind
// Components is the component count.
Components uint32
Format shader.VertexFormat // a vertex input's vertex format name ("float32x3"), "" otherwise
Offset uint32 // a vertex input's byte offset in its vertex
Interpolation Interpolation
}
StageVariable is an entry point's input or output.
type SubgroupOps ¶
type SubgroupOps = shader.SubgroupOps
SubgroupOps lists the classes of subgroup operations an entry point uses; see shader.SubgroupOps.
type Target ¶
Target is an output format; see shader.Target, which defines it for the generated code too. Targets are numbered from zero, so the zero Target is TargetSPIRV; a value of NumTargets or more is not a target.
func ParseTarget ¶
ParseTarget returns the target spelled "spirv", "msl", "wgsl", "ir" or "dxil"; see shader.ParseTarget.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
oneshader
command
Command oneshader compiles HLSL to SPIR-V, MSL and WGSL and writes Go bindings for it.
|
Command oneshader compiles HLSL to SPIR-V, MSL and WGSL and writes Go bindings for it. |
|
Package diag defines the diagnostics every compiler stage reports: positions, severities, stable codes and the Bag that collects them with a cap, so hostile input cannot grow the list without bound.
|
Package diag defines the diagnostics every compiler stage reports: positions, severities, stable codes and the Bag that collects them with a cap, so hostile input cannot grow the list without bound. |
|
Package dxil writes DXIL containers for Direct3D 12 from the intermediate representation: one container per entry point, shader model 6.0 to 6.8, with the resource bindings of each in its Entry.
|
Package dxil writes DXIL containers for Direct3D 12 from the intermediate representation: one container per entry point, shader model 6.0 to 6.8, with the resource bindings of each in its Entry. |
|
examples
|
|
|
particles
Package particles shows the Go bindings oneshader generates: structs laid out to the shader's byte layout, binding variables and the compiled entry points.
|
Package particles shows the Go bindings oneshader generates: structs laid out to the shader's byte layout, binding variables and the compiled entry points. |
|
Package gen writes Go bindings for compiled HLSL: one struct per constant buffer, push-constant block, structured-buffer element and vertex input, laid out to the shader's byte layout; binding constants; the entry points as shader.Entry values; and the compiled blobs, embedded with go:embed.
|
Package gen writes Go bindings for compiled HLSL: one struct per constant buffer, push-constant block, structured-buffer element and vertex input, laid out to the shader's byte layout; binding constants; the entry points as shader.Entry values; and the compiled blobs, embedded with go:embed. |
|
internal
|
|
|
cli
Package cli implements the oneshader command: "gen" writes Go bindings for HLSL files, "compile" is a DXC-style command line.
|
Package cli implements the oneshader command: "gen" writes Go bindings for HLSL files, "compile" is a DXC-style command line. |
|
core
Package core holds what the compiler packages share and the public packages must not expose: the default limits and the UTF-16 position converter.
|
Package core holds what the compiler packages share and the public packages must not expose: the default limits and the UTF-16 position converter. |
|
lower
Package lower turns the checked syntax tree of internal/sema into an ir.Module.
|
Package lower turns the checked syntax tree of internal/sema into an ir.Module. |
|
sema
Package sema checks a parsed HLSL file: it resolves names, types and overloads, evaluates constants, validates attributes, semantics, bindings and layouts, and records what it found next to the syntax tree in Info, which the lowering to the IR reads.
|
Package sema checks a parsed HLSL file: it resolves names, types and overloads, evaluates constants, validates attributes, semantics, bindings and layouts, and records what it found next to the syntax tree in Info, which the lowering to the IR reads. |
|
Package ir is the typed intermediate representation between the HLSL front end and the code generators.
|
Package ir is the typed intermediate representation between the HLSL front end and the code generators. |
|
opt
Package opt optimizes ir modules.
|
Package opt optimizes ir modules. |
|
Package layout is the type model of HLSL and the one byte layout every target shares for buffers.
|
Package layout is the type model of HLSL and the one byte layout every target shares for buffers. |
|
Package msl emits Metal Shading Language from the typed IR.
|
Package msl emits Metal Shading Language from the typed IR. |
|
Package pipeline turns the entry points of a compiled shader into what a renderer creates: descriptor set layouts and push-constant ranges for Vulkan, per-stage argument indices for Metal, bind group layouts for WebGPU, and vertex input for all three.
|
Package pipeline turns the entry points of a compiled shader into what a renderer creates: descriptor set layouts and push-constant ranges for Vulkan, per-stage argument indices for Metal, bind group layouts for WebGPU, and vertex input for all three. |
|
Package preprocess is the HLSL preprocessor: it lexes a file, runs the directives (#include, #define, #if and the rest) and expands macros, producing the token list the parser reads.
|
Package preprocess is the HLSL preprocessor: it lexes a file, runs the directives (#include, #define, #if and the rest) and expands macros, producing the token list the parser reads. |
|
Package shader is the single home of the types the compiler's reflection, the generated code and the pipeline layer share: stages, targets, resource kinds, device features, binding slots, vertex attributes and the Entry that carries one entry point's compiled blobs.
|
Package shader is the single home of the types the compiler's reflection, the generated code and the pipeline layer share: stages, targets, resource kinds, device features, binding slots, vertex attributes and the Entry that carries one entry point's compiled blobs. |
|
Package spirv emits SPIR-V for Vulkan from the typed IR.
|
Package spirv emits SPIR-V for Vulkan from the typed IR. |
|
Package syntax holds the HLSL lexer, the syntax tree and the parser.
|
Package syntax holds the HLSL lexer, the syntax tree and the parser. |
|
Package wgsl emits WGSL for WebGPU from the typed IR.
|
Package wgsl emits WGSL for WebGPU from the typed IR. |