我使用GLSL 4.0编写一个细分例程,通过几何着色器划分对象上的三角形。我没有使用重心坐标,而是使用矢量算法输出三角形顶点。我设法让细分工作,但我不明白如何插入顶点法线以产生正确的阴影:
#version 400
layout(triangles) in;
layout(triangle_strip, max_vertices = 93) out; //MAX 128
uniform mat4 mvMatrix;
uniform mat4 pMatrix;
uniform mat3 normalMatrix; //mv matrix without translation
uniform int subdivision_level;
uniform vec4 lightPosition_camSpace; //light Position in camera space
uniform int time;
in data
{
vec4 position_camSpace;
vec3 normal_camSpace;
vec2 textureCoordinate;
vec4 color;
}vertexIn[3];
out fragmentData
{
vec4 position_camSpace;
vec3 normal_camSpace;
vec2 textureCoordinate;
vec4 color;
} frag;
void emit_triangle(vec4 position, vec4 width, vec4 hyp, float s) {
/* NORMALS NOT FIXED */
//A
gl_Position = position;
frag.color = vertexIn[0].color;
frag.position_camSpace = vertexIn[0].position_camSpace;
frag.normal_camSpace = vertexIn[0].normal_camSpace;
frag.textureCoordinate = vertexIn[0].textureCoordinate;
EmitVertex();
//B
gl_Position = position + width;
frag.color = vertexIn[1].color;
frag.position_camSpace = vertexIn[1].position_camSpace;
frag.normal_camSpace = vertexIn[1].normal_camSpace;
frag.textureCoordinate = vertexIn[1].textureCoordinate;
EmitVertex();
//C
gl_Position = position + hyp;
frag.color = vertexIn[2].color;
frag.position_camSpace = vertexIn[2].position_camSpace;
frag.normal_camSpace = vertexIn[2].normal_camSpace;
frag.textureCoordinate = vertexIn[2].textureCoordinate;
EmitVertex();
EndPrimitive();
}
void main() {
// A gl_In[0].gl_Position;
// B gl_In[1].gl_Position;
// C gl_In[2].gl_Position;
float s = 1/pow(2,subdivision_level);
int triangles_render = int(1/s);
vec4 hyp_off = vec4(0.0,0.0,0.0,0.0);
vec4 width_off = vec4(0.0,0.0,0.0,0.0);
vec4 position = gl_in[0].gl_Position;
vec4 width = s*(gl_in[1].gl_Position - gl_in[0].gl_Position);
vec4 hyp = s*(gl_in[2].gl_Position - gl_in[0].gl_Position);
vec4 hyp_off_f = vec4(0.0,0.0,0.0,0.0);
vec4 width_off_f = width;
for (int i=0; i<=subdivision_level+1; i++) {
for (int j=0; j<triangles_render-i; j++) {
// Normal triangle
emit_triangle(position + hyp_off + width_off, width, hyp,s);
width_off += width;
// Flipped triangle
if (j <triangles_render-i-1)
{
emit_triangle(position + width_off_f + hyp_off_f, hyp, hyp - width,s);
width_off_f += width;
}
}
hyp_off += hyp;
width_off = vec4(0.0,0.0,0.0,0.0);
hyp_off_f += hyp;
width_off_f = width;
}
}
目前结果看起来像平面着色,因为我只使用顶点着色器顶点的法线。如何计算正确的法线以使阴影看起来正确?我也需要修改顶点位置吗?我对这一部分不确定。我读过了 Why does my OpenGL Phong shader behave like a flat shader?但他们使用重心坐标来解决问题。