|
1 | | -import tgpu, { d, std, type TgpuVertexFn } from 'typegpu'; |
| 1 | +import tgpu, { d, std, type TgpuBuffer, type TgpuVertexFn } from 'typegpu'; |
2 | 2 | import { |
3 | 3 | useFrame, |
4 | 4 | useRoot, |
@@ -51,12 +51,14 @@ const rotate = (v: d.v2f, angle: number) => { |
51 | 51 | return pos; |
52 | 52 | }; |
53 | 53 |
|
54 | | -function createRandomPositions() { |
55 | | - return Array.from({ length: PARTICLE_AMOUNT }, () => ({ |
56 | | - position: d.vec2f(Math.random() * 2 - 1, Math.random() * 2 + 1), |
57 | | - velocity: d.vec2f((Math.random() * 2 - 1) / 50, -(Math.random() / 25 + 0.01)), |
58 | | - seed: Math.random(), |
59 | | - })); |
| 54 | +function writeRandomPositions(buffer: TgpuBuffer<ReturnType<typeof dataLayout.schemaForCount>>) { |
| 55 | + buffer.write( |
| 56 | + Array.from({ length: PARTICLE_AMOUNT }, () => ({ |
| 57 | + position: d.vec2f(Math.random() * 2 - 1, Math.random() * 2 + 1), |
| 58 | + velocity: d.vec2f((Math.random() * 2 - 1) / 50, -(Math.random() / 25 + 0.01)), |
| 59 | + seed: Math.random(), |
| 60 | + })), |
| 61 | + ); |
60 | 62 | } |
61 | 63 |
|
62 | 64 | const computeLayout = tgpu.bindGroupLayout({ |
@@ -113,16 +115,19 @@ function App() { |
113 | 115 | // buffers |
114 | 116 |
|
115 | 117 | const particleGeometryBuffer = useBuffer(d.arrayOf(ParticleGeometry, PARTICLE_AMOUNT), { |
116 | | - initial: () => |
117 | | - Array.from({ length: PARTICLE_AMOUNT }, () => ({ |
118 | | - angle: Math.floor(Math.random() * 50) - 10, |
119 | | - tilt: Math.floor(Math.random() * 10) - 10 - 10, |
120 | | - color: COLOR_PALETTE[Math.floor(Math.random() * COLOR_PALETTE.length)], |
121 | | - })), |
| 118 | + initial: (buffer) => { |
| 119 | + buffer.write( |
| 120 | + Array.from({ length: PARTICLE_AMOUNT }, () => ({ |
| 121 | + angle: Math.floor(Math.random() * 50) - 10, |
| 122 | + tilt: Math.floor(Math.random() * 10) - 10 - 10, |
| 123 | + color: COLOR_PALETTE[Math.floor(Math.random() * COLOR_PALETTE.length)], |
| 124 | + })), |
| 125 | + ); |
| 126 | + }, |
122 | 127 | }).$usage('vertex'); |
123 | 128 |
|
124 | 129 | const particleDataBuffer = useBuffer(d.arrayOf(ParticleData, PARTICLE_AMOUNT), { |
125 | | - initial: createRandomPositions, |
| 130 | + initial: writeRandomPositions, |
126 | 131 | }).$usage('storage', 'uniform', 'vertex'); |
127 | 132 |
|
128 | 133 | const aspectRatio = useUniformValue(d.f32, 1); |
@@ -185,7 +190,7 @@ function App() { |
185 | 190 | <button |
186 | 191 | type="button" |
187 | 192 | className="text-4xl shadow rounded p-4" |
188 | | - onClick={() => particleDataBuffer.write(createRandomPositions())} |
| 193 | + onClick={() => writeRandomPositions(particleDataBuffer)} |
189 | 194 | > |
190 | 195 | 🎉 |
191 | 196 | </button> |
|
0 commit comments