opengl - 点精灵渲染问题

时间:2011-08-14 16:50:00

标签: opengl glsl opengl-3

我正在尝试渲染点精灵,但我得分。问题出在哪儿 ? (通过glUniform3f改变颜色)

顶点着色器:

private static String vertexShader =
"#version 330" + "\n" +
"layout (location = 0) in vec4 position;" + "\n" +
"uniform mat4 pMatrix;" + "\n" +
"uniform mat4 mMatrix;" + "\n" +
"void main()" + "\n" +
"{" + "\n" +
"gl_Position = pMatrix * mMatrix * position;" + "\n" +
"}";

片段着色器:

private static String fragmentShader =
"#version 330" + "\n" +
"out vec4 vFragColor;" + "\n" +
"uniform vec3 Color;" + "\n" +
"uniform vec3 lightDir;" + "\n" +
"void main()" + "\n" +
"{" + "\n" +
"vec3 N;" + "\n" +
"N.xy = gl_PointCoord* 2.0 - vec2(1.0);" + "\n" +    
"float mag = dot(N.xy, N.xy);" + "\n" +
"if (mag > 1.0) discard;" + "\n" +   
"N.z = sqrt(1.0-mag);" + "\n" +
"float diffuse = max(0.0, dot(lightDir, N));" + "\n" +
"vFragColor = vec4(Color,1) * diffuse;" + "\n" +
"}";

渲染:

gl.glUseProgram(shaderProgramID);
gl.glUniformMatrix4fv(projectionMatrixUniform, 1, false, projectionMatrix, 0);
gl.glUniformMatrix4fv(modelViewMatrixUniform, 1, false, modelViewMatrix, 0);
gl.glUniform3f(colorUniform, 1.0f, 0.0f, 0.0f);
gl.glUniform3f(lightDirUniform, 0.0f, 0.0f, 1.0f);
gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, vbo[0]);
gl.glEnableVertexAttribArray(0);
gl.glVertexAttribPointer(0, 4, GL3.GL_FLOAT, false, 0, 0);
gl.glDrawArrays(GL3.GL_POINTS, 0, n_particles);
gl.glDisableVertexAttribArray(0);
gl.glUseProgram(0);

1 个答案:

答案 0 :(得分:0)

为什么不简单地使用几何着色器进行操作? 您只需将变换后的顶点位置传递给几何着色器,然后让几何着色器在该点周围输出四个顶点即可完成。 它更加灵活和稳定。

示例:

顶点着色器:

void main()
{
  gl_TexCoord[0] = gl_MultiTexCoord0;

  // Output vertex position
  gl_Position = gl_ModelViewMatrix * gl_Vertex;
}

几何着色器:

#extension GL_EXT_geometry_shader4 : enable

uniform float particle_size;

void main()
{
    float halfsize = particle_size * 0.5;

    gl_TexCoord[0] = gl_TexCoordIn[0][0];
    gl_FrontColor = gl_FrontColorIn[0];

     // Vertex 4
    gl_TexCoord[0].st = vec2(1.0,1.0);
    gl_Position = gl_PositionIn[0];
    gl_Position = gl_ProjectionMatrix  * gl_Position;
    gl_Position.xy += vec2(halfsize, halfsize);
    EmitVertex();

    // Vertex 3
    gl_TexCoord[0].st = vec2(1.0,-1.0);
    gl_Position = gl_PositionIn[0];
    gl_Position = gl_ProjectionMatrix  * gl_Position;
    gl_Position.xy += vec2(halfsize, -halfsize);
    EmitVertex();

    // Vertex 2
    gl_TexCoord[0].st = vec2(-1.0,1.0);
    gl_Position = gl_PositionIn[0];
    gl_Position = gl_ProjectionMatrix  * gl_Position;
    gl_Position.xy += vec2(-halfsize, halfsize);
    EmitVertex();

    // Vertex 1
    gl_TexCoord[0].st = vec2(-1.0,-1.0);
    gl_Position = gl_PositionIn[0];
    gl_Position = gl_ProjectionMatrix  * gl_Position;
    gl_Position.xy += vec2(-halfsize, -halfsize);
    EmitVertex();



    EndPrimitive();
}