Hacker News new | ask | show | jobs
by dkersten 243 days ago
I don't think I posted about my particle system, so I don't think I'm the same person.

> But then Id have reimplement a lot of the libs like phaserjs etc?

The way I see it is that you either:

1. Do everything in WASM, using your languages native libraries (eg Emscripten supports SDL and WebGL, for example -- I hear newest wasm version also makes more directly available from browser WASM)

2. Use WASM to offload certain workfloads or simulation, and send data to Javascript and do all rendering in Javascript (using three.js, PIXI.js, or WebGL directly).

If using 2, you either send updates (I made a little toy test engine where I wrote messages to a SharedArrayBuffer that the JS side could read), or you operate directly on primitives in a SharedArrayBuffer (fastest since there's no serialisation needed, but harder to do).

Note for my particle system, I used PIXI.js to render and the webworker to simulate. I had a read index and a write index and the simulation would basically read the particle attributes from the read index and write them to the write index. The read index would be incremented for each particle and the write index only for live particles, meaning that as particles died it auto compacted:

    let read_index = 0
    let write_index = 0
    let numParticles = liveParticles
    const view = new DataView(sharedBuffer)
    do {
        const x = view.getFloat32(read_index + 0)
        const y = view.getFloat32(read_index + 4)
        const pos = update(x, y) // whatever your update logic actually is
        const stillAlive = // ...
        if (stillAlive) {
            view.setFloat32(write_index + 0, pos.x)
            view.setFloat32(write_index + 4, pos.y)
            // only advance for live particles
            write_index += SIZE_OF_PARTICLE_IN_BYTES
        }
        read_index += SIZE_OF_PARTICLE_IN_BYTES
    } while (--numParticles > 0)
Simplified for illustrative purposes. In real life, I used a wrapper than managed offsets automatically. But the point is that its a flat buffer, we don't try to serialise objects other than to read the properties out and write them back.