Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
ParticleSurface.cs
1using System.Buffers;
2using System.Drawing;
3using System.Runtime.CompilerServices;
9using SkiaSharp;
10
12
75public sealed partial class ParticleSurface : DirectDrawingMovableBase
76{
77 private readonly Particle[] _particles;
78 private readonly Random _rng = new();
79 private readonly SKPaint _paint = new() { IsAntialias = true };
80 private int _alive;
81 private long _particlesLastTick = 0;
82
83 // If you want textured particles, supply a tilesheet frame and draw bitmap quads instead of circles.
84 private readonly SKBitmap? _particleSprite;
85
90 public readonly List<ParticleEmitter> Emitters = new();
91
95 public int ActiveParticleCount => _alive;
96
129 public float GlobalEmitScale { get; set; } = 1f;
130
160 public SKColor GlobalColorTint { get; set; } = SKColors.White;
161
166 public float GravityX { get; set; } = 0f; // px/s^2
167
172 public float GravityY { get; set; } = 400f; // px/s^2
173
178 public float CullingMarginX { get; set; } = 32f;
179
183 public float CullingMarginY { get; set; } = 32f;
184
185 private ParticleSurface(
186 RenderSurfaceHostBase renderSurfaceHost,
188 SceneLayer? sceneLayer,
189 View? view,
190 Rectangle? screenBounds,
191 Rectangle? worldBounds,
192 string? nickname = null,
193 int maxParticles = 2000,
194 SKBitmap? particleSprite = null)
195 : base(
196 renderSurfaceHost,
197 mode,
198 sceneLayer,
199 view,
200 screenBounds,
201 worldBounds,
202 nickname)
203 {
204 _particles = ArrayPool<Particle>.Shared.Rent(maxParticles);
205 _particleSprite = particleSprite;
206 }
207
219 RenderSurfaceHostBase renderSurfaceHost,
220 SceneLayer sceneLayer,
221 Rectangle? worldBounds,
222 string? nickname = null,
223 int maxParticles = 2000,
224 SKBitmap? particleSprite = null)
225 : this(
226 renderSurfaceHost,
228 sceneLayer,
229 null,
230 null,
231 worldBounds,
232 nickname,
233 maxParticles,
234 particleSprite)
235 {
236 }
237
249 RenderSurfaceHostBase renderSurfaceHost,
250 View view,
251 Rectangle? screenBounds,
252 string? nickname = null,
253 int maxParticles = 2000,
254 SKBitmap? particleSprite = null)
255 : this(
256 renderSurfaceHost,
258 null,
259 view,
260 screenBounds,
261 null,
262 nickname,
263 maxParticles,
264 particleSprite)
265 {
266 }
267
287 public void Burst(ParticleEmitter emitter, int count) => EmitFrom(emitter, count);
288
293 protected override void Dispose(bool disposing)
294 {
295 if (disposing)
296 {
297 ArrayPool<Particle>.Shared.Return(_particles, clearArray: true);
298 _paint.Dispose();
299 _alive = 0;
300 _particlesLastTick = 0;
301 }
302
303 base.Dispose(disposing);
304 }
305
310 public override void Update(long tick)
311 {
312 if (tick <= _lastTick)
313 return;
314
315 // Compute dt from ticks (seconds)
316 float dt = 0f;
317
318 // no previous tick assume first frame, so skip dt-based updates
319 if (_particlesLastTick > 0)
320 dt = HighResTimer.GetDuration(_particlesLastTick, tick);
321
322 _particlesLastTick = tick;
323
324 // (A) per-emitter motion
325 for (int i = 0; i < Emitters.Count; i++)
326 Emitters[i].OnUpdate?.Invoke(Emitters[i], dt);
327
328 // (B) emission
329 for (int i = 0; i < Emitters.Count; i++)
330 {
331 var em = Emitters[i];
332 float rate = MathF.Max(0f, em.EmitRate * GlobalEmitScale);
333 em._accumulator += rate * dt;
334
335 int toEmit = (int)em._accumulator;
336
337 if (toEmit > 0)
338 {
339 em._accumulator -= toEmit;
340 EmitFrom(em, toEmit);
341 }
342 }
343
344 // (C) integrate & compact
345 int write = 0;
346
347 for (int i = 0; i < _alive; i++)
348 {
349 ref var p = ref _particles[i];
350
351 // integrate acceleration (including gravity)
352 p.VX += p.AX * dt;
353 p.VY += p.AY * dt;
354
355 // clamp max velocity
356 if (p.MaxVelocity > 0f)
357 {
358 // thank you, Pythagoras
359 float vx = p.VX, vy = p.VY;
360 float velocity2 = (vx * vx) + (vy * vy);
361 float max2 = p.MaxVelocity * p.MaxVelocity;
362
363 if (velocity2 > max2)
364 {
365 float inv = p.MaxVelocity / MathF.Sqrt(velocity2);
366 p.VX = vx * inv;
367 p.VY = vy * inv;
368 }
369 }
370
371 // integrate velocity
372 p.X += p.VX * dt;
373 p.Y += p.VY * dt;
374
375 // to every season...
376 p.Rotation += p.AngularVel * dt;
377 p.Life -= dt;
378
379 // cull if out of bounds (with margin)
380 Rectangle cullBounds = (Mode == DirectDrawingMode.SceneLayer)
382 : ScreenBounds;
383
384 bool isInView = p.X >= cullBounds.Left - CullingMarginX
385 && p.X <= cullBounds.Right + CullingMarginX
386 && p.Y >= cullBounds.Top - CullingMarginY
387 && p.Y <= cullBounds.Bottom + CullingMarginY;
388
389 if (p.Life > 0 && isInView)
390 _particles[write++] = p;
391 }
392
393 _alive = write;
394
395 ForceRefresh();
396
397 base.Update(tick);
398 }
399
429 protected override void OnDraw(BackbufferBase backbuffer, RectangleF destRectScreen)
430 {
431 var canvas = backbuffer.Canvas;
432
433 // Source bounds in the particle coordinate space
434 Rectangle srcBounds = (Mode == DirectDrawingMode.SceneLayer)
436 : ScreenBounds;
437
438 // Guard against divide-by-zero (shouldn't happen, but cheap insurance)
439 float sx = (srcBounds.Width > 0) ? (destRectScreen.Width / srcBounds.Width) : 1f;
440 float sy = (srcBounds.Height > 0) ? (destRectScreen.Height / srcBounds.Height) : 1f;
441
442 // Usually uniform; if not, pick one (or average) for size scaling
443 float sSize = (sx + sy) * 0.5f;
444
445 for (int i = 0; i < _alive; i++)
446 {
447 ref var p = ref _particles[i];
448
449 // blend mode
450 _paint.BlendMode = p.BlendMode;
451
452 // life-based fade
453 float t = 1f - (p.Life / p.MaxLife);
454 byte a = (byte)(255 * (1f - t));
455
456 // choose tint: emitter override if set, otherwise current global
457 var tint = p.Tint ?? GlobalColorTint;
458
459 // apply global tint
460 _paint.Color = ApplyTint(p.Color, a, tint);
461
462 // Map particle position from srcBounds space -> destRectScreen space
463 float x = destRectScreen.Left + (p.X - srcBounds.Left) * sx;
464 float y = destRectScreen.Top + (p.Y - srcBounds.Top) * sy;
465
466 if (p.ParticleSprite is null)
467 {
468 float size = (p.Size * sSize) * (1f + 0.5f * t);
469
470 canvas.DrawCircle(
471 x,
472 y,
473 size,
474 _paint);
475 }
476 else
477 {
478 float s = p.Size * sSize;
479
480 var dst = new SKRect(
481 x - s * 0.5f,
482 y - s * 0.5f,
483 x + s * 0.5f,
484 y + s * 0.5f);
485
486 canvas.Save();
487 canvas.RotateDegrees(p.Rotation, x, y);
488 canvas.DrawBitmap(p.ParticleSprite, dst, _paint);
489 canvas.Restore();
490 }
491 }
492 }
493
494 private void EmitFrom(ParticleEmitter em, int count)
495 {
496 for (int i = 0; i < count && _alive < _particles.Length; i++)
497 {
498 ref var p = ref _particles[_alive++];
499
500 // Position
501 if (em.JitterX == 0f && em.JitterY == 0f)
502 {
503 p.X = em.Position.X;
504 p.Y = em.Position.Y;
505 }
506 else
507 {
508 (float dx, float dy) = SampleSpawnOffset(em);
509 p.X = em.Position.X + dx;
510 p.Y = em.Position.Y + dy;
511 }
512
513 // Velocity
514 p.VX = NextRange(em.VelocityRangeX.Min, em.VelocityRangeX.Max);
515 p.VY = NextRange(em.VelocityRangeY.Min, em.VelocityRangeY.Max);
516
517 // Acceleration (emitter override or surface default)
518 p.AX = em.GravityX ?? this.GravityX;
519 p.AY = em.GravityY ?? this.GravityY;
520
521 // Life/Size
522 p.MaxLife = p.Life = NextRange(em.LifeRange.Min, em.LifeRange.Max);
523 p.Size = NextRange(em.SizeRange.Min, em.SizeRange.Max);
524
525 // Color & spin
526 p.Color = em.Color;
527 p.Rotation = NextRange(0f, 360f);
528 p.AngularVel = NextRange(-180f, 180f);
529
530 // choose sprite once; no emitter lookups in hot loop
531 p.ParticleSprite = em.ParticleSprite ?? this._particleSprite;
532
533 // tint override
534 p.Tint = em.Tint; // null means "use global at render"
535
536 // max speed clamp
537 p.MaxVelocity = em.MaxVelocity ?? 0f; // 0 = no clamp
538
539 // blend mode
540 p.BlendMode = em.BlendMode;
541
542 // User hook for last-mile per-particle tweaks
543 em.OnSpawn?.Invoke(ref p);
544 }
545 }
546
547 private float NextRange(float min, float max) => (float)(_rng.NextDouble() * (max - min) + min);
548
549 private (float dx, float dy) SampleSpawnOffset(ParticleEmitter em)
550 {
551 float jx = MathF.Abs(em.JitterX);
552 float jy = MathF.Abs(em.JitterY);
553
554 // Handle "line" cases cleanly (one axis zero)
555 if (jx == 0f)
556 return (0f, NextRange(-jy, jy));
557
558 if (jy == 0f)
559 return (NextRange(-jx, jx), 0f);
560
561 switch (em.SpawnDistribution)
562 {
563 default:
564 case ParticleSpawnDistribution.Rectangle:
565 return (NextRange(-jx, jx), NextRange(-jy, jy));
566
567 case ParticleSpawnDistribution.Ellipse:
568 {
569 // Uniform over area of ellipse
570 float a = NextRange(0f, MathF.Tau);
571 float r = MathF.Sqrt(NextRange(0f, 1f)); // sqrt => uniform area
572 return (MathF.Cos(a) * r * jx, MathF.Sin(a) * r * jy);
573 }
574
576 {
577 // Uniform over area of annulus (ellipse-scaled)
578 float inner = Math.Clamp(em.RingInnerRadius01, 0f, 1f);
579 float a = NextRange(0f, MathF.Tau);
580
581 // area-uniform annulus: r = sqrt(inner^2 + u*(1-inner^2))
582 float u = NextRange(0f, 1f);
583 float r = MathF.Sqrt(inner * inner + u * (1f - inner * inner));
584
585 return (MathF.Cos(a) * r * jx, MathF.Sin(a) * r * jy);
586 }
587
588 case ParticleSpawnDistribution.Gaussian:
589 {
590 // Center-weighted, then clamped to ellipse boundary
591 float sd = Math.Clamp(em.GaussianStdDev01, 1e-4f, 10f);
592
593 float dx = NextGaussian() * (jx * sd);
594 float dy = NextGaussian() * (jy * sd);
595
596 // Clamp to ellipse: (dx/jx)^2 + (dy/jy)^2 <= 1
597 float nx = dx / jx;
598 float ny = dy / jy;
599 float q = nx * nx + ny * ny;
600
601 if (q > 1f)
602 {
603 float s = 1f / MathF.Sqrt(q);
604 dx *= s;
605 dy *= s;
606 }
607
608 return (dx, dy);
609 }
610 }
611 }
612
613 private float NextGaussian()
614 {
615 // Box–Muller transform (standard normal)
616 // Guard u1 from 0 to avoid log(0)
617 double u1 = 1.0 - _rng.NextDouble();
618 double u2 = 1.0 - _rng.NextDouble();
619 double mag = Math.Sqrt(-2.0 * Math.Log(u1));
620 double z0 = mag * Math.Cos(Math.Tau * u2);
621 return (float)z0;
622 }
623
624 // Fast, branch-free tint (multiplies RGB by tint).
625 // Alpha combines the particle's base alpha, life fade, and tint alpha.
626 [MethodImpl(MethodImplOptions.AggressiveInlining)]
627 private SKColor ApplyTint(SKColor c, byte lifeAlpha, SKColor tint)
628 {
629 int r = (c.Red * tint.Red) / 255;
630 int g = (c.Green * tint.Green) / 255;
631 int b = (c.Blue * tint.Blue) / 255;
632 int a = (c.Alpha * lifeAlpha * tint.Alpha) / (255 * 255);
633
634 return new SKColor(
635 (byte)r,
636 (byte)g,
637 (byte)b,
638 (byte)a);
639 }
640}
View? View
Gets the view to which this direct drawing is attached, or null if the drawing is in scene-layer mode...
long _lastTick
The last engine tick value used for delta-time calculations in Update.
SceneLayer? SceneLayer
Gets the scene layer to which this direct drawing is attached, or null if the drawing is in view mode...
Rectangle WorldBounds
Gets or sets the world-space bounds of this direct drawing in pixels.
DirectDrawingMode Mode
Gets the drawing mode that determines how this direct drawing is positioned and transformed.
Rectangle ScreenBounds
Gets or sets the screen-space bounds of this direct drawing in pixels.
DirectDrawingMovableBase(RenderSurfaceHostBase renderSurfaceHost, DirectDrawingMode mode, SceneLayer? sceneLayer, View? view, Rectangle? screenBounds, Rectangle? worldBounds, string? name=null)
Initializes a new instance of the DirectDrawingMovableBase class with integrated movement capabilitie...
Configures how particles are spawned over time at a given location.
SKColor? Tint
Optional per-emitter tint. If set, it overrides the particle system's GlobalColorTint for particles s...
SKColor Color
Base color. Alpha will be modulated by lifetime fade. You can randomize in OnSpawn if desired.
float JitterX
Gets or sets the horizontal jitter value for spawning particles, which represents a random offset app...
SKBlendMode BlendMode
Blend mode used when rendering particles from this emitter. Defaults to SKBlendMode....
PointF Position
RenderHost / adapter pixel position where particles originate.
ParticleSpawnHandler? OnSpawn
Optional per-particle customization hook (e.g., perlin drift, hue jitter).
float JitterY
Gets or sets the vertical jitter value for spawning particles, which represents a random offset appli...
A flexible particle system for effects like smoke, sparks, fire, or snow, implemented as a DirectDraw...
override void Update(long tick)
Tick-driven update override. Computes delta internally and advances simulation.
float GravityY
Gets or sets the gravitational acceleration along the Y-axis, measured in pixels per second squared....
ParticleSurface(RenderSurfaceHostBase renderSurfaceHost, View view, Rectangle? screenBounds, string? nickname=null, int maxParticles=2000, SKBitmap? particleSprite=null)
Initializes a new instance of the ParticleSurface class for view-based rendering with screen-space co...
override void Dispose(bool disposing)
Releases the particle array back to the pool and disposes managed resources.
readonly List< ParticleEmitter > Emitters
Collection of particle emitters this system updates and renders. Add multiple emitters (e....
ParticleSurface(RenderSurfaceHostBase renderSurfaceHost, SceneLayer sceneLayer, Rectangle? worldBounds, string? nickname=null, int maxParticles=2000, SKBitmap? particleSprite=null)
Initializes a new instance of the ParticleSurface class for scene layer rendering with world-space co...
void Burst(ParticleEmitter emitter, int count)
Immediately spawns a fixed number of particles from the given emitter. Useful for explosions,...
int ActiveParticleCount
Gets the current number of active (alive) particles being simulated.
SKColor GlobalColorTint
Global tint color multiplied against every particle's own color during rendering.
float GlobalEmitScale
Global multiplier applied to all emitter EmitRate values in this particle system. Acts like a master ...
float GravityX
Gets or sets the horizontal component of gravity, measured in pixels per second squared....
float CullingMarginY
Gets or sets the vertical culling margin, in pixels, beyond the bounds of the viewport to keep elemen...
float CullingMarginX
Gets or sets the horizontal culling margin, in pixels, beyond the bounds of the viewport to keep elem...
override void OnDraw(BackbufferBase backbuffer, RectangleF destRectScreen)
Renders all live particles to the current backbuffer.
Represents a base class for managing a graphical backbuffer, and is the in-memory surface where rende...
SKCanvas Canvas
Gets the SkiaSharp canvas used for drawing operations on this backbuffer.
Represents a base class for hosting a render surface, providing functionality for managing rendering ...
ParticleSpawnDistribution
Defines the spatial distribution pattern used when spawning particles within an emitter.
@ Rectangle
Particles are spawned uniformly within a rectangular area. This is the default distribution.
DirectDrawingMode
Specifies where direct drawing operations are applied within the rendering pipeline.
@ View
Performs direct drawing at the view level using screen-space coordinates.
@ SceneLayer
Performs direct drawing within a scene layer using world-space coordinates.
Represents a single particle instance in the particle system.
Definition Particle.cs:15