Documentation
¶
Overview ¶
Package hotreload watches game assets on disk during development and delivers reloads on the NSGo engine goroutine without restarting the app.
In release builds (-tags release), Watcher compiles to a zero-cost stub that starts no goroutines and performs no file I/O.
Index ¶
- Constants
- func CompileShaderSource(filePath string, data []byte) (*gpu.ShaderModule, error)
- func DevAssetsDir() string
- func DevScene() string
- func EncodeMaterial(m *MaterialDef) ([]byte, error)
- func IsMaterialFile(p string) bool
- func IsShaderFile(p string) bool
- func MaterialBlendModes() []string
- func MaterialCullModes() []string
- func MaterialDepthCompares() []string
- func MaterialExtensions() []string
- func MaterialFrontFaces() []string
- func ShaderExtensions() []string
- type MaterialDef
- func (m *MaterialDef) ApplyToPipelineDesc(desc *gpu.PipelineDesc, depthFormat gpu.TextureFormat)
- func (m *MaterialDef) BlendState() *gpu.BlendState
- func (m *MaterialDef) Clone() *MaterialDef
- func (m *MaterialDef) Color(name string) (core.Color, bool)
- func (m *MaterialDef) CullMode() gpu.CullMode
- func (m *MaterialDef) DepthCompareFunc() gpu.CompareFunc
- func (m *MaterialDef) DepthStencilState(depthFormat gpu.TextureFormat) *gpu.DepthStencilState
- func (m *MaterialDef) EffectiveDepthWrite() bool
- func (m *MaterialDef) EffectiveFragmentEntry() string
- func (m *MaterialDef) EffectiveFragmentShader() string
- func (m *MaterialDef) EffectiveVertexEntry() string
- func (m *MaterialDef) EffectiveVertexShader() string
- func (m *MaterialDef) FrontFaceMode() gpu.FrontFace
- func (m *MaterialDef) ShaderPaths() []string
- func (m *MaterialDef) Validate() error
- type MaterialOption
- type MaterialPipelineBuilder
- type MaterialReloader
- func (r *MaterialReloader) ClearError(name string)
- func (r *MaterialReloader) Close()
- func (r *MaterialReloader) Errors() []ReloadError
- func (r *MaterialReloader) LastError(name string) (ReloadError, bool)
- func (r *MaterialReloader) Material(name string) *MaterialDef
- func (r *MaterialReloader) MaterialNames() []string
- func (r *MaterialReloader) MaterialPath(name string) (string, bool)
- func (r *MaterialReloader) Pipeline(name string) *gpu.Pipeline
- func (r *MaterialReloader) Register(name, relPath string, build MaterialPipelineBuilder) (*MaterialDef, *gpu.Pipeline, error)
- func (r *MaterialReloader) RegisterBytes(name, relPath string, data []byte, build MaterialPipelineBuilder) (*MaterialDef, *gpu.Pipeline, error)
- func (r *MaterialReloader) ReloadMaterial(relPath string, data []byte) (bool, error)
- func (r *MaterialReloader) ReloadMaterialFile(nameOrPath string) (string, int64, bool, error)
- func (r *MaterialReloader) Revision() uint64
- func (r *MaterialReloader) Watch(w *Watcher)
- type Option
- type PipelineSpec
- type ReloadError
- type ReloadKind
- type ShaderOption
- type ShaderReloader
- func (r *ShaderReloader) ClearError(name string)
- func (r *ShaderReloader) Close()
- func (r *ShaderReloader) Device() *gpu.Device
- func (r *ShaderReloader) Errors() []ReloadError
- func (r *ShaderReloader) LastError(name string) (ReloadError, bool)
- func (r *ShaderReloader) Pipeline(name string) *gpu.Pipeline
- func (r *ShaderReloader) PipelineNames() []string
- func (r *ShaderReloader) RegisterPipeline(name string, spec PipelineSpec) (*gpu.Pipeline, error)
- func (r *ShaderReloader) RegisterShader(name, relPath string) (*gpu.ShaderModule, error)
- func (r *ShaderReloader) RegisterShaderBytes(name, relPath string, data []byte) (*gpu.ShaderModule, error)
- func (r *ShaderReloader) ReloadShader(relPath string, data []byte) (bool, error)
- func (r *ShaderReloader) ReloadShaderFile(nameOrPath string) (string, int64, bool, error)
- func (r *ShaderReloader) Revision() uint64
- func (r *ShaderReloader) Shader(name string) *gpu.ShaderModule
- func (r *ShaderReloader) ShaderByPath(relPath string) *gpu.ShaderModule
- func (r *ShaderReloader) ShaderNames() []string
- func (r *ShaderReloader) ShaderPath(name string) (string, bool)
- func (r *ShaderReloader) Watch(w *Watcher)
- type Watcher
- func (w *Watcher) Dir() string
- func (w *Watcher) Generation() int
- func (w *Watcher) Stop()
- func (w *Watcher) Watch(relPath string, onChange func(data []byte))
- func (w *Watcher) WatchAssets(m *assets.Manager, onReload func(path string, names []string, err error))
- func (w *Watcher) WatchAtlas(jsonPath string, img core.ImageSource, onReload func(*sprite.Atlas, error))
- func (w *Watcher) WatchAtlasFiles(jsonPath, imagePath string, img core.ImageSource, ...)
- func (w *Watcher) WatchMaterials(r *MaterialReloader)
- func (w *Watcher) WatchPattern(ext string, onChange func(relPath string, data []byte))
- func (w *Watcher) WatchResources(lib *resource.Library, onReload func(path string, err error))
- func (w *Watcher) WatchShader(relPath string, onReload func(*gpu.ShaderModule, error))
- func (w *Watcher) WatchShaders(r *ShaderReloader)
Examples ¶
Constants ¶
const ( ShaderExtWGSL = ".wgsl" ShaderExtKage = ".kage" MaterialExtYAML = ".material.yaml" MaterialExtMat = ".mat.yaml" MaterialExtYML = ".material.yml" MaterialExtMatY = ".mat.yml" )
Recognized shader and material file extensions.
const AssetsDirEnv = "NSGO_GAME_ASSETS"
AssetsDirEnv is the environment variable `game dev` sets to the absolute path of the directory a game's "asset:" URIs name, its resources directory by default, for NewDevWatcher to watch.
const DefaultDebounce = 40 * time.Millisecond
DefaultDebounce is how long a changed file must keep the same metadata and content hash before its reload callback runs.
const DefaultPollInterval = 150 * time.Millisecond
DefaultPollInterval is how often a Watcher checks watched files on disk when no interval is set.
const MaterialVersion = 1
MaterialVersion is the schema version MaterialDef reads and writes.
const SceneEnv = "NSGO_GAME_SCENE"
SceneEnv is the environment variable `game dev -scene` (and the editor's Run command when starting at the open scene) sets to the slash-separated scene path relative to the project root, for DevScene to read.
Variables ¶
This section is empty.
Functions ¶
func CompileShaderSource ¶
func CompileShaderSource(filePath string, data []byte) (*gpu.ShaderModule, error)
CompileShaderSource compiles a WGSL (.wgsl) or Kage (.kage) shader from data. Compile and validation errors are returned as a structured *loaderr.Error naming filePath and the 1-based line and column when the compiler reports them.
func DevAssetsDir ¶
func DevAssetsDir() string
DevAssetsDir returns the asset directory `game dev` passes the game in AssetsDirEnv, cleaned, or "" when the game does not run under `game dev`.
func DevScene ¶
func DevScene() string
DevScene returns the start scene path `game dev -scene` (or the editor's Run command) passes the game in SceneEnv, or "" when none was requested.
func EncodeMaterial ¶
func EncodeMaterial(m *MaterialDef) ([]byte, error)
EncodeMaterial validates m and writes deterministic 2-space YAML with fixed field order and sorted parameter keys. A document produced by EncodeMaterial round-trips through ParseMaterial and EncodeMaterial with identical bytes.
func IsMaterialFile ¶
IsMaterialFile reports whether p has a recognized material YAML extension (.material.yaml, .mat.yaml, .material.yml, or .mat.yml), matched case-insensitively.
func IsShaderFile ¶
IsShaderFile reports whether p has a recognized shader extension (.wgsl or .kage), matched case-insensitively.
func MaterialBlendModes ¶
func MaterialBlendModes() []string
MaterialBlendModes returns the sorted blend mode names accepted by MaterialDef.Blend.
func MaterialCullModes ¶
func MaterialCullModes() []string
MaterialCullModes returns the sorted face-culling modes accepted by MaterialDef.Cull.
func MaterialDepthCompares ¶
func MaterialDepthCompares() []string
MaterialDepthCompares returns the sorted depth comparison functions accepted by MaterialDef.DepthCompare.
func MaterialExtensions ¶
func MaterialExtensions() []string
MaterialExtensions returns the material YAML file extensions recognized by hotreload, in a fixed order.
func MaterialFrontFaces ¶
func MaterialFrontFaces() []string
MaterialFrontFaces returns the sorted winding orders accepted by MaterialDef.FrontFace.
func ShaderExtensions ¶
func ShaderExtensions() []string
ShaderExtensions returns the shader file extensions recognized by hotreload, in a fixed order.
Types ¶
type MaterialDef ¶
type MaterialDef struct {
// Version is the schema version; it must equal MaterialVersion (1).
Version int `yaml:"version"`
// Name is an optional human-readable display name.
Name string `yaml:"name,omitempty"`
// Shader is a slash-separated relative path to a .wgsl or .kage shader file providing
// both vertex and fragment stages (unless overridden by VertexShader or FragmentShader).
Shader string `yaml:"shader,omitempty"`
// VertexShader overrides Shader for the vertex stage when split across files.
VertexShader string `yaml:"vertexShader,omitempty"`
// FragmentShader overrides Shader for the fragment stage when split across files.
FragmentShader string `yaml:"fragmentShader,omitempty"`
// VertexEntry names the @vertex entry point; empty defaults to "vs_main".
VertexEntry string `yaml:"vertexEntry,omitempty"`
// FragmentEntry names the @fragment entry point; empty defaults to "fs_main" (or "Fragment" for .kage).
FragmentEntry string `yaml:"fragmentEntry,omitempty"`
// Blend selects color/alpha blending ("opaque", "alpha", "premultiplied", "additive", "multiply"); empty is "opaque".
Blend string `yaml:"blend,omitempty"`
// Cull selects face culling ("none", "front", "back"); empty is "back".
Cull string `yaml:"cull,omitempty"`
// FrontFace selects front-facing triangle winding ("ccw", "cw"); empty is "ccw".
FrontFace string `yaml:"frontFace,omitempty"`
// DepthWrite controls whether fragments write depth; nil defaults to true when a depth attachment is used.
DepthWrite *bool `yaml:"depthWrite,omitempty"`
// DepthCompare selects the depth comparison function ("never", "less", "equal", "lessEqual", "greater", "notEqual", "greaterEqual", "always"); empty is "less".
DepthCompare string `yaml:"depthCompare,omitempty"`
// Scalars holds named float32 material parameters (for example roughness, metallic, timeScale).
Scalars map[string]float32 `yaml:"scalars,omitempty"`
// Vec2 holds named 2-component float32 parameters (for example uvScale, uvOffset).
Vec2 map[string][2]float32 `yaml:"vec2,omitempty"`
// Vec3 holds named 3-component float32 parameters (for example lightDir, rimColor).
Vec3 map[string][3]float32 `yaml:"vec3,omitempty"`
// Vec4 holds named 4-component float32 parameters (for example tint, params).
Vec4 map[string][4]float32 `yaml:"vec4,omitempty"`
// Colors holds named CSS color parameters parsed with core.ParseColor (for example "#ff8800", "rgb(10, 20, 30)").
Colors map[string]string `yaml:"colors,omitempty"`
// Textures holds named slash-separated relative paths to texture images.
Textures map[string]string `yaml:"textures,omitempty"`
}
MaterialDef is the text YAML definition of a 3D shader material: its shader path(s), pipeline render state (blend, cull, front face, depth test/write), and typed parameters (scalars, vectors, CSS colors, and texture paths).
Files use version: 1, refuse unknown fields, and round-trip deterministically through ParseMaterial and EncodeMaterial.
func ParseMaterial ¶
func ParseMaterial(data []byte) (*MaterialDef, error)
ParseMaterial decodes and validates a YAML MaterialDef, refusing unknown fields and trailing YAML documents. Errors are returned as *loaderr.Error with line, column, and field information when available.
func ParseMaterialFile ¶
func ParseMaterialFile(filePath string, data []byte) (*MaterialDef, error)
ParseMaterialFile decodes and validates a YAML MaterialDef and names filePath in any returned *loaderr.Error.
func (*MaterialDef) ApplyToPipelineDesc ¶
func (m *MaterialDef) ApplyToPipelineDesc(desc *gpu.PipelineDesc, depthFormat gpu.TextureFormat)
ApplyToPipelineDesc applies m's entry points, face culling, front face, blend state, and depth-stencil state (when depthFormat != gpu.FormatUndefined) onto desc.
func (*MaterialDef) BlendState ¶
func (m *MaterialDef) BlendState() *gpu.BlendState
BlendState returns the gpu.BlendState configured by m.Blend, defaulting to gpu.BlendOpaque().
func (*MaterialDef) Clone ¶
func (m *MaterialDef) Clone() *MaterialDef
Clone returns a deep copy of m so callers can inspect or modify it independently.
func (*MaterialDef) Color ¶
func (m *MaterialDef) Color(name string) (core.Color, bool)
Color parses and returns the named color from m.Colors, or (0, false) if absent or invalid.
func (*MaterialDef) CullMode ¶
func (m *MaterialDef) CullMode() gpu.CullMode
CullMode returns the gpu.CullMode configured by m.Cull, defaulting to gpu.CullBack.
func (*MaterialDef) DepthCompareFunc ¶
func (m *MaterialDef) DepthCompareFunc() gpu.CompareFunc
DepthCompareFunc returns the gpu.CompareFunc configured by m.DepthCompare, defaulting to gpu.CompareLess.
func (*MaterialDef) DepthStencilState ¶
func (m *MaterialDef) DepthStencilState(depthFormat gpu.TextureFormat) *gpu.DepthStencilState
DepthStencilState builds a gpu.DepthStencilState for depthFormat using m's DepthWrite and DepthCompare, returning nil when depthFormat is gpu.FormatUndefined.
func (*MaterialDef) EffectiveDepthWrite ¶
func (m *MaterialDef) EffectiveDepthWrite() bool
EffectiveDepthWrite returns DepthWrite when set, or true by default.
func (*MaterialDef) EffectiveFragmentEntry ¶
func (m *MaterialDef) EffectiveFragmentEntry() string
EffectiveFragmentEntry returns FragmentEntry if set, otherwise "Fragment" for .kage shaders or "fs_main" for WGSL shaders.
func (*MaterialDef) EffectiveFragmentShader ¶
func (m *MaterialDef) EffectiveFragmentShader() string
EffectiveFragmentShader returns FragmentShader if set, otherwise Shader.
func (*MaterialDef) EffectiveVertexEntry ¶
func (m *MaterialDef) EffectiveVertexEntry() string
EffectiveVertexEntry returns VertexEntry if set, otherwise "vs_main".
func (*MaterialDef) EffectiveVertexShader ¶
func (m *MaterialDef) EffectiveVertexShader() string
EffectiveVertexShader returns VertexShader if set, otherwise Shader.
func (*MaterialDef) FrontFaceMode ¶
func (m *MaterialDef) FrontFaceMode() gpu.FrontFace
FrontFaceMode returns the gpu.FrontFace configured by m.FrontFace, defaulting to gpu.FrontCCW.
func (*MaterialDef) ShaderPaths ¶
func (m *MaterialDef) ShaderPaths() []string
ShaderPaths returns the sorted, deduplicated list of shader paths referenced by m.
func (*MaterialDef) Validate ¶
func (m *MaterialDef) Validate() error
Validate checks m's version, shader paths, render state enums, numeric values, CSS colors, and texture paths.
type MaterialOption ¶
type MaterialOption func(*materialConfig)
MaterialOption configures a MaterialReloader.
func WithMaterialDir ¶
func WithMaterialDir(dir string) MaterialOption
WithMaterialDir sets a directory on disk used for initial material loads.
func WithMaterialFS ¶
func WithMaterialFS(fsys fs.FS) MaterialOption
WithMaterialFS sets the file system used for initial material loads.
func WithOnMaterialError ¶
func WithOnMaterialError(fn func(ReloadError)) MaterialOption
WithOnMaterialError sets a callback invoked whenever a material fails to parse, validate, compile its shader, or create its candidate GPU pipeline.
func WithOnMaterialReload ¶
func WithOnMaterialReload(fn func(name, path string)) MaterialOption
WithOnMaterialReload sets a callback invoked whenever a material reloads cleanly (either from an edited material YAML file or from an edited shader it depends on).
type MaterialPipelineBuilder ¶
type MaterialPipelineBuilder func(def *MaterialDef, vertex, fragment *gpu.ShaderModule) (gpu.PipelineDesc, error)
MaterialPipelineBuilder constructs a gpu.PipelineDesc for a material from its parsed MaterialDef and compiled vertex and fragment shader modules. Returning an error rejects the candidate and preserves the previous working material and pipeline.
type MaterialReloader ¶
type MaterialReloader struct {
// Version increments on every successful reload when created with a non-nil *core.Scope.
Version *core.Signal[int]
// contains filtered or unexported fields
}
MaterialReloader manages hot-reloadable 3D shader materials and their GPU pipelines, tracking dependencies on shaders managed by a ShaderReloader.
When a material YAML file changes, MaterialReloader parses and validates the candidate MaterialDef and builds a candidate gpu.Pipeline before swapping. On any parse, validation, shader compile, or pipeline creation error, the previous working material and pipeline stay active, a ReloadError is recorded, and OnError is invoked without crashing.
When a shader file referenced by one or more materials changes in the paired ShaderReloader, MaterialReloader automatically rebuilds and swaps every dependent material's pipeline.
func NewMaterialReloader ¶
func NewMaterialReloader(cx *core.Scope, shaders *ShaderReloader, opts ...MaterialOption) *MaterialReloader
NewMaterialReloader creates a MaterialReloader optionally paired with shaders (for GPU pipeline compilation and shader-to-material dependency tracking).
func (*MaterialReloader) ClearError ¶
func (r *MaterialReloader) ClearError(name string)
ClearError clears any recorded ReloadError for name.
func (*MaterialReloader) Close ¶
func (r *MaterialReloader) Close()
Close releases all active GPU pipelines owned by r. Safe to call more than once.
func (*MaterialReloader) Errors ¶
func (r *MaterialReloader) Errors() []ReloadError
Errors returns all currently unresolved material ReloadErrors, sorted by Name.
func (*MaterialReloader) LastError ¶
func (r *MaterialReloader) LastError(name string) (ReloadError, bool)
LastError returns the most recent unresolved ReloadError for name and whether one is active.
func (*MaterialReloader) Material ¶
func (r *MaterialReloader) Material(name string) *MaterialDef
Material returns a snapshot copy of the currently active MaterialDef for name, or nil.
func (*MaterialReloader) MaterialNames ¶
func (r *MaterialReloader) MaterialNames() []string
MaterialNames returns the sorted list of registered material names.
func (*MaterialReloader) MaterialPath ¶
func (r *MaterialReloader) MaterialPath(name string) (string, bool)
MaterialPath returns the slash-separated relative file path registered for material name.
func (*MaterialReloader) Pipeline ¶
func (r *MaterialReloader) Pipeline(name string) *gpu.Pipeline
Pipeline returns the currently active *gpu.Pipeline for name, or nil. While a broken material or shader edit is on disk, Pipeline continues returning the last good pipeline.
func (*MaterialReloader) Register ¶
func (r *MaterialReloader) Register(name, relPath string, build MaterialPipelineBuilder) (*MaterialDef, *gpu.Pipeline, error)
Register loads the material YAML file at relPath, validates it, builds its initial gpu.Pipeline (when build != nil and the paired ShaderReloader has a GPU device), and tracks it under name for live reloading.
func (*MaterialReloader) RegisterBytes ¶
func (r *MaterialReloader) RegisterBytes(name, relPath string, data []byte, build MaterialPipelineBuilder) (*MaterialDef, *gpu.Pipeline, error)
RegisterBytes parses data as the material YAML at relPath, builds its initial gpu.Pipeline (when build != nil and the paired ShaderReloader has a GPU device), and tracks it under name for live reloading.
func (*MaterialReloader) ReloadMaterial ¶
func (r *MaterialReloader) ReloadMaterial(relPath string, data []byte) (bool, error)
ReloadMaterial parses data as the new contents of relPath and atomically swaps every material registered at relPath whose candidate parses, validates, and builds cleanly. Untracked paths return (false, nil). On any error, the previous working material and pipeline remain active and OnError is called without crashing.
func (*MaterialReloader) ReloadMaterialFile ¶
ReloadMaterialFile resolves nameOrPath (a registered material name or relative path), reads fresh YAML bytes from the reloader's configured file system, and calls ReloadMaterial. It reports the resolved path, file byte length, whether the material is tracked, and any error.
func (*MaterialReloader) Revision ¶
func (r *MaterialReloader) Revision() uint64
Revision returns the monotonic count of successful material reloads.
func (*MaterialReloader) Watch ¶
func (r *MaterialReloader) Watch(w *Watcher)
Watch attaches r to w so edited material YAML files (.material.yaml, .mat.yaml, .material.yml, .mat.yml) reload on the engine goroutine. When r is paired with a ShaderReloader, Watch also attaches the ShaderReloader to w (idempotently) so editing a referenced shader automatically reloads every dependent material.
type Option ¶
type Option func(*config)
Option configures a Watcher.
func WithDebounce ¶
WithDebounce sets how long a changed file must stay stable before its callback runs, preventing half-written reads during rapid saves. When debouncing is enabled (d > 0), empty (0-byte) files wait longer to settle so truncate-then-write editor saves do not deliver a transient empty payload before the content arrives. Negative values are ignored; 0 delivers as soon as a changed hash is read.
func WithPollInterval ¶
WithPollInterval sets how often the watcher checks disk for changes. Non-positive values keep DefaultPollInterval.
type PipelineSpec ¶
type PipelineSpec struct {
// Shader is the slash-separated path of a single shader file providing both
// vertex and fragment stages. Used whenever VertexShader or FragmentShader is empty.
Shader string
// VertexShader overrides Shader for the vertex stage when split across two files.
VertexShader string
// FragmentShader overrides Shader for the fragment stage when split across two files.
FragmentShader string
// Build constructs the gpu.PipelineDesc from the newly compiled vertex and
// fragment ShaderModules. Returning an error rejects the candidate and keeps
// the previous working pipeline active.
Build func(vertex, fragment *gpu.ShaderModule) (gpu.PipelineDesc, error)
}
PipelineSpec describes a hot-reloadable GPU render pipeline and the shader file(s) it depends on.
type ReloadError ¶
type ReloadError struct {
Name string // registered shader, pipeline, or material name
Path string // slash-separated file path that failed
Kind ReloadKind // ReloadKindShader, ReloadKindPipeline, or ReloadKindMaterial
Line int // 1-based source line, 0 when unknown
Column int // 1-based source column, 0 when unknown
Message string // human-readable diagnostic message
Err error // underlying error, typically *loaderr.Error
At time.Time // wall-clock timestamp when the failure was recorded
}
ReloadError records why a shader, pipeline, or material failed to reload. It implements error and unwraps to Err (typically a *loaderr.Error), so errors.As and loaderr.As inspect the underlying diagnostic directly.
func (ReloadError) Error ¶
func (e ReloadError) Error() string
Error returns a formatted diagnostic string for the failed reload.
func (ReloadError) Unwrap ¶
func (e ReloadError) Unwrap() error
Unwrap returns the underlying error.
type ReloadKind ¶
type ReloadKind string
ReloadKind identifies what kind of GPU asset a ReloadError or reload event refers to.
const ( ReloadKindShader ReloadKind = "shader" ReloadKindPipeline ReloadKind = "pipeline" ReloadKindMaterial ReloadKind = "material" )
type ShaderOption ¶
type ShaderOption func(*shaderConfig)
ShaderOption configures a ShaderReloader.
func WithOnShaderError ¶
func WithOnShaderError(fn func(ReloadError)) ShaderOption
WithOnShaderError sets a callback invoked whenever a shader or pipeline fails to compile or validate. The previous working pipeline remains active.
func WithOnShaderReload ¶
func WithOnShaderReload(fn func(name, path string)) ShaderOption
WithOnShaderReload sets a callback invoked on the engine goroutine whenever a shader or pipeline reloads successfully.
func WithShaderDir ¶
func WithShaderDir(dir string) ShaderOption
WithShaderDir sets a directory on disk used for initial shader loads.
func WithShaderFS ¶
func WithShaderFS(fsys fs.FS) ShaderOption
WithShaderFS sets the file system used for initial shader loads.
type ShaderReloader ¶
type ShaderReloader struct {
// Version increments on every successful reload when created with a non-nil *core.Scope.
// Reading Version.Get() inside a reactive view or Draw callback triggers a redraw.
Version *core.Signal[int]
// contains filtered or unexported fields
}
ShaderReloader manages live-reloadable WGSL/Kage shaders and GPU render pipelines.
When a watched shader file changes, ShaderReloader compiles the candidate module and builds every dependent candidate gpu.Pipeline before swapping. On any compile or pipeline validation error, the previous working pipeline stays active, a ReloadError is recorded, and OnError is invoked without crashing. When a later edit compiles cleanly, the candidate pipeline swaps in atomically, the replaced pipeline is closed safely, and the error clears.
func NewShaderReloader ¶
func NewShaderReloader(cx *core.Scope, dev *gpu.Device, opts ...ShaderOption) *ShaderReloader
NewShaderReloader creates a ShaderReloader bound to dev (which may be nil when only compiling shaders without building GPU pipelines). When cx is non-nil, Version tracks reload generations reactively and Close is registered on cx.Cleanup.
func (*ShaderReloader) ClearError ¶
func (r *ShaderReloader) ClearError(name string)
ClearError clears any recorded ReloadError for name.
func (*ShaderReloader) Close ¶
func (r *ShaderReloader) Close()
Close releases all active GPU render pipelines owned by r. It is safe to call more than once and is registered automatically on cx.Cleanup when cx is non-nil.
func (*ShaderReloader) Device ¶
func (r *ShaderReloader) Device() *gpu.Device
Device returns the GPU device used to create pipelines, or nil.
func (*ShaderReloader) Errors ¶
func (r *ShaderReloader) Errors() []ReloadError
Errors returns all currently unresolved ReloadErrors, sorted by Name for deterministic display.
func (*ShaderReloader) LastError ¶
func (r *ShaderReloader) LastError(name string) (ReloadError, bool)
LastError returns the most recent unresolved ReloadError for name (a shader name, pipeline name, or shader path), and whether one is active.
func (*ShaderReloader) Pipeline ¶
func (r *ShaderReloader) Pipeline(name string) *gpu.Pipeline
Pipeline returns the currently active *gpu.Pipeline registered under name, or nil. While a broken shader edit is on disk, Pipeline continues returning the last good pipeline.
func (*ShaderReloader) PipelineNames ¶
func (r *ShaderReloader) PipelineNames() []string
PipelineNames returns the sorted list of registered pipeline names.
func (*ShaderReloader) RegisterPipeline ¶
func (r *ShaderReloader) RegisterPipeline(name string, spec PipelineSpec) (*gpu.Pipeline, error)
RegisterPipeline loads and compiles the shader(s) named by spec, builds the initial gpu.Pipeline, and registers it under name for automatic hot reload.
func (*ShaderReloader) RegisterShader ¶
func (r *ShaderReloader) RegisterShader(name, relPath string) (*gpu.ShaderModule, error)
RegisterShader loads and compiles the shader at relPath from the reloader's filesystem and registers it under name.
func (*ShaderReloader) RegisterShaderBytes ¶
func (r *ShaderReloader) RegisterShaderBytes(name, relPath string, data []byte) (*gpu.ShaderModule, error)
RegisterShaderBytes compiles data as the shader at relPath and registers it under name.
func (*ShaderReloader) ReloadShader ¶
func (r *ShaderReloader) ReloadShader(relPath string, data []byte) (bool, error)
ReloadShader compiles data as the new source for relPath and atomically swaps every affected shader and pipeline whose candidate builds cleanly.
It reports whether relPath is tracked by any registered shader, pipeline, or dependent MaterialReloader; untracked files return (false, nil). On a compile or pipeline creation error, the previous working shader and pipeline stay active, a ReloadError is recorded, and OnError is called without panicking.
func (*ShaderReloader) ReloadShaderFile ¶
ReloadShaderFile resolves nameOrPath (a registered shader name or relative path), reads fresh source bytes from the reloader's configured file system, and calls ReloadShader. It reports the resolved path, source byte length, whether the shader is tracked, and any error.
func (*ShaderReloader) Revision ¶
func (r *ShaderReloader) Revision() uint64
Revision returns the monotonic count of successful shader and pipeline reloads.
func (*ShaderReloader) Shader ¶
func (r *ShaderReloader) Shader(name string) *gpu.ShaderModule
Shader returns the currently active compiled *gpu.ShaderModule registered under name, or nil.
func (*ShaderReloader) ShaderByPath ¶
func (r *ShaderReloader) ShaderByPath(relPath string) *gpu.ShaderModule
ShaderByPath returns the currently active compiled *gpu.ShaderModule for relPath, or nil.
func (*ShaderReloader) ShaderNames ¶
func (r *ShaderReloader) ShaderNames() []string
ShaderNames returns the sorted list of explicitly registered shader names.
func (*ShaderReloader) ShaderPath ¶
func (r *ShaderReloader) ShaderPath(name string) (string, bool)
ShaderPath returns the slash-separated relative file path registered for shader name.
func (*ShaderReloader) Watch ¶
func (r *ShaderReloader) Watch(w *Watcher)
Watch attaches r to w so edited .wgsl and .kage files under w.Dir() are compiled and reloaded on the engine goroutine. Calling Watch with a nil Watcher (for example from NewDevWatcher outside `game dev` or in `-tags release`) is a safe no-op. Calling Watch multiple times with the same Watcher registers patterns only once.
type Watcher ¶
type Watcher struct {
// Version increments on every delivered reload. Read it (or call Generation) inside a core.Canvas Draw callback or core.Effect to react automatically.
Version *core.Signal[int]
// contains filtered or unexported fields
}
Watcher polls a directory off the engine goroutine and delivers asset reloads back onto the engine goroutine via core.Scope.Post.
It bumps Version on every reload so a core.Canvas or core.Effect reading Version.Get or Generation redraws automatically, and stops itself when the scope that owns it is disposed.
func NewDevWatcher ¶
NewDevWatcher starts a Watcher on DevAssetsDir under cx when the game runs under `game dev`, and returns nil otherwise. Every Watcher method does nothing on nil, so a game can call it unconditionally and register what it reloads:
w := hotreload.NewDevWatcher(cx) w.WatchAssets(mgr, nil)
func NewWatcher ¶
NewWatcher starts a Watcher polling dir under cx until cx is disposed or Stop is called.
Example ¶
NewWatcher starts polling an asset directory during development; Watch and WatchPattern register callbacks that run on the engine goroutine when a watched file changes, so a running game picks up edited levels or sprites without a restart. The watcher polls on wall time in the background, so this example shows only the setup: nothing has been reloaded yet and Generation is 0.
package main
import (
"fmt"
"os"
"github.com/nsgo-dev/game/pkg/tooling/hotreload"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
dir, err := os.MkdirTemp("", "assets")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
root := core.NewRoot(core.RootOptions{})
defer root.Dispose()
w := hotreload.NewWatcher(root, dir)
defer w.Stop()
w.Watch("levels/1.yaml", func(data []byte) { fmt.Println("level reloaded:", len(data), "bytes") })
w.WatchPattern(".png", func(rel string, data []byte) { fmt.Println("image reloaded:", rel) })
fmt.Println(w.Dir() == dir, w.Generation())
}
Output: true 0
func (*Watcher) Generation ¶
Generation returns the current reload generation counter. Reading it inside a reactive computation or core.Canvas Draw callback subscribes to future reloads.
func (*Watcher) Stop ¶
func (w *Watcher) Stop()
Stop halts background polling. It is safe to call more than once and is registered automatically on the watcher's scope cleanup.
func (*Watcher) Watch ¶
Watch watches relPath under the watcher's directory and calls onChange on the engine goroutine whenever the file's content changes and stabilizes.
func (*Watcher) WatchAssets ¶
func (w *Watcher) WatchAssets(m *assets.Manager, onReload func(path string, names []string, err error))
WatchAssets reloads m's assets when their files change: it watches every file under the watcher's directory and passes a changed one to assets.Manager.Reload as "asset:<path>" on the engine goroutine, so an atlas's JSON or image, an image or raw bytes that m has loaded show the edit. The watcher's directory must be the one m reads "asset:" URIs from: a Manager made with assets.WithFS(os.DirFS(hotreload.DevAssetsDir())) under `game dev`. Registering reads no file that has not changed in the last two seconds, so a large asset directory does not hold up the game's start; the watcher compares the others' contents from the first change on. onReload, if not nil, is then called with the file's slash-separated path, the names of the assets Reload replaced and its error; files that replaced nothing and failed nothing are skipped.
func (*Watcher) WatchAtlas ¶
func (w *Watcher) WatchAtlas(jsonPath string, img core.ImageSource, onReload func(*sprite.Atlas, error))
WatchAtlas watches a sprite atlas JSON file at jsonPath, parses it with sprite.LoadAtlas using img, and delivers the result to onReload on the engine goroutine.
func (*Watcher) WatchAtlasFiles ¶
func (w *Watcher) WatchAtlasFiles(jsonPath, imagePath string, img core.ImageSource, onReload func(*sprite.Atlas, error))
WatchAtlasFiles watches a sprite atlas's JSON at jsonPath and its image at imagePath, both relative to the watcher's directory, and delivers the atlas to onReload on the engine goroutine when either changes: the JSON parsed with sprite.LoadAtlas over img, which once the image file has changed shows that file's bytes, keeping img's Size and its URI, or for an img with several densities (Scales) naming the file at imagePath as an "asset:" URI so its density is that file's; pass the density the screen shows, such as sprites@2x.png on a 2x screen. Use it for an atlas the game loads itself, such as one embedded with go:embed; WatchAssets covers atlases an assets.Manager loads. If the JSON cannot be read when it is called, onReload gets that error once the image changes.
func (*Watcher) WatchMaterials ¶
func (w *Watcher) WatchMaterials(r *MaterialReloader)
WatchMaterials attaches r to w so edited material YAML files (.material.yaml, .mat.yaml, .material.yml, .mat.yml) and any shaders referenced by r's ShaderReloader reload live on the engine goroutine, keeping the previous working material and pipeline on errors.
func (*Watcher) WatchPattern ¶
WatchPattern watches every file under the watcher's directory whose extension matches ext (for example ".json" or "json", or "" / "*" for all files) and calls onChange on the engine goroutine with the slash-separated relative path and file bytes when a matching file is created or modified.
func (*Watcher) WatchResources ¶
WatchResources reloads lib's resources when their files change: it watches every .yaml and .yml file under the watcher's directory and passes a changed file that lib has loaded to resource.Library.Reload on the engine goroutine, so everything holding the resource sees the edit. The watcher's directory must be lib's root, so the paths match. onReload, if not nil, is then called with the file's slash-separated path and Reload's error, nil on success; files lib has not loaded are skipped.
func (*Watcher) WatchShader ¶
func (w *Watcher) WatchShader(relPath string, onReload func(*gpu.ShaderModule, error))
WatchShader watches a WGSL (.wgsl) or Kage (.kage) shader file at relPath, compiles it with CompileShaderSource, and delivers the compiled module or a *loaderr.Error to onReload on the engine goroutine.
func (*Watcher) WatchShaders ¶
func (w *Watcher) WatchShaders(r *ShaderReloader)
WatchShaders attaches r to w so edited .wgsl and .kage shader files recompile and swap candidate pipelines on the engine goroutine, keeping the previous working pipeline on compile errors.