Hello! Help me with texture loading?

firefly431

Registered
Hello! This is my first post but I am having problems loading a NSImage to a OpenGL Texture. I found lots of source code online but none work (I use a TIFF). Here is my code for texture loading. (Code load NSImage =
Code:
                NSImage *texImg = [NSImage imageNamed:@"Wood.tif"];
		glGenTextures(1, &bgTex);
		[self makeTextureFromImage:texImg forTexture:&bgTex];
)
makeTextureFromImage:

Code:
-(void) makeTextureFromImage:(NSImage*)theImg forTexture:(GLuint*)texName {
	
    NSBitmapImageRep* bitmap = [NSBitmapImageRep alloc];
    int samplesPerPixel = 0;
    NSSize imgSize = [theImg size];
	
    [theImg lockFocus];
    [bitmap initWithFocusedViewRect:NSMakeRect(0.0, 0.0, imgSize.width, imgSize.height)];
    [theImg unlockFocus];
	
    // Set proper unpacking row length for bitmap.
    glPixelStorei(GL_UNPACK_ROW_LENGTH, [bitmap pixelsWide]);
	
    // Set byte aligned unpacking (needed for 3 byte per pixel bitmaps).
    glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
	
    // Generate a new texture name if one was not provided.
    if (*texName == 0)
        glGenTextures (1, texName);
    glBindTexture (GL_TEXTURE_RECTANGLE_EXT, *texName);
	
    // Non-mipmap filtering (redundant for texture_rectangle).
    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_MIN_FILTER,  GL_LINEAR);
    samplesPerPixel = [bitmap samplesPerPixel];
	
    // Nonplanar, RGB 24 bit bitmap, or RGBA 32 bit bitmap.
    if(![bitmap isPlanar] && (samplesPerPixel == 3 || samplesPerPixel == 4)) {
		
        glTexImage2D(GL_TEXTURE_RECTANGLE_EXT, 0,
					 samplesPerPixel == 4 ? GL_RGBA8 : GL_RGB8,
					 [bitmap pixelsWide],
					 [bitmap pixelsHigh],
					 0,
					 samplesPerPixel == 4 ? GL_RGBA : GL_RGB,
					 GL_UNSIGNED_BYTE,
					 [bitmap bitmapData]);
    } else {
        // Handle other bitmap formats.
    }
	
    // Clean up.
    [bitmap release];
}
 
Some suggestions/questions:

Set a breakpoint on the first line of code (the call to imageNamed: ) and step through the code in the debugger. Stepping through the code should help you pinpoint the problem.

Check the results of your calls to imageNamed: and initWithFocusedViewRect: to make sure they're not nil.

Have you added the file Wood.tif to your project? Is it part of the application bundle? If not, the call to imageNamed: will fail and the file won't load. Make sure Wood.tif is part of the target's Copy Bundle Resources build phase.

Have you drawn the image to a window? The method initWithFocusedViewRect: loads bitmap data from a rendered image. You may want to use NSBitmapImageRep's initWithData: method to load the bitmap data and use NSBitmapImageRep's TIFFRepresentation: method to get the image data into the NSData format that initWithData: needs.
 
Back
Top