OpenGLES 3 iOS对象显示为三角形而未填充

时间:2017-04-02 20:37:05

标签: ios iphone opengl-es

我正在尝试使用OpenGLES在iOS中显示香蕉。我很确定我已经正确设置了所有设置,但是当应用程序启动时,香蕉没有正确绘制。它显示如下:

我试图显示的香蕉对象来自obj2opengl提供的样本banana.h。

App running on iPhone 5 simulator

以下是设置:

    - (void)setupGL {
    [EAGLContext setCurrentContext:self.context];

    [self loadShaders];

    glEnable(GL_BLEND);

    self.effect = [[GLKBaseEffect alloc] init];
    self.effect.light0.enabled = GL_TRUE;
    self.effect.light0.diffuseColor = GLKVector4Make(1.0f, 0.4f, 0.4f, 1.0f);

    glGenVertexArrays(1, &_vertexArray);
    glBindVertexArray(_vertexArray);

    glGenBuffers(1, &_vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(bananaVerts), bananaVerts, GL_STATIC_DRAW);

    glGenBuffers(1, &_textureCoords);
    glBindBuffer(GL_ARRAY_BUFFER, _textureCoords);
    glBufferData(GL_ARRAY_BUFFER, sizeof(bananaTexCoords), bananaTexCoords, GL_STATIC_DRAW);

    //Vertex attribute
    glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 0,0);
    glEnableVertexAttribArray(GLKVertexAttribPosition);
    // Normal attribute
    /*glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 0,0);
    glEnableVertexAttribArray(GLKVertexAttribNormal);*/
    // TexCoord attribute
    glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(GLKVertexAttribTexCoord0);

    [self loadTexture];

    glBindVertexArray(0);
}

这是绘图方法:

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    glClearColor(0.65f, 0.65f, 0.65f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    [self calculateMatrices];

    glUseProgram(_program);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, _texture.name);
    glUniform1i(glGetUniformLocation(_program, "texture1"), 0);

    glUniformMatrix4fv(glGetUniformLocation(_program, "viewMatrix"), 1, GL_FALSE, _modelViewMatrix.m);
    glUniformMatrix4fv(glGetUniformLocation(_program, "projectionMatrix"), 1, GL_FALSE, _projectionMatrix.m);

    glBindVertexArray(_vertexArray);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, bananaNumVerts);
}

顶点着色器:

attribute vec3 position;
attribute vec2 texCoord;

uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;

varying vec2 TexCoord;
varying vec3 vNormal;

void main()
{
    gl_Position = viewMatrix * projectionMatrix * vec4(position, 1.0);
    TexCoord = vec2(texCoord.x, 1.0 - texCoord.y);
}

Fragment Shader:

precision mediump float;

varying vec2 TexCoord;

uniform sampler2D texture1;

void main()
{
    gl_FragColor = texture2D(texture1, TexCoord);
}

编辑:

我通过将绘图命令更改为

来解决问题
GL_LINES 

而不是

GL_TRIANGLES.

1 个答案:

答案 0 :(得分:0)

您对glVertexAttribPointer的使用看起来不对。

在调用glBindBuffer(GL_ARRAY_BUFFER, ...)引用它之前,您需要调用相关缓冲区的glVertexAttribPointer。目前,您正在为位置和纹理坐标引用_textureCoords缓冲区。