WIP on (no branch): a99e3f3 WIP on master: 6e5d406 Decouple ParticleSimulation into separate class

This commit is contained in:
orosmatthew 2021-12-28 14:32:11 -05:00
commit 430e05e921
7 changed files with 177 additions and 137 deletions

36
Main.cs
View File

@ -1,34 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Godot; using Godot;
using Particles; using Particles.ParticleSimulation;
// ReSharper disable once CheckNamespace
// ReSharper disable once ClassNeverInstantiated.Global
public class Main : Node2D public class Main : Node2D
{ {
private Node2D _particleNodes;
private ParticleSimulation _particleSimulation; private ParticleSimulation _particleSimulation;
private Node2D _particleNodes; public float PhysicsInterpolationFraction;
public override void _Ready() public override void _Ready()
{ {
_particleNodes = GetNode<Node2D>("ParticlesNodes"); _particleNodes = GetNode<Node2D>("ParticlesNodes");
GD.Randomize(); GD.Randomize();
var randomSeed = GD.Randi();
GD.Seed(randomSeed);
GD.Print("Last Seed: " + randomSeed);
_particleSimulation = new ParticleSimulation _particleSimulation = new ParticleSimulation
{ {
ScreenSize = GetViewportRect().Size SpaceSize = GetViewportRect().Size * 1.15f
}; };
_particleSimulation.Initialize(); _particleSimulation.Initialize();
foreach (var id in _particleSimulation.LastParticlesAdded) foreach (var id in _particleSimulation.LastParticlesAdded) CreateParticleNode(id);
{
CreateParticleNode(id);
}
} }
public override void _Process(float delta) public override void _Process(float delta)
{ {
if (Input.IsActionJustPressed("quit")) GetTree().Quit(); if (Input.IsActionJustPressed("quit")) GetTree().Quit();
if (Input.IsActionJustPressed("reset")) GetTree().ReloadCurrentScene(); if (Input.IsActionJustPressed("reset")) GetTree().ReloadCurrentScene();
PhysicsInterpolationFraction = Engine.GetPhysicsInterpolationFraction();
} }
public override void _PhysicsProcess(float delta) public override void _PhysicsProcess(float delta)
@ -39,17 +40,18 @@ public class Main : Node2D
var particleNode = _particleNodes.GetNode<ParticleNode>(id.ToString()); var particleNode = _particleNodes.GetNode<ParticleNode>(id.ToString());
particleNode.Free(); particleNode.Free();
} }
foreach (var id in _particleSimulation.LastParticlesAdded)
{ foreach (var id in _particleSimulation.LastParticlesAdded) CreateParticleNode(id);
CreateParticleNode(id);
}
var particleNodes = _particleNodes.GetChildren(); var particleNodes = _particleNodes.GetChildren();
foreach (ParticleNode particleNode in particleNodes) foreach (ParticleNode particleNode in particleNodes)
{ {
var simulationParticle = _particleSimulation.GetParticle(particleNode.SimulationId); var simulationParticle = _particleSimulation.GetParticle(particleNode.SimulationId);
particleNode.Position = simulationParticle.Position; particleNode.LastSimulationPosition = particleNode.Position;
particleNode.SetColor(simulationParticle.Type.Hue, simulationParticle.Health); particleNode.CurrentSimulationPosition = simulationParticle.Position;
particleNode.SetColor(simulationParticle.Type.Hue, simulationParticle.Health,
Mathf.Clamp(simulationParticle.AverageSpeed / 1.5f, 1f, 1f));
particleNode.ScreenWrappedLast = simulationParticle.ScreenWrappedLast;
} }
} }

View File

@ -6,3 +6,8 @@
script = ExtResource( 1 ) script = ExtResource( 1 )
[node name="ParticlesNodes" type="Node2D" parent="."] [node name="ParticlesNodes" type="Node2D" parent="."]
[node name="Camera2D" type="Camera2D" parent="."]
anchor_mode = 0
current = true
zoom = Vector2( 1.15, 1.15 )

View File

