Reputation: 991
This question, where the OP was reporting a warning being issued when executing instruction gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);
got me thinking: what if I want to have a scene with two (let's assume: flat) shapes in it, one with a texture and one with a uniform color? In the fragment shader's main
, if I uncomment the second instruction and comment out the first, like so:
void main(void) {
//gl_FragColor = vColor;
gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
}
the warning is still being issued, but this time in regards to the instruction gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);
.
If I leave both uncommented, it still complains about the vertexColorAttribute because clearly it's being overridden.
So how can I have both? Am I to use two different fragment shaders? If so, how can it be done?
Upvotes: 0
Views: 757
Reputation: 8123
The proper way would be to have two separate shaders since you want to render either textured or colored.
At the cost of memory and execution time, you may always have color and texture attributes in your vertex data and use some kind of blending depending on your use case.
As you describe it you could use simple additive blending as most WebGL implementations bind a black pixel [0,0,0,255] texture as default when no texture is bound.
Thus having something like
void main(void) {
gl_FragColor = vColor + texture2D(uSampler, vTexCoord);
}
would render the color when no texture is bound and correctly render the bound texture when color is [0,0,0,0].
See wikipedia for an overview of various blend modes
As an even more expensive solution you could just use a uniform as flag to indicate what "method" you want to use and branch inside the shader accordingly. This still requires all vertex attributes to be available though, also branching is quite inefficient on some platforms.
void main(void) {
if (uMethod == 1)
gl_FragColor = vColor;
else if (uMethod == 2)
gl_FragColor = texture2D(uSampler, vTexCoord);
else
gl_FragColor = vColor + texture2D(uSampler, vTexCoord);
}
Upvotes: 1