简体   繁体   English

OpenGL ES2颜色和纹理着色器

[英]OpenGL ES2 color and texture shader

I want to write one vertex shader to work with colors and textures I used this code 我想编写一个顶点着色器来处理颜色和纹理,我使用了这段代码

precision mediump float;
varying vec4 v_Color;
uniform sampler2D u_TextureUnit;
varying vec2 v_TextureCoordinates;

void main() {
    gl_FragColor= (v_Color*texture2D(u_TextureUnit, v_TextureCoordinates));
}

it works when the model has a texture map but if the model has only color it loads black, I want to check the sampler2D u_TextureUnit before putting gl_FragColor 当模型具有纹理贴图时可以使用,但是如果模型只有颜色则加载黑色,我想在放置u_TextureUnit之前检查sampler2D gl_FragColor

You have written a shader that reads from a texture unit; 您已经编写了一个从纹理单元读取的着色器。 you should generally avoid conditionality in shaders as it potentially splits the execution path. 通常应避免在着色器中使用条件,因为它可能会分割执行路径。 Usually a compiler can figure it out if the thing you're acting conditionally upon is a uniform but you may end up paying for a recompile every time you set the uniform. 通常,如果您要有条件地执行的操作是统一的,则编译器可以弄清楚,但是每次设置统一后,您可能最终都要为重新编译付费。 ES 2 has no means of introspecting the current properties of a sampling unit so the prima facie solution might be something like: ES 2无法自检采样单元的当前属性,因此表面上的解决方案可能类似于:

uniform bool u_ApplyTexture;
...
if(u_ApplyTexture)
    gl_FragColor = {what you already have};
else
    gl_FragColor = v_Color;

A non-conditional alternative possibly to profile as an alternative might be: 可以将概要文件作为替代方案的无条件替代方案可能是:

uniform float u_TextureWeight;
...
gl_FragColor = v_Color*
                   mix(vec4(1.0), 
                       texture2D(u_TextureUnit, v_TextureCoordinates), 
                       u_TextureWeight);

As that would evaluate to v_Color*vec4(1.0) when u_TextureWeight is 0.0 and v_Color*texture2D(u_TextureUnit, v_TextureCoordinates) when u_TextureWeight is 1.0 . 作为将评估为v_Color*vec4(1.0)u_TextureWeight0.0v_Color*texture2D(u_TextureUnit, v_TextureCoordinates)u_TextureWeight1.0

If you were really looking to be hacky, you might just upload your textures as negative images and negative them again in the shader: 如果您真的想变黑,则可以将纹理作为负图像上传,然后在着色器中再次负它们:

gl_FragColor = v_Color*(vec4(1.0) - texture2D(u_TextureUnit, v_TextureCoordinates));

As then obviously if you're getting vec4(0.0) from the sampling unit because no texture is attached, that ends up multiplying v_Color by 1.0 . 显然,如果您由于没有附着纹理而从采样单元获取vec4(0.0) ,则最终v_Color乘以1.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM