OpenGL学习——Shader(补)

Posted yiqian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了OpenGL学习——Shader(补)相关的知识,希望对你有一定的参考价值。

完成章节后练习。

练习

1. Adjust the vertex shader so that the triangle is upside down.

#version 330 core
layout (location = 0) in vec3 Pos;
layout (location = 1) in vec3 Col;
out vec4 Color;
void main()
{
    gl_Position = vec4(Pos.x, -Pos.y, Pos.z, 1.0f);
    Color = vec4(Col, 1.0f);
}

2. Specify a horizontal offset via a uniform and move the triangle to the right side of the screen in the vertex shader using this offset value.

#version 330 core
layout (location = 0) in vec3 Pos;
layout (location = 1) in vec3 Col;
uniform float offset;
out vec4 Color;
void main()
{
    gl_Position = vec4(Pos.x + offset, Pos.y, Pos.z, 1.0f);
    Color = vec4(Col, 1.0f);
}
ourShader.use();
float offset = 0.5;
int uniformlocation = glGetUniformLocation(ourShader.ID, "offset");
glUniform1f(uniformlocation, offset);

3. Output the vertex position to the fragment shader using the out keyword and set the fragment‘s color equal to this vertex position (see how even the vertex position values are interpolated across the triangle). Once you managed to do this; try to answer the following question: why is the bottom-left side of our triangle black?

#version 330 core
layout (location = 0) in vec3 Pos;
layout (location = 1) in vec3 Col;
out vec3 fragPos;
void main()
{
    gl_Position = vec4(Pos.x, Pos.y, Pos.z, 1.0f);
    fragPos = Pos;
}
#version 330 core
out vec4 FragColor;
in vec3 fragPos;
void main()
{
    FragColor = vec4(fragPos, 1.0f);
}

技术图片
左上角顶点坐标(-0.5, 0.5, 0),右下角顶点坐标(0.5, -0.5, 0),在顶点间二分之一处插值得到的结果是(0, 0, 0),因此渲染成黑色。

以上是关于OpenGL学习——Shader(补)的主要内容,如果未能解决你的问题,请参考以下文章

初识OpenGL 片段着色器(Fragment Shader)

Visual Studio 2012 和 2010 中基于 Opengl Sierpinski Shader 的 C 代码

我的OpenGL学习进阶之旅解决着色器语法错误:The shader uses varying u_Color, but previous shader does not write to it

我的OpenGL学习进阶之旅解决着色器语法错误:The shader uses varying u_Color, but previous shader does not write to it

我的OpenGL学习进阶之旅解决着色器语法错误:The shader uses varying u_Color, but previous shader does not write to it

我的OpenGL学习进阶之旅 C++ 长行字符串多行书写的方法以及如何书写正确的OpenGL Shader着色器代码