【问题标题】:opengl es 2.0 - optimizing fragment shaderopengl es 2.0 - 优化片段着色器
【发布时间】:2013-10-10 14:21:34
【问题描述】:

我正在为 Android/iOS 开发游戏,需要优化渲染。 游戏使用户能够变形地形,所以我使用地形的灰度图像(地形中的值 1 表示实心地面,0 表示无地面)并在其上应用片段着色器(还有背景图像)。这适用于 60 fps 常数,但问题是我还需要在地形边缘渲染边框。因此,我在变形时模糊了边缘,在片段着色器中,我根据地形密度/透明度(边界是 1x64 纹理)绘制边界。

问题是,在渲染边框时,我需要进行动态纹理读取,这会将帧速率降至 20。有什么办法可以优化吗?如果我用统一的浮点数组替换边框纹理会有所帮助还是与从 2d 纹理读取相同?

着色器代码:

 varying mediump vec2 frag_background_texcoord;
 varying mediump vec2 frag_density_texcoord;
 varying mediump vec2 frag_terrain_texcoord;

 uniform sampler2D density_texture;
 uniform sampler2D terrain_texture;
 uniform sampler2D mix_texture;
 uniform sampler2D background_texture;

 void main()
 {
    lowp vec4 background_color = texture2D(background_texture, frag_background_texcoord);
    lowp vec4 terrain_color = texture2D(terrain_texture, frag_terrain_texcoord);

    highp float density = texture2D(density_texture, frag_density_texcoord).a;

    if(density > 0.5)
    {
         lowp vec4 mix_color = texture2D(mix_texture, vec2(density, 1.0)); <- dynamic texture read (FPS drops to 20), would replacing this with a uniform float array help (would also need to calculate the index in the array)?
         gl_FragColor = mix(terrain_color, mix_color, mix_color.a);
    } else
    {
         gl_FragColor =  background_color;
    }
 }

【问题讨论】:

  • 你是否尝试过移动纹理读取?这样它可能会被gpu优化。
  • 是的,它甚至更慢:/
  • 我不确定您通过将密度设置为 highp 来实现什么。 sampler2D 默认为lowp,因此将查找结果存储在highp 变量中不会获得任何精度;您只是在浪费 GPU 周期将其转换为 highp,然后为纹理坐标创建高精度 vec2
  • 事实上,highp 甚至不需要在片段着色器中工作,除非预处理器宏:GL_FRAGMENT_PRECISION_HIGH 被实现设置为1。您应该在尝试在片段着色器中使用 highp 之前检查此值。
  • 感谢您的提示,但最大的性能提升是删除分支,请参阅我的回答。

标签: opengl-es-2.0 glsl


【解决方案1】:

想通了。我修复它的方法是删除所有分支。现在运行〜60fps。 优化后的代码:

varying mediump vec2 frag_background_texcoord;
varying mediump vec2 frag_density_texcoord;
varying mediump vec2 frag_terrain_texcoord;

uniform sampler2D density_texture;   
uniform sampler2D terrain_texture;
uniform sampler2D mix_texture;
uniform sampler2D background_texture;

void main()
{
   lowp vec4 background_color = texture2D(background_texture, frag_background_texcoord);
   lowp vec4 terrain_color = texture2D(terrain_texture, frag_terrain_texcoord);

   lowp vec4 mix_color = texture2D(mix_texture, vec2(density, 0.0));
   lowp float density = texture2D(density_texture, frag_density_texcoord).a;

   gl_FragColor = mix(mix(bg_color, terrain_color, mix_color.r), mix_color, mix_color.a);       
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    相关资源
    最近更新 更多