Documentation
¶
Overview ¶
Package particles is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package particles provides a deterministic 2D particle emitter stepped by game.Loop and drawn through sprite.Batch.
Index ¶
- Constants
- func MarshalConfig3DJSON(cfg Emitter3DConfig) ([]byte, error)
- func MarshalConfig3DYAML(cfg Emitter3DConfig) ([]byte, error)
- func MarshalConfigJSON(cfg Config) ([]byte, error)
- func MarshalConfigYAML(cfg Config) ([]byte, error)
- func MarshalEffectYAML(e Effect) ([]byte, error)
- func NewMeshParticlePipeline(cx *core.Scope, dev *gpu.Device, opts MeshParticlePipelineOptions) (*gpu.Pipeline, error)
- func NewParticlePipeline(cx *core.Scope, dev *gpu.Device, opts ParticlePipelineOptions) (*gpu.Pipeline, error)
- func NewTrail3DPipeline(cx *core.Scope, dev *gpu.Device, opts Trail3DPipelineOptions) (*gpu.Pipeline, error)
- func ParticleFlipbookVertexLayouts() []gpu.VertexBufferLayout
- func ParticleMeshVertexLayouts() []gpu.VertexBufferLayout
- func ParticleVertexLayouts() []gpu.VertexBufferLayout
- func SaveConfig3DFile(path string, cfg Emitter3DConfig) error
- func SaveConfigFile(path string, cfg Config) error
- func Trail3DVertexLayout() gpu.VertexBufferLayout
- func ValidateGPUConfig3D(dev *gpu.Device, cfg Emitter3DConfig) error
- type Attractor3D
- type Attractor3DDoc
- type Attractor3DKind
- type BillboardMode3D
- type Burst
- type BurstDoc
- type CircleCollider
- type Collider
- type Collider3D
- func BoxCollider3D(center, size math3d.Vec3, bounce, friction float32) Collider3D
- func HeightFieldCollider3D(hf HeightField3D, bounce, friction float32) Collider3D
- func PlaneCollider3D(point, normal math3d.Vec3, bounce, friction float32) Collider3D
- func RaycastCollider3D(...) Collider3D
- func SDFCollider3D(fn func(math3d.Vec3) float32, bounce, friction float32) Collider3D
- func SDFGridCollider3D(grid *SDFGrid3D, bounce, friction float32) Collider3D
- func SphereCollider3D(center math3d.Vec3, radius, bounce, friction float32) Collider3D
- type Collider3DDoc
- type Collider3DKind
- type CollisionConfig
- type CollisionDoc
- type CollisionMode
- type ColorCurve
- type ColorStop
- type ColorStopDoc
- type Config
- type Curve
- type DrawPass3D
- type DrawPass3DDoc
- type DrawPass3DKind
- type Effect
- type EffectBinding
- type EffectCull
- type EffectEmitter
- type EffectEmitter3D
- type EffectEventKind
- type EffectEvents
- type EffectFiles
- type EffectParam
- type EffectParamType
- type EffectPlayer
- func (p *EffectPlayer) ClearZ()
- func (p *EffectPlayer) Culled() bool
- func (p *EffectPlayer) Draw(d *core.Drawing)
- func (p *EffectPlayer) Elapsed() time.Duration
- func (p *EffectPlayer) Emitters() []*Emitter
- func (p *EffectPlayer) Emitters3D() []*Emitter3D
- func (p *EffectPlayer) Err() error
- func (p *EffectPlayer) OnEvent(fn func(Event))
- func (p *EffectPlayer) Play(x, y float32)
- func (p *EffectPlayer) Playing() bool
- func (p *EffectPlayer) Quality() quality.Level
- func (p *EffectPlayer) SetAtlas(a *sprite.Atlas) error
- func (p *EffectPlayer) SetCull(c EffectCull)
- func (p *EffectPlayer) SetQuality(level quality.Level)
- func (p *EffectPlayer) SetTransform(x, y, rotation float32)
- func (p *EffectPlayer) SetZ(z int)
- func (p *EffectPlayer) Stop()
- func (p *EffectPlayer) TotalCount() int
- func (p *EffectPlayer) Update(dt time.Duration)
- type Emitter
- func (e *Emitter) Advance(dt time.Duration)
- func (e *Emitter) Attach(posFn func() (float32, float32))
- func (e *Emitter) AttachTrail(cfg TrailConfig)
- func (e *Emitter) AttachTransform(fn func() (x, y, rotation float32))
- func (e *Emitter) Burst(count int)
- func (e *Emitter) Children() []*Emitter
- func (e *Emitter) Clear()
- func (e *Emitter) Config() Config
- func (e *Emitter) Count() int
- func (e *Emitter) Detach()
- func (e *Emitter) DetachTrail()
- func (e *Emitter) Draw(d *core.Drawing)
- func (e *Emitter) Follow(x, y float32)
- func (e *Emitter) ParticleTrails() []*Trail
- func (e *Emitter) ParticleWorldPos(p Particle) (x, y float32)
- func (e *Emitter) Particles() []Particle
- func (e *Emitter) ReloadConfig(cfg Config)
- func (e *Emitter) Reset()
- func (e *Emitter) TotalCount() int
- func (e *Emitter) TrailCount() int
- func (e *Emitter) Update(dt time.Duration)
- type Emitter3D
- func (e *Emitter3D) Active() bool
- func (e *Emitter3D) Advance(dt time.Duration)
- func (e *Emitter3D) AppendFlipbookInstances(dst []byte, camRight, camUp math3d.Vec3) []byte
- func (e *Emitter3D) AppendInstances(dst []byte, camRight, camUp math3d.Vec3) []byte
- func (e *Emitter3D) AppendMeshInstances(dst []byte) []byte
- func (e *Emitter3D) AppendParticles(dst []Particle3D) []Particle3D
- func (e *Emitter3D) AppendTrailVertices(dst []byte, camPos, camRight, camUp math3d.Vec3) []byte
- func (e *Emitter3D) AttachTrail3D(cfg Trail3DConfig)
- func (e *Emitter3D) Burst(count int)
- func (e *Emitter3D) Children() []*Emitter3D
- func (e *Emitter3D) Clear()
- func (e *Emitter3D) Config() Emitter3DConfig
- func (e *Emitter3D) Count() int
- func (e *Emitter3D) DetachTrail3D()
- func (e *Emitter3D) FrameUV(i int) (u0, v0, uScale, vScale float32)
- func (e *Emitter3D) Particle(i int) Particle3D
- func (e *Emitter3D) ParticleWorldPos(i int) math3d.Vec3
- func (e *Emitter3D) Particles() []Particle3D
- func (e *Emitter3D) ReloadConfig(cfg Emitter3DConfig)
- func (e *Emitter3D) Reset()
- func (e *Emitter3D) SortByDepth(camPos, camForward math3d.Vec3)
- func (e *Emitter3D) Step(dt time.Duration)
- func (e *Emitter3D) TotalCount() int
- func (e *Emitter3D) TrailCount() int
- func (e *Emitter3D) Update(dt time.Duration)
- type Emitter3DConfig
- type Emitter3DDoc
- type Emitter3DFieldsDoc
- type EmitterDoc
- type EmitterFieldsDoc
- type Event
- type Flipbook3D
- type Flipbook3DDoc
- type FloatCurve
- type FloatStop
- type FloatStopDoc
- type GPUEmitter3D
- func (g *GPUEmitter3D) Active() bool
- func (g *GPUEmitter3D) Advance(dt time.Duration)
- func (g *GPUEmitter3D) Burst(count int)
- func (g *GPUEmitter3D) ByteSize() uint64
- func (g *GPUEmitter3D) Capacity() int
- func (g *GPUEmitter3D) Clear()
- func (g *GPUEmitter3D) Close() error
- func (g *GPUEmitter3D) Config() Emitter3DConfig
- func (g *GPUEmitter3D) Count() int
- func (g *GPUEmitter3D) Draw(pass *gpu.RenderPass)
- func (g *GPUEmitter3D) InstanceBuffer() *gpu.Buffer
- func (g *GPUEmitter3D) Reset()
- func (g *GPUEmitter3D) SetTransform(position math3d.Vec3, rotation math3d.Quat)
- func (g *GPUEmitter3D) Simulate(pass *gpu.ComputePass, camRight, camUp math3d.Vec3) error
- func (g *GPUEmitter3D) Step(dt time.Duration)
- func (g *GPUEmitter3D) Update(dt time.Duration)
- func (g *GPUEmitter3D) Valid() bool
- type GPUEmitter3DOptions
- type GPUMeshParticles3D
- func (g *GPUMeshParticles3D) ByteSize() uint64
- func (g *GPUMeshParticles3D) Capacity() int
- func (g *GPUMeshParticles3D) Close() error
- func (g *GPUMeshParticles3D) Count() uint32
- func (g *GPUMeshParticles3D) Draw(pass *gpu.RenderPass)
- func (g *GPUMeshParticles3D) Upload(e *Emitter3D) error
- func (g *GPUMeshParticles3D) UploadBytes(data []byte) error
- func (g *GPUMeshParticles3D) Valid() bool
- type GPUMeshParticles3DOptions
- type GPUParticleTrails3D
- func (g *GPUParticleTrails3D) ByteSize() uint64
- func (g *GPUParticleTrails3D) Capacity() int
- func (g *GPUParticleTrails3D) Close() error
- func (g *GPUParticleTrails3D) Draw(pass *gpu.RenderPass)
- func (g *GPUParticleTrails3D) Upload(e *Emitter3D, camPos, camRight, camUp math3d.Vec3) error
- func (g *GPUParticleTrails3D) UploadBytes(data []byte) error
- func (g *GPUParticleTrails3D) Valid() bool
- func (g *GPUParticleTrails3D) VertexCount() uint32
- type GPUParticleTrails3DOptions
- type GPUParticles3D
- func (g *GPUParticles3D) ByteSize() uint64
- func (g *GPUParticles3D) Capacity() int
- func (g *GPUParticles3D) Close() error
- func (g *GPUParticles3D) Count() uint32
- func (g *GPUParticles3D) Draw(pass *gpu.RenderPass)
- func (g *GPUParticles3D) InstanceBuffer() *gpu.Buffer
- func (g *GPUParticles3D) QuadIndexBuffer() *gpu.Buffer
- func (g *GPUParticles3D) QuadVertexBuffer() *gpu.Buffer
- func (g *GPUParticles3D) Upload(e *Emitter3D, camRight, camUp math3d.Vec3) error
- func (g *GPUParticles3D) UploadBytes(data []byte) error
- func (g *GPUParticles3D) Valid() bool
- type GPUParticles3DOptions
- type HeightField3D
- type HeightGrid3D
- type HeightGrid3DDoc
- type HotConfig
- func (h *HotConfig) Apply(cfg Config)
- func (h *HotConfig) Bind(e *Emitter)
- func (h *HotConfig) Config() Config
- func (h *HotConfig) Flush() bool
- func (h *HotConfig) OnReload(fn func(Config))
- func (h *HotConfig) ReloadBytes(data []byte) error
- func (h *HotConfig) ReloadFile(path string) error
- func (h *HotConfig) ReloadHook() func(path string) error
- func (h *HotConfig) StageBytes(data []byte) error
- func (h *HotConfig) Unbind(e *Emitter)
- func (h *HotConfig) Version() uint64
- type MeshData3D
- type MeshParticlePipelineOptions
- type MeshSurface3D
- type MultiCollider
- type Particle
- type Particle3D
- type ParticleBlendMode
- type ParticleEvent
- type ParticleEventKind
- type ParticlePipelineOptions
- type QuatDoc
- type RectCollider
- type SDFGrid3D
- type SDFGrid3DDoc
- type Shape
- type Shape3D
- func Box(width, height, depth float32) Shape3D
- func Cone(radius, angle float32) Shape3D
- func EmitFromTriangles(positions []math3d.Vec3, indices []uint32) Shape3D
- func Hemisphere(radius float32) Shape3D
- func MeshShape3D(meshPath string, surf *MeshSurface3D) Shape3D
- func MeshSurface(surf *MeshSurface3D) Shape3D
- func Point3D() Shape3D
- func Points3D(points []math3d.Vec3) Shape3D
- func PointsWithNormals3D(points, normals []math3d.Vec3) Shape3D
- func Ring3D(radius float32) Shape3D
- func Sphere(radius float32) Shape3D
- type Shape3DDoc
- type ShapeDoc
- type SimulatedEmitter3D
- func (s *SimulatedEmitter3D) Active() bool
- func (s *SimulatedEmitter3D) Advance(dt time.Duration)
- func (s *SimulatedEmitter3D) Burst(count int)
- func (s *SimulatedEmitter3D) CPU() *Emitter3D
- func (s *SimulatedEmitter3D) Clear()
- func (s *SimulatedEmitter3D) Close() error
- func (s *SimulatedEmitter3D) Config() Emitter3DConfig
- func (s *SimulatedEmitter3D) Count() int
- func (s *SimulatedEmitter3D) Draw(pass *gpu.RenderPass)
- func (s *SimulatedEmitter3D) GPU() *GPUEmitter3D
- func (s *SimulatedEmitter3D) OnGPU() bool
- func (s *SimulatedEmitter3D) Prepare(pass *gpu.ComputePass, camPos, camForward, camRight, camUp math3d.Vec3) error
- func (s *SimulatedEmitter3D) Reset()
- func (s *SimulatedEmitter3D) SetReduceFlashes(fn func() bool)
- func (s *SimulatedEmitter3D) SetTransform(position math3d.Vec3, rotation math3d.Quat)
- func (s *SimulatedEmitter3D) Step(dt time.Duration)
- func (s *SimulatedEmitter3D) Update(dt time.Duration)
- type SimulatedEmitter3DOptions
- type SimulationSpace
- type SubEmitter3DDoc
- type SubEmitterDoc
- type SubEmitterMode3D
- type SubEmitterRule
- type SubEmitterRule3D
- type SubEmitterTrigger
- type System
- type TileGridCollider
- type Trail
- func (t *Trail) AddPoint(x, y float32)
- func (t *Trail) Attach(posFn func() (float32, float32))
- func (t *Trail) Clear()
- func (t *Trail) Config() TrailConfig
- func (t *Trail) Detach()
- func (t *Trail) Draw(d *core.Drawing)
- func (t *Trail) EvaluateAt(u float32) (width float32, color core.Color)
- func (t *Trail) Follow(x, y float32)
- func (t *Trail) PointCount() int
- func (t *Trail) Points() []TrailPoint
- func (t *Trail) SetConfig(cfg TrailConfig)
- func (t *Trail) Update(dt float32)
- type Trail3DConfig
- type Trail3DDoc
- type Trail3DMode
- type Trail3DPipelineOptions
- type TrailConfig
- type TrailDoc
- type TrailManager
- func (m *TrailManager) Add(cfg TrailConfig) *Trail
- func (m *TrailManager) AddTrail(tr *Trail)
- func (m *TrailManager) Clear()
- func (m *TrailManager) Count() int
- func (m *TrailManager) Draw(d *core.Drawing)
- func (m *TrailManager) Remove(tr *Trail)
- func (m *TrailManager) Trails() []*Trail
- func (m *TrailManager) Update(dt float32)
- type TrailPoint
- type Turbulence3D
- type Turbulence3DDoc
- type Vec3Doc
- type VectorField3D
- type VectorField3DDoc
Examples ¶
Constants ¶
const ( // EventDeath reports a particle whose lifetime ended or that a CollideKill impact removed. EventDeath = ParticleEventDeath // EventCollision reports a particle that hit a collider. EventCollision = ParticleEventCollision )
The particle event kinds an Effect reports.
const ( // ParticleQuadVertexStride is the byte size of one unit-quad vertex: corner (float32x2) + UV (float32x2). ParticleQuadVertexStride = 16 // ParticleQuadCornerOffset is the byte offset of the float32x2 corner in [-0.5, 0.5]². ParticleQuadCornerOffset = 0 // ParticleQuadUVOffset is the byte offset of the float32x2 texture coordinate in [0, 1]². ParticleQuadUVOffset = 8 // ParticleInstanceStride is the byte size of one packed 3D particle instance: center (12), right (12), up (12), RGBA8 color (4). ParticleInstanceStride = 40 // ParticleInstanceCenterOffset is the byte offset of the float32x3 world-space quad center. ParticleInstanceCenterOffset = 0 // ParticleInstanceRightOffset is the byte offset of the float32x3 world-space quad right vector (scaled by width). ParticleInstanceRightOffset = 12 // ParticleInstanceUpOffset is the byte offset of the float32x3 world-space quad up vector (scaled by height). ParticleInstanceUpOffset = 24 // ParticleInstanceColorOffset is the byte offset of the unorm8x4 RGBA particle color. ParticleInstanceColorOffset = 36 // ParticleFlipbookInstanceStride is the byte size of one packed flipbook particle instance: // the 40-byte [ParticleInstanceStride] record followed by uvRect (float32x4: uOffset, vOffset, uScale, vScale). ParticleFlipbookInstanceStride = 56 // ParticleFlipbookUVRectOffset is the byte offset of the float32x4 flipbook UV sub-rect. ParticleFlipbookUVRectOffset = 40 // ParticleMeshVertexStride is the byte size of one interleaved mesh vertex matching render3d.MeshVertexStride: // position (12), normal (12), UV (8). ParticleMeshVertexStride = 32 // ParticleMeshInstanceStride is the byte size of one mesh particle instance matching render3d.InstanceStride: // column-major Mat4 model (64), RGBA8 color (4), custom vec4 (16). ParticleMeshInstanceStride = 84 // Shader @location indices for [ParticleVertexLayouts] and [ParticleFlipbookVertexLayouts]. ParticleCornerLocation = 0 ParticleUVLocation = 1 ParticleCenterLocation = 2 ParticleRightLocation = 3 ParticleUpLocation = 4 ParticleColorLocation = 5 ParticleFlipbookUVRectLocation = 6 )
Interleaved vertex and per-instance layouts for instanced 3D particle drawing on gpu.View.
Slot 0 holds the shared 4-vertex unit quad ([StepVertex]); slot 1 holds one 40-byte instance per live particle ([StepInstance]) written by Emitter3D.AppendInstances, or one 56-byte flipbook instance written by Emitter3D.AppendFlipbookInstances.
const ( // SimulationCPU, like an empty Emitter3DConfig.Simulation, runs a definition on an [Emitter3D]. SimulationCPU = "cpu" // SimulationGPU runs a definition on a [GPUEmitter3D] where the device has compute shaders. SimulationGPU = "gpu" )
const EffectFormatVersion = 1
EffectFormatVersion is the current schema version of an effect file, written by MarshalEffectYAML and required by UnmarshalEffectYAML.
const FormatVersion = 1
FormatVersion is the current schema version of an emitter definition, written by MarshalConfigYAML and MarshalConfigJSON and required by UnmarshalConfigYAML and UnmarshalConfigJSON.
const MaxReducedBurstsPerSecond = 3
MaxReducedBurstsPerSecond is the most bursts an emitter allows in any rolling simulated second while ReduceFlashes reports true, keeping strobe-like repeating bursts within the WCAG 2.3.1 / XAG 118 three-flashes-per-second guideline.
const ParticleFlipbookTexturedWGSL = `` /* 1059-byte string literal not displayed */
ParticleFlipbookTexturedWGSL is a WGSL shader module for textured instanced 3D billboard particles with per-instance flipbook UV sub-rectangles.
It binds the standard camera uniform at @group(0) @binding(0), the particle atlas texture at @group(1) @binding(0), and the sampler at @group(1) @binding(1). Entry points are "vs_main" and "fs_textured".
const ParticleMeshTexturedWGSL = `` /* 1606-byte string literal not displayed */
ParticleMeshTexturedWGSL is a WGSL shader module for textured instanced 3D mesh particles (supporting per-instance flipbook UV sub-rects in @location(8)).
It binds the standard camera uniform at @group(0) @binding(0), the texture at @group(1) @binding(0), and the sampler at @group(1) @binding(1). Entry points are "vs_main" and "fs_textured".
const ParticleMeshWGSL = `` /* 1409-byte string literal not displayed */
ParticleMeshWGSL is a WGSL shader module for instanced 3D mesh particles using ParticleMeshVertexLayouts (matching render3d.MeshVertexLayout + render3d.InstancedMeshLayout).
It binds the standard camera uniform at @group(0) @binding(0). Entry points are "vs_main" and "fs_main".
const ParticleSoftCircleWGSL = `` /* 955-byte string literal not displayed */
ParticleSoftCircleWGSL is a WGSL shader module for soft radial-falloff instanced 3D billboard particles without requiring a texture.
It binds the standard camera uniform at @group(0) @binding(0). Entry points are "vs_main" and "fs_main".
const ParticleTexturedWGSL = `` /* 993-byte string literal not displayed */
ParticleTexturedWGSL is a WGSL shader module for textured instanced 3D billboard particles.
It binds the standard camera uniform at @group(0) @binding(0), the particle texture at @group(1) @binding(0), and the sampler at @group(1) @binding(1). Entry points are "vs_main" and "fs_textured".
const ParticleTrail3DWGSL = `` /* 682-byte string literal not displayed */
ParticleTrail3DWGSL is a WGSL shader module for 3D particle ribbon and tube trails. It binds the standard 3D camera uniform at @group(0) @binding(0). Entry points are "vs_main" and "fs_main".
const ParticleWGSL = `` /* 824-byte string literal not displayed */
ParticleWGSL is a WGSL shader module for solid-colored instanced 3D billboard particles.
Its @group(0) @binding(0) camera uniform block matches render3d.CameraWGSL (view, proj, view_proj, eye) byte for byte, so render3d.CameraBuffer binds directly to it. Entry points are "vs_main" and "fs_main".
const ReducedFlashAlpha float32 = 0.25
ReducedFlashAlpha caps particle opacity when Emitter.ReduceFlashes or Emitter3D.ReduceFlashes reports true, turning harsh strobe particles into a low-contrast tint.
const Schema3DURL = "https://nsgo.games/schemas/particles3d.v1.json"
Schema3DURL is where the JSON Schema of version 1 3D particle emitter definitions is published.
const SchemaURL = "https://nsgo.games/schemas/particles.v1.json"
SchemaURL is where the JSON Schema of version 1 2D particle emitter definitions is published.
const ( // Trail3DVertexStride is the byte size of one packed 3D trail vertex: // position (float32x3, 12B) + normal (float32x3, 12B) + uv (float32x2, 8B) + color (unorm8x4, 4B) = 36 bytes. // It matches render3d.TrailVertexStride byte for byte. Trail3DVertexStride = 36 )
Variables ¶
This section is empty.
Functions ¶
func MarshalConfig3DJSON ¶
func MarshalConfig3DJSON(cfg Emitter3DConfig) ([]byte, error)
MarshalConfig3DJSON encodes cfg into the versioned JSON form of the 3D emitter definition (version: 1).
func MarshalConfig3DYAML ¶
func MarshalConfig3DYAML(cfg Emitter3DConfig) ([]byte, error)
MarshalConfig3DYAML encodes cfg as a versioned YAML 3D emitter definition (version: 1) with fixed key order and 2-space indentation, so saving the same Emitter3DConfig always yields the same bytes.
func MarshalConfigJSON ¶
MarshalConfigJSON encodes cfg into the versioned JSON form of the emitter definition (version: 1). Files people write use YAML (MarshalConfigYAML, SaveConfigFile); the JSON form is for programs that exchange definitions as JSON.
Example ¶
MarshalConfigJSON saves an emitter's configuration as text that UnmarshalConfigJSON loads back unchanged.
package main
import (
"fmt"
"math"
"time"
"github.com/nsgo-dev/game/pkg/particles"
)
func sparks() particles.Config {
return particles.Config{
X: 100, Y: 100,
Shape: particles.Circle(4),
LifetimeMin: 500 * time.Millisecond, LifetimeMax: time.Second,
SpeedMin: 40, SpeedMax: 80,
AngleMin: 0, AngleMax: 2 * math.Pi,
GravityY: 200,
AlphaCurve: particles.FloatCurve{{T: 0, Value: 1}, {T: 1, Value: 0}},
Seed: 7,
}
}
func main() {
data, err := particles.MarshalConfigJSON(sparks())
if err != nil {
fmt.Println(err)
return
}
cfg, err := particles.UnmarshalConfigJSON(data)
if err != nil {
fmt.Println(err)
return
}
again, _ := particles.MarshalConfigJSON(cfg)
fmt.Println(string(again) == string(data), cfg.Seed, cfg.LifetimeMax)
}
Output: true 7 1s
func MarshalConfigYAML ¶
MarshalConfigYAML encodes cfg as a versioned YAML emitter definition (version: 1) with fixed key order and 2-space indentation, so saving the same Config always yields the same bytes.
func MarshalEffectYAML ¶
MarshalEffectYAML encodes e as a versioned YAML effect file (version: 1) with fixed key order (parameters sorted by name) and 2-space indentation, so saving the same Effect always yields the same bytes. It refuses an Effect that UnmarshalEffectYAML would refuse.
func NewMeshParticlePipeline ¶
func NewMeshParticlePipeline(cx *core.Scope, dev *gpu.Device, opts MeshParticlePipelineOptions) (*gpu.Pipeline, error)
NewMeshParticlePipeline compiles ParticleMeshWGSL (or ParticleMeshTexturedWGSL when TextureLayout is non-nil) and creates a gpu.Pipeline for GPUMeshParticles3D.Draw.
func NewParticlePipeline ¶
func NewParticlePipeline(cx *core.Scope, dev *gpu.Device, opts ParticlePipelineOptions) (*gpu.Pipeline, error)
NewParticlePipeline compiles the built-in 3D particle WGSL module and creates a gpu.Pipeline configured for GPUParticles3D.Draw, scoped to cx.
func NewTrail3DPipeline ¶
func NewTrail3DPipeline(cx *core.Scope, dev *gpu.Device, opts Trail3DPipelineOptions) (*gpu.Pipeline, error)
NewTrail3DPipeline compiles ParticleTrail3DWGSL and creates a gpu.Pipeline for GPUParticleTrails3D.Draw.
func ParticleFlipbookVertexLayouts ¶
func ParticleFlipbookVertexLayouts() []gpu.VertexBufferLayout
ParticleFlipbookVertexLayouts returns the two vertex buffer layouts (slot 0 = unit quad per-vertex, slot 1 = 56-byte flipbook per-instance) expected by ParticleFlipbookTexturedWGSL and flipbook GPUParticles3D.Draw.
func ParticleMeshVertexLayouts ¶
func ParticleMeshVertexLayouts() []gpu.VertexBufferLayout
ParticleMeshVertexLayouts returns the two vertex buffer layouts for instanced mesh particles: slot 0 = 32-byte mesh vertices (matching render3d.MeshVertexLayout), slot 1 = 84-byte mesh instances (matching render3d.InstancedMeshLayout).
func ParticleVertexLayouts ¶
func ParticleVertexLayouts() []gpu.VertexBufferLayout
ParticleVertexLayouts returns the two vertex buffer layouts (slot 0 = unit quad per-vertex, slot 1 = packed particle per-instance) expected by ParticleWGSL, ParticleTexturedWGSL and GPUParticles3D.Draw.
func SaveConfig3DFile ¶
func SaveConfig3DFile(path string, cfg Emitter3DConfig) error
SaveConfig3DFile writes cfg as a versioned YAML 3D emitter definition file to path.
func SaveConfigFile ¶
SaveConfigFile encodes cfg as a versioned YAML emitter definition and writes it to path.
func Trail3DVertexLayout ¶
func Trail3DVertexLayout() gpu.VertexBufferLayout
Trail3DVertexLayout returns the slot-0 per-vertex layout matching Emitter3D.AppendTrailVertices, ParticleTrail3DWGSL, and render3d.TrailVertexLayout.
func ValidateGPUConfig3D ¶
func ValidateGPUConfig3D(dev *gpu.Device, cfg Emitter3DConfig) error
ValidateGPUConfig3D reports whether dev can simulate cfg with NewGPUEmitter3D, naming the field to change when it cannot.
Types ¶
type Attractor3D ¶
type Attractor3D struct {
Kind Attractor3DKind
Position math3d.Vec3
Rotation math3d.Quat
Radius float32
Size math3d.Vec3
Strength float32
Attenuation float32
Directionality float32
Direction math3d.Vec3
VectorField *VectorField3D
// VectorFieldFn is an optional runtime vector field callback for Attractor3DVectorField. Not serialized.
VectorFieldFn func(p math3d.Vec3) math3d.Vec3
}
Attractor3D applies an attraction, repulsion, or vector-field acceleration to 3D particles inside its volume.
func BoxAttractor3D ¶
func BoxAttractor3D(pos, size math3d.Vec3, strength, attenuation float32) Attractor3D
BoxAttractor3D returns a box attractor centered at pos with full extents size, strength, and falloff attenuation.
func SphereAttractor3D ¶
func SphereAttractor3D(pos math3d.Vec3, radius, strength, attenuation float32) Attractor3D
SphereAttractor3D returns a spherical attractor centered at pos with influence radius, strength, and falloff attenuation.
func VectorFieldAttractor3D ¶
func VectorFieldAttractor3D(pos, size math3d.Vec3, field *VectorField3D, strength float32) Attractor3D
VectorFieldAttractor3D returns a vector-field attractor backed by field.
type Attractor3DDoc ¶
type Attractor3DDoc struct {
// Kind selects the attractor volume: "sphere", "box" or "vectorField".
Kind string `yaml:"kind,omitempty" schema:"enum=sphere|box|vectorField"`
// Position is the world-space center of the attractor.
Position *Vec3Doc `yaml:"position,omitempty"`
// Rotation is the optional orientation quaternion of a box or vector-field attractor.
Rotation *QuatDoc `yaml:"rotation,omitempty"`
// Radius is the influence radius of a sphere attractor.
Radius float32 `yaml:"radius,omitempty" schema:"minimum=0"`
// Size is the full width, height and depth of a box or vector-field attractor.
Size *Vec3Doc `yaml:"size,omitempty"`
// Strength is the acceleration magnitude (positive attracts, negative repels).
Strength float32 `yaml:"strength,omitempty"`
// Attenuation is the falloff exponent from center to boundary (>= 0).
Attenuation float32 `yaml:"attenuation,omitempty" schema:"minimum=0"`
// Directionality blends radial pull (0) with directional push along Direction (1).
Directionality float32 `yaml:"directionality,omitempty" schema:"minimum=0"`
// Direction is the optional directional axis used when directionality > 0 (defaults to -Z).
Direction *Vec3Doc `yaml:"direction,omitempty"`
// VectorField is an optional inline 3D vector grid for kind "vectorField".
VectorField *VectorField3DDoc `yaml:"vectorField,omitempty"`
}
Attractor3DDoc describes one 3D particle attractor in YAML.
type Attractor3DKind ¶
type Attractor3DKind uint8
Attractor3DKind selects the influence volume and force field of an Attractor3D.
const ( // Attractor3DSphere attracts particles within Radius of Position ("sphere"). Attractor3DSphere Attractor3DKind = iota // Attractor3DBox attracts particles inside an oriented box of full extents Size centered at Position ("box"). Attractor3DBox // Attractor3DVectorField accelerates particles using a 3D vector field grid or callback ("vectorField"). Attractor3DVectorField )
func (Attractor3DKind) String ¶
func (k Attractor3DKind) String() string
String returns the canonical string name of the 3D attractor kind.
type BillboardMode3D ¶
type BillboardMode3D uint8
BillboardMode3D selects how Emitter3D orients each particle quad toward the camera when packing GPU instances.
const ( // BillboardSpherical aligns every particle quad with the camera's view plane (right and up axes), applying per-particle roll rotation. This is the zero value and fastest mode. BillboardSpherical BillboardMode3D = iota // BillboardCylindrical locks each quad's up axis to [Emitter3D.Axis] (defaulting to +Y) and rotates only around that axis to face the camera. BillboardCylindrical // BillboardStretched aligns each quad's height axis with the particle's velocity vector and stretches its length proportionally to speed while facing the camera across the velocity axis. BillboardStretched )
func (BillboardMode3D) String ¶
func (m BillboardMode3D) String() string
String returns the canonical string name of the billboard mode.
type Burst ¶
type Burst struct {
// Time is the elapsed emitter time when the first burst fires (>= 0).
Time time.Duration
// Count is how many particles to emit on each firing (> 0).
Count int
// Cycles is how many times the burst fires: 0 or 1 means once, and a negative value repeats indefinitely every Interval.
Cycles int
// Interval is the delay between repeated firings when Cycles != 1 (must be > 0 to repeat).
Interval time.Duration
}
Burst schedules an automatic burst of particles during Emitter.Update.
type BurstDoc ¶
type BurstDoc struct {
// Time is the elapsed emitter time when the first burst fires, as a Go duration string such as "250ms".
Time time.Duration `yaml:"time,omitempty"`
// Count is the number of particles emitted on each firing.
Count int `yaml:"count,omitempty" schema:"minimum=0"`
// Cycles is how many times the burst fires (0 or 1 means once; negative repeats indefinitely every interval).
Cycles int `yaml:"cycles,omitempty"`
// Interval is the delay between repeated firings as a Go duration string such as "1s".
Interval time.Duration `yaml:"interval,omitempty"`
}
BurstDoc describes one scheduled particle burst in YAML.
type CircleCollider ¶
type CircleCollider struct {
X, Y, Radius float32
}
CircleCollider resolves particle collisions against a solid circle centered at (X, Y) with Radius.
func (*CircleCollider) ResolveParticle ¶
func (c *CircleCollider) ResolveParticle(prevX, prevY, x, y, radius float32) (hit bool, hitX, hitY, nx, ny float32)
ResolveParticle implements Collider with zero heap allocations.
type Collider ¶
type Collider interface {
ResolveParticle(prevX, prevY, x, y, radius float32) (hit bool, hitX, hitY, nx, ny float32)
}
Collider resolves a particle's movement from (prevX, prevY) to (x, y) with the given radius. When hit is true, (hitX, hitY) is the resolved particle center position and (nx, ny) is the unit surface normal pointing out of the obstacle.
type Collider3D ¶
type Collider3D struct {
Kind Collider3DKind
Position math3d.Vec3
Normal math3d.Vec3
Size math3d.Vec3
Radius float32
Rotation math3d.Quat
Bounce float32
Friction float32
Kill bool
// SDF is an optional serializable 3D signed distance grid for Collider3DSDF.
SDF *SDFGrid3D
// SDFFunc is an optional runtime signed distance function for Collider3DSDF (negative = inside). Not serialized.
SDFFunc func(p math3d.Vec3) float32
// HeightGrid is an optional serializable height field for Collider3DHeightField.
HeightGrid *HeightGrid3D
// HeightField is an optional runtime height field for Collider3DHeightField (e.g. *world3d.Heightmap). Not serialized.
HeightField HeightField3D
// Raycast is an optional runtime swept collision callback for Collider3DRaycast (e.g. physics3d raycasts). Not serialized.
Raycast func(from, to math3d.Vec3, radius float32) (hit bool, hitPos, normal math3d.Vec3)
}
Collider3D describes one 3D obstacle that particles collide against during Emitter3D.Step.
func BoxCollider3D ¶
func BoxCollider3D(center, size math3d.Vec3, bounce, friction float32) Collider3D
BoxCollider3D returns a box collider centered at center with full extents size.
func HeightFieldCollider3D ¶
func HeightFieldCollider3D(hf HeightField3D, bounce, friction float32) Collider3D
HeightFieldCollider3D returns a collider backed by a HeightField3D (such as *world3d.Heightmap or *HeightGrid3D).
func PlaneCollider3D ¶
func PlaneCollider3D(point, normal math3d.Vec3, bounce, friction float32) Collider3D
PlaneCollider3D returns an infinite plane collider through point with outward normal.
func RaycastCollider3D ¶
func RaycastCollider3D(fn func(from, to math3d.Vec3, radius float32) (hit bool, hitPos, normal math3d.Vec3), bounce, friction float32) Collider3D
RaycastCollider3D returns a collider backed by a custom swept raycast callback (such as physics3d.World.Raycast).
func SDFCollider3D ¶
func SDFCollider3D(fn func(math3d.Vec3) float32, bounce, friction float32) Collider3D
SDFCollider3D returns a collider backed by a runtime signed distance function (negative = inside).
func SDFGridCollider3D ¶
func SDFGridCollider3D(grid *SDFGrid3D, bounce, friction float32) Collider3D
SDFGridCollider3D returns a collider backed by a 3D signed distance grid.
func SphereCollider3D ¶
func SphereCollider3D(center math3d.Vec3, radius, bounce, friction float32) Collider3D
SphereCollider3D returns a sphere collider centered at center with radius.
type Collider3DDoc ¶
type Collider3DDoc struct {
// Kind selects the obstacle shape: "plane", "box", "sphere", "sdf", "heightfield" or "raycast".
Kind string `yaml:"kind,omitempty" schema:"enum=plane|box|sphere|sdf|heightfield|raycast"`
// Position is a point on the plane or the center of a box or sphere collider.
Position *Vec3Doc `yaml:"position,omitempty"`
// Normal is the outward surface normal for a plane collider (defaults to +Y).
Normal *Vec3Doc `yaml:"normal,omitempty"`
// Size is the full width, height and depth of a box collider.
Size *Vec3Doc `yaml:"size,omitempty"`
// Radius is the radius of a sphere collider.
Radius float32 `yaml:"radius,omitempty" schema:"minimum=0"`
// Rotation is the optional orientation quaternion of a box collider.
Rotation *QuatDoc `yaml:"rotation,omitempty"`
// Bounce is the restitution factor applied to normal impact velocity (>= 0).
Bounce float32 `yaml:"bounce,omitempty" schema:"minimum=0"`
// Friction damps tangential velocity on impact, in [0, 1].
Friction float32 `yaml:"friction,omitempty" schema:"minimum=0"`
// Kill immediately expires particles upon impact.
Kill bool `yaml:"kill,omitempty"`
// SDF is an optional inline 3D signed distance grid for kind "sdf".
SDF *SDFGrid3DDoc `yaml:"sdf,omitempty"`
// HeightGrid is an optional inline height field grid for kind "heightfield".
HeightGrid *HeightGrid3DDoc `yaml:"heightGrid,omitempty"`
}
Collider3DDoc describes one 3D particle collider in YAML.
type Collider3DKind ¶
type Collider3DKind uint8
Collider3DKind selects the geometry type of a Collider3D.
const ( // Collider3DPlane is an infinite half-space defined by Position (a point on the plane) and Normal ("plane"). Collider3DPlane Collider3DKind = iota // Collider3DBox is an oriented box centered at Position with full extents Size and optional Rotation ("box"). Collider3DBox // Collider3DSphere is a sphere centered at Position with Radius ("sphere"). Collider3DSphere // Collider3DSDF is a signed distance field backed by SDF (grid) or SDFFunc (callback) ("sdf"). Collider3DSDF // Collider3DHeightField is a height field backed by HeightGrid or HeightField (e.g. *world3d.Heightmap) ("heightfield"). Collider3DHeightField // Collider3DRaycast delegates swept particle collision to Raycast (e.g. physics3d raycasts) ("raycast"). Collider3DRaycast )
func (Collider3DKind) String ¶
func (k Collider3DKind) String() string
String returns the canonical string name of the 3D collider kind.
type CollisionConfig ¶
type CollisionConfig struct {
// Enabled turns collision checking on during Update when true and Collider is non-nil.
Enabled bool
// Mode controls the particle's response on impact.
Mode CollisionMode
// Bounce is the restitution factor applied to the normal velocity component in CollideBounce mode.
Bounce float32
// Friction damps tangential velocity on impact in CollideBounce mode, clamped to [0, 1].
Friction float32
// Radius is the particle's collision radius in points (>= 0).
Radius float32
// Collider tests and resolves particle contacts. Not serialized in JSON configs.
Collider Collider
}
CollisionConfig configures particle collision detection and response on an Emitter.
type CollisionDoc ¶
type CollisionDoc struct {
// Enabled turns particle collision checking on when a runtime Collider is attached.
Enabled bool `yaml:"enabled,omitempty"`
// Mode selects the impact response: "none", "stop", "bounce" or "kill".
Mode string `yaml:"mode,omitempty" schema:"enum=none|stop|bounce|kill"`
// Bounce is the restitution factor applied to normal velocity in "bounce" mode.
Bounce float32 `yaml:"bounce,omitempty"`
// Friction damps tangential velocity on impact in "bounce" mode, clamped to [0, 1].
Friction float32 `yaml:"friction,omitempty"`
// Radius is the particle collision radius in points.
Radius float32 `yaml:"radius,omitempty"`
}
CollisionDoc describes particle collision settings in YAML.
type CollisionMode ¶
type CollisionMode uint8
CollisionMode controls how a particle responds when it hits a Collider.
const ( // CollideNone disables collision response. CollideNone CollisionMode = iota // CollideStop halts the particle at the contact point with zero velocity. CollideStop // CollideBounce reflects the particle's velocity using Bounce (restitution) and Friction. CollideBounce // CollideKill immediately expires the particle upon impact. CollideKill )
func (CollisionMode) String ¶
func (m CollisionMode) String() string
String returns the canonical string name of the collision mode.
type ColorCurve ¶
type ColorCurve []ColorStop
ColorCurve maps a particle's normalized age in [0, 1] to a core.Color by linear RGBA interpolation between stops ordered by T. An empty curve returns opaque white (0xffffffff).
type ColorStop ¶
ColorStop is one control point on a ColorCurve at normalized particle age T in [0, 1].
type ColorStopDoc ¶
type ColorStopDoc struct {
// T is the normalized particle age in [0, 1].
T float32 `yaml:"t"`
// Color is a quoted hex color string "#rrggbb" or "#rrggbbaa".
Color string `yaml:"color"`
}
ColorStopDoc is one control point on a color curve at normalized age t in [0, 1].
type Config ¶
type Config struct {
X, Y float32
Rotation float32
Space SimulationSpace
Shape Shape
Rate float32
Bursts []Burst
MaxParticles int
LifetimeMin time.Duration
LifetimeMax time.Duration
SpeedMin float32
SpeedMax float32
AngleMin float32
AngleMax float32
GravityX float32
GravityY float32
DampingMin float32
DampingMax float32
RadialAccelMin float32
RadialAccelMax float32
TangentialAccelMin float32
TangentialAccelMax float32
InitialRotationMin float32
InitialRotationMax float32
RotationSpeedMin float32
RotationSpeedMax float32
SizeCurve FloatCurve
AlphaCurve FloatCurve
RotationCurve FloatCurve
ColorCurve ColorCurve
Seed uint64
Z int
FrameNames []string
Collision CollisionConfig
Trail *TrailConfig
SubEmitters []SubEmitterRule
}
Config is a serializable, reloadable snapshot of an Emitter's configuration.
func LoadConfigFS ¶
LoadConfigFS reads and decodes a versioned YAML emitter definition file from fsys. Its errors are *loaderr.Error values that name the file.
func LoadConfigFile ¶
LoadConfigFile reads and decodes a versioned YAML emitter definition file from disk. Its errors are *loaderr.Error values that name path.
func UnmarshalConfigJSON ¶
UnmarshalConfigJSON decodes the versioned JSON form of an emitter definition into a Config. Its errors are *loaderr.Error values, as UnmarshalConfigYAML's are.
func UnmarshalConfigYAML ¶
UnmarshalConfigYAML decodes a versioned YAML emitter definition into a Config. It refuses unknown fields, a key with no value, a second YAML document, a version other than FormatVersion or one inside a sub-emitter, an integer field written with a fraction, a shape size that does not apply to its kind, durations that are not strings such as "500ms", and colors that are not quoted "#rrggbb" or "#rrggbbaa" strings.
Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile, as LoadConfigFile does.
type DrawPass3D ¶
type DrawPass3D struct {
Kind DrawPass3DKind
MeshPath string
Material string
}
DrawPass3D describes one rendering pass declared on an Emitter3DConfig.
type DrawPass3DDoc ¶
type DrawPass3DDoc struct {
// Kind selects how particles render in this pass: "quad", "mesh" or "trail".
Kind string `yaml:"kind,omitempty" schema:"enum=quad|mesh|trail"`
// MeshPath is the project-relative mesh asset path when kind is "mesh".
MeshPath string `yaml:"meshPath,omitempty"`
// Material is an optional project-relative material asset path for this pass.
Material string `yaml:"material,omitempty"`
}
DrawPass3DDoc describes one 3D rendering pass in YAML.
type DrawPass3DKind ¶
type DrawPass3DKind uint8
DrawPass3DKind selects how one draw pass of an Emitter3D renders particles.
const ( // DrawPass3DQuad draws particles as camera-facing or stretched billboard quads ("quad"). DrawPass3DQuad DrawPass3DKind = iota // DrawPass3DMesh draws each particle as an instanced 3D mesh ("mesh"). DrawPass3DMesh // DrawPass3DTrail draws each particle's ribbon or tube trail ("trail"). DrawPass3DTrail )
func (DrawPass3DKind) String ¶
func (k DrawPass3DKind) String() string
String returns the canonical string name of the 3D draw pass kind.
type Effect ¶
type Effect struct {
Emitters []EffectEmitter
// Emitters3D are the effect's 3D emitters, in the same file shape as Emitters.
Emitters3D []EffectEmitter3D
// Params maps a parameter's name to its type and current value; the file holds the defaults.
Params map[string]EffectParam
// contains filtered or unexported fields
}
Effect is an effect file: several emitters that play as one effect, and the typed parameters the game sets on it.
func UnmarshalEffectYAML ¶
UnmarshalEffectYAML decodes a versioned YAML effect file. Besides what UnmarshalConfigYAML refuses in an inline config (and a version inside one), it refuses a version other than EffectFormatVersion, an effect with no emitters, an emitter with both or neither of file and config, a file path that is not a valid slash-separated relative path, a negative delay or duration, an unknown minQuality, a parameter of an unknown type, and a parameter whose value is missing, not finite, or written under another type's key.
Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it.
func (*Effect) Revision ¶
Revision returns a counter that starts at 0 and increments on every successful SetParam or SetParamValue that changes a parameter. An EffectPlayer compares it to know when to resolve bindings again.
func (*Effect) SetParam ¶
SetParam sets the declared parameter name to value, which must be of the parameter's type: a float64 or float32 for float, an int for int, a core.Color for color, and a [2]float32 for vec2. It refuses an undeclared name, a value of another type, and a value that is not finite, leaving the parameter unchanged.
func (*Effect) SetParamValue ¶
SetParamValue sets a declared parameter from a YAML-decoded value, as a scene's particles params mapping gives them: a whole number or float for float and int params, a quoted color string such as "#rrggbb" or "#rrggbbaa" for color params, and a list of two numbers for vec2 params. A float param also accepts whole numbers. It refuses an undeclared name, a value of another type, a fractional int, and a color it cannot parse, leaving the parameter unchanged.
type EffectBinding ¶
type EffectBinding struct {
// Field is the field's path within the emitter's inline config, such as "rate" or "sizeCurve[1].value"; for the emitter's placement it is "offsetX", "offsetY" or "offsetZ".
Field string
// Param is the declared parameter that drives the field.
Param string
// Scale multiplies the parameter before it is written; 1 leaves it as it is. It applies to float and int fields; color fields take no scale.
Scale float64
// Kind is the field's type: EffectParamFloat, EffectParamInt or EffectParamColor; the parameter must have the same type.
Kind EffectParamType
}
EffectBinding writes an effect parameter into one field of an emitter, with an optional scale.
type EffectCull ¶
type EffectCull struct {
// View is the world-space rectangle a camera shows; a zero width or height disables off-screen culling.
View core.Bounds
// Viewer is the point distances are measured from, such as the camera's center.
Viewer core.Point
// MaxDistance culls the effect when its bounds lie farther than this many points from Viewer; zero or less disables distance culling.
MaxDistance float32
}
EffectCull controls distance and off-screen culling of an EffectPlayer.
type EffectEmitter ¶
type EffectEmitter struct {
// File is the slash-separated path of a particle emitter definition, relative to the asset root.
File string
// Config is an inline emitter definition, in the schema of an emitter file without its version.
Config *Config
// OffsetX and OffsetY move the emitter from the effect's origin.
OffsetX, OffsetY float32
// Delay is how long after the effect starts the emitter starts.
Delay time.Duration
// Duration is how long the emitter emits once started; zero means until the effect stops.
Duration time.Duration
// MinQuality is the lowest quality level the emitter plays at ("low", "medium" or "high"); empty means every level.
MinQuality string
// Bindings bind fields of Config to parameters; they are only set on inline configs.
Bindings []EffectBinding
// Events selects which particle events this emitter reports to Effect.OnEvent and how many per second.
Events EffectEvents
}
EffectEmitter is one 2D emitter of an Effect: exactly one of File and Config is set.
type EffectEmitter3D ¶
type EffectEmitter3D struct {
// File is the slash-separated path of a 3D particle emitter definition, relative to the asset root.
File string
// Config is an inline 3D emitter definition, in the schema of a 3D emitter file without its version.
Config *Emitter3DConfig
// OffsetX, OffsetY and OffsetZ move the emitter from the effect's origin.
OffsetX, OffsetY, OffsetZ float32
// Delay is how long after the effect starts the emitter starts.
Delay time.Duration
// Duration is how long the emitter emits once started; zero means until the effect stops.
Duration time.Duration
// MinQuality is the lowest quality level the emitter plays at ("low", "medium" or "high"); empty means every level.
MinQuality string
// Bindings bind fields of Config to parameters; they are only set on inline configs.
Bindings []EffectBinding
}
EffectEmitter3D is one 3D emitter of an Effect: exactly one of File and Config is set.
type EffectEventKind ¶
type EffectEventKind = ParticleEventKind
EffectEventKind identifies the particle event an Effect reports.
type EffectEvents ¶
type EffectEvents struct {
// Death reports particle deaths.
Death bool
// Collision reports particles hitting a collider.
Collision bool
// MaxPerSecond caps the events this emitter reports per second; zero reports every event.
MaxPerSecond int
}
EffectEvents configures which particle events an effect emitter reports and how many per second.
type EffectFiles ¶
type EffectFiles struct {
// Particle2D loads a 2D emitter definition, required when the effect has a file-backed 2D emitter.
Particle2D func(path string) (Config, error)
// Particle3D loads a 3D emitter definition, required when the effect has a file-backed 3D emitter.
Particle3D func(path string) (Emitter3DConfig, error)
}
EffectFiles loads the emitter definitions an Effect's file-backed emitters name.
type EffectParam ¶
type EffectParam struct {
Type EffectParamType
Float float64
Int int
Color core.Color
Vec2 [2]float32
}
EffectParam is a typed effect parameter. Only the value field of its Type is set.
type EffectParamType ¶
type EffectParamType string
EffectParamType names the type of an effect parameter.
const ( EffectParamFloat EffectParamType = "float" EffectParamInt EffectParamType = "int" EffectParamColor EffectParamType = "color" EffectParamVec2 EffectParamType = "vec2" )
The effect parameter types.
type EffectPlayer ¶
type EffectPlayer struct {
// contains filtered or unexported fields
}
EffectPlayer plays an Effect in the world: it builds one live emitter per effect emitter, loads file-backed definitions, honours each emitter's delay, duration and minQuality, binds parameters to emitter fields, reports particle events, and culls the effect by distance and visibility.
Call Play once to start it, Update from the game's fixed step and Draw from the canvas callback. SetParam on the Effect it was built from changes a bound field on the player's next Update. The zero value is not usable; use NewEffectPlayer.
func NewEffectPlayer ¶
func NewEffectPlayer(e *Effect, files EffectFiles) (*EffectPlayer, error)
NewEffectPlayer builds a player for e, loading each file-backed emitter through files. It fails when e is invalid or a file-backed emitter has no loader or its definition fails to load, and leaves e unchanged. The player reports events only after OnEvent is called, and starts at the High quality level so every emitter plays until SetQuality says otherwise.
func (*EffectPlayer) ClearZ ¶
func (p *EffectPlayer) ClearZ()
ClearZ drops a SetZ override, returning each emitter to its config's z.
func (*EffectPlayer) Culled ¶
func (p *EffectPlayer) Culled() bool
Culled reports whether the effect is currently culled by SetCull, so Update and Draw skip it.
func (*EffectPlayer) Draw ¶
func (p *EffectPlayer) Draw(d *core.Drawing)
Draw draws every 2D emitter that has started and is allowed at the current quality level.
func (*EffectPlayer) Elapsed ¶
func (p *EffectPlayer) Elapsed() time.Duration
Elapsed returns how long the current play has run.
func (*EffectPlayer) Emitters ¶
func (p *EffectPlayer) Emitters() []*Emitter
Emitters returns the player's live 2D emitters in effect order, for attaching colliders or reading particle counts.
func (*EffectPlayer) Emitters3D ¶
func (p *EffectPlayer) Emitters3D() []*Emitter3D
Emitters3D returns the player's live 3D emitters in effect order, for packing and drawing instances.
func (*EffectPlayer) Err ¶
func (p *EffectPlayer) Err() error
Err returns the last parameter-resolution error, or nil. A player reports one only when a param was removed or retyped after load, or when a scaled binding value overflows.
func (*EffectPlayer) OnEvent ¶
func (p *EffectPlayer) OnEvent(fn func(Event))
OnEvent sets the callback that receives the death and collision events the effect's emitters opt in to. Passing nil stops reporting.
func (*EffectPlayer) Play ¶
func (p *EffectPlayer) Play(x, y float32)
Play starts or restarts the effect at (x, y), re-seeding every emitter so the same seed replays identically.
func (*EffectPlayer) Playing ¶
func (p *EffectPlayer) Playing() bool
Playing reports whether the effect has started and not been stopped.
func (*EffectPlayer) Quality ¶
func (p *EffectPlayer) Quality() quality.Level
Quality returns the level the player compares minQuality against.
func (*EffectPlayer) SetAtlas ¶
func (p *EffectPlayer) SetAtlas(a *sprite.Atlas) error
SetAtlas sets the atlas every 2D emitter resolves its frame names from. It refuses an atlas missing any emitter's (or sub-emitter's) frame names without modifying the player. Passing nil clears the atlas and resolved frames.
func (*EffectPlayer) SetCull ¶
func (p *EffectPlayer) SetCull(c EffectCull)
SetCull sets the distance and off-screen culling the player applies before stepping and drawing.
func (*EffectPlayer) SetQuality ¶
func (p *EffectPlayer) SetQuality(level quality.Level)
SetQuality sets the quality level the player compares each emitter's minQuality against. The default is High, so every emitter plays. An emitter below the level stops emitting from the next step and keeps its live particles.
func (*EffectPlayer) SetTransform ¶
func (p *EffectPlayer) SetTransform(x, y, rotation float32)
SetTransform moves and rotates the effect, applying the emitter offsets rotated around the effect origin. Scenes call it when their object moves. Non-finite coordinates or rotations are ignored.
func (*EffectPlayer) SetZ ¶
func (p *EffectPlayer) SetZ(z int)
SetZ overrides the Z draw order of every 2D emitter, as a scene object's z does.
func (*EffectPlayer) Stop ¶
func (p *EffectPlayer) Stop()
Stop stops all emission. Emitters with no duration stop at the player's current time, and live particles age out through their lifetimes.
func (*EffectPlayer) TotalCount ¶
func (p *EffectPlayer) TotalCount() int
TotalCount returns the live particles across every 2D emitter and its sub-emitters.
func (*EffectPlayer) Update ¶
func (p *EffectPlayer) Update(dt time.Duration)
Update advances the effect by dt, starting and stopping each emitter at its delay and duration, and applies any parameter change since the last step. A culled effect does not step, so it resumes where it stopped.
type Emitter ¶
type Emitter struct {
// Atlas holds the image that Frames reference. Draw skips particle sprites when Atlas is nil.
Atlas *sprite.Atlas
// Frames are the atlas frames particles choose from at spawn time.
Frames []sprite.Frame
// X and Y are the emitter's position in the drawing.
X, Y float32
// Rotation is the emitter's rotation in radians, clockwise on the screen.
Rotation float32
// Space controls whether particles simulate in world space (SpaceWorld, default) or emitter-local space (SpaceLocal).
Space SimulationSpace
// Shape controls where particles spawn relative to X, Y; its zero value is Point.
Shape Shape
// Rate is how many particles emit per second during Update; 0 or less disables continuous emission.
Rate float32
// Bursts schedules automatic bursts of particles at specific elapsed times during Update.
Bursts []Burst
// MaxParticles caps how many particles may be live at once, 256 when 0 or less.
MaxParticles int
// LifetimeMin and LifetimeMax give how long each particle lives; both 0 defaults to one second, and a LifetimeMax below LifetimeMin matches LifetimeMin.
LifetimeMin, LifetimeMax time.Duration
// SpeedMin and SpeedMax give each particle's initial speed in points per second.
SpeedMin, SpeedMax float32
// AngleMin and AngleMax give each particle's initial direction of travel in radians, clockwise from +X.
AngleMin, AngleMax float32
// GravityX and GravityY are constant acceleration applied to live particles, in points per second squared.
GravityX, GravityY float32
// DampingMin and DampingMax give each particle's damping, picked once at spawn: how much its speed drops per second, in points per second squared, never below zero. A negative value does not damp.
DampingMin, DampingMax float32
// RadialAccelMin and RadialAccelMax give each particle's radial acceleration, picked once at spawn, in points per second squared: positive pushes it away from the emitter's position and negative pulls it in. The emitter's position is X, Y in SpaceWorld and the local origin in SpaceLocal.
RadialAccelMin, RadialAccelMax float32
// TangentialAccelMin and TangentialAccelMax give each particle's acceleration perpendicular to its radial direction, picked once at spawn, in points per second squared: positive turns it clockwise on the screen around the emitter's position.
TangentialAccelMin, TangentialAccelMax float32
// InitialRotationMin and InitialRotationMax give each particle's starting rotation in radians.
InitialRotationMin, InitialRotationMax float32
// RotationSpeedMin and RotationSpeedMax give each particle's angular velocity in radians per second.
RotationSpeedMin, RotationSpeedMax float32
// SizeCurve scales each particle over its normalized life in [0, 1]; empty scales by 1.
SizeCurve FloatCurve
// AlphaCurve fades each particle over its normalized life in [0, 1]; empty keeps opacity at 1.
AlphaCurve FloatCurve
// RotationCurve adds rotation in radians over a particle's normalized life in [0, 1]; empty adds 0.
RotationCurve FloatCurve
// ColorCurve evaluates a color over each particle's normalized life in [0, 1] and stores it on Particle.Color. Draw tints each particle's sprite by the color's RGB, and its alpha channel multiplies AlphaCurve into Particle.Alpha.
ColorCurve ColorCurve
// Seed seeds the emitter's PCG PRNG for deterministic emission and motion.
Seed uint64
// Z sets the sprite Z order used when drawing this emitter's particles.
Z int
// Tint multiplies every drawn particle's sRGB and alpha channels (on top of ColorCurve and AlphaCurve), as sprite.Sprite.Tint does.
// The zero value and opaque white leave particles untinted; any other tint with alpha 0 draws nothing.
Tint core.Color
// Collision configures optional particle collision detection and response against a Collider.
Collision CollisionConfig
// Trail, when non-nil, automatically attaches a 2D ribbon trail to each emitted particle.
Trail *TrailConfig
// SubEmitters configures child bursts triggered on particle birth, death, or collision.
SubEmitters []SubEmitterRule
// OnParticleEvent, when non-nil, is called for every particle death and collision during Update, with the event's world position and velocity. It is not called for the emitter's child sub-emitters' own particles. Compiling event reporting into the game is opt-in: leave it nil to pay nothing.
OnParticleEvent func(ParticleEvent)
// Stats, when not nil, counts draw submissions and batch-break reasons for this emitter's particle batch (and any child sub-emitters without their own Stats). Draw adds to it and never resets it. Compiled to nothing under -tags release.
Stats *sprite.DrawCounter
// ReduceFlashes, when set, is asked during Update and Burst; while it reports true, strobe-like bursts (both scheduled Bursts and manual Burst calls) are rate-limited to at most MaxReducedBurstsPerSecond (3) per simulated second, particle opacity is capped at ReducedFlashAlpha (0.25), and saturated-red particle colors are desaturated. Pass an a11y.Assist's ReduceFlashes.
ReduceFlashes func() bool
// contains filtered or unexported fields
}
Emitter spawns, updates and draws 2D particles deterministically from a seeded PRNG.
Call Update from a game.Loop's fixed step and Draw from a Canvas's Draw callback. Continuous emission runs whenever Rate > 0; call Burst to emit particles on demand regardless of Rate.
Two emitters configured with the same fields and Seed and stepped identically produce bit-for-bit identical particles and draw operations.
Example ¶
An Emitter spawns particles in bursts or at a steady Rate and steps them on the game's fixed update; particles die when their lifetime runs out.
package main
import (
"fmt"
"math"
"time"
"github.com/nsgo-dev/game/pkg/particles"
)
func sparks() particles.Config {
return particles.Config{
X: 100, Y: 100,
Shape: particles.Circle(4),
LifetimeMin: 500 * time.Millisecond, LifetimeMax: time.Second,
SpeedMin: 40, SpeedMax: 80,
AngleMin: 0, AngleMax: 2 * math.Pi,
GravityY: 200,
AlphaCurve: particles.FloatCurve{{T: 0, Value: 1}, {T: 1, Value: 0}},
Seed: 7,
}
}
func main() {
e := particles.NewEmitter(sparks())
e.Burst(20)
fmt.Println(e.Count())
for range 30 {
e.Update(time.Second / 60)
}
fmt.Println(e.Count() > 0 && e.Count() <= 20)
for range 60 {
e.Update(time.Second / 60)
}
fmt.Println(e.Count())
}
Output: 20 true 0
func NewEmitter ¶
NewEmitter constructs an Emitter initialized from cfg.
Example ¶
Emitters with the same configuration and seed produce identical particles, so replays and tests can rely on them.
package main
import (
"fmt"
"math"
"time"
"github.com/nsgo-dev/game/pkg/particles"
)
func sparks() particles.Config {
return particles.Config{
X: 100, Y: 100,
Shape: particles.Circle(4),
LifetimeMin: 500 * time.Millisecond, LifetimeMax: time.Second,
SpeedMin: 40, SpeedMax: 80,
AngleMin: 0, AngleMax: 2 * math.Pi,
GravityY: 200,
AlphaCurve: particles.FloatCurve{{T: 0, Value: 1}, {T: 1, Value: 0}},
Seed: 7,
}
}
func main() {
a, b := particles.NewEmitter(sparks()), particles.NewEmitter(sparks())
for _, e := range []*particles.Emitter{a, b} {
e.Burst(5)
e.Update(time.Second / 10)
}
pa, pb := a.Particles()[3], b.Particles()[3]
fmt.Println(pa.X == pb.X && pa.Y == pb.Y)
}
Output: true
func (*Emitter) Advance ¶
Advance advances live particles by dt as Update does but emits none: continuous emission and scheduled bursts stay off, while live particles age, collide, and expire, and death-triggered sub-emitter bursts still fire. A stopped effect ages its trailing particles with it.
func (*Emitter) Attach ¶
Attach binds a position callback so the emitter tracks a moving object on every Update. Calling Attach immediately syncs X, Y to posFn(). Passing nil detaches.
func (*Emitter) AttachTrail ¶
func (e *Emitter) AttachTrail(cfg TrailConfig)
AttachTrail enables automatic per-particle ribbon trails on the emitter using cfg.
func (*Emitter) AttachTransform ¶
AttachTransform binds a position and rotation callback so the emitter tracks a moving, rotating object on every Update. Calling AttachTransform immediately syncs X, Y, Rotation. Passing nil detaches.
func (*Emitter) Burst ¶
Burst immediately emits up to count particles without waiting for Update or requiring Rate > 0, stopping at MaxParticles. When ReduceFlashes reports true, bursts are rate-limited to at most MaxReducedBurstsPerSecond per simulated second.
func (*Emitter) Clear ¶
func (e *Emitter) Clear()
Clear removes all live particles, trails, and child sub-emitter particles, and resets the fractional emission accumulator without resetting the PRNG.
func (*Emitter) Config ¶
Config returns a deep-copied Config reflecting the emitter's current settings.
func (*Emitter) Count ¶
Count returns the number of currently live particles in this emitter (excluding child sub-emitters).
func (*Emitter) Detach ¶
func (e *Emitter) Detach()
Detach clears any callback bound via Attach or AttachTransform.
func (*Emitter) DetachTrail ¶
func (e *Emitter) DetachTrail()
DetachTrail disables automatic per-particle ribbon trails on the emitter. Existing particle trails fade out naturally as their points expire.
func (*Emitter) Draw ¶
Draw draws particle trails, all live particles through a reusable sprite.Batch (oldest first), and any managed child sub-emitters into d.
func (*Emitter) Follow ¶
Follow moves the emitter smoothly to (x, y), recording the previous position so multi-particle continuous emission interpolates along the motion path.
func (*Emitter) ParticleTrails ¶
ParticleTrails returns the currently live particle trails in spawn order.
func (*Emitter) ParticleWorldPos ¶
ParticleWorldPos converts a particle's coordinates to world coordinates. For SpaceWorld emitters this returns (p.X, p.Y) unchanged; for SpaceLocal emitters it applies Rotation and the particle's sub-emitter trigger anchor (or the emitter's current X, Y for top-level emitters).
func (*Emitter) Particles ¶
Particles returns the live particles in spawn order. The returned slice is backed by the emitter's storage and reused on subsequent updates; copy it to retain a snapshot.
func (*Emitter) ReloadConfig ¶
ReloadConfig applies cfg to a running Emitter without resetting live particles, PRNG state, attachment callbacks, or runtime colliders.
func (*Emitter) Reset ¶
func (e *Emitter) Reset()
Reset clears all live particles, trails, and child sub-emitters and re-seeds the PRNG from Seed so subsequent updates replay identically.
func (*Emitter) TotalCount ¶
TotalCount returns the number of live particles in this emitter plus all managed child sub-emitters recursively.
func (*Emitter) TrailCount ¶
TrailCount returns the total number of active and fading particle trails owned by the emitter.
type Emitter3D ¶
type Emitter3D struct {
// Simulation records which simulator the definition asks for; an Emitter3D always simulates on the CPU, and [NewSimulatedEmitter3D] reads it to choose.
Simulation string
// FallbackMaxParticles records the definition's CPU fallback cap; see [Emitter3DConfig.FallbackMaxParticles].
FallbackMaxParticles int
// Position is the emitter's world-space origin.
Position math3d.Vec3
// Direction is the primary emission axis; zero defaults to +Y (0, 1, 0).
Direction math3d.Vec3
// Up is the reference up axis used to build the emitter's local frame; zero picks a deterministic perpendicular axis.
Up math3d.Vec3
// Rotation is an optional emitter orientation quaternion; zero is treated as identity. In SpaceLocal it rotates all live particles when packing; in SpaceWorld it rotates spawned offsets and velocities.
Rotation math3d.Quat
// Space controls whether particles simulate in world coordinates (SpaceWorld, default) or emitter-local coordinates (SpaceLocal).
Space SimulationSpace
// Shape controls where new particles spawn relative to Position; its zero value is Point3D.
Shape Shape3D
// Billboard selects how quads face the camera when AppendInstances packs GPU data.
Billboard BillboardMode3D
// Blend records the preferred GPU blend mode for pipelines built for this emitter.
Blend ParticleBlendMode
// StretchFactor scales velocity elongation in seconds for BillboardStretched (length = size + speed * StretchFactor); <= 0 defaults to 0.05.
StretchFactor float32
// Axis is the locked world up axis for BillboardCylindrical; zero defaults to +Y (0, 1, 0).
Axis math3d.Vec3
// Rate is how many particles emit per second during Step/Update; 0 or less disables continuous emission.
Rate float32
// MaxParticles caps how many particles may be live at once, 256 when 0 or less.
MaxParticles int
// MaxTotalParticles caps total live particles across this emitter and all nested sub-emitters (0 uses a safe default hierarchy budget).
MaxTotalParticles int
// LifetimeMin and LifetimeMax give how long each particle lives; both 0 defaults to one second, and a LifetimeMax below LifetimeMin matches LifetimeMin.
LifetimeMin, LifetimeMax time.Duration
// SpeedMin and SpeedMax give each particle's initial speed in world units per second.
SpeedMin, SpeedMax float32
// Spread is the emission cone half-angle in radians around Direction, clamped to [0, pi]. Zero emits straight along Direction; pi emits uniformly in all directions.
Spread float32
// Drag is exponential linear velocity damping in 1/s (>= 0); zero disables drag.
Drag float32
// Gravity is constant acceleration applied to live particles in world units per second squared.
Gravity math3d.Vec3
// OrbitVelocity rotates particles around the emitter's Direction axis at angular velocity (rad/s) evaluated over normalized age t.
OrbitVelocity FloatCurve
// RadialAccel accelerates particles away from the emitter origin (world units/s²) evaluated over normalized age t.
RadialAccel FloatCurve
// TangentialAccel accelerates particles perpendicular to the radial direction and emitter axis (world units/s²) over normalized age t.
TangentialAccel FloatCurve
// Damping lowers particle speed linearly (world units/s²) over normalized age t, stopping at zero without reversing.
Damping FloatCurve
// SizeMin and SizeMax give each particle's base world-space quad size before SizeCurve; both <= 0 defaults to 1.
SizeMin, SizeMax float32
// InitialRotationMin and InitialRotationMax give each particle's starting roll angle in radians.
InitialRotationMin, InitialRotationMax float32
// RotationSpeedMin and RotationSpeedMax give each particle's roll angular velocity in radians per second.
RotationSpeedMin, RotationSpeedMax float32
// AngularVelocityMin and AngularVelocityMax give each mesh particle's 3D angular velocity in radians per second around X, Y, Z.
AngularVelocityMin, AngularVelocityMax math3d.Vec3
// AlignToVelocity aligns each mesh particle's orientation along its velocity vector during Step.
AlignToVelocity bool
// SizeCurve scales each particle's base size over its normalized age in [0, 1]; empty scales by 1.
SizeCurve FloatCurve
// AlphaCurve fades each particle over its normalized age in [0, 1]; empty keeps opacity at 1.
AlphaCurve FloatCurve
// RotationCurve adds roll rotation in radians over a particle's normalized age in [0, 1]; empty adds 0.
RotationCurve FloatCurve
// ColorCurve evaluates a color over each particle's normalized age in [0, 1]; empty uses Color (or opaque white when Color is 0).
ColorCurve ColorCurve
// Color is the base particle color used when ColorCurve is empty; zero means opaque white (0xffffffff).
Color core.Color
// Flipbook configures animated grid-atlas UV playback for 3D particles.
Flipbook Flipbook3D
// CollisionRadius is each particle's collision sphere radius in world units (>= 0).
CollisionRadius float32
// Colliders lists 3D obstacles (planes, boxes, spheres, SDFs, height fields, raycast callbacks) that particles collide against.
Colliders []Collider3D
// Attractors lists sphere, box, and vector-field attractors applied during Step.
Attractors []Attractor3D
// Turbulence configures seeded 3D curl-of-value-noise turbulence applied during Step.
Turbulence Turbulence3D
// Trail configures optional per-particle 3D ribbon or tube trails.
Trail *Trail3DConfig
// SubEmitters configures child emitters triggered on particle start, end, collision, or constantly while alive.
SubEmitters []SubEmitterRule3D
// DrawPasses optionally declares one or more quad, mesh, or trail draw passes for serialized 3D particle definitions.
DrawPasses []DrawPass3D
// Seed seeds the emitter's PCG PRNG for deterministic emission and motion.
Seed uint64
// ReduceFlashes, when set, is asked during Step and Burst; while it reports true, Burst calls are rate-limited to at most MaxReducedBurstsPerSecond (3) per simulated second, particle opacity is capped at ReducedFlashAlpha (0.25), and saturated-red particle colors are desaturated. Pass an a11y.Assist's ReduceFlashes.
ReduceFlashes func() bool
// contains filtered or unexported fields
}
Emitter3D spawns, updates and packs 3D particles deterministically from a seeded PRNG for instanced GPU rendering.
It shares the emitter model of 2D Emitter (Rate, MaxParticles, LifetimeMin/Max, SpeedMin/Max, curves, SimulationSpace, Seed, Burst, Clear, Reset) and stores live particles in dense structure-of-arrays slices with swap-remove expiration so stepping and packing 10,000 particles allocates zero memory in steady state.
Two emitters configured with the same fields and Seed and stepped identically produce bit-for-bit identical particles and packed GPU instance bytes.
Example ¶
Emitter3D steps 3D particles deterministically and packs them into 40-byte GPU instances ready for instanced rendering.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/math3d"
"github.com/nsgo-dev/game/pkg/particles"
)
func main() {
e := particles.NewEmitter3D(particles.Emitter3DConfig{
Position: math3d.Vec3{Y: 1},
Direction: math3d.Vec3Up(),
Shape: particles.Cone(0.25, 0.3),
MaxParticles: 1000,
LifetimeMin: 500 * time.Millisecond,
LifetimeMax: time.Second,
SpeedMin: 2,
SpeedMax: 5,
Gravity: math3d.Vec3{Y: -9.8},
Blend: particles.BlendAdditive,
Seed: 42,
})
e.Burst(50)
e.Step(time.Second / 60)
raw := e.AppendInstances(nil, math3d.Vec3Right(), math3d.Vec3Up())
fmt.Println(e.Count(), len(raw)/particles.ParticleInstanceStride)
}
Output: 50 50
func NewEmitter3D ¶
func NewEmitter3D(cfg Emitter3DConfig) *Emitter3D
NewEmitter3D constructs an Emitter3D initialized from cfg.
func (*Emitter3D) Active ¶
Active reports whether the emitter or any of its child sub-emitters currently has at least one live particle.
func (*Emitter3D) Advance ¶
Advance advances live particles by dt as Step does but emits none, so a stopped effect's trailing 3D particles age out and expire.
func (*Emitter3D) AppendFlipbookInstances ¶
AppendFlipbookInstances packs all live particles (including child sub-emitters) into dst in the little-endian 56-byte ParticleFlipbookInstanceStride GPU layout (40-byte quad instance + 16-byte UV sub-rect) facing (camRight, camUp).
func (*Emitter3D) AppendInstances ¶
AppendInstances packs all live particles (including child sub-emitters) into dst in the little-endian 40-byte ParticleInstanceStride GPU layout facing (camRight, camUp) and returns the extended slice.
If Emitter3D.SortByDepth was called since the last mutation, instances are written in back-to-front sorted order. It allocates only when dst lacks capacity for TotalCount() * ParticleInstanceStride more bytes.
func (*Emitter3D) AppendMeshInstances ¶
AppendMeshInstances packs all live particles (including child sub-emitters) into dst in the little-endian 84-byte ParticleMeshInstanceStride layout matching render3d.InstanceStride: column-major Mat4 model transform (64B) + RGBA8 color (4B) + Vec4 custom flipbook UV rect (16B).
func (*Emitter3D) AppendParticles ¶
func (e *Emitter3D) AppendParticles(dst []Particle3D) []Particle3D
AppendParticles appends snapshots of all live particles to dst and returns the extended slice.
func (*Emitter3D) AppendTrailVertices ¶
AppendTrailVertices builds triangle-list vertices of Trail3DVertexStride bytes for all active and fading 3D trails on e and its child sub-emitters.
func (*Emitter3D) AttachTrail3D ¶
func (e *Emitter3D) AttachTrail3D(cfg Trail3DConfig)
AttachTrail3D enables automatic per-particle 3D ribbon or tube trails on e using cfg.
func (*Emitter3D) Burst ¶
Burst immediately emits up to count particles without waiting for Step or requiring Rate > 0, stopping at MaxParticles. When ReduceFlashes reports true, bursts are rate-limited to at most MaxReducedBurstsPerSecond per simulated second.
func (*Emitter3D) Children ¶
Children returns the managed child emitters created for Emitter3D.SubEmitters.
func (*Emitter3D) Clear ¶
func (e *Emitter3D) Clear()
Clear removes all live particles, child sub-emitter particles, and trails, and resets the fractional emission accumulator without resetting the PRNG.
func (*Emitter3D) Config ¶
func (e *Emitter3D) Config() Emitter3DConfig
Config returns a deep-copied Emitter3DConfig reflecting the emitter's current settings.
func (*Emitter3D) DetachTrail3D ¶
func (e *Emitter3D) DetachTrail3D()
DetachTrail3D disables automatic per-particle 3D trails on e; existing trails fade out cleanly as their points expire.
func (*Emitter3D) FrameUV ¶
FrameUV returns the flipbook UV sub-rectangle (uOffset, vOffset, uScale, vScale) for live particle i.
func (*Emitter3D) Particle ¶
func (e *Emitter3D) Particle(i int) Particle3D
Particle returns a snapshot of the live particle at index i (0 <= i < Count()).
func (*Emitter3D) ParticleWorldPos ¶
ParticleWorldPos returns the world-space position of particle i. For SpaceWorld emitters this returns the stored position directly; for SpaceLocal emitters it applies the emitter's Rotation and trigger anchor (or Position).
func (*Emitter3D) Particles ¶
func (e *Emitter3D) Particles() []Particle3D
Particles returns a slice containing snapshots of all live particles.
func (*Emitter3D) ReloadConfig ¶
func (e *Emitter3D) ReloadConfig(cfg Emitter3DConfig)
ReloadConfig applies cfg to e without clearing live particles or resetting the PRNG. If the new MaxParticles is smaller than the live particle count, excess particles are dropped.
func (*Emitter3D) Reset ¶
func (e *Emitter3D) Reset()
Reset clears all live particles, child sub-emitters, trails, and elapsed time, and re-seeds the PRNG from Seed so subsequent steps replay identically.
func (*Emitter3D) SortByDepth ¶
SortByDepth orders live particles back-to-front along camForward from camPos so alpha-blended particles pack farthest first in subsequent Emitter3D.AppendInstances calls.
It uses a deterministic, zero-allocation 4-pass radix sort over IEEE-754 depth keys. The sorted order remains active until the next Step, Burst, Clear, or Reset.
func (*Emitter3D) Step ¶
Step advances live particles by dt, removes expired ones via dense swap-remove, evaluates lifetime curves, forces, collisions, trails, and sub-emitters, and emits new particles at Rate. Non-positive dt does nothing.
func (*Emitter3D) TotalCount ¶
TotalCount returns the number of live particles in e plus all managed child sub-emitters recursively.
func (*Emitter3D) TrailCount ¶
TrailCount returns the total number of active and fading 3D trails owned by e.
func (*Emitter3D) Update ¶
Update advances live particles by dt, expires dead ones, and emits new particles at Rate. It is equivalent to Emitter3D.Step and matches 2D Emitter.Update for use in game.Loop.
type Emitter3DConfig ¶
type Emitter3DConfig struct {
// Simulation selects the simulator [NewSimulatedEmitter3D] runs: empty and "cpu" an [Emitter3D], "gpu" a [GPUEmitter3D] on devices with compute shaders.
Simulation string
// FallbackMaxParticles, when positive, replaces MaxParticles on the CPU emitter a "gpu" definition falls back to on devices without compute shaders.
FallbackMaxParticles int
Position math3d.Vec3
Direction math3d.Vec3
Up math3d.Vec3
Rotation math3d.Quat
Space SimulationSpace
Shape Shape3D
Billboard BillboardMode3D
Blend ParticleBlendMode
StretchFactor float32
Axis math3d.Vec3
Rate float32
MaxParticles int
// MaxTotalParticles caps total live particles across this emitter and all nested sub-emitters (0 uses a safe default hierarchy budget).
MaxTotalParticles int
LifetimeMin time.Duration
LifetimeMax time.Duration
SpeedMin float32
SpeedMax float32
Spread float32
Drag float32
Gravity math3d.Vec3
OrbitVelocity FloatCurve
RadialAccel FloatCurve
TangentialAccel FloatCurve
Damping FloatCurve
SizeMin float32
SizeMax float32
InitialRotationMin float32
InitialRotationMax float32
RotationSpeedMin float32
RotationSpeedMax float32
AngularVelocityMin math3d.Vec3
AngularVelocityMax math3d.Vec3
AlignToVelocity bool
SizeCurve FloatCurve
AlphaCurve FloatCurve
RotationCurve FloatCurve
ColorCurve ColorCurve
Color core.Color
Flipbook Flipbook3D
CollisionRadius float32
Colliders []Collider3D
Attractors []Attractor3D
Turbulence Turbulence3D
Trail *Trail3DConfig
SubEmitters []SubEmitterRule3D
DrawPasses []DrawPass3D
Seed uint64
}
Emitter3DConfig is a serializable, reloadable snapshot of an Emitter3D's configuration.
func LoadConfig3DFS ¶
func LoadConfig3DFS(fsys fs.FS, name string) (Emitter3DConfig, error)
LoadConfig3DFS reads and decodes a versioned YAML 3D emitter definition file from fsys.
func LoadConfig3DFile ¶
func LoadConfig3DFile(path string) (Emitter3DConfig, error)
LoadConfig3DFile reads and decodes a versioned YAML 3D emitter definition file from disk.
func UnmarshalConfig3DJSON ¶
func UnmarshalConfig3DJSON(data []byte) (Emitter3DConfig, error)
UnmarshalConfig3DJSON decodes the versioned JSON form of a 3D emitter definition into an Emitter3DConfig.
func UnmarshalConfig3DYAML ¶
func UnmarshalConfig3DYAML(data []byte) (Emitter3DConfig, error)
UnmarshalConfig3DYAML decodes a versioned YAML 3D emitter definition into an Emitter3DConfig. It refuses unknown fields, keys with no value, trailing YAML documents, unsupported versions, fractions in integer fields, shape fields that do not apply to the shape kind, excessive sub-emitter depth, and non-finite numbers.
type Emitter3DDoc ¶
type Emitter3DDoc struct {
// Version is the schema version; it must be FormatVersion (1).
Version int `yaml:"version" schema:"required"`
// Emitter3DFieldsDoc holds the 3D emitter fields written alongside version at the top level.
Emitter3DFieldsDoc `yaml:",inline"`
}
Emitter3DDoc describes the versioned YAML schema of a 3D particle emitter definition (version: 1) for JSON Schema generation.
type Emitter3DFieldsDoc ¶
type Emitter3DFieldsDoc struct {
// Simulation selects the intended simulator metadata: "cpu" (default) or "gpu".
Simulation string `yaml:"simulation,omitempty" schema:"enum=cpu|gpu"`
// FallbackMaxParticles caps a CPU fallback when simulation is "gpu".
FallbackMaxParticles int `yaml:"fallbackMaxParticles,omitempty" schema:"minimum=0"`
// Position is the emitter's world-space origin.
Position *Vec3Doc `yaml:"position,omitempty"`
// Direction is the primary emission axis; defaults to +Y (0, 1, 0) when omitted.
Direction *Vec3Doc `yaml:"direction,omitempty"`
// Up is the reference up axis used to construct the emitter's local frame.
Up *Vec3Doc `yaml:"up,omitempty"`
// Rotation is the emitter's orientation quaternion (x, y, z, w).
Rotation *QuatDoc `yaml:"rotation,omitempty"`
// Space controls whether particles simulate in world coordinates ("world") or emitter-local coordinates ("local").
Space string `yaml:"space,omitempty" schema:"enum=world|local"`
// Shape controls where new particles spawn relative to the emitter's Position.
Shape *Shape3DDoc `yaml:"shape,omitempty"`
// Billboard selects how quads face the camera: "spherical", "cylindrical" or "stretched".
Billboard string `yaml:"billboard,omitempty" schema:"enum=spherical|cylindrical|stretched"`
// Blend selects GPU blending: "alpha", "additive" or "premultiplied".
Blend string `yaml:"blend,omitempty" schema:"enum=alpha|additive|premultiplied"`
// StretchFactor scales velocity elongation in seconds for "stretched" billboards.
StretchFactor float32 `yaml:"stretchFactor,omitempty"`
// Axis is the locked world up axis for "cylindrical" billboards.
Axis *Vec3Doc `yaml:"axis,omitempty"`
// Rate is how many particles emit per second during Step; 0 disables continuous emission.
Rate float32 `yaml:"rate,omitempty"`
// MaxParticles caps how many particles may be live at once (defaults to 256 when 0 or omitted).
MaxParticles int `yaml:"maxParticles,omitempty" schema:"minimum=0"`
// MaxTotalParticles caps total live particles across this emitter and all nested sub-emitters.
MaxTotalParticles int `yaml:"maxTotalParticles,omitempty" schema:"minimum=0"`
// LifetimeMin is the minimum particle lifetime as a Go duration string such as "300ms".
LifetimeMin time.Duration `yaml:"lifetimeMin,omitempty"`
// LifetimeMax is the maximum particle lifetime as a Go duration string such as "900ms".
LifetimeMax time.Duration `yaml:"lifetimeMax,omitempty"`
// SpeedMin is the minimum initial speed in world units per second.
SpeedMin float32 `yaml:"speedMin,omitempty"`
// SpeedMax is the maximum initial speed in world units per second.
SpeedMax float32 `yaml:"speedMax,omitempty"`
// Spread is the emission cone half-angle in radians around Direction.
Spread float32 `yaml:"spread,omitempty" schema:"minimum=0"`
// Drag is exponential linear velocity damping in 1/s.
Drag float32 `yaml:"drag,omitempty" schema:"minimum=0"`
// Gravity is constant 3D acceleration in world units per second squared.
Gravity *Vec3Doc `yaml:"gravity,omitempty"`
// OrbitVelocity rotates particles around Direction at angular velocity (rad/s) over normalized age t in [0, 1].
OrbitVelocity []FloatStopDoc `yaml:"orbitVelocity,omitempty"`
// RadialAccel accelerates particles away from the emitter origin over normalized age t in [0, 1].
RadialAccel []FloatStopDoc `yaml:"radialAccel,omitempty"`
// TangentialAccel accelerates particles perpendicular to radial direction and Direction over normalized age t in [0, 1].
TangentialAccel []FloatStopDoc `yaml:"tangentialAccel,omitempty"`
// Damping lowers particle speed linearly (world units/s²) over normalized age t in [0, 1].
Damping []FloatStopDoc `yaml:"damping,omitempty"`
// SizeMin is the minimum base world-space particle size.
SizeMin float32 `yaml:"sizeMin,omitempty"`
// SizeMax is the maximum base world-space particle size.
SizeMax float32 `yaml:"sizeMax,omitempty"`
// InitialRotationMin is the minimum starting roll angle in radians.
InitialRotationMin float32 `yaml:"initialRotationMin,omitempty"`
// InitialRotationMax is the maximum starting roll angle in radians.
InitialRotationMax float32 `yaml:"initialRotationMax,omitempty"`
// RotationSpeedMin is the minimum roll angular velocity in radians per second.
RotationSpeedMin float32 `yaml:"rotationSpeedMin,omitempty"`
// RotationSpeedMax is the maximum roll angular velocity in radians per second.
RotationSpeedMax float32 `yaml:"rotationSpeedMax,omitempty"`
// AngularVelocityMin is the minimum 3D angular velocity in radians per second for mesh particles.
AngularVelocityMin *Vec3Doc `yaml:"angularVelocityMin,omitempty"`
// AngularVelocityMax is the maximum 3D angular velocity in radians per second for mesh particles.
AngularVelocityMax *Vec3Doc `yaml:"angularVelocityMax,omitempty"`
// AlignToVelocity aligns each mesh particle's orientation along its velocity vector.
AlignToVelocity bool `yaml:"alignToVelocity,omitempty"`
// SizeCurve scales each particle's base size over its normalized age in [0, 1].
SizeCurve []FloatStopDoc `yaml:"sizeCurve,omitempty"`
// AlphaCurve fades each particle's opacity over its normalized age in [0, 1].
AlphaCurve []FloatStopDoc `yaml:"alphaCurve,omitempty"`
// RotationCurve adds roll rotation in radians over normalized age in [0, 1].
RotationCurve []FloatStopDoc `yaml:"rotationCurve,omitempty"`
// ColorCurve evaluates RGBA color over normalized age in [0, 1].
ColorCurve []ColorStopDoc `yaml:"colorCurve,omitempty"`
// Color is the fallback solid hex color "#rrggbb" or "#rrggbbaa" when colorCurve is empty.
Color string `yaml:"color,omitempty"`
// Flipbook configures animated grid-atlas UV playback for 3D particles.
Flipbook *Flipbook3DDoc `yaml:"flipbook,omitempty"`
// CollisionRadius is each particle's collision sphere radius in world units.
CollisionRadius float32 `yaml:"collisionRadius,omitempty" schema:"minimum=0"`
// Colliders lists 3D obstacles (planes, boxes, spheres, SDFs, height fields, raycast callbacks) that particles collide against.
Colliders []Collider3DDoc `yaml:"colliders,omitempty"`
// Attractors lists sphere, box and vector-field attractors applied during simulation.
Attractors []Attractor3DDoc `yaml:"attractors,omitempty"`
// Turbulence configures seeded 3D curl-of-value-noise turbulence.
Turbulence *Turbulence3DDoc `yaml:"turbulence,omitempty"`
// Trail configures optional per-particle 3D ribbon or tube trails.
Trail *Trail3DDoc `yaml:"trail,omitempty"`
// SubEmitters configures child 3D emitters triggered on particle start, end, collision or constantly while alive.
SubEmitters []SubEmitter3DDoc `yaml:"subEmitters,omitempty"`
// DrawPasses optionally declares quad, mesh or trail draw passes for this 3D emitter.
DrawPasses []DrawPass3DDoc `yaml:"drawPasses,omitempty"`
// Seed seeds the emitter's deterministic PCG PRNG.
Seed uint64 `yaml:"seed,omitempty"`
}
Emitter3DFieldsDoc describes the fields of a 3D particle emitter configuration (used at the top level and inside 3D sub-emitters without version).
type EmitterDoc ¶
type EmitterDoc struct {
// Version is the schema version; it must be FormatVersion (1).
Version int `yaml:"version" schema:"required"`
// EmitterFieldsDoc holds the emitter fields written alongside version at the top level.
EmitterFieldsDoc `yaml:",inline"`
}
EmitterDoc describes the versioned YAML schema of a 2D particle emitter definition (version: 1) for JSON Schema generation.
type EmitterFieldsDoc ¶
type EmitterFieldsDoc struct {
// X is the emitter's default horizontal position in points.
X float32 `yaml:"x,omitempty"`
// Y is the emitter's default vertical position in points.
Y float32 `yaml:"y,omitempty"`
// Rotation is the emitter's rotation in radians, clockwise on screen.
Rotation float32 `yaml:"rotation,omitempty"`
// Space controls whether particles simulate in world coordinates ("world") or emitter-local coordinates ("local").
Space string `yaml:"space,omitempty" schema:"enum=world|local"`
// Shape controls where new particles spawn relative to the emitter's origin.
Shape *ShapeDoc `yaml:"shape,omitempty"`
// Rate is how many particles emit per second during Update; 0 disables continuous emission.
Rate float32 `yaml:"rate,omitempty"`
// Bursts schedules automatic bursts of particles at specific elapsed times during Update.
Bursts []BurstDoc `yaml:"bursts,omitempty"`
// MaxParticles caps how many particles may be live at once (defaults to 256 when 0 or omitted).
MaxParticles int `yaml:"maxParticles,omitempty"`
// LifetimeMin is the minimum particle lifetime as a Go duration string such as "300ms".
LifetimeMin time.Duration `yaml:"lifetimeMin,omitempty"`
// LifetimeMax is the maximum particle lifetime as a Go duration string such as "700ms".
LifetimeMax time.Duration `yaml:"lifetimeMax,omitempty"`
// SpeedMin is the minimum initial particle speed in points per second.
SpeedMin float32 `yaml:"speedMin,omitempty"`
// SpeedMax is the maximum initial particle speed in points per second.
SpeedMax float32 `yaml:"speedMax,omitempty"`
// AngleMin is the minimum initial direction of travel in radians, clockwise from +X.
AngleMin float32 `yaml:"angleMin,omitempty"`
// AngleMax is the maximum initial direction of travel in radians, clockwise from +X.
AngleMax float32 `yaml:"angleMax,omitempty"`
// GravityX is constant horizontal acceleration in points per second squared.
GravityX float32 `yaml:"gravityX,omitempty"`
// GravityY is constant vertical acceleration in points per second squared.
GravityY float32 `yaml:"gravityY,omitempty"`
// DampingMin is the minimum of each particle's damping, picked at spawn: how much its speed drops per second, in points per second squared; zero or negative does not damp.
DampingMin float32 `yaml:"dampingMin,omitempty"`
// DampingMax is the maximum of each particle's damping, picked at spawn; a value not above dampingMin uses dampingMin.
DampingMax float32 `yaml:"dampingMax,omitempty"`
// RadialAccelMin is the minimum of each particle's acceleration away from the emitter's position (the local origin in local space), picked at spawn, in points per second squared; negative pulls particles in.
RadialAccelMin float32 `yaml:"radialAccelMin,omitempty"`
// RadialAccelMax is the maximum of each particle's radial acceleration, picked at spawn; a value not above radialAccelMin uses radialAccelMin.
RadialAccelMax float32 `yaml:"radialAccelMax,omitempty"`
// TangentialAccelMin is the minimum of each particle's acceleration at right angles to its radial direction, clockwise on screen when positive, picked at spawn, in points per second squared.
TangentialAccelMin float32 `yaml:"tangentialAccelMin,omitempty"`
// TangentialAccelMax is the maximum of each particle's tangential acceleration, picked at spawn; a value not above tangentialAccelMin uses tangentialAccelMin.
TangentialAccelMax float32 `yaml:"tangentialAccelMax,omitempty"`
// InitialRotationMin is the minimum starting particle rotation in radians.
InitialRotationMin float32 `yaml:"initialRotationMin,omitempty"`
// InitialRotationMax is the maximum starting particle rotation in radians.
InitialRotationMax float32 `yaml:"initialRotationMax,omitempty"`
// RotationSpeedMin is the minimum angular velocity in radians per second.
RotationSpeedMin float32 `yaml:"rotationSpeedMin,omitempty"`
// RotationSpeedMax is the maximum angular velocity in radians per second.
RotationSpeedMax float32 `yaml:"rotationSpeedMax,omitempty"`
// SizeCurve scales each particle over its normalized lifetime in [0, 1].
SizeCurve []FloatStopDoc `yaml:"sizeCurve,omitempty"`
// AlphaCurve fades each particle's opacity over its normalized lifetime in [0, 1].
AlphaCurve []FloatStopDoc `yaml:"alphaCurve,omitempty"`
// RotationCurve adds rotation in radians over a particle's normalized lifetime in [0, 1].
RotationCurve []FloatStopDoc `yaml:"rotationCurve,omitempty"`
// ColorCurve tints each particle over its normalized lifetime in [0, 1].
ColorCurve []ColorStopDoc `yaml:"colorCurve,omitempty"`
// Seed seeds the emitter's deterministic PCG PRNG.
Seed uint64 `yaml:"seed,omitempty"`
// Z sets the sprite Z draw order of emitted particles.
Z int `yaml:"z,omitempty"`
// FrameNames lists the atlas frame names particles pick from at spawn time.
FrameNames []string `yaml:"frameNames,omitempty"`
// Collision configures optional particle collision response.
Collision *CollisionDoc `yaml:"collision,omitempty"`
// Trail configures optional per-particle 2D ribbon trails.
Trail *TrailDoc `yaml:"trail,omitempty"`
// SubEmitters configures child bursts triggered on particle birth, death or collision.
SubEmitters []SubEmitterDoc `yaml:"subEmitters,omitempty"`
}
EmitterFieldsDoc describes the fields of a 2D particle emitter configuration (used at the top level and inside sub-emitters without version).
type Event ¶
type Event struct {
// Kind is what happened to the particle.
Kind EffectEventKind
// Emitter is the index of the effect emitter that reported it, in Emitters (or Emitters3D) order.
Emitter int
// X and Y are the event position in world coordinates.
X, Y float32
// VX and VY are the particle's world velocity at the event, in points per second.
VX, VY float32
}
Event is one particle event an Effect reports through Effect.OnEvent.
type Flipbook3D ¶
type Flipbook3D struct {
// Columns is the horizontal frame count (HFrames); <= 1 means 1 column.
Columns int
// Rows is the vertical frame count (VFrames); <= 1 means 1 row.
Rows int
// FPS is the playback frame rate in frames per second. When <= 0, frames play linearly across each particle's lifetime [0, 1].
FPS float32
// Offset is the starting frame index offset (>= 0).
Offset float32
// Loop wraps frame indices modulo Columns*Rows instead of clamping at the last frame.
Loop bool
// RandomStart picks a deterministic random starting frame per particle from the emitter's PRNG.
RandomStart bool
}
Flipbook3D configures animated grid-atlas UV playback for 3D particles.
func (Flipbook3D) Active ¶
func (f Flipbook3D) Active() bool
Active reports whether f subdivides the texture into more than one frame.
func (Flipbook3D) FrameIndex ¶
func (f Flipbook3D) FrameIndex(ageSec, normT float32, startFrame int) int
FrameIndex computes the frame index in [0, TotalFrames()-1] for a particle at ageSec and normalized age t in [0, 1].
func (Flipbook3D) TotalFrames ¶
func (f Flipbook3D) TotalFrames() int
TotalFrames returns Columns * Rows (at least 1).
func (Flipbook3D) UVRect ¶
func (f Flipbook3D) UVRect(idx int) [4]float32
UVRect returns (u0, v0, uScale, vScale) for frame index idx in row-major order (left-to-right, top-to-bottom).
type Flipbook3DDoc ¶
type Flipbook3DDoc struct {
// Columns is the horizontal frame count (HFrames).
Columns int `yaml:"columns,omitempty" schema:"minimum=0"`
// Rows is the vertical frame count (VFrames).
Rows int `yaml:"rows,omitempty" schema:"minimum=0"`
// FPS is the playback frame rate in frames per second (0 plays frames across each particle's lifetime).
FPS float32 `yaml:"fps,omitempty" schema:"minimum=0"`
// Offset is the starting frame offset.
Offset float32 `yaml:"offset,omitempty" schema:"minimum=0"`
// Loop wraps frames modulo columns*rows instead of clamping to the final frame.
Loop bool `yaml:"loop,omitempty"`
// RandomStart picks a deterministic random starting frame per particle.
RandomStart bool `yaml:"randomStart,omitempty"`
}
Flipbook3DDoc describes grid-atlas flipbook animation settings in YAML.
type FloatCurve ¶
type FloatCurve []FloatStop
FloatCurve maps a particle's normalized age in [0, 1] to a float32 by linear interpolation between stops ordered by T. An empty curve returns 1 at any age.
Example ¶
A FloatCurve maps a particle's age, from 0 at birth to 1 at death, to a value such as its size or opacity.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/particles"
)
func main() {
grow := particles.FloatCurve{{T: 0, Value: 0.5}, {T: 0.5, Value: 2}, {T: 1, Value: 0}}
for _, t := range []float32{0, 0.25, 0.5, 0.75, 1} {
fmt.Println(t, grow.At(t))
}
}
Output: 0 0.5 0.25 1.25 0.5 2 0.75 1 1 0
func (FloatCurve) At ¶
func (c FloatCurve) At(t float32) float32
At returns the curve's value at normalized age t, clamped to [0, 1].
type FloatStop ¶
FloatStop is one control point on a FloatCurve at normalized particle age T in [0, 1].
type FloatStopDoc ¶
type FloatStopDoc struct {
// T is the normalized particle age in [0, 1].
T float32 `yaml:"t"`
// Value is the curve value at T.
Value float32 `yaml:"value"`
}
FloatStopDoc is one control point on a float curve at normalized age t in [0, 1].
type GPUEmitter3D ¶
type GPUEmitter3D struct {
// ReduceFlashes, when set, is asked during Burst and Simulate; while it reports true, bursts are rate-limited to MaxReducedBurstsPerSecond per simulated second, opacity is capped at ReducedFlashAlpha and saturated reds are desaturated, as on [Emitter3D].
ReduceFlashes func() bool
// contains filtered or unexported fields
}
GPUEmitter3D simulates an Emitter3DConfig's particles in compute shaders, so the per-frame cost of stepping and packing every live particle lands on the GPU instead of the engine goroutine.
Emission stays on the CPU: Step and Burst draw each new particle's shape position, velocity, lifetime, size and rotation from the same seeded PCG stream, in the same order, as an Emitter3D with the same config, and upload only those new particles. The GPU ages, integrates, expires and packs every slot, and the CPU never reads particle data back. Count comes from lifetimes the CPU already knows, so it matches an Emitter3D's count within one step.
GPU results are not bit-identical across vendors: treat a GPUEmitter3D as visual only and keep it out of replay state checks. Per-particle reads (Emitter3D.Particle, SortByDepth) do not exist here; slots are packed in slot order, so alpha-blended effects draw unsorted.
Use it on the engine goroutine, like the gpu.Device it came from. Its buffers and pipelines belong to the scope passed to NewGPUEmitter3D.
func NewGPUEmitter3D ¶
func NewGPUEmitter3D(cx *core.Scope, dev *gpu.Device, cfg Emitter3DConfig, opts GPUEmitter3DOptions) (*GPUEmitter3D, error)
NewGPUEmitter3D creates the compute pipelines and buffers that simulate cfg on dev, scoped to cx. It returns the error of ValidateGPUConfig3D when dev cannot simulate cfg.
func (*GPUEmitter3D) Active ¶
func (g *GPUEmitter3D) Active() bool
Active reports whether the emitter has at least one live particle.
func (*GPUEmitter3D) Advance ¶
func (g *GPUEmitter3D) Advance(dt time.Duration)
Advance queues a simulation step of dt that emits nothing, so a stopped effect's particles age out.
func (*GPUEmitter3D) Burst ¶
func (g *GPUEmitter3D) Burst(count int)
Burst queues up to count new particles, stopping at MaxParticles, without stepping. While ReduceFlashes reports true, bursts are rate-limited to MaxReducedBurstsPerSecond per simulated second.
func (*GPUEmitter3D) ByteSize ¶
func (g *GPUEmitter3D) ByteSize() uint64
ByteSize returns the GPU memory the emitter's buffers hold.
func (*GPUEmitter3D) Capacity ¶
func (g *GPUEmitter3D) Capacity() int
Capacity returns MaxParticles, the number of slots Draw draws.
func (*GPUEmitter3D) Clear ¶
func (g *GPUEmitter3D) Clear()
Clear removes every live particle and resets the emission accumulator without reseeding the PRNG; the next Simulate clears the GPU state.
func (*GPUEmitter3D) Close ¶
func (g *GPUEmitter3D) Close() error
Close releases the emitter's GPU resources now rather than when its scope is disposed. It is safe to call more than once.
func (*GPUEmitter3D) Config ¶
func (g *GPUEmitter3D) Config() Emitter3DConfig
Config returns a deep copy of the emitter's configuration, with its current Position and Rotation.
func (*GPUEmitter3D) Count ¶
func (g *GPUEmitter3D) Count() int
Count returns the number of live particles.
func (*GPUEmitter3D) Draw ¶
func (g *GPUEmitter3D) Draw(pass *gpu.RenderPass)
Draw binds the unit quad and the instance buffer Simulate packed, then records one gpu.RenderPass.DrawIndexedInstanced over every slot; dead slots are zero-sized and cover no pixels. The pass needs a pipeline built with ParticleVertexLayouts, such as NewParticlePipeline's, and its bind groups set.
func (*GPUEmitter3D) InstanceBuffer ¶
func (g *GPUEmitter3D) InstanceBuffer() *gpu.Buffer
InstanceBuffer returns the storage and vertex buffer Simulate packs, one ParticleInstanceStride instance per slot.
func (*GPUEmitter3D) Reset ¶
func (g *GPUEmitter3D) Reset()
Reset clears every particle and reseeds the PRNG from Seed, so later steps replay the same emission.
func (*GPUEmitter3D) SetTransform ¶
func (g *GPUEmitter3D) SetTransform(position math3d.Vec3, rotation math3d.Quat)
SetTransform moves the emitter: new particles spawn from position and rotation, and in SpaceLocal every live particle follows them.
func (*GPUEmitter3D) Simulate ¶
func (g *GPUEmitter3D) Simulate(pass *gpu.ComputePass, camRight, camUp math3d.Vec3) error
Simulate records every step and burst queued since the last call into pass, then packs every slot into the instance buffer facing (camRight, camUp) for GPUEmitter3D.Draw. Record it before the render pass that draws the emitter, and every frame the emitter steps, drawn or not, so the queue stays one frame long.
func (*GPUEmitter3D) Step ¶
func (g *GPUEmitter3D) Step(dt time.Duration)
Step queues a simulation step of dt and the particles emitted at Rate during it; the next GPUEmitter3D.Simulate runs them. Non-positive dt does nothing. Each queued step holds a small uniform buffer until Simulate records it, so call Simulate every frame the emitter steps, also while it is off screen and not drawn.
func (*GPUEmitter3D) Update ¶
func (g *GPUEmitter3D) Update(dt time.Duration)
Update advances live particles by dt and emits new ones at Rate; it is GPUEmitter3D.Step.
func (*GPUEmitter3D) Valid ¶
func (g *GPUEmitter3D) Valid() bool
Valid reports whether the emitter's buffers and pipelines are open on a live device.
type GPUEmitter3DOptions ¶
type GPUEmitter3DOptions struct {
// Label names the GPU buffers and pipelines in capture tools.
Label string
}
GPUEmitter3DOptions configures NewGPUEmitter3D.
type GPUMeshParticles3D ¶
type GPUMeshParticles3D struct {
// contains filtered or unexported fields
}
GPUMeshParticles3D owns the static mesh geometry buffers and growable 84-byte per-instance buffer needed to draw an Emitter3D as instanced 3D meshes in one draw call.
func NewGPUMeshParticles3D ¶
func NewGPUMeshParticles3D(cx *core.Scope, dev *gpu.Device, mesh MeshData3D, opts GPUMeshParticles3DOptions) (*GPUMeshParticles3D, error)
NewGPUMeshParticles3D uploads mesh and creates a growable per-instance vertex buffer on dev, scoped to cx.
func (*GPUMeshParticles3D) ByteSize ¶
func (g *GPUMeshParticles3D) ByteSize() uint64
ByteSize returns the total GPU memory held by the mesh and instance buffers.
func (*GPUMeshParticles3D) Capacity ¶
func (g *GPUMeshParticles3D) Capacity() int
Capacity returns the maximum number of instances held before growing.
func (*GPUMeshParticles3D) Close ¶
func (g *GPUMeshParticles3D) Close() error
Close releases all GPU buffers now. Safe to call more than once.
func (*GPUMeshParticles3D) Count ¶
func (g *GPUMeshParticles3D) Count() uint32
Count returns the number of mesh particle instances currently uploaded.
func (*GPUMeshParticles3D) Draw ¶
func (g *GPUMeshParticles3D) Draw(pass *gpu.RenderPass)
Draw binds the mesh and instance buffers to pass and records one instanced draw call for all uploaded particles.
func (*GPUMeshParticles3D) Upload ¶
func (g *GPUMeshParticles3D) Upload(e *Emitter3D) error
Upload packs e's live particles (and any sub-emitter particles) as 84-byte mesh instances and uploads them to the GPU buffer.
func (*GPUMeshParticles3D) UploadBytes ¶
func (g *GPUMeshParticles3D) UploadBytes(data []byte) error
UploadBytes uploads pre-packed ParticleMeshInstanceStride mesh instance bytes to the GPU instance buffer.
func (*GPUMeshParticles3D) Valid ¶
func (g *GPUMeshParticles3D) Valid() bool
Valid reports whether all underlying GPU buffers are open and belong to a live device.
type GPUMeshParticles3DOptions ¶
GPUMeshParticles3DOptions configures NewGPUMeshParticles3D.
type GPUParticleTrails3D ¶
type GPUParticleTrails3D struct {
// contains filtered or unexported fields
}
GPUParticleTrails3D owns a growable dynamic GPU vertex buffer for drawing an Emitter3D's ribbon or tube trails in one draw call.
func NewGPUParticleTrails3D ¶
func NewGPUParticleTrails3D(cx *core.Scope, dev *gpu.Device, opts GPUParticleTrails3DOptions) (*GPUParticleTrails3D, error)
NewGPUParticleTrails3D allocates a growable vertex buffer for 3D particle trails on dev, scoped to cx.
func (*GPUParticleTrails3D) ByteSize ¶
func (g *GPUParticleTrails3D) ByteSize() uint64
ByteSize returns the GPU memory held by the trail vertex buffer.
func (*GPUParticleTrails3D) Capacity ¶
func (g *GPUParticleTrails3D) Capacity() int
Capacity returns the maximum number of vertices the current GPU buffer holds without growing.
func (*GPUParticleTrails3D) Close ¶
func (g *GPUParticleTrails3D) Close() error
Close releases the trail GPU vertex buffer. Safe to call more than once.
func (*GPUParticleTrails3D) Draw ¶
func (g *GPUParticleTrails3D) Draw(pass *gpu.RenderPass)
Draw binds the trail vertex buffer and records one non-indexed triangle-list draw call.
func (*GPUParticleTrails3D) Upload ¶
func (g *GPUParticleTrails3D) Upload(e *Emitter3D, camPos, camRight, camUp math3d.Vec3) error
Upload packs e's live and fading 3D particle trails (and any sub-emitter trails) and uploads them to the GPU buffer.
func (*GPUParticleTrails3D) UploadBytes ¶
func (g *GPUParticleTrails3D) UploadBytes(data []byte) error
UploadBytes uploads pre-packed Trail3DVertexStride trail vertex bytes to the GPU vertex buffer.
func (*GPUParticleTrails3D) Valid ¶
func (g *GPUParticleTrails3D) Valid() bool
Valid reports whether the underlying GPU buffer is open and belongs to a live device.
func (*GPUParticleTrails3D) VertexCount ¶
func (g *GPUParticleTrails3D) VertexCount() uint32
VertexCount returns the number of trail vertices currently uploaded.
type GPUParticleTrails3DOptions ¶
GPUParticleTrails3DOptions configures NewGPUParticleTrails3D.
type GPUParticles3D ¶
type GPUParticles3D struct {
// contains filtered or unexported fields
}
GPUParticles3D owns the static unit-quad geometry and dynamic per-instance vertex buffer needed to draw an Emitter3D in a single gpu.RenderPass.DrawIndexedInstanced call.
Its buffers belong to the *core.Scope passed to NewGPUParticles3D and are released automatically when that scope is disposed, or earlier via GPUParticles3D.Close. Use it on the engine goroutine, like the gpu.Device it came from.
func NewGPUParticles3D ¶
func NewGPUParticles3D(cx *core.Scope, dev *gpu.Device, opts GPUParticles3DOptions) (*GPUParticles3D, error)
NewGPUParticles3D creates the static quad vertex/index buffers and an initial instance vertex buffer on dev, scoped to cx.
func (*GPUParticles3D) ByteSize ¶
func (g *GPUParticles3D) ByteSize() uint64
ByteSize returns the total GPU memory held by the quad and instance buffers.
func (*GPUParticles3D) Capacity ¶
func (g *GPUParticles3D) Capacity() int
Capacity returns the maximum number of particle instances the current GPU buffer holds without growing.
func (*GPUParticles3D) Close ¶
func (g *GPUParticles3D) Close() error
Close releases all GPU buffers now rather than waiting for scope disposal. Safe to call more than once.
func (*GPUParticles3D) Count ¶
func (g *GPUParticles3D) Count() uint32
Count returns the number of particle instances currently uploaded for drawing.
func (*GPUParticles3D) Draw ¶
func (g *GPUParticles3D) Draw(pass *gpu.RenderPass)
Draw binds the unit quad and instance buffers to pass and records one gpu.RenderPass.DrawIndexedInstanced call for all uploaded particles. The pass must already have a pipeline built with ParticleVertexLayouts (or ParticleFlipbookVertexLayouts) and its bind groups set. When g is invalid or has 0 uploaded particles, Draw records nothing.
func (*GPUParticles3D) InstanceBuffer ¶
func (g *GPUParticles3D) InstanceBuffer() *gpu.Buffer
InstanceBuffer returns the dynamic per-instance vertex buffer (slot 1).
func (*GPUParticles3D) QuadIndexBuffer ¶
func (g *GPUParticles3D) QuadIndexBuffer() *gpu.Buffer
QuadIndexBuffer returns the static unit-quad uint16 index buffer.
func (*GPUParticles3D) QuadVertexBuffer ¶
func (g *GPUParticles3D) QuadVertexBuffer() *gpu.Buffer
QuadVertexBuffer returns the static unit-quad vertex buffer (slot 0).
func (*GPUParticles3D) Upload ¶
func (g *GPUParticles3D) Upload(e *Emitter3D, camRight, camUp math3d.Vec3) error
Upload packs e's live particles (and any child sub-emitter particles) facing (camRight, camUp) into reusable scratch storage and uploads them to the GPU instance buffer. If e has more live particles than the current GPU buffer capacity, the instance buffer grows automatically.
func (*GPUParticles3D) UploadBytes ¶
func (g *GPUParticles3D) UploadBytes(data []byte) error
UploadBytes uploads pre-packed instance bytes (whose length must be a multiple of ParticleInstanceStride, or ParticleFlipbookInstanceStride when constructed with Flipbook: true) to the GPU instance buffer. This allows packing several emitters into one byte slice and drawing them in a single instanced draw call.
func (*GPUParticles3D) Valid ¶
func (g *GPUParticles3D) Valid() bool
Valid reports whether all underlying GPU buffers are open and belong to a live device.
type GPUParticles3DOptions ¶
type GPUParticles3DOptions struct {
// Label names the GPU buffers in capture tools.
Label string
// Capacity is the initial maximum number of particle instances the GPU buffer holds before growing; defaults to 256 when <= 0.
Capacity int
// Flipbook uses the 56-byte [ParticleFlipbookInstanceStride] instance layout (per-instance UV sub-rect) instead of the 40-byte [ParticleInstanceStride].
Flipbook bool
// Retained keeps the buffers retained across GPU device loss.
Retained bool
}
GPUParticles3DOptions configures NewGPUParticles3D.
type HeightField3D ¶
type HeightField3D interface {
HeightAt(x, z float32) (float32, bool)
NormalAt(x, z float32) math3d.Vec3
}
HeightField3D queries world-space terrain elevation and surface normal at (x, z). *world3d.Heightmap satisfies this interface directly.
type HeightGrid3D ¶
type HeightGrid3D struct {
Origin math3d.Vec3
CellSize float32
HeightScale float32
Cols int
Rows int
Heights []float32
}
HeightGrid3D is a serializable regular-grid height field implementing HeightField3D.
type HeightGrid3DDoc ¶
type HeightGrid3DDoc struct {
// Origin is the world-space origin of sample (0, 0).
Origin *Vec3Doc `yaml:"origin,omitempty"`
// CellSize is the horizontal grid spacing in world units.
CellSize float32 `yaml:"cellSize,omitempty"`
// HeightScale multiplies stored heights (0 defaults to 1).
HeightScale float32 `yaml:"heightScale,omitempty"`
// Cols is the number of height samples along X (at least 2).
Cols int `yaml:"cols,omitempty" schema:"minimum=2"`
// Rows is the number of height samples along Z (at least 2).
Rows int `yaml:"rows,omitempty" schema:"minimum=2"`
// Heights holds Cols*Rows height values in row-major order.
Heights []float32 `yaml:"heights,omitempty"`
}
HeightGrid3DDoc describes a regular 3D height field collider in YAML.
type HotConfig ¶
type HotConfig struct {
// contains filtered or unexported fields
}
HotConfig holds a live, versioned emitter Config and pushes hot-reloaded definitions to bound Emitters. It is composable with file-watching hot-reload hooks via ReloadHook.
func LoadHotConfigFile ¶
LoadHotConfigFile loads a versioned YAML emitter definition from path and returns a HotConfig bound to that file path.
func NewHotConfig ¶
NewHotConfig creates a HotConfig initialized with initial.
func (*HotConfig) Apply ¶
Apply updates the stored Config and reloads all bound Emitters immediately.
func (*HotConfig) Bind ¶
Bind registers e to receive config updates whenever Apply, ReloadBytes, ReloadFile, or Flush runs, and immediately applies the current config to e.
func (*HotConfig) Flush ¶
Flush applies any config staged via StageBytes to all bound Emitters and reports whether a reload occurred.
func (*HotConfig) OnReload ¶
OnReload sets an optional callback invoked after a config reload succeeds.
func (*HotConfig) ReloadBytes ¶
ReloadBytes decodes a versioned YAML emitter definition and, if valid, applies the new Config to all bound Emitters. An invalid definition returns an error and leaves the current Config and Emitters unchanged.
func (*HotConfig) ReloadFile ¶
ReloadFile reads a versioned YAML emitter definition from path (or the stored file path if path is empty) and applies it.
func (*HotConfig) ReloadHook ¶
ReloadHook returns a file-change callback suitable for plugging into hot-reload watchers (such as tooling/hotreload).
func (*HotConfig) StageBytes ¶
StageBytes decodes a versioned YAML emitter definition from a background watcher thread without touching Emitters yet. Call Flush from the game loop thread to apply the staged config safely.
type MeshData3D ¶
type MeshData3D struct {
Positions []math3d.Vec3
Normals []math3d.Vec3
UVs []math3d.Vec2
Indices []uint32
}
MeshData3D describes CPU triangle-list mesh geometry uploaded for GPUMeshParticles3D. Positions is required; Normals, UVs, and Indices are optional (matching render3d.Mesh).
type MeshParticlePipelineOptions ¶
type MeshParticlePipelineOptions struct {
Label string
CameraLayout *gpu.BindGroupLayout
TextureLayout *gpu.BindGroupLayout
ColorFormat gpu.TextureFormat
DepthFormat gpu.TextureFormat
DepthWrite bool
CullMode gpu.CullMode
Blend ParticleBlendMode
SampleCount int
Retained bool
}
MeshParticlePipelineOptions configures NewMeshParticlePipeline.
type MeshSurface3D ¶
type MeshSurface3D struct {
// contains filtered or unexported fields
}
MeshSurface3D is a precomputed area-weighted triangle surface for deterministic O(log T) particle emission. Construct one with NewMeshSurface3D or EmitFromTriangles.
func NewMeshSurface3D ¶
func NewMeshSurface3D(positions []math3d.Vec3, indices []uint32) *MeshSurface3D
NewMeshSurface3D builds an area-weighted triangle sampler from vertex positions and optional triangle indices. When indices is empty, every three consecutive positions form a triangle. Degenerate (zero-area), non-finite, and out-of-range triangles are safely skipped.
func (*MeshSurface3D) TotalArea ¶
func (s *MeshSurface3D) TotalArea() float64
TotalArea returns the total surface area of all valid triangles in s.
func (*MeshSurface3D) TriangleCount ¶
func (s *MeshSurface3D) TriangleCount() int
TriangleCount returns the number of valid non-degenerate triangles in s.
type MultiCollider ¶
type MultiCollider []Collider
MultiCollider combines multiple Colliders and reports the earliest/first hit.
func (MultiCollider) ResolveParticle ¶
func (m MultiCollider) ResolveParticle(prevX, prevY, x, y, radius float32) (hit bool, hitX, hitY, nx, ny float32)
ResolveParticle implements Collider with zero heap allocations.
type Particle ¶
type Particle struct {
// Frame is the atlas frame this particle draws.
Frame sprite.Frame
// X and Y are the particle's position in the drawing (or emitter-local coordinates when Emitter.Space is SpaceLocal).
X, Y float32
// VX and VY are the particle's velocity in points per second.
VX, VY float32
// Age is how long the particle has lived so far.
Age time.Duration
// Lifetime is how long the particle lives before expiring.
Lifetime time.Duration
// Size is the particle's uniform scale evaluated from Emitter.SizeCurve.
Size float32
// Alpha is the particle's opacity in [0, 1], evaluated from Emitter.AlphaCurve and Emitter.ColorCurve.
Alpha float32
// Rotation is the particle's angle in radians, clockwise on the screen.
Rotation float32
// Color is the particle's color evaluated from Emitter.ColorCurve.
Color core.Color
// contains filtered or unexported fields
}
Particle is the live state of one emitted particle.
type Particle3D ¶
type Particle3D struct {
// Position is the particle's position in world space (or emitter-local space when Space is SpaceLocal).
Position math3d.Vec3
// Velocity is the particle's velocity in world units per second.
Velocity math3d.Vec3
// Age is how long the particle has lived so far.
Age time.Duration
// Lifetime is how long the particle lives before expiring.
Lifetime time.Duration
// Size is the particle's world-space quad size after applying SizeCurve.
Size float32
// Alpha is the particle's opacity in [0, 1] after applying AlphaCurve and ColorCurve.
Alpha float32
// Rotation is the particle's roll angle in radians.
Rotation float32
// Color is the particle's RGB color evaluated from ColorCurve (or Emitter3D.Color when empty) with alpha in the low byte.
Color core.Color
// Orientation is the particle's 3D orientation quaternion used for mesh particle instances.
Orientation math3d.Quat
// Frame is the current flipbook frame index (0 when Flipbook is inactive).
Frame int
// UVRect is the flipbook texture sub-rectangle (uOffset, vOffset, uScale, vScale); (0, 0, 1, 1) when Flipbook is inactive.
UVRect [4]float32
}
Particle3D is a read-only snapshot of one live particle in an Emitter3D.
type ParticleBlendMode ¶
type ParticleBlendMode uint8
ParticleBlendMode selects how 3D particles blend into the color target in a GPU pipeline.
const ( // BlendAlpha uses standard non-premultiplied alpha blending (srcAlpha, 1-srcAlpha). Call [Emitter3D.SortByDepth] before packing for correct transparency order. BlendAlpha ParticleBlendMode = iota // BlendAdditive uses additive blending (srcAlpha, 1). Order-independent, so depth sorting is unnecessary for fire, sparks and glow effects. BlendAdditive // BlendPremultiplied uses premultiplied alpha blending (1, 1-srcAlpha). BlendPremultiplied )
func (ParticleBlendMode) BlendState ¶
func (m ParticleBlendMode) BlendState() *gpu.BlendState
BlendState returns the gpu.BlendState corresponding to m.
func (ParticleBlendMode) String ¶
func (m ParticleBlendMode) String() string
String returns the canonical string name of the blend mode.
type ParticleEvent ¶
type ParticleEvent struct {
// Kind is what happened to the particle.
Kind ParticleEventKind
// X and Y are the event position in world coordinates.
X, Y float32
// VX and VY are the particle's world velocity at the event, in points per second.
VX, VY float32
}
ParticleEvent describes one death or collision reported by an Emitter.
type ParticleEventKind ¶
type ParticleEventKind uint8
ParticleEventKind identifies what happened to a particle.
const ( // ParticleEventDeath fires when a particle's lifetime ends or a CollideKill impact removes it. ParticleEventDeath ParticleEventKind = iota // ParticleEventCollision fires when a particle hits a Collider. ParticleEventCollision )
func (ParticleEventKind) String ¶
func (k ParticleEventKind) String() string
String returns the kind's name: "death" or "collision".
type ParticlePipelineOptions ¶
type ParticlePipelineOptions struct {
// Label names the pipeline in GPU capture tools.
Label string
// CameraLayout is the bind group layout for @group(0) (required; matches render3d.CameraBuffer.Layout()).
CameraLayout *gpu.BindGroupLayout
// TextureLayout is an optional bind group layout for @group(1) (texture at binding 0, sampler at binding 1). When non-nil, NewParticlePipeline compiles ParticleTexturedWGSL (or ParticleFlipbookTexturedWGSL when Flipbook is true).
TextureLayout *gpu.BindGroupLayout
// ColorFormat is the color target format; FormatUndefined defaults to dev.SurfaceFormat().
ColorFormat gpu.TextureFormat
// DepthFormat enables depth testing when not FormatUndefined.
DepthFormat gpu.TextureFormat
// DepthWrite controls whether particles write to the depth buffer; false (the default) is standard for translucent particles.
DepthWrite bool
// Blend selects alpha, additive, or premultiplied blending; the zero value is BlendAlpha.
Blend ParticleBlendMode
// SoftCircle selects [ParticleSoftCircleWGSL] (smooth radial falloff) when TextureLayout is nil.
SoftCircle bool
// Flipbook enables per-instance flipbook UV sub-rect sampling ([ParticleFlipbookVertexLayouts] and [ParticleFlipbookTexturedWGSL]) when TextureLayout is non-nil.
Flipbook bool
// SampleCount sets the MSAA sample count (0 or 1 for non-MSAA).
SampleCount int
// Retained opts into automatic pipeline recreation across GPU device loss.
Retained bool
}
ParticlePipelineOptions configures NewParticlePipeline.
type QuatDoc ¶
type QuatDoc struct {
// X is the imaginary i component.
X float32 `yaml:"x,omitempty"`
// Y is the imaginary j component.
Y float32 `yaml:"y,omitempty"`
// Z is the imaginary k component.
Z float32 `yaml:"z,omitempty"`
// W is the real scalar component.
W float32 `yaml:"w,omitempty"`
}
QuatDoc describes a 3D orientation quaternion in YAML.
type RectCollider ¶
type RectCollider struct {
X, Y, W, H float32
}
RectCollider resolves particle collisions against an axis-aligned rectangle [X, X+W] x [Y, Y+H].
func (*RectCollider) ResolveParticle ¶
func (c *RectCollider) ResolveParticle(prevX, prevY, x, y, radius float32) (hit bool, hitX, hitY, nx, ny float32)
ResolveParticle implements Collider with zero heap allocations.
type SDFGrid3D ¶
type SDFGrid3D struct {
Min math3d.Vec3
Max math3d.Vec3
SizeX int
SizeY int
SizeZ int
Distances []float32
}
SDFGrid3D is a serializable 3D signed distance field over [Min, Max]. Negative values lie inside solid geometry, positive values outside. Samples are laid out in X-major order: index = (z*SizeY + y)*SizeX + x.
type SDFGrid3DDoc ¶
type SDFGrid3DDoc struct {
// Min is the minimum world corner of the SDF grid bounds.
Min *Vec3Doc `yaml:"min,omitempty"`
// Max is the maximum world corner of the SDF grid bounds.
Max *Vec3Doc `yaml:"max,omitempty"`
// SizeX is the number of grid samples along X (at least 2).
SizeX int `yaml:"sizeX,omitempty" schema:"minimum=2"`
// SizeY is the number of grid samples along Y (at least 2).
SizeY int `yaml:"sizeY,omitempty" schema:"minimum=2"`
// SizeZ is the number of grid samples along Z (at least 2).
SizeZ int `yaml:"sizeZ,omitempty" schema:"minimum=2"`
// Distances holds SizeX*SizeY*SizeZ signed distance samples in X-major order.
Distances []float32 `yaml:"distances,omitempty"`
}
SDFGrid3DDoc describes a regular 3D signed distance grid collider in YAML.
type Shape ¶
type Shape struct {
// contains filtered or unexported fields
}
Shape describes where an Emitter places each new particle relative to its X, Y position. Its zero value is Point, which emits at X, Y.
func Circle ¶
Circle returns a shape that emits particles uniformly over a disk of radius centered on X, Y.
func Point ¶
func Point() Shape
Point returns a shape that emits particles at the emitter's X, Y position.
func Rect ¶
Rect returns a shape that emits particles uniformly inside a width by height rectangle centered on X, Y.
func Ring ¶
Ring returns a shape that emits particles uniformly on the circumference of a circle of radius centered on X, Y.
type Shape3D ¶
type Shape3D struct {
// contains filtered or unexported fields
}
Shape3D describes where an Emitter3D places each new particle relative to its Position. Its zero value is Point3D, which emits at Position.
func Box ¶
Box returns a 3D shape that emits particles uniformly inside a width × height × depth box centered on Position, aligned with the emitter's basis (width along side, height along Direction, depth along forward).
func Cone ¶
Cone returns a 3D shape that emits particles from a disk of radius perpendicular to Direction and directs them outward within a cone of half-angle angle (in radians, clamped to [0, pi/2]).
func EmitFromTriangles ¶
EmitFromTriangles returns a 3D emission shape that emits uniformly (area-weighted) across the triangles defined by positions and optional indices.
func Hemisphere ¶
Hemisphere returns a 3D shape that emits particles uniformly throughout the upper hemisphere (along the emitter's Direction) of radius centered on Position.
func MeshShape3D ¶
func MeshShape3D(meshPath string, surf *MeshSurface3D) Shape3D
MeshShape3D returns a 3D mesh emission shape carrying an optional serializable meshPath alongside a runtime surface sampler.
func MeshSurface ¶
func MeshSurface(surf *MeshSurface3D) Shape3D
MeshSurface returns a 3D emission shape that emits uniformly (area-weighted) across surf's triangles along their outward face normals.
func Point3D ¶
func Point3D() Shape3D
Point3D returns a 3D shape that emits particles at the emitter's Position.
func Points3D ¶
Points3D returns a 3D emission shape that picks uniformly from an explicit set of local positions. Empty or all-non-finite point slices safely emit at the emitter origin.
func PointsWithNormals3D ¶
PointsWithNormals3D returns a 3D emission shape that picks uniformly from an explicit set of local positions and emits along their corresponding normals. If len(normals) != len(points), normals are omitted and emission falls back to the emitter Direction.
func Ring3D ¶
Ring3D returns a 3D shape that emits particles uniformly on the circumference of a circle of radius in the plane perpendicular to Direction.
func Sphere ¶
Sphere returns a 3D shape that emits particles uniformly throughout a sphere of radius centered on Position.
func (Shape3D) MeshPath ¶
MeshPath returns the serialized mesh path if s is a mesh shape, or "" otherwise.
func (Shape3D) PointNormals ¶
PointNormals returns a copy of the point normals if s is a points shape with normals, or nil otherwise.
func (Shape3D) Points ¶
Points returns a copy of the point set if s is a points shape, or nil otherwise.
func (Shape3D) Surface ¶
func (s Shape3D) Surface() *MeshSurface3D
Surface returns the precomputed MeshSurface3D if s is a mesh shape, or nil otherwise.
type Shape3DDoc ¶
type Shape3DDoc struct {
// Kind selects the 3D emission shape: "point", "sphere", "hemisphere", "box", "cone", "ring", "points" or "mesh".
Kind string `yaml:"kind,omitempty" schema:"enum=point|sphere|hemisphere|box|cone|ring|points|mesh"`
// Radius is the radius in world units for sphere, hemisphere, ring and cone shapes.
Radius float32 `yaml:"radius,omitempty" schema:"minimum=0"`
// Angle is the cone half-angle in radians for a cone shape.
Angle float32 `yaml:"angle,omitempty" schema:"minimum=0"`
// Width is the X extent in world units for a box shape.
Width float32 `yaml:"width,omitempty" schema:"minimum=0"`
// Height is the Y extent in world units for a box shape.
Height float32 `yaml:"height,omitempty" schema:"minimum=0"`
// Depth is the Z extent in world units for a box shape.
Depth float32 `yaml:"depth,omitempty" schema:"minimum=0"`
// Points lists explicit local spawn positions for a "points" shape.
Points []Vec3Doc `yaml:"points,omitempty"`
// Normals lists optional per-point emission directions matching points in length.
Normals []Vec3Doc `yaml:"normals,omitempty"`
// MeshPath is the project-relative asset path of the mesh surface for a "mesh" shape.
MeshPath string `yaml:"meshPath,omitempty"`
}
Shape3DDoc describes a 3D emission shape in YAML.
type ShapeDoc ¶
type ShapeDoc struct {
// Kind selects the shape: "point", "circle", "ring" or "rect".
Kind string `yaml:"kind,omitempty" schema:"enum=point|circle|ring|rect"`
// Radius is the radius in points for "circle" and "ring" shapes.
Radius float32 `yaml:"radius,omitempty"`
// Width is the width in points for a "rect" shape.
Width float32 `yaml:"width,omitempty"`
// Height is the height in points for a "rect" shape.
Height float32 `yaml:"height,omitempty"`
}
ShapeDoc describes a 2D emission shape in YAML.
type SimulatedEmitter3D ¶
type SimulatedEmitter3D struct {
// contains filtered or unexported fields
}
SimulatedEmitter3D runs one 3D emitter definition on the simulator it asks for: a GPUEmitter3D when Simulation is "gpu" and the device has compute shaders, and otherwise an Emitter3D drawn through GPUParticles3D, with FallbackMaxParticles, when set, in place of MaxParticles when a "gpu" definition falls back. Games switch simulators by editing the definition, not their code.
func NewSimulatedEmitter3D ¶
func NewSimulatedEmitter3D(cx *core.Scope, dev *gpu.Device, cfg Emitter3DConfig, opts SimulatedEmitter3DOptions) (*SimulatedEmitter3D, error)
NewSimulatedEmitter3D creates the simulator cfg selects on dev, scoped to cx. A "gpu" definition that dev cannot simulate for a reason other than missing compute, such as a maxParticles over its limits, returns that error rather than falling back.
func (*SimulatedEmitter3D) Active ¶
func (s *SimulatedEmitter3D) Active() bool
Active reports whether at least one particle is live.
func (*SimulatedEmitter3D) Advance ¶
func (s *SimulatedEmitter3D) Advance(dt time.Duration)
Advance advances the particles by dt without emitting.
func (*SimulatedEmitter3D) Burst ¶
func (s *SimulatedEmitter3D) Burst(count int)
Burst emits up to count particles at once, stopping at the simulator's MaxParticles.
func (*SimulatedEmitter3D) CPU ¶
func (s *SimulatedEmitter3D) CPU() *Emitter3D
CPU returns the CPU emitter, with its per-particle reads and depth sorting, or nil when the particles simulate on the GPU.
func (*SimulatedEmitter3D) Clear ¶
func (s *SimulatedEmitter3D) Clear()
Clear removes every particle without reseeding the PRNG.
func (*SimulatedEmitter3D) Close ¶
func (s *SimulatedEmitter3D) Close() error
Close releases the GPU resources now rather than when the scope is disposed.
func (*SimulatedEmitter3D) Config ¶
func (s *SimulatedEmitter3D) Config() Emitter3DConfig
Config returns the configuration the running simulator uses; a fallback's MaxParticles is its FallbackMaxParticles.
func (*SimulatedEmitter3D) Count ¶
func (s *SimulatedEmitter3D) Count() int
Count returns the number of live particles.
func (*SimulatedEmitter3D) Draw ¶
func (s *SimulatedEmitter3D) Draw(pass *gpu.RenderPass)
Draw records one instanced draw of the particles Prepare made ready into pass, which needs a pipeline built with ParticleVertexLayouts and its bind groups set.
func (*SimulatedEmitter3D) GPU ¶
func (s *SimulatedEmitter3D) GPU() *GPUEmitter3D
GPU returns the GPU emitter, or nil when the particles simulate on the CPU.
func (*SimulatedEmitter3D) OnGPU ¶
func (s *SimulatedEmitter3D) OnGPU() bool
OnGPU reports whether the particles simulate in compute shaders.
func (*SimulatedEmitter3D) Prepare ¶
func (s *SimulatedEmitter3D) Prepare(pass *gpu.ComputePass, camPos, camForward, camRight, camUp math3d.Vec3) error
Prepare makes the particles ready to draw facing (camRight, camUp): on the GPU it records the queued simulation into pass, which may then be nil only on the CPU; on the CPU it packs and uploads the live particles, sorted back to front from camPos along camForward unless the blend is additive. Call it every frame the emitter steps, also while it is off screen and Draw is skipped, as the GPU simulator's queue grows until it runs.
func (*SimulatedEmitter3D) Reset ¶
func (s *SimulatedEmitter3D) Reset()
Reset removes every particle and reseeds the PRNG from Seed.
func (*SimulatedEmitter3D) SetReduceFlashes ¶
func (s *SimulatedEmitter3D) SetReduceFlashes(fn func() bool)
SetReduceFlashes sets the ReduceFlashes check of the running simulator.
func (*SimulatedEmitter3D) SetTransform ¶
func (s *SimulatedEmitter3D) SetTransform(position math3d.Vec3, rotation math3d.Quat)
SetTransform moves the emitter's Position and Rotation.
func (*SimulatedEmitter3D) Step ¶
func (s *SimulatedEmitter3D) Step(dt time.Duration)
Step advances the particles by dt and emits new ones at Rate.
func (*SimulatedEmitter3D) Update ¶
func (s *SimulatedEmitter3D) Update(dt time.Duration)
Update advances the particles by dt and emits new ones at Rate.
type SimulatedEmitter3DOptions ¶
type SimulatedEmitter3DOptions struct {
// Label names the GPU resources in capture tools.
Label string
}
SimulatedEmitter3DOptions configures NewSimulatedEmitter3D.
type SimulationSpace ¶
type SimulationSpace uint8
SimulationSpace controls whether particles simulate in world coordinates or emitter-local coordinates.
const ( // SpaceWorld simulates particles in world coordinates so they keep their positions when the emitter moves (default). SpaceWorld SimulationSpace = iota // SpaceLocal simulates particles in emitter-local coordinates and transforms them by the emitter's current X, Y, and Rotation at Draw time. // On child sub-emitters, each trigger anchors its spawned local particles at the trigger point so subsequent triggers do not move earlier live children. SpaceLocal )
func (SimulationSpace) String ¶
func (s SimulationSpace) String() string
String returns the canonical string name of the simulation space.
type SubEmitter3DDoc ¶
type SubEmitter3DDoc struct {
// Mode selects when child particles emit: "atStart", "atEnd", "atCollision" or "constant".
Mode string `yaml:"mode,omitempty" schema:"enum=atStart|atEnd|atCollision|constant"`
// Amount is how many child particles emit per trigger or constant tick (defaults to 1).
Amount int `yaml:"amount,omitempty" schema:"minimum=0"`
// Frequency is the emission rate in Hz per live parent particle when mode is "constant".
Frequency float32 `yaml:"frequency,omitempty" schema:"minimum=0"`
// InheritVelocity multiplies parent world velocity added to each spawned child particle.
InheritVelocity float32 `yaml:"inheritVelocity,omitempty"`
// Config configures the child 3D emitter (without a version key).
Config *Emitter3DFieldsDoc `yaml:"config,omitempty"`
}
SubEmitter3DDoc describes one 3D child sub-emitter rule in YAML.
type SubEmitterDoc ¶
type SubEmitterDoc struct {
// Trigger selects which parent particle event fires the burst: "birth", "death" or "collision".
Trigger string `yaml:"trigger,omitempty" schema:"enum=birth|death|collision"`
// BurstCount is how many child particles to emit on each trigger event.
BurstCount int `yaml:"burstCount,omitempty"`
// InheritVelocity multiplies parent velocity added to each spawned child particle.
InheritVelocity float32 `yaml:"inheritVelocity,omitempty"`
// Config configures the child emitter (without a version key).
Config *EmitterFieldsDoc `yaml:"config,omitempty"`
}
SubEmitterDoc describes one child burst rule in YAML.
type SubEmitterMode3D ¶
type SubEmitterMode3D uint8
SubEmitterMode3D selects when a SubEmitterRule3D spawns child particles.
const ( // SubEmitterAtStart fires when a parent particle is spawned ("atStart"). SubEmitterAtStart SubEmitterMode3D = iota // SubEmitterAtEnd fires when a parent particle expires or is killed by collision ("atEnd"). SubEmitterAtEnd // SubEmitterAtCollision fires when a parent particle collides with a [Collider3D] ("atCollision"). SubEmitterAtCollision // SubEmitterConstant emits continuously from live parent particles at Frequency Hz ("constant"). SubEmitterConstant )
func (SubEmitterMode3D) String ¶
func (m SubEmitterMode3D) String() string
String returns the canonical string name of the 3D sub-emitter mode.
type SubEmitterRule ¶
type SubEmitterRule struct {
// Trigger selects when the sub-emitter fires.
Trigger SubEmitterTrigger
// Config configures the child emitter spawned by this rule.
Config Config
// BurstCount is how many child particles to emit on each trigger event; defaults to 1 when <= 0.
BurstCount int
// InheritVelocity adds InheritVelocity * parentVelocity to each spawned child particle's initial velocity.
InheritVelocity float32
}
SubEmitterRule spawns a burst of child particles from a parent particle event.
type SubEmitterRule3D ¶
type SubEmitterRule3D struct {
// Mode selects when child particles are emitted: SubEmitterAtStart, SubEmitterAtEnd, SubEmitterAtCollision, or SubEmitterConstant.
Mode SubEmitterMode3D
// Config configures the child emitter spawned by this rule.
Config Emitter3DConfig
// Amount is how many child particles emit per trigger (or per constant tick); defaults to 1 when <= 0.
Amount int
// Frequency is the emission rate in Hz per live parent particle when Mode is SubEmitterConstant; defaults to 1 when <= 0.
Frequency float32
// InheritVelocity adds InheritVelocity * parentWorldVelocity to each spawned child particle's initial velocity.
InheritVelocity float32
}
SubEmitterRule3D configures a child Emitter3D triggered by parent particle events.
type SubEmitterTrigger ¶
type SubEmitterTrigger uint8
SubEmitterTrigger specifies which parent particle lifecycle event fires a SubEmitterRule.
const ( // TriggerOnBirth fires when a parent particle is spawned. TriggerOnBirth SubEmitterTrigger = iota // TriggerOnDeath fires when a parent particle expires (or is killed by CollideKill). TriggerOnDeath // TriggerOnCollision fires when a parent particle hits a Collider. TriggerOnCollision )
func (SubEmitterTrigger) String ¶
func (t SubEmitterTrigger) String() string
String returns the canonical string name of the sub-emitter trigger.
type System ¶
type System struct {
// contains filtered or unexported fields
}
System manages multiple Emitters (and their sub-emitters and trails) as a single unit stepped by game.Loop.
Example ¶
A System steps and draws several emitters together, such as the parts of one explosion.
package main
import (
"fmt"
"math"
"time"
"github.com/nsgo-dev/game/pkg/particles"
)
func sparks() particles.Config {
return particles.Config{
X: 100, Y: 100,
Shape: particles.Circle(4),
LifetimeMin: 500 * time.Millisecond, LifetimeMax: time.Second,
SpeedMin: 40, SpeedMax: 80,
AngleMin: 0, AngleMax: 2 * math.Pi,
GravityY: 200,
AlphaCurve: particles.FloatCurve{{T: 0, Value: 1}, {T: 1, Value: 0}},
Seed: 7,
}
}
func main() {
smoke := sparks()
smoke.Rate = 30
sys := particles.NewSystem(particles.NewEmitter(sparks()), particles.NewEmitter(smoke))
sys.Emitters()[0].Burst(10)
sys.Update(time.Second / 2)
fmt.Println(len(sys.Emitters()), sys.TotalCount())
}
Output: 2 25
func (*System) Clear ¶
func (s *System) Clear()
Clear clears all live particles from all registered emitters.
func (*System) Reset ¶
func (s *System) Reset()
Reset resets all registered emitters and their PRNGs.
func (*System) TotalCount ¶
TotalCount returns the total number of live particles across all registered emitters and their sub-emitters.
type TileGridCollider ¶
type TileGridCollider struct {
// TileSize is the width and height of one tile in points. Non-positive disables collisions.
TileSize float32
// OriginX and OriginY are the world coordinates of tile (0, 0)'s top-left corner.
OriginX float32
OriginY float32
// SolidAt reports whether the tile at (col, row) is solid.
SolidAt func(col, row int) bool
}
TileGridCollider resolves particle collisions against a uniform 2D tile grid via a SolidAt lookup callback.
func (*TileGridCollider) ResolveParticle ¶
func (c *TileGridCollider) ResolveParticle(prevX, prevY, x, y, radius float32) (hit bool, hitX, hitY, nx, ny float32)
ResolveParticle implements Collider with zero heap allocations.
type Trail ¶
type Trail struct {
// contains filtered or unexported fields
}
Trail builds and draws a smooth 2D ribbon from a sequence of sampled positions.
func NewTrail ¶
func NewTrail(cfg TrailConfig) *Trail
NewTrail creates a new Trail with the given configuration.
func (*Trail) AddPoint ¶
AddPoint appends (x, y) to the trail head if it is at least MinDistance from the previous point.
func (*Trail) Attach ¶
Attach binds a position callback sampled automatically on each Update call. Passing nil detaches any existing callback.
func (*Trail) Config ¶
func (t *Trail) Config() TrailConfig
Config returns a copy of the trail's configuration.
func (*Trail) Draw ¶
Draw builds the ribbon strip along perpendicular normals and draws it into d. Does nothing if fewer than 2 points are active.
func (*Trail) EvaluateAt ¶
EvaluateAt evaluates the ribbon width and color at normalized parameter u in [0, 1], where 0 is the newest head and 1 is the oldest tail.
func (*Trail) PointCount ¶
PointCount returns the number of active vertices in the trail.
func (*Trail) Points ¶
func (t *Trail) Points() []TrailPoint
Points returns the active trail vertices from oldest (tail, index 0) to newest (head, last index). The returned slice is backed by internal storage; copy it to retain a snapshot.
func (*Trail) SetConfig ¶
func (t *Trail) SetConfig(cfg TrailConfig)
SetConfig updates the trail's configuration without clearing live points.
type Trail3DConfig ¶
type Trail3DConfig struct {
// Mode selects Trail3DRibbon (camera-facing strip) or Trail3DTube (cylindrical tube mesh).
Mode Trail3DMode
// MaxPoints caps the recorded polyline vertices per particle trail; defaults to 32 when <= 0 (clamped to 256).
MaxPoints int
// Lifetime is how long each trail vertex lives before expiring; defaults to 500ms when <= 0.
Lifetime time.Duration
// MinDistance is the minimum world distance from the newest point before appending a new vertex.
MinDistance float32
// Width is the base ribbon width or tube diameter in world units; defaults to 0.2 when <= 0.
Width float32
// RadialSegments is the cross-section side count in Trail3DTube mode; defaults to 6 when < 3 (clamped to [3, 32]).
RadialSegments int
// WidthCurve scales Width from head (u=0, newest) to tail (u=1, oldest). Empty keeps 1.
WidthCurve FloatCurve
// ColorCurve evaluates trail color from head (u=0) to tail (u=1). Empty uses Color (or opaque white).
ColorCurve ColorCurve
// Color is the fallback solid color when ColorCurve is empty; zero uses opaque white.
Color core.Color
}
Trail3DConfig configures automatic per-particle 3D ribbon or tube trails on an Emitter3D.
type Trail3DDoc ¶
type Trail3DDoc struct {
// Mode selects the trail geometry: "ribbon" (camera-facing strip) or "tube" (cylindrical mesh).
Mode string `yaml:"mode,omitempty" schema:"enum=ribbon|tube"`
// MaxPoints caps the recorded polyline vertices per particle trail (defaults to 32).
MaxPoints int `yaml:"maxPoints,omitempty" schema:"minimum=0"`
// Lifetime is how long each trail vertex lives as a Go duration string such as "500ms".
Lifetime time.Duration `yaml:"lifetime,omitempty"`
// MinDistance is the minimum world distance between consecutive trail points.
MinDistance float32 `yaml:"minDistance,omitempty" schema:"minimum=0"`
// Width is the base ribbon width or tube diameter in world units (defaults to 0.2).
Width float32 `yaml:"width,omitempty" schema:"minimum=0"`
// RadialSegments is the cross-section side count in "tube" mode (defaults to 6).
RadialSegments int `yaml:"radialSegments,omitempty" schema:"minimum=0"`
// WidthCurve scales Width from head (t=0) to tail (t=1).
WidthCurve []FloatStopDoc `yaml:"widthCurve,omitempty"`
// ColorCurve evaluates RGBA color from head (t=0) to tail (t=1).
ColorCurve []ColorStopDoc `yaml:"colorCurve,omitempty"`
// Color is the fallback solid hex color "#rrggbb" or "#rrggbbaa" when colorCurve is empty.
Color string `yaml:"color,omitempty"`
}
Trail3DDoc describes per-particle 3D ribbon or tube trail settings in YAML.
type Trail3DMode ¶
type Trail3DMode uint8
Trail3DMode selects the cross-section geometry built for per-particle 3D trails.
const ( // Trail3DRibbon builds a camera-facing ribbon strip along tangent × toCamera ("ribbon"). Trail3DRibbon Trail3DMode = iota // Trail3DTube builds a 3D cylindrical tube around the trail centerline using a parallel-transport frame ("tube"). Trail3DTube )
func (Trail3DMode) String ¶
func (m Trail3DMode) String() string
String returns the canonical string name of the 3D trail mode.
type Trail3DPipelineOptions ¶
type Trail3DPipelineOptions struct {
Label string
CameraLayout *gpu.BindGroupLayout
ColorFormat gpu.TextureFormat
DepthFormat gpu.TextureFormat
DepthWrite bool
Blend ParticleBlendMode
SampleCount int
Retained bool
}
Trail3DPipelineOptions configures NewTrail3DPipeline.
type TrailConfig ¶
type TrailConfig struct {
// MaxPoints caps the number of recorded polyline vertices; defaults to 64 when <= 0.
MaxPoints int
// Lifetime is how long each vertex lives in seconds before expiring; defaults to 0.5 when <= 0.
Lifetime float32
// MinDistance is the minimum distance in points from the newest vertex before appending a new vertex.
// Zero or negative records every distinct point (exact duplicates refresh the newest vertex's age).
MinDistance float32
// Width is the base ribbon width in points; defaults to 4 when <= 0.
Width float32
// WidthCurve scales Width along the trail from head (t=0, newest) to tail (t=1, oldest). Empty keeps 1.
WidthCurve Curve
// ColorGradient evaluates color along the trail from head (t=0, newest) to tail (t=1, oldest).
// When empty, Color is used (defaulting to opaque white when 0).
ColorGradient ColorCurve
// Color is the fallback solid color when ColorGradient is empty; defaults to opaque white when 0.
Color core.Color
// Texture is an optional image mapped across each ribbon segment when non-empty.
Texture core.ImageSource
}
TrailConfig configures a 2D ribbon trail.
type TrailDoc ¶
type TrailDoc struct {
// MaxPoints caps the recorded polyline vertices per trail (defaults to 64 when 0).
MaxPoints int `yaml:"maxPoints,omitempty"`
// Lifetime is how long each trail vertex lives in seconds (defaults to 0.5 when 0).
Lifetime float32 `yaml:"lifetime,omitempty"`
// MinDistance is the minimum spacing in points between consecutive trail vertices.
MinDistance float32 `yaml:"minDistance,omitempty"`
// Width is the base ribbon width in points (defaults to 4 when 0).
Width float32 `yaml:"width,omitempty"`
// WidthCurve scales Width from head (t=0) to tail (t=1).
WidthCurve []FloatStopDoc `yaml:"widthCurve,omitempty"`
// ColorGradient evaluates color from head (t=0) to tail (t=1).
ColorGradient []ColorStopDoc `yaml:"colorGradient,omitempty"`
// Color is the fallback solid hex color "#rrggbb" or "#rrggbbaa" when colorGradient is empty.
Color string `yaml:"color,omitempty"`
// TextureURI is an optional image URI mapped across trail segments.
TextureURI string `yaml:"textureURI,omitempty"`
}
TrailDoc describes per-particle ribbon trail settings in YAML.
type TrailManager ¶
type TrailManager struct {
// contains filtered or unexported fields
}
TrailManager updates and draws a collection of trails (such as moving sprite or projectile ribbons).
func NewTrailManager ¶
func NewTrailManager() *TrailManager
NewTrailManager creates an empty TrailManager.
func (*TrailManager) Add ¶
func (m *TrailManager) Add(cfg TrailConfig) *Trail
Add creates a new Trail with cfg, registers it with the manager, and returns it.
func (*TrailManager) AddTrail ¶
func (m *TrailManager) AddTrail(tr *Trail)
AddTrail registers an existing Trail with the manager.
func (*TrailManager) Clear ¶
func (m *TrailManager) Clear()
Clear removes all points from all managed trails without unregistering them.
func (*TrailManager) Count ¶
func (m *TrailManager) Count() int
Count returns the number of trails registered with the manager.
func (*TrailManager) Draw ¶
func (m *TrailManager) Draw(d *core.Drawing)
Draw draws all managed trails into d in registration order.
func (*TrailManager) Remove ¶
func (m *TrailManager) Remove(tr *Trail)
Remove unregisters tr from the manager.
func (*TrailManager) Trails ¶
func (m *TrailManager) Trails() []*Trail
Trails returns the slice of managed trails.
func (*TrailManager) Update ¶
func (m *TrailManager) Update(dt float32)
Update advances all managed trails by dt seconds.
type TrailPoint ¶
TrailPoint is one recorded vertex along a Trail polyline.
type Turbulence3D ¶
type Turbulence3D struct {
// Strength scales the turbulence acceleration in world units per second squared; <= 0 disables turbulence.
Strength float32
// Scale controls spatial frequency in inverse world units; <= 0 defaults to 1.
Scale float32
// Speed shifts the noise field over elapsed time; 0 produces a static deterministic field.
Speed float32
// Seed mixes into Emitter3D.Seed for deterministic field variation.
Seed uint64
}
Turbulence3D applies deterministic seeded 3D curl-of-value-noise turbulence to live particles.
type Turbulence3DDoc ¶
type Turbulence3DDoc struct {
// Strength scales the turbulence acceleration in world units per second squared.
Strength float32 `yaml:"strength,omitempty" schema:"minimum=0"`
// Scale sets the spatial frequency in inverse world units (defaults to 1).
Scale float32 `yaml:"scale,omitempty" schema:"minimum=0"`
// Speed animates the turbulence noise field over time.
Speed float32 `yaml:"speed,omitempty"`
// Seed mixes into the emitter seed for deterministic turbulence variation.
Seed uint64 `yaml:"seed,omitempty"`
}
Turbulence3DDoc describes seeded 3D curl-of-value-noise turbulence in YAML.
type Vec3Doc ¶
type Vec3Doc struct {
// X is the horizontal component.
X float32 `yaml:"x,omitempty"`
// Y is the vertical component.
Y float32 `yaml:"y,omitempty"`
// Z is the depth component.
Z float32 `yaml:"z,omitempty"`
}
Vec3Doc describes a 3D vector in YAML.
type VectorField3D ¶
type VectorField3D struct {
Min math3d.Vec3
Max math3d.Vec3
SizeX int
SizeY int
SizeZ int
Vectors []math3d.Vec3
}
VectorField3D is a serializable regular 3D vector grid sampled trilinearly over [Min, Max]. Vectors are laid out in X-major order: index = (z*SizeY + y)*SizeX + x.
type VectorField3DDoc ¶
type VectorField3DDoc struct {
// Min is the minimum world corner of the vector field bounds.
Min *Vec3Doc `yaml:"min,omitempty"`
// Max is the maximum world corner of the vector field bounds.
Max *Vec3Doc `yaml:"max,omitempty"`
// SizeX is the number of samples along X (at least 2).
SizeX int `yaml:"sizeX,omitempty" schema:"minimum=2"`
// SizeY is the number of samples along Y (at least 2).
SizeY int `yaml:"sizeY,omitempty" schema:"minimum=2"`
// SizeZ is the number of samples along Z (at least 2).
SizeZ int `yaml:"sizeZ,omitempty" schema:"minimum=2"`
// Vectors holds SizeX*SizeY*SizeZ acceleration direction vectors in X-major order.
Vectors []Vec3Doc `yaml:"vectors,omitempty"`
}
VectorField3DDoc describes a regular 3D vector field grid in YAML.