particles/ParticleSimulation/Simulation/ParticleSimulation.cs
2022-01-18 12:01:37 -05:00

291 lines
11 KiB
C#

#define MULTITHREADED
using System.Collections.Generic;
using System.Linq;
using Godot;
#if MULTITHREADED
using System.Threading.Tasks;
#endif
namespace Particles.ParticleSimulation
{
public class ParticleSimulation
{
// size of simulation space
public Vector2 SpaceSize;
// dictionary of particles with particle Id being the key
private readonly Dictionary<int, Particle> _particles = new Dictionary<int, Particle>();
private readonly List<ParticleType> _particleTypes = new List<ParticleType>();
// task list if multi-threaded
#if MULTITHREADED
private readonly List<Task> _tasks = new List<Task>();
#endif
// updated on every simulation update
public List<int> LastParticlesAdded { get; private set; } = new List<int>();
public List<int> LastParticlesRemoved { get; private set; } = new List<int>();
// counts up for each particle added
private int _idCount;
private int _maxParticles;
private const int MaxParticleTypes = 10;
private const float HealthDelta = 0.005f;
private const float NegativeHealthMultiplier = 2f;
private const float PositiveHealthMultiplier = 4f;
private const float ParticleCollisionRadius = 20f;
public void Initialize(int nParticles)
{
_maxParticles = nParticles;
for (var i = 0; i < MaxParticleTypes; i++)
CreateRandomParticleType();
}
public void Update()
{
LastParticlesRemoved.Clear();
LastParticlesAdded.Clear();
// update all particles
#if MULTITHREADED
_tasks.Clear();
foreach (var id in _particles.Keys)
_tasks.Add(Task.Factory.StartNew(UpdateParticle, id));
Task.WaitAll(_tasks.ToArray());
#else
foreach (var id in _particles.Keys)
UpdateParticle(id);
#endif
// used to ensure only one particle is moved per update
var movedParticle = false;
foreach (var particle in _particles.Select(p => p.Value))
{
particle.WasTeleportedLast = false;
if (movedParticle == false && particle.Health == 0f)
{
if (GD.Randf() < 0.1f)
{
particle.Position = GetRandomParticlePosition();
particle.WasTeleportedLast = true;
particle.Health = 1f;
movedParticle = true;
continue;
}
}
var position = particle.Position;
particle.Velocity = particle.Velocity.Clamped(5f);
position += particle.Velocity;
particle.Velocity *= 0.855f; // friction
if (position.x > SpaceSize.x)
{
position.x -= SpaceSize.x;
particle.WasTeleportedLast = true;
}
else if (position.x < 0)
{
position.x += SpaceSize.x;
particle.WasTeleportedLast = true;
}
if (position.y > SpaceSize.y)
{
position.y -= SpaceSize.y;
particle.WasTeleportedLast = true;
}
else if (position.y < 0)
{
position.y += SpaceSize.y;
particle.WasTeleportedLast = true;
}
/*
particle.AddAverageSpeedValue(particle.Velocity.Length());
if (particle.AverageSpeed < 0.5f)
particle.Health -= HealthDelta * NegativeHealthMultiplier;
else
particle.Health += HealthDelta * PositiveHealthMultiplier;
if (movedParticle == false && particle.Health == 0f)
{
if (GD.Randf() < 0.1f)
{
particle.Position = GetRandomParticlePosition();
particle.ResetAverageSpeed();
particle.WasTeleportedLast = true;
particle.Health = 1f;
movedParticle = true;
continue;
}
}
*/
particle.Position = position;
}
// ReSharper disable once InvertIf
if (_particles.Count < _maxParticles)
{
for (var i = 0; i < 3 && _particles.Count < _maxParticles; i++)
CreateRandomParticle();
}
}
// ReSharper disable once UnusedMember.Local
private void RemoveParticleType(ParticleType type)
{
_particleTypes.Remove(type);
foreach (var t in _particleTypes)
{
t.RemoveRelationship(type);
}
}
// ReSharper disable once UnusedMember.Local
private void RemoveParticle(int id)
{
_particles.Remove(id);
LastParticlesRemoved.Add(id);
}
private void CreateRandomParticleType()
{
var type = new ParticleType()
{
Hue = (float) GD.RandRange(0, 1)
};
_particleTypes.Add(type);
foreach (var type1 in _particleTypes)
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, (GetRandomParticlePosition() / 50f) + (SpaceSize / 2f));
}
private void CreateParticle(ParticleType type, Vector2 position)
{
var particle = new Particle(_idCount, type)
{
Position = position,
Health = 1f
};
LastParticlesAdded.Add(_idCount);
_particles.Add(_idCount, particle);
_idCount++;
}
private Vector2 GetRandomParticlePosition()
{
var position = new Vector2(
(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 + (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;
}
public Particle GetParticle(int id)
{
return _particles[id];
}
private void 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 > (55f * 55f))
continue;
if (distanceSquared < (35f * 35f))
closeCount++;
// collision force
float distance;
Vector2 direction;
if (distanceSquared < (ParticleCollisionRadius * ParticleCollisionRadius))
{
direction = particle1.Position.DirectionTo(position);
distance = particle1.Position.DistanceTo(position);
var collisionForce = 1f / (0.35f + Mathf.Pow(Mathf.E, -1.15f * (distance - 12f))) - 1f / 0.35f;
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)
{
direction = particle1.Position.DirectionTo(position);
distance = particle1.Position.DistanceTo(position);
var mid = (props.MinRadius + props.MaxRadius) / 2f;
float particleForce;
if (props.Force > 0)
{
if (distance <= mid)
{
particleForce = 1f / ((1f / props.Force) + Mathf.Pow(Mathf.E, -4 * (distance - props.MinRadius - 1f)));
}
else
{
particleForce = 1f / ((1f / props.Force) + Mathf.Pow(Mathf.E, 4 * (distance - props.MaxRadius + 1f)));
}
}
else
{
if (distance <= mid)
{
particleForce = -1f / ((-1f / props.Force) + Mathf.Pow(Mathf.E, -4 * (distance - props.MinRadius - 1f)));
}
else
{
particleForce = -1f / ((-1f / props.Force) + Mathf.Pow(Mathf.E, 4 * (distance - props.MaxRadius + 1f)));
}
}
particle1.Velocity += direction * particleForce;
}
}
if (closeCount > 70)
particle1.Health -= HealthDelta * NegativeHealthMultiplier;
else
particle1.Health += HealthDelta * PositiveHealthMultiplier;
}
}
}