Performing Translations in the Vertex Shader

If you take a look at the code in ch05_04_bouncing-balls-optimized.html, you will see that we have taken an extra step to cache the Model-View matrix.

The basic idea behind this is to transfer the original matrix to the GPU (global) once and then perform the translation for each ball (local) inside the vertex shader. This change significantly improves the performance because of the parallel nature of the vertex shader.

This is what we do, step by step:

  1. Create a new uniform that tells the vertex shader whether it should perform a translation (uTranslate).
  2. Create a new uniform that contains the ball position for each ball (uTranslation).
  1. Map these two new uniforms to JavaScript variables (we do this in the configure function):
// Create program variable that maps the uniform uTranslation
gl.uniform3fv(program.uTranslation, [0, 0, 0]);

// Create program variable that maps the uniform uTranslate
gl.uniform1i(program.uTranslate, false);
  1. Perform the translation inside the vertex shader. This part is probably the trickiest part since it requires a little bit of ESSL programming:
// Transformed vertex position
vec3 vecPosition = aVertexPosition;
if (uTranslate) {
vecPosition += uTranslation;
}
  1. In this code fragment, we are defining vecPosition, a variable of the vec3 type. If the uTranslate uniform is true (meaning we are trying to render a bouncing ball), then we update vecPosition with the translation. This is implemented using vector-addition.
  2. Make sure that the transformed vertex carries the translation in case of having one, so the following line looks like this:
vec4 vertex = uModelViewMatrix * vec4(vecPosition, 1.0);
  1. In drawBall, pass the current ball position as the content for the uTranslation uniform:
gl.uniform3fv(program.uTranslation, ball.position);
  1. In drawBalls, set the uTranslate uniform to true:
gl.uniform1i(program.uTranslate, true);
  1. In draw, pass the Model-View matrix once for all balls by using the following line of code:
transforms.setMatrixUniforms();
  1. Increase the ballsCount global variable from 50 to 500 and watch how the application continues to perform reasonably well, regardless of the increased scene complexity. The improvement in execution times is shown in the following screenshot:

  1. After these optimizations, the example runs at a smooth 60 frames per second. The optimized source code is available at ch05_bouncing-balls-optimized.html.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.19.31.73