在我的第一个 opengl 'voxel' 项目中,我使用几何着色器从 gl_points 创建立方体,它工作得很好,但我相信它可以做得更好。在 alpha 颜色中,我传递有关应该渲染哪些面的信息(以跳过与其他立方体相邻的面),然后使用“参考”立方体定义创建可见面的顶点。每个点乘以 3 个矩阵。本能告诉我,也许整张脸都可以乘以它们而不是每个点,但是我的数学能力很差,所以请指教。
#version 330
layout (points) in;
layout (triangle_strip,max_vertices=24) out;
smooth out vec4 oColor;
in VertexData
{
vec4 colour;
//vec3 normal;
} vertexData[];
uniform mat4 cameraToClipMatrix;
uniform mat4 worldToCameraMatrix;
uniform mat4 modelToWorldMatrix;
const vec4 cubeVerts[8] = vec4[8](
vec4(-0.5 , -0.5, -0.5,1), //LB 0
vec4(-0.5, 0.5, -0.5,1), //L T 1
vec4(0.5, -0.5, -0.5,1), //R B 2
vec4( 0.5, 0.5, -0.5,1), //R T 3
//back face
vec4(-0.5, -0.5, 0.5,1), // LB 4
vec4(-0.5, 0.5, 0.5,1), // LT 5
vec4(0.5, -0.5, 0.5,1), // RB 6
vec4(0.5, 0.5, 0.5,1) // RT 7
);
const int cubeIndices[24] = int [24]
(
0,1,2,3, //front
7,6,3,2, //right
7,5,6,4, //back or whatever
4,0,6,2, //btm
1,0,5,4, //left
3,1,7,5
);
void main()
{
vec4 temp;
int a = int(vertexData[0].colour[3]);
//btm face
if (a>31)
{
for (int i=12;i<16; i++)
{
int v = cubeIndices[i];
temp = modelToWorldMatrix * (gl_in[0].gl_Position + cubeVerts[v]);
temp = worldToCameraMatrix * temp;
gl_Position = cameraToClipMatrix * temp;
//oColor = vertexData[0].colour;
//oColor[3]=1;
oColor=vec4(1,1,1,1);
EmitVertex();
}
a = a - 32;
EndPrimitive();
}
//top face
if (a >15 )
...
}
-------- 更新代码:-----
//one matrix to transform them all
mat4 mvp = cameraToClipMatrix * worldToCameraMatrix * modelToWorldMatrix;
//transform and store cube verts for future use
for (int i=0;i<8; i++)
{
transVerts[i]=mvp * (gl_in[0].gl_Position + cubeVerts[i]);
}
//btm face
if (a>31)
{
for (int i=12;i<16; i++)
{
int v = cubeIndices[i];
gl_Position = transVerts[v];
oColor = vertexData[0].colour*0.55;
//oColor = vertexData[0].colour;
EmitVertex();
}
a = a - 32;
EndPrimitive();
}