implement // Check if line created and line life time
const PARTICLE_COUNT = 50;
const PARTICLE_SIZE = 4 * 2; // vec2 position
const LINE_VERTEX_SIZE = 4 * 2; // vec2 position
const LINE_COUNT = PARTICLE_COUNT; // one line per particle (to nearest neighbor)
const LINE_VERTICES = LINE_COUNT * 2; // 2 vertices per line
window.hueByDistance = true; // if false, get hue from time of line exist (0 sec blue, to 5sec red)
// Configure canvas context
const format = navigator.gpu.getPreferredCanvasFormat();
context.configure({
device,
format,
alphaMode: 'opaque',
});
// Particle data on CPU
const particlesArray = new Float32Array(PARTICLE_COUNT * 2); // x,y per particle
const velocitiesArray = new Float32Array(PARTICLE_COUNT * 2); // vx, vy per particle
// Line vertex buffer (output from compute shader)
// Each line has 2 vertices (vec2 positions)
const lineVertexBuffer = device.createBuffer({
size: LINE_VERTICES * LINE_VERTEX_SIZE,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.STORAGE,
});
// Each line has 2 vertices, each vertex gets a vec4 color
const lineColorBuffer = device.createBuffer({
size: LINE_VERTICES * 4 * Float32Array.BYTES_PER_ELEMENT,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.STORAGE,
});
const lineTimesBuffer = device.createBuffer({
size: LINE_COUNT * Float32Array.BYTES_PER_ELEMENT,
usage: GPUBufferUsage.STORAGE,
mappedAtCreation: true,
});
// Initialize all times to current time
new Float32Array(lineTimesBuffer.getMappedRange()).fill(performance.now() / 1000);
lineTimesBuffer.unmap();
// Uniform buffer for time and settings
const timeUniformBuffer = device.createBuffer({
size: 8, // float32 time + float32 hueByDistance
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
fn hsl2rgb(h: f32, s: f32, l: f32) -> vec3 {
if (s == 0.0) {
return vec3(l, l, l);
}
let q = select(l * (1.0 + s), l + s - l*s, l < 0.5);
let p = 2.0 * l - q;
let r = hue2rgb(p, q, h + 1.0/3.0);
let g = hue2rgb(p, q, h);
let b = hue2rgb(p, q, h - 1.0/3.0);
return vec3(r, g, b);
}
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) global_id : vec3) {
let i = global_id.x;
if (i >= uCount) { return; }
let p = particles.positions[i];
var minDist = 1e6;
var nearest: u32 = 0u;
// find nearest neighbor
for (var j: u32 = 0u; j < uCount; j = j + 1u) {
if (i == j) { continue; }
let q = particles.positions[j];
let d = distance(p, q);
if (d < minDist) {
minDist = d;
nearest = j;
}
}
// write endpoints
let a = p;
let b = particles.positions[nearest];
// Check if line created and line life time
if (line created) {
lineTimes[i] = timeSettings.currentTime;
}
lines[i * 2u] = a;
lines[i * 2u + 1u] = b;
var h: f32;
if (timeSettings.hueByDistance > 0.5) {
// Distance-based coloring
let redThresh = 0.05; // ~10px in normalized coords, tweak to suit
let maxDist = 0.1; // 2 * 1.41421356; is longest across [-1,1]×[-1,1]
let t = clamp((minDist - redThresh) / (maxDist - redThresh), 0.0, 1.0);
h = t * (2.0/3.0); // hue: 0°→240° = 0.0→(240/360)=2/3
} else {
// Time-based coloring
let lineAge = timeSettings.currentTime - lineTimes[i];
let maxAge = 5.0; // 5 seconds from blue to red
let t = clamp(lineAge / maxAge, 0.0, 1.0);
h = (1.0 - t) * (2.0/3.0); // Reverse mapping: newer = blue, older = red
}
let rgb = hsl2rgb(h, 1.0, 0.5);
let col = vec4(rgb, 1.0);
// same color into both vertices
colors[i * 2u] = col;
colors[i * 2u + 1u] = col;
}
`;
// Render shader WGSL: draw points and lines
// We'll use two pipelines: one for points, one for lines
// Resize canvas to fit window
function resize() {
const dpr = window.devicePixelRatio || 1;
canvas.width = canvas.clientWidth * dpr;
canvas.height = canvas.clientHeight * dpr;
}
window.addEventListener('resize', resize);
resize();
function loop() {
// Update particle positions on CPU
for (let i = 0; i < PARTICLE_COUNT; i++) {
let x = particlesArray[i * 2];
let y = particlesArray[i * 2 + 1];
let vx = velocitiesArray[i * 2];
let vy = velocitiesArray[i * 2 + 1];
code
x += vx;
y += vy;
// Bounce off edges [-1,1]
if (x < -1 || x > 1) {
vx = -vx;
x = Math.min(1, Math.max(-1, x));
}
if (y < -1 || y > 1) {
vy = -vy;
y = Math.min(1, Math.max(-1, y));
}
particlesArray[i * 2] = x;
particlesArray[i * 2 + 1] = y;
velocitiesArray[i * 2] = vx;
velocitiesArray[i * 2 + 1] = vy;
}
// Upload updated particle positions to GPU
device.queue.writeBuffer(particleBuffer, 0, particlesArray);
// Update time uniform buffer
const timeData = new Float32Array([
performance.now() / 1000, // Current time in seconds
hueByDistance ? 1.0 : 0.0 // Convert boolean to float
]);
device.queue.writeBuffer(timeUniformBuffer, 0, timeData);
//console.log('timeData:', Array.from(timeData), hueByDistance);
To implement the "Check if line created and line life time" functionality, we need to modify the compute shader to track when a line is created and update its lifetime accordingly.
Here's the modified compute shader code:
wgsl
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) global_id : vec3<u32>) {
let i = global_id.x;
if (i >= uCount) { return; }
let p = particles.positions[i];
var minDist = 1e6;
var nearest: u32 = 0u;
// find nearest neighbor
for (var j: u32 = 0u; j < uCount; j = j + 1u) {
if (i == j) { continue; }
let q = particles.positions[j];
let d = distance(p, q);
if (d < minDist) {
minDist = d;
nearest = j;
}
}
// write endpoints
let a = p;
let b = particles.positions[nearest];
// Check if line created and line life time
var lineCreated = false;
if (lineTimes[i] == 0.0) {
lineCreated = true;
}
if (distance(a, b) < 0.1) { // adjust this threshold as needed
lineTimes[i] = timeSettings.currentTime;
lineCreated = true;
}
if (lineCreated) {
lineTimes[i] = timeSettings.currentTime;
}
lines[i * 2u] = a;
lines[i * 2u + 1u] = b;
var h: f32;
if (timeSettings.hueByDistance > 0.5) {
// Distance-based coloring
let redThresh = 0.05; // ~10px in normalized coords, tweak to suit
let maxDist = 0.1; // 2 * 1.41421356; is longest across [-1,1]×[-1,1]
let t = clamp((minDist - redThresh) / (maxDist - redThresh), 0.0, 1.0);
h = t * (2.0/3.0); // hue: 0°→240° = 0.0→(240/360)=2/3
} else {
// Time-based coloring
let lineAge = timeSettings.currentTime - lineTimes[i];
let maxAge = 5.0; // 5 seconds from blue to red
let t = clamp(lineAge / maxAge, 0.0, 1.0);
h = (1.0 - t) * (2.0/3.0); // Reverse mapping: newer = blue, older = red
}
let rgb = hsl2rgb(h, 1.0, 0.5);
let col = vec4<f32>(rgb, 1.0);
// same color into both vertices
colors[i * 2u] = col;
colors[i * 2u + 1u] = col;
}
However, the above code still has an issue. The lineTimes buffer is not being initialized with zeros. We need to initialize it with zeros.
Here's the corrected JavaScript code to initialize lineTimesBuffer with zeros:
javascript
const lineTimesBuffer = device.createBuffer({
size: LINE_COUNT * Float32Array.BYTES_PER_ELEMENT,
usage: GPUBufferUsage.STORAGE,
mappedAtCreation: true,
});
// Initialize all times to zero
new Float32Array(lineTimesBuffer.getMappedRange()).fill(0.0);
lineTimesBuffer.unmap();
With these changes, the code should now correctly track when a line is created and update its lifetime accordingly.