Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma kernel CSMain
- struct Particle
- {
- float posX;
- float posY;
- float velX;
- float velY;
- int type;
- };
- RWTexture2D<float4> Result;
- RWStructuredBuffer<Particle> particles;
- StructuredBuffer<float> attractionMatrix;
- float deltaTime;
- float maxDist;
- float forceFactor;
- float frictionFactor;
- uint resolution;
- uint particleCount;
- float Force(float dist, float attraction)
- {
- const float beta = 0.3;
- if (dist < beta)
- {
- return dist / beta - 1;
- }
- else if (beta < dist && dist < 1)
- {
- return attraction * (1 - abs(2 * dist - 1 - beta) / (1 - beta));
- }
- else
- {
- return 0;
- }
- }
- float4 GetParticleColor(uint type)
- {
- if(type == 0)
- return float4(1, 0, 0, 1);
- else if(type == 1)
- return float4(0, 0, 1, 1);
- else if(type == 2)
- return float4(1, 0.92, 0.016, 1);
- else if(type == 3)
- return float4(0, 1, 0, 1);
- else if(type == 4)
- return float4(0, 1, 1, 1);
- else if (type == 5)
- return float4(1, 0, 1, 1);
- else
- return float4(1, 1, 1, 1);
- }
- [numthreads(64,1,1)]
- void CSMain (uint3 id : SV_DispatchThreadID)
- {
- particles[id.x].posX += particles[id.x].velX * deltaTime;
- particles[id.x].posY += particles[id.x].velY * deltaTime;
- float2 totalForce = float2(0, 0);
- uint thisType = particles[id.x].type;
- uint res = resolution - maxDist;
- for(uint i = 0; i < particleCount; i++)
- {
- if(i == id.x) { continue; }
- uint targetType = particles[i].type;
- float diffX = particles[i].posX - particles[id.x].posX;
- float diffY = particles[i].posY - particles[id.x].posY;
- // Adiust for wrap-around to find shortest path
- if (abs(diffX) > (float)(resolution / 2))
- {
- diffX -= resolution * sign(diffX);
- }
- if (abs(diffY) > (float)(resolution / 2))
- {
- diffY -= resolution * sign(diffY);
- }
- float dist = length(float2(diffX, diffY));
- if(dist > 0 && dist < maxDist)
- {
- float force = Force(dist / maxDist, attractionMatrix[thisType + (targetType * 6)]);
- totalForce += float2(diffX / dist * force, diffY / dist * force);
- }
- }
- totalForce *= maxDist * forceFactor;
- // Apply friction and update velocity
- particles[id.x].velX *= frictionFactor;
- particles[id.x].velY *= frictionFactor;
- particles[id.x].velX += totalForce.x * deltaTime;
- particles[id.x].velY += totalForce.y * deltaTime;
- // Apply wrap-around to position
- if(particles[id.x].posX >= (float)resolution) { particles[id.x].posX -= resolution; }
- if(particles[id.x].posY >= (float)resolution) { particles[id.x].posY -= resolution; }
- if(particles[id.x].posX < 0.0) { particles[id.x].posX += resolution; }
- if(particles[id.x].posY < 0.0) { particles[id.x].posY += resolution; }
- int x = (uint)particles[id.x].posX;
- int y = (uint)particles[id.x].posY;
- Result[int2(x, y)] = GetParticleColor(thisType);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement