Tôi có một cảnh với 150000 trường hợp. Tôi sử dụng glsl và opengl 4.0. Shader A chậm hơn 2 lần so với shader BIe với shader AI nhận 20fps, với shader BI trung bình 40fps. Tôi có thể làm gì để cải thiện shader A?
Shader A:
#version 400
struct Light {
vec3 position;
vec3 intensities; //a.k.a the color of the light
float ambientCoefficient;
float attenuation;
};
uniform bool useLight;
uniform mat4 modelMatrix;
uniform bool useTex;
uniform sampler2D tex;
uniform Light light;
uniform vec4 diffuseColor;
in vec2 fragTexCoord;
in vec3 fragNormal;
in vec3 fragVert;
out vec4 finalColor;
void main() {
vec3 normal = normalize(transpose(inverse(mat3(modelMatrix))) * fragNormal);
vec3 surfacePos = vec3(modelMatrix * vec4(fragVert, 1));
vec4 surfaceColor = vec4(0,0,0,1);
if(useTex) {
surfaceColor = texture(tex, fragTexCoord);
}
else {
//surfaceColor = diffuseColor;
surfaceColor = vec4(0,1,0,1);
}
if(useLight) {
vec3 surfaceToLight = normalize(light.position - surfacePos);
//ambient
vec3 ambient = light.ambientCoefficient * surfaceColor.rgb * light.intensities;
//diffuse
float diffuseCoefficient = max(0.0, dot(normal, surfaceToLight));
vec3 diffuse = diffuseCoefficient * surfaceColor.rgb * light.intensities;
//attenuation
float distanceToLight = length(light.position - surfacePos);
float attenuation = 1.0 / (1.0 + light.attenuation * pow(distanceToLight, 2));
//linear color (color before gamma correction)
vec3 linearColor = ambient + attenuation*(diffuse);
//final color (after gamma correction)
vec3 gamma = vec3(1.0/2.2);
finalColor = vec4(pow(linearColor, gamma), surfaceColor.a);
}
else {
finalColor = surfaceColor;
}
}
Shader B:
#version 400
struct Light {
vec3 position;
vec3 intensities; //a.k.a the color of the light
float ambientCoefficient;
float attenuation;
};
uniform bool useLight;
uniform mat4 modelMatrix;
uniform bool useTex;
uniform sampler2D tex;
uniform Light light;
uniform vec4 diffuseColor;
in vec2 fragTexCoord;
in vec3 fragNormal;
in vec3 fragVert;
out vec4 finalColor;
void main() {
finalColor = vec4(0,0,0.7,1);
}