GitHubEmpezar

La referencia de API proviene de los comentarios de documentación de Go en el código fuente y está redactada en inglés.

package hotreload

import "github.com/nsgo-dev/game/pkg/tooling/hotreload"

Resumen

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.

Índice

Constantes

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.

Funciones

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() 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() 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(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(p string) bool

IsMaterialFile reports whether p has a recognized material YAML extension (.material.yaml, .mat.yaml, .material.yml, or .mat.yml), matched case-insensitively.

func IsShaderFile(p string) bool

IsShaderFile reports whether p has a recognized shader extension (.wgsl or .kage), matched case-insensitively.

func MaterialBlendModes() []string

MaterialBlendModes returns the sorted blend mode names accepted by MaterialDef.Blend.

func MaterialCullModes() []string

MaterialCullModes returns the sorted face-culling modes accepted by MaterialDef.Cull.

func MaterialDepthCompares() []string

MaterialDepthCompares returns the sorted depth comparison functions accepted by MaterialDef.DepthCompare.

func MaterialExtensions() []string

MaterialExtensions returns the material YAML file extensions recognized by hotreload, in a fixed order.

func MaterialFrontFaces() []string

MaterialFrontFaces returns the sorted winding orders accepted by MaterialDef.FrontFace.

func ShaderExtensions() []string

ShaderExtensions returns the shader file extensions recognized by hotreload, in a fixed order.

Tipos

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(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(filePath string, data []byte) (*MaterialDef, error)

ParseMaterialFile decodes and validates a YAML MaterialDef and names filePath in any returned *loaderr.Error.

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 (m *MaterialDef) BlendState() *gpu.BlendState

BlendState returns the gpu.BlendState configured by m.Blend, defaulting to gpu.BlendOpaque().

func (m *MaterialDef) Clone() *MaterialDef

Clone returns a deep copy of m so callers can inspect or modify it independently.

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 (m *MaterialDef) CullMode() gpu.CullMode

CullMode returns the gpu.CullMode configured by m.Cull, defaulting to gpu.CullBack.

func (m *MaterialDef) DepthCompareFunc() gpu.CompareFunc

DepthCompareFunc returns the gpu.CompareFunc configured by m.DepthCompare, defaulting to gpu.CompareLess.

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 (m *MaterialDef) EffectiveDepthWrite() bool

EffectiveDepthWrite returns DepthWrite when set, or true by default.

func (m *MaterialDef) EffectiveFragmentEntry() string

EffectiveFragmentEntry returns FragmentEntry if set, otherwise "Fragment" for .kage shaders or "fs_main" for WGSL shaders.

func (m *MaterialDef) EffectiveFragmentShader() string

EffectiveFragmentShader returns FragmentShader if set, otherwise Shader.

func (m *MaterialDef) EffectiveVertexEntry() string

EffectiveVertexEntry returns VertexEntry if set, otherwise "vs_main".

func (m *MaterialDef) EffectiveVertexShader() string

EffectiveVertexShader returns VertexShader if set, otherwise Shader.

func (m *MaterialDef) FrontFaceMode() gpu.FrontFace

FrontFaceMode returns the gpu.FrontFace configured by m.FrontFace, defaulting to gpu.FrontCCW.

func (m *MaterialDef) ShaderPaths() []string

ShaderPaths returns the sorted, deduplicated list of shader paths referenced by m.

func (m *MaterialDef) Validate() error

Validate checks m's version, shader paths, render state enums, numeric values, CSS colors, and texture paths.

type MaterialOption func(*materialConfig)

MaterialOption configures a MaterialReloader.

func WithMaterialDir(dir string) MaterialOption

WithMaterialDir sets a directory on disk used for initial material loads.

func WithMaterialFS(fsys fs.FS) MaterialOption

WithMaterialFS sets the file system used for initial material loads.

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(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 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 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(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 (r *MaterialReloader) ClearError(name string)

ClearError clears any recorded ReloadError for name.

func (r *MaterialReloader) Close()

Close releases all active GPU pipelines owned by r. Safe to call more than once.

func (r *MaterialReloader) Errors() []ReloadError

Errors returns all currently unresolved material ReloadErrors, sorted by Name.

func (r *MaterialReloader) LastError(name string) (ReloadError, bool)

LastError returns the most recent unresolved ReloadError for name and whether one is active.

func (r *MaterialReloader) Material(name string) *MaterialDef

Material returns a snapshot copy of the currently active MaterialDef for name, or nil.

func (r *MaterialReloader) MaterialNames() []string

MaterialNames returns the sorted list of registered material names.

func (r *MaterialReloader) MaterialPath(name string) (string, bool)

MaterialPath returns the slash-separated relative file path registered for material name.

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 (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 (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 (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 (r *MaterialReloader) ReloadMaterialFile(nameOrPath string) (string, int64, bool, error)

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 (r *MaterialReloader) Revision() uint64

Revision returns the monotonic count of successful material reloads.

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 func(*config)

Option configures a Watcher.

func WithDebounce(d time.Duration) Option

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(d time.Duration) Option

WithPollInterval sets how often the watcher checks disk for changes. Non-positive values keep DefaultPollInterval.

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 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 (e ReloadError) Error() string

Error returns a formatted diagnostic string for the failed reload.

func (e ReloadError) Unwrap() error

Unwrap returns the underlying error.

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 func(*shaderConfig)

ShaderOption configures a ShaderReloader.

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(fn func(name, path string)) ShaderOption

WithOnShaderReload sets a callback invoked on the engine goroutine whenever a shader or pipeline reloads successfully.

func WithShaderDir(dir string) ShaderOption

WithShaderDir sets a directory on disk used for initial shader loads.

func WithShaderFS(fsys fs.FS) ShaderOption

WithShaderFS sets the file system used for initial shader loads.

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(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 (r *ShaderReloader) ClearError(name string)

ClearError clears any recorded ReloadError for name.

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 (r *ShaderReloader) Device() *gpu.Device

Device returns the GPU device used to create pipelines, or nil.

func (r *ShaderReloader) Errors() []ReloadError

Errors returns all currently unresolved ReloadErrors, sorted by Name for deterministic display.

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 (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 (r *ShaderReloader) PipelineNames() []string

PipelineNames returns the sorted list of registered pipeline names.

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 (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 (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 (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 (r *ShaderReloader) ReloadShaderFile(nameOrPath string) (string, int64, bool, error)

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 (r *ShaderReloader) Revision() uint64

Revision returns the monotonic count of successful shader and pipeline reloads.

func (r *ShaderReloader) Shader(name string) *gpu.ShaderModule

Shader returns the currently active compiled *gpu.ShaderModule registered under name, or nil.

func (r *ShaderReloader) ShaderByPath(relPath string) *gpu.ShaderModule

ShaderByPath returns the currently active compiled *gpu.ShaderModule for relPath, or nil.

func (r *ShaderReloader) ShaderNames() []string

ShaderNames returns the sorted list of explicitly registered shader names.

func (r *ShaderReloader) ShaderPath(name string) (string, bool)

ShaderPath returns the slash-separated relative file path registered for shader name.

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 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(cx *core.Scope, opts ...Option) *Watcher

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(cx *core.Scope, dir string, opts ...Option) *Watcher

NewWatcher starts a Watcher polling dir under cx until cx is disposed or Stop is called.

func (w *Watcher) Dir() string

Dir returns the cleaned root directory being watched.

func (w *Watcher) Generation() int

Generation returns the current reload generation counter. Reading it inside a reactive computation or core.Canvas Draw callback subscribes to future reloads.

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 (w *Watcher) Watch(relPath string, onChange func(data []byte))

Watch watches relPath under the watcher's directory and calls onChange on the engine goroutine whenever the file's content changes and stabilizes.

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 (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 (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 (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 (w *Watcher) WatchPattern(ext string, onChange func(relPath string, data []byte))

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 (w *Watcher) WatchResources(lib *resource.Library, onReload func(path string, err error))

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 (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 (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.