Decouple ParticleSimulation into separate class

This commit is contained in:
orosmatthew 2021-12-27 23:29:02 -05:00
parent 8406578b80
commit 6e5d40614c
8 changed files with 327 additions and 252 deletions

233
Main.cs
View File

@ -3,26 +3,26 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Godot;
using Particles;
public class Main : Node2D
{
private const int ParticleScreenPadding = 16;
private readonly List<ParticleType> _particleTypes = new List<ParticleType>();
private List<Particle> _particles;
private const int MaxParticles = 600;
private const float HealthDelta = 0.002f;
private const float PositiveHealthMultiplier = 2f;
private Task[] tasks = new Task[MaxParticles];
private ParticleSimulation _particleSimulation;
private Node2D _particleNodes;
public override void _Ready()
{
_particleNodes = GetNode<Node2D>("ParticlesNodes");
GD.Randomize();
InitializeParticleTypes(10);
InitializeParticles(MaxParticles);
_particleSimulation = new ParticleSimulation
{
ScreenSize = GetViewportRect().Size
};
_particleSimulation.Initialize();
foreach (var id in _particleSimulation.LastParticlesAdded)
{
CreateParticleNode(id);
}
}
public override void _Process(float delta)
@ -33,197 +33,32 @@ public class Main : Node2D
public override void _PhysicsProcess(float delta)
{
UpdateParticles();
}
private void InitializeParticleTypes(int nTypes)
_particleSimulation.Update();
foreach (var id in _particleSimulation.LastParticlesRemoved)
{
for (var i = 0; i < nTypes; i++)
var particleNode = _particleNodes.GetNode<ParticleNode>(id.ToString());
particleNode.Free();
}
foreach (var id in _particleSimulation.LastParticlesAdded)
{
var type = new ParticleType
CreateParticleNode(id);
}
var particleNodes = _particleNodes.GetChildren();
foreach (ParticleNode particleNode in particleNodes)
{
Hue = (float) GD.RandRange(0, 1)
};
_particleTypes.Add(type);
var simulationParticle = _particleSimulation.GetParticle(particleNode.SimulationId);
particleNode.Position = simulationParticle.Position;
particleNode.SetColor(simulationParticle.Type.Hue, simulationParticle.Health);
}
}
foreach (var type1 in _particleTypes)
foreach (var type2 in _particleTypes)
type1.AddRelationship(type2,
new ParticleRelationshipProps(20, (float) GD.RandRange(25, 60),
(float) GD.RandRange(-0.33 * 2f, 0.35 * 2f)));
}
private void InitializeParticles(int nParticles)
private void CreateParticleNode(int id)
{
var typeCount = 0;
var particleScene = GD.Load<PackedScene>("res://Particle.tscn");
for (var i = 0; i < nParticles; i++)
{
var particle = particleScene.Instance<Particle>();
GetNode<Node2D>("Particles").AddChild(particle);
particle.Position = GetRandomParticlePosition();
particle.Type = _particleTypes[typeCount];
particle.Health = 1f;
if (typeCount < _particleTypes.Count - 1)
typeCount++;
else
typeCount = 0;
}
}
private void CreateParticle(ParticleType type)
{
var particleScene = GD.Load<PackedScene>("res://Particle.tscn");
var particle = particleScene.Instance<Particle>();
GetNode<Node2D>("Particles").AddChild(particle);
particle.Position = GetRandomParticlePosition();
particle.Type = type;
particle.Health = 1f;
}
private void CreateRandomParticle()
{
var randomIndex = (int) (GD.Randi() % _particleTypes.Count);
var type = _particleTypes[randomIndex];
CreateParticle(type);
}
private Vector2 GetRandomParticlePosition()
{
var viewportRect = GetViewportRect();
var position = new Vector2(
(float) GD.RandRange(ParticleScreenPadding, viewportRect.Size.x - ParticleScreenPadding),
(float) GD.RandRange(ParticleScreenPadding, viewportRect.Size.y - ParticleScreenPadding));
return position;
}
private void UpdateParticles()
{
_particles = GetNode<Node2D>("Particles").GetChildren().Cast<Particle>().ToList();
var viewportRect = GetViewportRect();
Array.Resize(ref tasks, _particles.Count);
for (int i = 0; i < _particles.Count; i++)
tasks[i] = Task.Factory.StartNew(UpdateParticle, _particles[i]);
Task.WaitAll(tasks);
var deletedParticle = false;
foreach (var p in _particles)
{
if (deletedParticle == false && p.Health == 0f)
{
if (GD.Randf() < 0.2f)
{
p.Free();
deletedParticle = true;
continue;
}
}
var screenSize = viewportRect.Size;
var position = p.Position;
p.Velocity = p.Velocity.Clamped(3f * 4f);
position += p.Velocity;
p.Velocity *= 0.875f; // friction
if (position.x > screenSize.x)
position.x -= screenSize.x;
else if (position.x < 0)
position.x += screenSize.x;
if (position.y > screenSize.y)
position.y -= screenSize.y;
else if (position.y < 0)
position.y += screenSize.y;
//position.x = Mathf.Clamp(position.x, ParticleScreenPadding, viewportRect.Size.x - ParticleScreenPadding);
//position.y = Mathf.Clamp(position.y, ParticleScreenPadding, viewportRect.Size.y - ParticleScreenPadding);
p.AddAverageSpeedValue(p.Position.DistanceTo(position));
if (p.AverageSpeed < 0.3f)
p.Health -= HealthDelta * 1.5f;
else
p.Health += HealthDelta;
if (deletedParticle == false && p.Health == 0f)
{
if (GD.Randf() < 0.2f)
{
p.Free();
deletedParticle = true;
continue;
}
}
p.Position = position;
}
if (_particles.Count < MaxParticles)
if (GD.Randf() < 0.3f)
CreateRandomParticle();
}
private void UpdateParticle(object particle)
{
var p1 = (Particle) particle;
var closeCount = 0;
foreach (var p2 in _particles)
{
var viewportRect = GetViewportRect();
if (p1 == p2)
continue;
var position = GetScreenWrapPosition(viewportRect.Size, p1.Position, p2.Position);
var distanceSquared = p1.Position.DistanceSquaredTo(position);
if (distanceSquared > (60f * 60f))
continue;
var direction = p1.Position.DirectionTo(position);
var distance = 0f;
if (distanceSquared < (70f * 70f))
{
closeCount++;
}
// collision force
if (distanceSquared < (20f * 20f))
{
distance = p1.Position.DistanceTo(position);
var collisionForce = 1f / (0.6f + Mathf.Pow(Mathf.E, -(distance - 12f))) - 1f / 0.6f;
p1.Velocity += direction * collisionForce;
}
// particle relationship force
var props = p1.Type.GetRelationship(p2.Type);
if (props.Force == 0f || !(distanceSquared >= props.MinRadius * props.MinRadius) || !(distanceSquared <= props.MaxRadius * props.MaxRadius))
continue;
distance = p1.Position.DistanceTo(position);
var slope = props.Force / ((props.MaxRadius - props.MinRadius) / 2f);
var particleForce = -slope * Mathf.Abs(distance - (props.MinRadius + props.MaxRadius) / 2f) +
props.Force;
p1.Velocity += direction * particleForce;
}
if (closeCount < 3 || closeCount > 35)
p1.Health -= HealthDelta * 1.5f;
else
p1.Health += HealthDelta;
}
private Vector2 GetScreenWrapPosition(Vector2 screenSize, Vector2 p1, Vector2 p2)
{
var newPosition = p2;
if (p2.x > (p1.x + (screenSize.x / 2f)))
newPosition.x = p2.x - screenSize.x;
else if (p2.x < (p1.x - (screenSize.x / 2f)))
newPosition.x = p2.x + screenSize.x;
if (p2.y > (p1.y + (screenSize.y / 2f)))
newPosition.y = p2.y - screenSize.y;
else if (p2.y < (p1.y - (screenSize.y / 2f)))
newPosition.y = p2.y + screenSize.y;
return newPosition;
var particleScene = GD.Load<PackedScene>("res://ParticleNode.tscn");
var particleNode = particleScene.Instance<ParticleNode>();
particleNode.Name = id.ToString();
particleNode.SimulationId = id;
_particleNodes.AddChild(particleNode);
}
}