@ -1,10 +1,15 @@
using Godot; using Godot;
// ReSharper disable once CheckNamespace
// ReSharper disable once ClassNeverInstantiated.Global
public class ParticleNode : Node2D public class ParticleNode : Node2D
{ {
private Sprite _spriteNode;
private Label _labelNode; private Label _labelNode;
private Sprite _spriteNode;
public Vector2 CurrentSimulationPosition = new Vector2();
public Vector2 LastSimulationPosition;
public bool ScreenWrappedLast = false;
public int SimulationId; public int SimulationId;
public override void _Ready() public override void _Ready()
@ -13,13 +18,21 @@ public class ParticleNode : Node2D
_labelNode = GetNode<Label>("Label"); _labelNode = GetNode<Label>("Label");
} }
public override void _Process(float delta)
{
Position = ScreenWrappedLast == false
? LastSimulationPosition.LinearInterpolate(CurrentSimulationPosition,
GetParent<Node2D>().GetParent<Main>().PhysicsInterpolationFraction)
: CurrentSimulationPosition;
}
public void SetLabelText(string text) public void SetLabelText(string text)
{ {
_labelNode.Text = text; _labelNode.Text = text;
} }
public void SetColor(float hue, float saturation) public void SetColor(float hue, float saturation, float opacity)
{ {
_spriteNode.Modulate = Color.FromHsv(hue, saturation, 1); _spriteNode.Modulate = Color.FromHsv(hue, saturation, 1, opacity);
} }
} }

View File

@ -7,7 +7,7 @@
script = ExtResource( 1 ) script = ExtResource( 1 )
[node name="Sprite" type="Sprite" parent="."] [node name="Sprite" type="Sprite" parent="."]
scale = Vector2( 0.2, 0.2 ) scale = Vector2( 0.25, 0.25 )
texture = ExtResource( 2 ) texture = ExtResource( 2 )
[node name="Label" type="Label" parent="."] [node name="Label" type="Label" parent="."]

View File

@ -1,23 +1,14 @@
using Godot; using Godot;
namespace Particles namespace Particles.ParticleSimulation
{ {
public class Particle public class Particle
{ {
private float _health = 1f;
public Vector2 Position = new Vector2(); public Vector2 Position = new Vector2();
public bool ScreenWrappedLast = true;
public Vector2 Velocity = new Vector2(); public Vector2 Velocity = new Vector2();
public ParticleType Type { get; }
public float AverageSpeed { get; private set; } = 1f;
public int Id { get; }
public float Health
{
get => _health;
set => _health = Mathf.Clamp(value, 0f, 1f);
}
private float _health = 1f;
public Particle(int id, ParticleType type) public Particle(int id, ParticleType type)
{ {
@ -25,9 +16,22 @@ namespace Particles
Type = type; Type = type;
} }
public ParticleType Type { get; }
public float AverageSpeed { get; private set; } = 1f;
// ReSharper disable once UnusedAutoPropertyAccessor.Global
// ReSharper disable once MemberCanBePrivate.Global
public int Id { get; }
public float Health
{
get => _health;
set => _health = Mathf.Clamp(value, 0f, 1f);
}
public void AddAverageSpeedValue(float speed) public void AddAverageSpeedValue(float speed)
{ {
AverageSpeed = (0.99f * AverageSpeed) + (0.01f * speed); AverageSpeed = 0.99f * AverageSpeed + 0.01f * speed;
} }
} }
} }

View File

