可可 OpenGL 纹理创建

3

我正在使用Cocoa开发我的第一个OpenGL应用程序(我之前在iPhone上使用过OpenGL ES),但是我在从图像文件中加载纹理时遇到了一些问题。以下是我的纹理加载代码:

@interface MyOpenGLView : NSOpenGLView 
{
GLenum texFormat[ 1 ];   // Format of texture (GL_RGB, GL_RGBA)
NSSize texSize[ 1 ];     // Width and height

GLuint textures[1];     // Storage for one texture
}

- (BOOL) loadBitmap:(NSString *)filename intoIndex:(int)texIndex
{
BOOL success = FALSE;
NSBitmapImageRep *theImage;
int bitsPPixel, bytesPRow;
unsigned char *theImageData;

NSData* imgData = [NSData dataWithContentsOfFile:filename options:NSUncachedRead error:nil];

theImage = [NSBitmapImageRep imageRepWithData:imgData]; 

if( theImage != nil )
{
    bitsPPixel = [theImage bitsPerPixel];
    bytesPRow = [theImage bytesPerRow];
    if( bitsPPixel == 24 )        // No alpha channel
        texFormat[texIndex] = GL_RGB;
    else if( bitsPPixel == 32 )   // There is an alpha channel
        texFormat[texIndex] = GL_RGBA;
    texSize[texIndex].width = [theImage pixelsWide];
    texSize[texIndex].height = [theImage pixelsHigh];

    if( theImageData != NULL )
    {
        NSLog(@"Good so far...");
        success = TRUE;

        // Create the texture

        glGenTextures(1, &textures[texIndex]);

        NSLog(@"tex: %i", textures[texIndex]);

        NSLog(@"%i", glIsTexture(textures[texIndex]));

        glPixelStorei(GL_UNPACK_ROW_LENGTH, [theImage pixelsWide]);

        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

        // Typical texture generation using data from the bitmap
        glBindTexture(GL_TEXTURE_2D, textures[texIndex]);

        NSLog(@"%i", glIsTexture(textures[texIndex]));

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texSize[texIndex].width, texSize[texIndex].height, 0, texFormat[texIndex], GL_UNSIGNED_BYTE, [theImage bitmapData]);

        NSLog(@"%i", glIsTexture(textures[texIndex]));
    }
}


return success;
}

看起来 glGenTextures() 函数实际上并没有创建纹理,因为 textures[0] 的值仍为 0。此外,记录 glIsTexture(textures[texIndex]) 总是返回 false。
有什么建议吗?
谢谢, Kyle
2个回答

1
glGenTextures(1, &textures[texIndex] );

你的纹理定义是什么?

glIsTexture只有在纹理已经准备好时才返回true。由glGenTextures返回的名称,但尚未通过调用glBindTexture与纹理相关联的名称不是纹理的名称。

检查是否在glBegin和glEnd之间意外执行了glGenTextures--这是唯一的官方失败原因。

另外:

检查纹理是否为正方形,并且具有2的幂次方维度。

尽管iPhone的OpenGL ES实现没有足够强调这一点。


它被定义为GLuint textures[1](我更新了我的帖子以包括头文件定义)。在调用glBindTexture()之后,我还检查了glIsTexture(),它仍然返回false。它也没有在glBegin()glEnd()之间调用,它是在计时器启动之前的初始化方法中调用的。该纹理是一个256x256的PNG文件。 - Kyle
这实际上是错误的。glIsTexture将对任何绑定的纹理名称返回true。它不必是“准备就绪”的(在OpenGL术语中称为complete)。此外,我很惊讶iPhone纹理必须是正方形的。2的幂次方,没错...但是正方形?我非常确定GL ES规范要求使用32x16纹理。 - Bahbar
这个页面说的就是我说的。它需要使用glBindTexture进行调用(即之前已经绑定)。与准备无关。那么正方形呢? - Bahbar

0

好的,我搞定了。原来是因为我在设置上下文之前尝试加载纹理。一旦我把加载纹理放在初始化方法的最后,它就正常工作了。

感谢你们的回答。

Kyle


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接