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 Particles;
using Particles.ParticleSimulation;
// ReSharper disable once CheckNamespace
// ReSharper disable once ClassNeverInstantiated.Global
public class Main : Node2D
{
private Node2D _particleNodes;
private ParticleSimulation _particleSimulation;
private Node2D _particleNodes;
public float PhysicsInterpolationFraction;
public override void _Ready()
{
_particleNodes = GetNode<Node2D>("ParticlesNodes");
GD.Randomize();
var randomSeed = GD.Randi();
GD.Seed(randomSeed);
GD.Print("Last Seed: " + randomSeed);
_particleSimulation = new ParticleSimulation
{
ScreenSize = GetViewportRect().Size
SpaceSize = GetViewportRect().Size * 1.15f
};
_particleSimulation.Initialize();
foreach (var id in _particleSimulation.LastParticlesAdded)
{
CreateParticleNode(id);
}
foreach (var id in _particleSimulation.LastParticlesAdded) CreateParticleNode(id);
}
public override void _Process(float delta)
{
if (Input.IsActionJustPressed("quit")) GetTree().Quit();
if (Input.IsActionJustPressed("reset")) GetTree().ReloadCurrentScene();
PhysicsInterpolationFraction = Engine.GetPhysicsInterpolationFraction();
}
public override void _PhysicsProcess(float delta)
@ -39,17 +40,18 @@ public class Main : Node2D
var particleNode = _particleNodes.GetNode<ParticleNode>(id.ToString());
particleNode.Free();
}
foreach (var id in _particleSimulation.LastParticlesAdded)
{
CreateParticleNode(id);
}
foreach (var id in _particleSimulation.LastParticlesAdded) CreateParticleNode(id);
var particleNodes = _particleNodes.GetChildren();
foreach (ParticleNode particleNode in particleNodes)
{
var simulationParticle = _particleSimulation.GetParticle(particleNode.SimulationId);
particleNode.Position = simulationParticle.Position;
particleNode.SetColor(simulationParticle.Type.Hue, simulationParticle.Health);
particleNode.LastSimulationPosition = particleNode.Position;
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 )
[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;
// ReSharper disable once CheckNamespace
// ReSharper disable once ClassNeverInstantiated.Global
public class ParticleNode : Node2D
{
private Sprite _spriteNode;
private Label _labelNode;
private Sprite _spriteNode;
public Vector2 CurrentSimulationPosition = new Vector2();
public Vector2 LastSimulationPosition;
public bool ScreenWrappedLast = false;
public int SimulationId;
public override void _Ready()
@ -13,13 +18,21 @@ public class ParticleNode : Node2D
_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)
{
_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 )
[node name="Sprite" type="Sprite" parent="."]
scale = Vector2( 0.2, 0.2 )
scale = Vector2( 0.25, 0.25 )
texture = ExtResource( 2 )
[node name="Label" type="Label" parent="."]

View File

@ -1,33 +1,37 @@
using Godot;
namespace Particles
namespace Particles.ParticleSimulation
{
public class Particle
{
private float _health = 1f;
public Vector2 Position = new Vector2();
public bool ScreenWrappedLast = true;
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 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)
{
AverageSpeed = (0.99f * AverageSpeed) + (0.01f * speed);
AverageSpeed = 0.99f * AverageSpeed + 0.01f * speed;
}
}
}

View File

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

View File

@ -1,48 +1,51 @@
using System.Collections.Generic;
using Godot;
public struct ParticleRelationshipProps
namespace Particles.ParticleSimulation
{
public ParticleRelationshipProps(float minRadius, float maxRadius, float force)
public struct ParticleRelationshipProps
{
MinRadius = minRadius;
MaxRadius = maxRadius;
Force = force;
public ParticleRelationshipProps(float minRadius, float maxRadius, float force)
{
MinRadius = minRadius;
MaxRadius = maxRadius;
Force = force;
}
public float MinRadius { get; }
public float MaxRadius { get; }
public float Force { get; }
}
public float MinRadius { get; }
public float MaxRadius { get; }
public float Force { get; }
}
public class ParticleType
{
private readonly Dictionary<ParticleType, ParticleRelationshipProps> _particleRelationships =
new Dictionary<ParticleType, ParticleRelationshipProps>();
private float _hue;
public float Hue
public class ParticleType
{
get => _hue;
set => _hue = Mathf.Clamp(value, 0, 1);
}
private readonly Dictionary<ParticleType, ParticleRelationshipProps> _particleRelationships =
new Dictionary<ParticleType, ParticleRelationshipProps>();
public void AddRelationship(ParticleType type, ParticleRelationshipProps props)
{
if (_particleRelationships.ContainsKey(type))
return;
_particleRelationships[type] = props;
}
private float _hue;
public void RemoveRelationship(ParticleType type)
{
if (_particleRelationships.ContainsKey(type))
_particleRelationships.Remove(type);
}
public float Hue
{
get => _hue;
set => _hue = Mathf.Clamp(value, 0, 1);
}
public ParticleRelationshipProps GetRelationship(ParticleType type)
{
return _particleRelationships[type];
public void AddRelationship(ParticleType type, ParticleRelationshipProps props)
{
if (_particleRelationships.ContainsKey(type))
return;
_particleRelationships[type] = props;
}
public void RemoveRelationship(ParticleType type)
{
if (_particleRelationships.ContainsKey(type))
_particleRelationships.Remove(type);
}
public ParticleRelationshipProps GetRelationship(ParticleType type)
{
return _particleRelationships[type];
}
}
}