OpenGL学习17——混合

2021-07-05  本文已影响0人  蓬篙人

混合(Blending)

1. 丢弃片元

glTexImage2D(GL_TEXTURE_2D, 0, FL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
void main()
{
    FragColor = texture(texture1, TexCoords);
}

下面我们使用深度测试的例子,添加一些青草纹理来展示混合的效果。

std::vector<glm::vec3> vegation;
vegation.push_back(glm::vec3(-1.5f, 0.0f, -0.48f))
vegation.push_back(glm::vec3( 1.5f, 0.0f,  0.51f))
vegation.push_back(glm::vec3( 0.0f, 0.0f,  0.7f));
vegation.push_back(glm::vec3(-0.3f, 0.0f, -2.3f));
vegation.push_back(glm::vec3( 0.5f, 0.0f, -0.6f));
// grass
glBindVertexArray(grassVAO);
glBindTexture(GL_TEXTURE_2D, grassTexture);
model = glm::mat4(1.0f);
for (int i = 0; i < vegation.size(); i++)
{
    model = glm::mat4(1.0f);
    model = glm::translate(model, vegation[i]);
    shader.setMat4("model", model);
    glDrawArrays(GL_TRIANGLES, 0, 6);
}
void main()
{   
    //FragColor = texture(texture1, TexCoords);
    vec4 texColor = texture(texture1, TexCoords);
    if(texColor.a < 0.1)
        discard;
    FragColor = texColor;
}

2. 混合

glEnable(GL_BLEND);
glBlendFunc(GLenum sfactor, GLenum dfactor);
选项
GL_ZERO 影响因子为0
GL_ONE 影响因子为1
GL_SRC_COLOR 影响因子等于源颜色矢量\overline{\color{green}{C}}_{source}
GL_ONE_MINUS_SRC_COLOR 影响因子等于1减去源颜色矢量1-\overline{\color{green}{C}}_{source}
GL_DST_COLOR 影响因子等于目标颜色矢量\overline{\color{red}{C}}_{destination}
GL_ONE_MINUS_DST_COLOR 影响因子等于1减去目标颜色矢量1-\overline{\color{red}{C}}_{destination}
GL_SRC_ALPHA 影响因子等于源颜色矢量\overline{\color{green}{C}}_{source}的alpha分量值
GL_ONE_MINUS_SRC_ALPHA 影响因子等于1减去源颜色矢量\overline{\color{green}{C}}_{source}的alpha分量值
GL_DST_ALPHA 影响因子等于目标颜色矢量\overline{\color{red}{C}}_{destination}的alpha分量值
GL_ONE_MINUS_DST_ALPHA 影响因子等于1减去目标颜色矢量\overline{\color{red}{C}}_{destination}的alpha分量值
GL_CONSTANT_COLOR 影响因子等于常量颜色矢量\overline{\color{blue}{C}}_{constant}
GL_ONE_MINUS_CONSTANT_COLOR 影响因子等于1减去常量颜色矢量\overline{\color{blue}{C}}_{constant}
GL_CONSTANT_ALPHA 影响因子等于常量颜色矢量\overline{\color{blue}{C}}_{constant}的alpha分量
GL_ONE_MINUS_CONSTANT_ALPHA 影响因子等于1减去常量颜色矢量\overline{\color{blue}{C}}_{constant}的alpha分量
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
glBlendEquation(GLenum mode);

3. 渲染半透明纹理

glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
void main()
{   
    FragColor = texture(texture1, TexCoords);
}
std::map<float, glm::vec3> sorted;
for (unsigned int i = 0; i < vegation.size(); i++)
{
    float distance = glm::length(camera.Position - vegation[i]);
    sorted[distance] = vegation[i];
}
for (std::map<float, glm::vec3>::reverse_iterator it = sorted.rbegin(); it != sorted.rend(); ++it)
{
    model = glm::mat4(1.0f);
    model = glm::translate(model, it->second);
    shader.setMat4("model", model);
    glDrawArrays(GL_TRIANGLES, 0, 6);
}
上一篇下一篇

猜你喜欢

热点阅读