Documentation
¶
Overview ¶
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 NewParticlePipeline(cx *core.Scope, dev *gpu.Device, opts ParticlePipelineOptions) (*gpu.Pipeline, error)
- func ParticleVertexLayouts() []gpu.VertexBufferLayout
- func SaveConfig3DFile(path string, cfg Emitter3DConfig) error
- func SaveConfigFile(path string, cfg Config) error
- type BillboardMode3D
- type Burst
- type BurstDoc
- type CircleCollider
- type Collider
- type CollisionConfig
- type CollisionDoc
- type CollisionMode
- type ColorCurve
- type ColorStop
- type ColorStopDoc
- type Config
- type Curve
- type Emitter
- 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) AppendInstances(dst []byte, camRight, camUp math3d.Vec3) []byte
- func (e *Emitter3D) AppendParticles(dst []Particle3D) []Particle3D
- func (e *Emitter3D) Burst(count int)
- func (e *Emitter3D) Clear()
- func (e *Emitter3D) Config() Emitter3DConfig
- func (e *Emitter3D) Count() int
- 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) Update(dt time.Duration)
- type Emitter3DConfig
- type EmitterDoc
- type EmitterFieldsDoc
- type FloatCurve
- type FloatStop
- type FloatStopDoc
- 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 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 MultiCollider
- type Particle
- type Particle3D
- type ParticleBlendMode
- type ParticlePipelineOptions
- type RectCollider
- type Shape
- type Shape3D
- type ShapeDoc
- type SimulationSpace
- type SubEmitterDoc
- type SubEmitterRule
- 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 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
Examples ¶
Constants ¶
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 // Shader @location indices for [ParticleVertexLayouts]. ParticleCornerLocation = 0 ParticleUVLocation = 1 ParticleCenterLocation = 2 ParticleRightLocation = 3 ParticleUpLocation = 4 ParticleColorLocation = 5 )
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.
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 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 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 SchemaURL = "https://game.nsgo.dev/schemas/particles.v1.json"
SchemaURL is where the JSON Schema of version 1 2D particle emitter definitions is published.
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/packages/game/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 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 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.
Types ¶
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 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
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 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
// 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
// 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
// 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/packages/game/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/packages/game/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) 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.
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 X, Y, and Rotation.
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 {
// 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
// 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
// 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
// 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
// Seed seeds the emitter's PCG PRNG for deterministic emission and motion.
Seed uint64
// 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/packages/game/math3d"
"github.com/nsgo-dev/game/packages/game/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 currently has at least one live particle.
func (*Emitter3D) AppendInstances ¶
AppendInstances packs all live particles 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 Count() * ParticleInstanceStride more bytes.
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) Burst ¶
Burst immediately emits up to count particles without waiting for Step or requiring Rate > 0, stopping at MaxParticles.
func (*Emitter3D) Clear ¶
func (e *Emitter3D) Clear()
Clear removes all live particles 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) 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 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 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, and emits new particles at Rate. Non-positive dt does nothing.
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 {
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
LifetimeMin time.Duration
LifetimeMax time.Duration
SpeedMin float32
SpeedMax float32
Spread float32
Drag float32
Gravity math3d.Vec3
SizeMin float32
SizeMax float32
InitialRotationMin float32
InitialRotationMax float32
RotationSpeedMin float32
RotationSpeedMax float32
SizeCurve FloatCurve
AlphaCurve FloatCurve
RotationCurve FloatCurve
ColorCurve ColorCurve
Color core.Color
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, and non-finite numbers.
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"`
// 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 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/packages/game/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 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 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 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) 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
// Retained keeps the buffers retained across GPU device loss.
Retained bool
}
GPUParticles3DOptions configures NewGPUParticles3D.
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 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
}
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 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 instead of ParticleWGSL.
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
// 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 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 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 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 Point3D ¶
func Point3D() Shape3D
Point3D returns a 3D shape that emits particles at the emitter's Position.
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.
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 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. SpaceLocal )
func (SimulationSpace) String ¶
func (s SimulationSpace) String() string
String returns the canonical string name of the simulation space.
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 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 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/packages/game/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 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.