|
| 1 | +import { |
| 2 | + useWebGLContext, |
| 3 | + useLoop, |
| 4 | + usePingPongFBO, |
| 5 | + useWebGLCanvas, |
| 6 | + createFloatDataTexture, |
| 7 | +} from "usegl"; |
| 8 | +import "./styles.css"; |
| 9 | + |
| 10 | +const { gl, canvas } = useWebGLContext("#glCanvas"); |
| 11 | + |
| 12 | +const positionsFragment = /* glsl */ ` |
| 13 | + uniform float uDeltaTime; |
| 14 | + uniform sampler2D tPositions; |
| 15 | + uniform sampler2D tVelocities; |
| 16 | +
|
| 17 | + in vec2 uv; |
| 18 | + out vec4 fragColor; |
| 19 | +
|
| 20 | + vec2 wrapToRange(vec2 value) { |
| 21 | + vec2 shifted = value + 1.0; |
| 22 | + vec2 wrapped = mod(mod(shifted, 2.0) + 2.0, 2.0); |
| 23 | + return wrapped - 1.0; |
| 24 | + } |
| 25 | +
|
| 26 | + void main() { |
| 27 | + vec2 position = texture(tPositions, uv).xy; |
| 28 | + vec2 velocity = texture(tVelocities, uv).xy; |
| 29 | +
|
| 30 | + fragColor = vec4(wrapToRange(position + velocity * uDeltaTime), 0.0, 0.0); |
| 31 | + } |
| 32 | +`; |
| 33 | + |
| 34 | +const count = 100; |
| 35 | + |
| 36 | +const positions = usePingPongFBO(gl, { |
| 37 | + fragment: positionsFragment, |
| 38 | + uniforms: { |
| 39 | + uDeltaTime: 0, |
| 40 | + tVelocities: createFloatDataTexture( |
| 41 | + Array.from({ length: count }).flatMap(() => [ |
| 42 | + /* R */ Math.random() * 0.2 - 0.1, |
| 43 | + /* G */ Math.random() * 0.2 - 0.1, |
| 44 | + /* B */ 0, |
| 45 | + /* A */ 0, |
| 46 | + ]), |
| 47 | + ), |
| 48 | + }, |
| 49 | + dataTexture: { |
| 50 | + name: "tPositions", |
| 51 | + initialData: Array.from({ length: count }).flatMap(() => [ |
| 52 | + /* R */ Math.random() * 2 - 1, |
| 53 | + /* G */ Math.random() * 2 - 1, |
| 54 | + /* B */ 0, |
| 55 | + /* A */ 0, |
| 56 | + ]), |
| 57 | + }, |
| 58 | +}); |
| 59 | + |
| 60 | +const renderPass = useWebGLCanvas({ |
| 61 | + canvas, |
| 62 | + vertex: ` |
| 63 | + uniform sampler2D uPositions; |
| 64 | + in vec2 aCoords; |
| 65 | +
|
| 66 | + void main() { |
| 67 | + gl_Position = vec4(texture2D(uPositions, aCoords).xy, 0, 1); |
| 68 | + gl_PointSize = 20.0; |
| 69 | + } |
| 70 | + `, |
| 71 | + fragment: ` |
| 72 | + in vec2 uv; |
| 73 | + out vec4 outColor; |
| 74 | +
|
| 75 | + void main() { |
| 76 | + vec2 uv = gl_PointCoord.xy; |
| 77 | + outColor = vec4(0, 1, .5, smoothstep(0.5, 0.4, length(uv - 0.5))); |
| 78 | + } |
| 79 | + `, |
| 80 | + uniforms: { |
| 81 | + uPositions: () => positions.texture, |
| 82 | + }, |
| 83 | + attributes: { |
| 84 | + aCoords: positions.coords, |
| 85 | + }, |
| 86 | + transparent: true, |
| 87 | +}); |
| 88 | + |
| 89 | +// Wait for the canvas to be resized to avoid a flash at the first renders |
| 90 | +renderPass.onCanvasReady(() => { |
| 91 | + useLoop(({ deltaTime }) => { |
| 92 | + positions.uniforms.uDeltaTime = deltaTime / 500; |
| 93 | + positions.render(); |
| 94 | + renderPass.render(); |
| 95 | + }); |
| 96 | +}); |
0 commit comments