#pragma kernel CSParticle // Particle's data struct Particle { float3 position; float3 velocity; float life; }; // Particle's data, shared with the shader RWStructuredBuffer particleBuffer; // Variables set from the CPU float deltaTime; float2 mousePosition; float nrand(float2 uv) { return frac(sin(dot(uv, float2(12.9898, 78.233))) * 43758.5453); } uint rng_state; uint rand_xorshift() { // Xorshift algorithm from George Marsaglia's paper rng_state ^= (rng_state << 13); rng_state ^= (rng_state >> 17); rng_state ^= (rng_state << 5); return rng_state; } [numthreads(256, 1, 1)] void CSParticle(uint3 id : SV_DispatchThreadID) { // subtract the life based on deltaTime particleBuffer[id.x].life -= deltaTime; float3 delta = float3(mousePosition.xy, 3) - particleBuffer[id.x].position; float3 dir = normalize(delta); particleBuffer[id.x].velocity += dir; particleBuffer[id.x].position += particleBuffer[id.x].velocity * deltaTime; if (particleBuffer[id.x].life < 0) { // http://www.reedbeta.com/blog/quick-and-easy-gpu-random-numbers-in-d3d11/ rng_state = id.x; float f0 = float(rand_xorshift()) * (1.0 / 4294967296.0) - 0.5; float f1 = float(rand_xorshift()) * (1.0 / 4294967296.0) - 0.5; float f2 = float(rand_xorshift()) * (1.0 / 4294967296.0) - 0.5; float3 normalF3 = normalize(float3(f0, f1, f2)) * 0.8f; normalF3 *= float(rand_xorshift()) * (1.0 / 4294967296.0); particleBuffer[id.x].position = float3(normalF3.x + mousePosition.x, normalF3.y + mousePosition.y, normalF3.z + 3.0); // reset the life of this particle particleBuffer[id.x].life = 4; particleBuffer[id.x].velocity = float3(0, 0,0); } }