View File

@ -5,4 +5,4 @@
[node name="Main" type="Node2D"]
script = ExtResource( 1 )
[node name="Particles" type="Node2D" parent="."]
[node name="ParticlesNodes" type="Node2D" parent="."]

View File

@ -1,49 +0,0 @@
using Godot;
public class Particle : Node2D
{
private Sprite _spriteNode;
private Label _labelNode;
private ParticleType _type;
private float _health = 0f;
private float _averageSpeed = 1f;
public Vector2 Velocity { get; set; }
public float AverageSpeed { get => _averageSpeed; }
public float Health
{
get => _health;
set
{
_health = Mathf.Clamp(value, 0f, 1f);
_spriteNode.Modulate = Color.FromHsv(_type.Hue, Health, 1);
}
}
public ParticleType Type
{
get => _type;
set
{
_type = value;
_spriteNode.Modulate = Color.FromHsv(_type.Hue, Health, 1);
}
}
public override void _Ready()
{
_spriteNode = GetNode<Sprite>("Sprite");
_labelNode = GetNode<Label>("Label");
}
public void AddAverageSpeedValue(float speed)
{
_averageSpeed = (0.99f * _averageSpeed) + (0.01f * speed);
}
public void SetLabelText(string text)
{
_labelNode.Text = text;
}
}

