jeudi 30 juin 2016

GLSL : Accessing an array in a for-loop hinders performance

Okay, so I'm developing an android app for a game I'm making (with LibGDX). And I have a fragment shader and I noticed that I had ~41 FPS. I was playing around with the code to see where the problem was, and I saw that changing how I accessed an array from arrayName[i] to arrayName[0] increased the performance back to 60 FPS, even though the loop only iterated once in this specific instance.
Here's the code :

#version 300 es

precision highp float;

uniform sampler2D u_texture;

in vec2 vTexCoord0;

struct BlackHole {
    vec2 position;
    float radius;
    float deformRadius;
};

uniform vec2 screenSize;
uniform vec3 cameraPos;
uniform float cameraZoom;

uniform BlackHole blackHole[4];
uniform int count;

out vec4 fragColor;

void main() {
    vec2 pos = vTexCoord0;

    bool doSample = true;

    for (int i = 0; i < count; i++) {
        vec2 position = (blackHole[i].position - cameraPos.xy) / cameraZoom + screenSize*0.5; // <--------
        float radius = blackHole[i].radius / cameraZoom; // <-------- blackHole is the array, and changing from [i] to [0]
        float deformRadius = blackHole[i].deformRadius / cameraZoom; // <--------

        vec2 deltaPos = vec2(position.x - gl_FragCoord.x, position.y - gl_FragCoord.y);
        float dist = length(deltaPos);

        if (dist <= radius) {
            fragColor = vec4(0, 0, 0, 1);
            doSample = false;
            break;
        } else if (dist <= radius + 1.0) {
            fragColor = vec4(1);
            doSample = false;
        } else if (dist <= deformRadius) {lensing
            float distToEdge = deformRadius - dist;
            pos += distToEdge * normalize(deltaPos) / screenSize;
        }
    }

    if (doSample)
        fragColor = texture(u_texture, pos);
}

In this specific case, "count" is 1.
Is this just an intrinsic property of GLSL? Or is there some fix to it – the highest value of "count" would be 4, so I could expand it out and not use a for loop, but I feel like that isn't a very good solution.
So, does anyone know why this is happening and/or a way to fix it?

Aucun commentaire:

Enregistrer un commentaire