glsl将计算片段着色器绑定到立方体面

时间:2014-12-15 19:47:02

标签: opengl-es glsl

我有一个立方体,我想将计算的片段着色器绑定到立方体面。有什么帮助吗?

我的顶点着色器是:

precision highp float;
attribute vec3 position;
attribute vec3 normal;
uniform mat3 normalMatrix;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
varying vec3 fNormal;
varying vec3 fPosition;

void main()
{
  fNormal = normalize(normalMatrix * normal);
  vec4 pos = modelViewMatrix * vec4(position, 1.0);
  fPosition = pos.xyz;
  gl_Position = projectionMatrix * pos;
}

和我的片段着色器:

precision highp float;
uniform float time;
uniform vec2 resolution;
varying vec3 fPosition;
varying vec3 fNormal;

void main()
{
  float minDimension = min(resolution.x, resolution.y);
    vec2 bounds = vec2(resolution.x / minDimension, resolution.y / minDimension);
    vec2 uv = gl_FragCoord.xy / minDimension;
    vec2 midUV = vec2(bounds.x * 0.5, bounds.y * 0.5);
    uv.xy-=midUV;

    float dist = sqrt(dot(uv, uv));
    float t = smoothstep(0.2+0.1*cos(time), 0.1-0.01, dist);
    vec4 disc_color=vec4(1.0,0.,0.,1.);
    vec4 bkg_color=vec4(0.0, 0.0, 0.0, 1.0);

    vec4 resultColor;
    resultColor = mix(bkg_color, disc_color, t);   
     gl_FragColor = resultColor;
}

我在孔图像上得到一个带点的立方体。

但我想要的是每张脸都有点。

您可以直接在http://shdr.bkcore.com/

下测试代码

2 个答案:

答案 0 :(得分:0)

在OpenGL中执行此操作的标准方法是首先将内容呈现给FBO(帧缓冲区对象)。这允许您渲染到纹理。然后,您可以在渲染立方体时将此纹理用于其中一个边。

以下不是完整的代码,只是一个给出起点的大纲:

// create a texture, and bind it
GLuint texId = 0;
glGenTextures(1, &texId);
glBindTexture(GL_TEXTURE_2D, texId);

// set texture parameters (filters, wrap mode, etc)
glTexParameteri(GL_TEXTURE_2D, ...);

// allocate texture data (no data provided)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_FLOAT, 0);
glBindTexture(GL_TEXTURE_2D, texId);

// create and set up FBO with texture as attachment
GLuint fboId = 0;
glGenFramebuffers(1, &fboId);
glBindFramebuffer(GL_FRAMEBUFFER, fboId);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texId, 0);

// create a depth renderbuffer and attach it if depth testing is needed

// start rendering
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
glDraw...(...);

// back to default framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, windowWidth, windowHeight);
glClear(GL_COLOR_BUFFER_BIT);

// render cube using texture we rendered to
glBindTexture(GL_TEXTURE_2D, texId);
// rest of state setup and rendering

答案 1 :(得分:0)

对于答案来说,这是正确的,但我找到了一种更好的方式,然后渲染到纹理。我传递了纹理坐标并使用它们代替片段着色器中的glfragcoord。