Debian Codegraph @

tests/inputs/updateSprites.wgsl

raw
1 /*
2 https://raw.githubusercontent.com/hexops/mach/main/examples/boids/updateSprites.wgsl
3 */
4 struct Particle {
5 pos : vec2<f32>,
6 vel : vec2<f32>,
7 };
8 struct SimParams {
9 deltaT : f32,
10 rule1Distance : f32,
11 rule2Distance : f32,
12 rule3Distance : f32,
13 rule1Scale : f32,
14 rule2Scale : f32,
15 rule3Scale : f32,
16 };
17 struct Particles {
18 particles : array<Particle>,
19 };
20 @binding(0) @group(0) var<uniform> params : SimParams;
21 @binding(1) @group(0) var<storage, read> particlesA : Particles;
22 @binding(2) @group(0) var<storage, read_write> particlesB : Particles;
23
24 // https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp
25 @compute @workgroup_size(64)
26 fn main(@builtin(global_invocation_id) GlobalInvocationID : vec3<u32>) {
27 var index : u32 = GlobalInvocationID.x;
28
29 var vPos = particlesA.particles[index].pos;
30 var vVel = particlesA.particles[index].vel;
31 var cMass = vec2<f32>(0.0, 0.0);
32 var cVel = vec2<f32>(0.0, 0.0);
33 var colVel = vec2<f32>(0.0, 0.0);
34 var cMassCount : u32 = 0u;
35 var cVelCount : u32 = 0u;
36 var pos : vec2<f32>;
37 var vel : vec2<f32>;
38
39 for (var i : u32 = 0u; i < arrayLength(&particlesA.particles); i = i + 1u) {
40 if (i == index) {
41 continue;
42 }
43
44 pos = particlesA.particles[i].pos.xy;
45 vel = particlesA.particles[i].vel.xy;
46 if (distance(pos, vPos) < params.rule1Distance) {
47 cMass = cMass + pos;
48 cMassCount = cMassCount + 1u;
49 }
50 if (distance(pos, vPos) < params.rule2Distance) {
51 colVel = colVel - (pos - vPos);
52 }
53 if (distance(pos, vPos) < params.rule3Distance) {
54 cVel = cVel + vel;
55 cVelCount = cVelCount + 1u;
56 }
57 }
58 if (cMassCount > 0u) {
59 var temp = f32(cMassCount);
60 cMass = (cMass / vec2<f32>(temp, temp)) - vPos;
61 }
62 if (cVelCount > 0u) {
63 var temp = f32(cVelCount);
64 cVel = cVel / vec2<f32>(temp, temp);
65 }
66 vVel = vVel + (cMass * params.rule1Scale) + (colVel * params.rule2Scale) +
67 (cVel * params.rule3Scale);
68
69 // clamp velocity for a more pleasing simulation
70 vVel = normalize(vVel) * clamp(length(vVel), 0.0, 0.1);
71 // kinematic update
72 vPos = vPos + (vVel * params.deltaT);
73 // Wrap around boundary
74 if (vPos.x < -1.0) {
75 vPos.x = 1.0;
76 }
77 if (vPos.x > 1.0) {
78 vPos.x = -1.0;
79 }
80 if (vPos.y < -1.0) {
81 vPos.y = 1.0;
82 }
83 if (vPos.y > 1.0) {
84 vPos.y = -1.0;
85 }
86 // Write back
87 particlesB.particles[index].pos = vPos;
88 particlesB.particles[index].vel = vVel;
89 }