25
ParticleNode.cs Normal file
View File

@ -0,0 +1,25 @@
using Godot;
public class ParticleNode : Node2D
{
private Sprite _spriteNode;
private Label _labelNode;
public int SimulationId;
public override void _Ready()
{
_spriteNode = GetNode<Sprite>("Sprite");
_labelNode = GetNode<Label>("Label");
}
public void SetLabelText(string text)
{
_labelNode.Text = text;
}
public void SetColor(float hue, float saturation)
{
_spriteNode.Modulate = Color.FromHsv(hue, saturation, 1);
}
}

View File

@ -1,14 +1,14 @@
[gd_scene load_steps=3 format=2]
[ext_resource path="res://textures/particle.png" type="Texture" id=1]
[ext_resource path="res://Particle.cs" type="Script" id=2]
[ext_resource path="res://ParticleNode.cs" type="Script" id=1]
[ext_resource path="res://textures/particle.png" type="Texture" id=2]
[node name="Particle" type="Node2D"]
script = ExtResource( 2 )
[node name="ParticleNode" type="Node2D"]
script = ExtResource( 1 )
[node name="Sprite" type="Sprite" parent="."]
scale = Vector2( 0.25, 0.25 )
texture = ExtResource( 1 )
texture = ExtResource( 2 )
[node name="Label" type="Label" parent="."]
visible = false

View File

@ -0,0 +1,33 @@
using Godot;
namespace Particles
{
public class Particle
{
public Vector2 Position = 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)
{
Id = id;
Type = type;
}
public void AddAverageSpeedValue(float speed)
{
AverageSpeed = (0.99f * AverageSpeed) + (0.01f * speed);
}
}
}

View File