@ -1,90 +1,106 @@
using System; using System.Collections.Generic;
using Godot;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks; using System.Threading.Tasks;
using Godot;
namespace Particles namespace Particles.ParticleSimulation
{ {
public class ParticleSimulation public class ParticleSimulation
{ {
public Vector2 ScreenSize; public Vector2 SpaceSize;
private Dictionary<int, Particle> _particles = new Dictionary<int, Particle>(); private readonly Dictionary<int, Particle> _particles = new Dictionary<int, Particle>();
private List<ParticleType> _particleTypes = new List<ParticleType>(); private readonly List<ParticleType> _particleTypes = new List<ParticleType>();
private Dictionary<ParticleType, int> _particleTypeCounts = new Dictionary<ParticleType, int>(); private readonly List<Task> _tasks = new List<Task>();
private List<Task> tasks = new List<Task>();
public List<int> LastParticlesAdded { get; private set; } = new List<int>(); public List<int> LastParticlesAdded { get; private set; } = new List<int>();
// ReSharper disable once CollectionNeverUpdated.Global
public List<int> LastParticlesRemoved { get; private set; } = new List<int>(); public List<int> LastParticlesRemoved { get; private set; } = new List<int>();
private int _idCount = 0; private int _idCount;
private const int MaxParticles = 1000; private const int MaxParticles = 1100;
private const int MaxParticleTypes = 10; private const int MaxParticleTypes = 12;
private const float HealthDelta = 0.002f; private const float HealthDelta = 0.005f;
private const float NegativeHealthMultiplier = 1.5f; private const float NegativeHealthMultiplier = 2f;
private const float PositiveHealthMultiplier = 4f;
private const float ParticleCollisionRadius = 13f; private const float ParticleCollisionRadius = 20f;
private const float ParticleCollisionStrength = 2.5f;
private const float ParticleCollisionResponse = 2f;
public void Initialize() public void Initialize()
{ {
for (var i = 0; i < MaxParticleTypes; i++) for (var i = 0; i < MaxParticleTypes; i++)
CreateRandomParticleType(); CreateRandomParticleType();
for (var i = 0; i < MaxParticles; i++) //for (var i = 0; i < MaxParticles; i++)
CreateRandomParticle(); // CreateRandomParticle();
} }
public void Update() public void Update()
{ {
LastParticlesRemoved.Clear(); LastParticlesRemoved.Clear();
LastParticlesAdded.Clear(); LastParticlesAdded.Clear();
tasks.Clear(); _tasks.Clear();
foreach (var id in _particles.Keys) foreach (var id in _particles.Keys)
tasks.Add(Task.Factory.StartNew(UpdateParticle, id)); _tasks.Add(Task.Factory.StartNew(UpdateParticle, id));
Task.WaitAll(tasks.ToArray()); Task.WaitAll(_tasks.ToArray());
var deletedParticle = false; var deletedParticle = false;
foreach (var p in _particles) foreach (var p in _particles)
{ {
var particle = p.Value; var particle = p.Value;
particle.ScreenWrappedLast = false;
if (deletedParticle == false && particle.Health == 0f) if (deletedParticle == false && particle.Health == 0f)
{ {
if (GD.Randf() < 0.2f) if (GD.Randf() < 0.2f)
{ {
LastParticlesRemoved.Add(p.Key); particle.Position = GetRandomParticlePosition();
particle.ScreenWrappedLast = true;
//LastParticlesRemoved.Add(p.Key);
deletedParticle = true; deletedParticle = true;
continue; continue;
} }
} }
var position = particle.Position; var position = particle.Position;
particle.Velocity = particle.Velocity.Clamped(4f); particle.Velocity = particle.Velocity.Clamped(5f);
position += particle.Velocity; position += particle.Velocity;
particle.Velocity *= 0.875f; // friction particle.Velocity *= 0.855f; // friction
if (position.x > ScreenSize.x) if (position.x > SpaceSize.x)
position.x -= ScreenSize.x; {
position.x -= SpaceSize.x;
particle.ScreenWrappedLast = true;
}
else if (position.x < 0) else if (position.x < 0)
position.x += ScreenSize.x; {
if (position.y > ScreenSize.y) position.x += SpaceSize.x;
position.y -= ScreenSize.y; particle.ScreenWrappedLast = true;
else if (position.y < 0) }
position.y += ScreenSize.y;
particle.AddAverageSpeedValue(particle.Position.DistanceTo(position));
if (particle.AverageSpeed < 0.15f) if (position.y > SpaceSize.y)
{
position.y -= SpaceSize.y;
particle.ScreenWrappedLast = true;
}
else if (position.y < 0)
{
position.y += SpaceSize.y;
particle.ScreenWrappedLast = true;
}
particle.AddAverageSpeedValue(particle.Position.DistanceTo(position));
/*
if (particle.AverageSpeed < 0.3f)
particle.Health -= HealthDelta * NegativeHealthMultiplier; particle.Health -= HealthDelta * NegativeHealthMultiplier;
else else
particle.Health += HealthDelta; particle.Health += HealthDelta;
*/
if (deletedParticle == false && particle.Health == 0f) if (deletedParticle == false && particle.Health == 0f)
{ {
if (GD.Randf() < 0.2f) if (GD.Randf() < 0.2f)
{ {
LastParticlesRemoved.Add(p.Key); //LastParticlesRemoved.Add(p.Key);
particle.Position = GetRandomParticlePosition();
particle.ScreenWrappedLast = true;
deletedParticle = true; deletedParticle = true;
continue; continue;
} }
@ -98,15 +114,15 @@ namespace Particles
_particles.Remove(id); _particles.Remove(id);
} }
// ReSharper disable once InvertIf
if (_particles.Count < MaxParticles) if (_particles.Count < MaxParticles)
{ {
if (GD.Randf() < 0.3f) for (var i = 0; i < 3 && _particles.Count < MaxParticles; i++)
{
CreateRandomParticle(); CreateRandomParticle();
} }
} }
}
// ReSharper disable once UnusedMember.Local
private void RemoveParticleType(ParticleType type) private void RemoveParticleType(ParticleType type)
{ {
_particleTypes.Remove(type); _particleTypes.Remove(type);
@ -123,53 +139,51 @@ namespace Particles
Hue = (float) GD.RandRange(0, 1) Hue = (float) GD.RandRange(0, 1)
}; };
_particleTypes.Add(type); _particleTypes.Add(type);
_particleTypeCounts[type] = 0;
foreach (var type1 in _particleTypes) foreach (var type1 in _particleTypes)
foreach(var type2 in _particleTypes) foreach (var type2 in _particleTypes)
type1.AddRelationship(type2, type1.AddRelationship(type2,
new ParticleRelationshipProps(ParticleCollisionRadius, (float)GD.RandRange(22, 50), new ParticleRelationshipProps(ParticleCollisionRadius, (float) GD.RandRange(25, 55),
(float)GD.RandRange(-0.3, 0.3))); (float)GD.RandRange(-0.675, 0.7)));
} }
private void CreateRandomParticle() private void CreateRandomParticle()
{ {
var randomIndex = (int) (GD.Randi() % _particleTypes.Count); var randomIndex = (int) (GD.Randi() % _particleTypes.Count);
var type = _particleTypes[randomIndex]; var type = _particleTypes[randomIndex];
CreateParticle(type); CreateParticle(type, (GetRandomParticlePosition() / 50f) + (SpaceSize / 2f));
} }
private void CreateParticle(ParticleType type) private void CreateParticle(ParticleType type, Vector2 position)
{ {
var particle = new Particle(_idCount, type) var particle = new Particle(_idCount, type)
{ {
Position = GetRandomParticlePosition(), Position = position,
Health = 1f Health = 1f
}; };
LastParticlesAdded.Add(_idCount); LastParticlesAdded.Add(_idCount);
_particles.Add(_idCount, particle); _particles.Add(_idCount, particle);
_idCount++; _idCount++;
_particleTypeCounts[type]++;
} }
private Vector2 GetRandomParticlePosition() private Vector2 GetRandomParticlePosition()
{ {
var position = new Vector2( var position = new Vector2(
(float) GD.RandRange(0, ScreenSize.x), (float) GD.RandRange(0, SpaceSize.x),
(float) GD.RandRange(0, ScreenSize.y)); (float) GD.RandRange(0, SpaceSize.y));
return position; return position;
} }
private Vector2 GetScreenWrapPosition(Vector2 p1, Vector2 p2) private Vector2 GetScreenWrapPosition(Vector2 p1, Vector2 p2)
{ {
var newPosition = p2; var newPosition = p2;
if (p2.x > (p1.x + (ScreenSize.x / 2f))) if (p2.x > (p1.x + (SpaceSize.x / 2f)))
newPosition.x = p2.x - ScreenSize.x; newPosition.x = p2.x - SpaceSize.x;
else if (p2.x < (p1.x - (ScreenSize.x / 2f))) else if (p2.x < (p1.x - (SpaceSize.x / 2f)))
newPosition.x = p2.x + ScreenSize.x; newPosition.x = p2.x + SpaceSize.x;
if (p2.y > (p1.y + (ScreenSize.y / 2f))) if (p2.y > (p1.y + (SpaceSize.y / 2f)))
newPosition.y = p2.y - ScreenSize.y; newPosition.y = p2.y - SpaceSize.y;
else if (p2.y < (p1.y - (ScreenSize.y / 2f))) else if (p2.y < (p1.y - (SpaceSize.y / 2f)))
newPosition.y = p2.y + ScreenSize.y; newPosition.y = p2.y + SpaceSize.y;
return newPosition; return newPosition;
} }
@ -190,11 +204,11 @@ namespace Particles
continue; continue;
var position = GetScreenWrapPosition(particle1.Position, particle2.Position); var position = GetScreenWrapPosition(particle1.Position, particle2.Position);
var distanceSquared = particle1.Position.DistanceSquaredTo(position); var distanceSquared = particle1.Position.DistanceSquaredTo(position);
if (distanceSquared > (50f * 50f)) if (distanceSquared > (55f * 55f))
continue; continue;
var direction = particle1.Position.DirectionTo(position); var direction = particle1.Position.DirectionTo(position);
if (distanceSquared < (50f * 50f)) if (distanceSquared < (35f * 35f))
closeCount++; closeCount++;
// collision force // collision force
@ -202,8 +216,7 @@ namespace Particles
if (distanceSquared < (ParticleCollisionRadius * ParticleCollisionRadius)) if (distanceSquared < (ParticleCollisionRadius * ParticleCollisionRadius))
{ {
distance = particle1.Position.DistanceTo(position); distance = particle1.Position.DistanceTo(position);
var collisionForce = 1f / ((1f / ParticleCollisionStrength) + Mathf.Pow(Mathf.E, -ParticleCollisionResponse * (distance - ParticleCollisionRadius + 3f))) - 1f / (1f / ParticleCollisionStrength); var collisionForce = 1f / (0.35f + Mathf.Pow(Mathf.E, -1.15f * (distance - 12f))) - 1f / 0.35f;
//var collisionForce = 1f / (0.6f + Mathf.Pow(Mathf.E, -(distance - ParticleCollisionRadius - 2f))) - 1f / 0.6f;
particle1.Velocity += direction * collisionForce; particle1.Velocity += direction * collisionForce;
} }
@ -243,10 +256,10 @@ namespace Particles
} }
} }
if (closeCount < 4 || closeCount > 33) if (closeCount > 50)
particle1.Health -= HealthDelta * NegativeHealthMultiplier; particle1.Health -= HealthDelta * NegativeHealthMultiplier;
else else
particle1.Health += HealthDelta; particle1.Health += HealthDelta * PositiveHealthMultiplier;
return Task.CompletedTask; return Task.CompletedTask;
} }

View File

@ -1,8 +1,10 @@
using System.Collections.Generic; using System.Collections.Generic;
using Godot; using Godot;
public struct ParticleRelationshipProps namespace Particles.ParticleSimulation
{ {
public struct ParticleRelationshipProps
{
public ParticleRelationshipProps(float minRadius, float maxRadius, float force) public ParticleRelationshipProps(float minRadius, float maxRadius, float force)
{ {
MinRadius = minRadius; MinRadius = minRadius;
@ -13,10 +15,10 @@ public struct ParticleRelationshipProps
public float MinRadius { get; } public float MinRadius { get; }
public float MaxRadius { get; } public float MaxRadius { get; }
public float Force { get; } public float Force { get; }
} }
public class ParticleType public class ParticleType
{ {
private readonly Dictionary<ParticleType, ParticleRelationshipProps> _particleRelationships = private readonly Dictionary<ParticleType, ParticleRelationshipProps> _particleRelationships =
new Dictionary<ParticleType, ParticleRelationshipProps>(); new Dictionary<ParticleType, ParticleRelationshipProps>();
@ -45,4 +47,5 @@ public class ParticleType
{ {
return _particleRelationships[type]; return _particleRelationships[type];
} }
}
} }