Tuqire Hussain
Tuqire Hussain

Reputation: 181

three.js: Change attributes value in vertex shader and pass to buffer

Is it possible to change the value of an attribute in the shader and have this reflected in the buffer for the next frame render?

So for example change the position of a vertex in the vertex shader and send this new value back to the javascript buffer object?

Code sample below:

attribute vec3 newPosition;
attribute vec3 divideVal;

void main() {
    vec3 difference = newPosition - position;

    velocity = difference / divideVal;

    position += velocity;

    vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);

    gl_PointSize = size * (sizeMultipler / -mvPosition.z);

    gl_Position = projectionMatrix * mvPosition;
}

Edit:

Right now I do this in the JS itself, but understand it will be faster if I move as much calculation as I can to the shaders? This is my current JS:

const positions = this.geometry.attributes.position.array;
const newPositions = this.geometry.attributes.newPosition.array;

for (let i = 0, i3 = 0; i < this.numParticles; i++, i3 += 3) {
    const velocity = [newPositions[i3] - positions[i3], newPositions[i3 + 1] - positions[i3 + 1], newPositions[i3 + 2] - positions[i3 + 2]];

    if (velocity[0] || velocity[1] || velocity[2]) {
        const minReset = 1;

        velocity[0] = velocity[0] / 60;
        velocity[1] = velocity[1] / 60;
        velocity[2] = velocity[2] / 60;

        positions[i3] = positions[i3] + velocity[0];
        positions[i3 + 1] = positions[i3 + 1] + velocity[1];
        positions[i3 + 2] = positions[i3 + 2] + velocity[2];
    }
}

Upvotes: 1

Views: 3044

Answers (1)

Tuqire Hussain
Tuqire Hussain

Reputation: 181

I found out how to do this.

Using a concept called FBO Simulation, I created a simulation shader, which computes the calculations in its glsl shaders, and then rather than displaying the results on screens, writes them to a texture. I then read from that texture in the "real" shader and wrote the results to the screen. This also allowed me to compare different output textures to work out velocity and size differences of particles between frames.

You can read more about it being discussed here: https://github.com/mrdoob/three.js/issues/1183

Example: http://barradeau.com/blog/?p=621

Upvotes: 3

Related Questions