@ -0,0 +1,225 @@
using Godot;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
namespace Particles
{
public class ParticleSimulation
{
public Vector2 ScreenSize;
private Dictionary<int, Particle> _particles = new Dictionary<int, Particle>();
private List<ParticleType> _particleTypes = new List<ParticleType>();
private Dictionary<ParticleType, int> _particleTypeCounts = new Dictionary<ParticleType, int>();
private List<Task> tasks = new List<Task>();
public List<int> LastParticlesAdded { get; private set; } = new List<int>();
public List<int> LastParticlesRemoved { get; private set; } = new List<int>();
private int _idCount = 0;
private const int MaxParticles = 1200;
private const int MaxParticleTypes = 10;
private const float HealthDelta = 0.002f;
private const float NegativeHealthMultiplier = 1.5f;
public void Initialize()
{
for (var i = 0; i < MaxParticleTypes; i++)
CreateRandomParticleType();
for (var i = 0; i < MaxParticles; i++)
CreateRandomParticle();
}
public void Update()
{
LastParticlesRemoved.Clear();
LastParticlesAdded.Clear();
tasks.Clear();
foreach (var id in _particles.Keys)
tasks.Add(Task.Factory.StartNew(UpdateParticle, id));
Task.WaitAll(tasks.ToArray());
var deletedParticle = false;
foreach (var p in _particles)
{
var particle = p.Value;
if (deletedParticle == false && particle.Health == 0f)
{
if (GD.Randf() < 0.2f)
{
LastParticlesRemoved.Add(p.Key);
deletedParticle = true;
continue;
}
}
var position = particle.Position;
particle.Velocity = particle.Velocity.Clamped(3f * 4f);
position += particle.Velocity;
particle.Velocity *= 0.855f; // friction
if (position.x > ScreenSize.x)
position.x -= ScreenSize.x;
else if (position.x < 0)
position.x += ScreenSize.x;
if (position.y > ScreenSize.y)
position.y -= ScreenSize.y;
else if (position.y < 0)
position.y += ScreenSize.y;
particle.AddAverageSpeedValue(particle.Position.DistanceTo(position));
if (particle.AverageSpeed < 0.3f)
particle.Health -= HealthDelta * NegativeHealthMultiplier;
else
particle.Health += HealthDelta;
if (deletedParticle == false && particle.Health == 0f)
{
if (GD.Randf() < 0.2f)
{
LastParticlesRemoved.Add(p.Key);
deletedParticle = true;
continue;
}
}
particle.Position = position;
}
foreach (var id in LastParticlesRemoved)
{
_particles.Remove(id);
}
if (_particles.Count < MaxParticles)
{
if (GD.Randf() < 0.2f)
{
CreateRandomParticle();
}
}
}
private void RemoveParticleType(ParticleType type)
{
_particleTypes.Remove(type);
foreach (var t in _particleTypes)
{
t.RemoveRelationship(type);
}
}
private void CreateRandomParticleType()
{
var type = new ParticleType()
{
Hue = (float) GD.RandRange(0, 1)
};
_particleTypes.Add(type);
_particleTypeCounts[type] = 0;
foreach (var type1 in _particleTypes)
foreach(var type2 in _particleTypes)
type1.AddRelationship(type2,
new ParticleRelationshipProps(16, (float)GD.RandRange(20, 60),
(float)GD.RandRange(-0.35 * 2, 0.35 * 2)));
}
private void CreateRandomParticle()
{
var randomIndex = (int) (GD.Randi() % _particleTypes.Count);
var type = _particleTypes[randomIndex];
CreateParticle(type);
}
private void CreateParticle(ParticleType type)
{
var particle = new Particle(_idCount, type)
{
Position = GetRandomParticlePosition(),
Health = 1f
};
LastParticlesAdded.Add(_idCount);
_particles.Add(_idCount, particle);
_idCount++;
_particleTypeCounts[type]++;
}
private Vector2 GetRandomParticlePosition()
{
var position = new Vector2(
(float) GD.RandRange(0, ScreenSize.x),
(float) GD.RandRange(0, ScreenSize.y));
return position;
}
private Vector2 GetScreenWrapPosition(Vector2 p1, Vector2 p2)
{
var newPosition = p2;
if (p2.x > (p1.x + (ScreenSize.x / 2f)))
newPosition.x = p2.x - ScreenSize.x;
else if (p2.x < (p1.x - (ScreenSize.x / 2f)))
newPosition.x = p2.x + ScreenSize.x;
if (p2.y > (p1.y + (ScreenSize.y / 2f)))
newPosition.y = p2.y - ScreenSize.y;
else if (p2.y < (p1.y - (ScreenSize.y / 2f)))
newPosition.y = p2.y + ScreenSize.y;
return newPosition;
}
public Particle GetParticle(int id)
{
return _particles[id];
}
private Task UpdateParticle(object i)
{
var id = (int)i;
var particle1 = _particles[id];
var closeCount = 0;
foreach (var p2 in _particles)
{
var particle2 = p2.Value;
if (particle1 == particle2)
continue;
var position = GetScreenWrapPosition(particle1.Position, particle2.Position);
var distanceSquared = particle1.Position.DistanceSquaredTo(position);
if (distanceSquared > (60f * 60f))
continue;
var direction = particle1.Position.DirectionTo(position);
if (distanceSquared < (70f * 70f))
closeCount++;
// collision force
float distance;
if (distanceSquared < (16f * 16f))
{
distance = particle1.Position.DistanceTo(position);
var collisionForce = 1f / (0.3f + Mathf.Pow(Mathf.E, -(distance - 11f))) - 1f / 0.3f;
particle1.Velocity += direction * collisionForce;
}
// particle relationship force
var props = particle1.Type.GetRelationship(particle2.Type);
if (props.Force != 0f && distanceSquared >= props.MinRadius * props.MinRadius &&
distanceSquared <= props.MaxRadius * props.MaxRadius)
{
distance = particle1.Position.DistanceTo(position);
var slope = props.Force / ((props.MaxRadius - props.MinRadius) / 2f);
var particleForce = -slope * Mathf.Abs(distance - (props.MinRadius + props.MaxRadius) / 2f) +
props.Force;
particle1.Velocity += direction * particleForce;
}
}
if (closeCount < 4 || closeCount > 33)
particle1.Health -= HealthDelta * NegativeHealthMultiplier;
else
particle1.Health += HealthDelta;
return Task.CompletedTask;
}
}
}

View File

@ -35,6 +35,12 @@ public class ParticleType
_particleRelationships[type] = props;
}
public void RemoveRelationship(ParticleType type)
{
if (_particleRelationships.ContainsKey(type))
_particleRelationships.Remove(type);
}
public ParticleRelationshipProps GetRelationship(ParticleType type)
{
return _particleRelationships[type];