[fpc-pascal] Loading PNG files as OpenGL textures

Ryan Joseph ryan at thealchemistguild.com
Mon Oct 12 07:02:56 CEST 2015


> On Oct 12, 2015, at 10:57 AM, Anthony Walter <sysrpl at gmail.com> wrote:
> 
> I tend to use OS core elements or well known open source libraries for a few reasons.
> 
> 1) less code compiled and small programs
> 2) superior performance
> 3) more features
> 
> Example: When loading hundreds of textures you bet the Apple Quartz graphics libs are faster and more reliable. Same goes to WIC on Windows and Cario on linux.
> 

So your advice would be to keep my Apple libraries I use on Mac and something else for Windows? What would be the equivalent libraries on Windows for CGImage and CGBitmapContext be?

Loading PNG’s into a bitmap seems like a pretty thing for single unit but I could do the native route also if it was easier. I just wanted to get started on cross platform basically and I’m looking for the easiest strategy.


Here’s an example function to load a texture on Mac (given a CGImageRef you load from CGImageCreateWithURL). Pretty easy using Apple frameworks and I assume those would have some FPC RTL equivalents.

function GenerateTextureFromImage (image: CGImageRef): GLuint;
var
	textureWidth, textureHeight: integer;
	textureName: GLuint;
	bounds: CGRect;
	bitmapData: pointer;
	colorSpace: CGColorSpaceRef;
	context: CGContextRef;
begin
	result := 0;
	
	// generate texture
	textureWidth := CGImageGetWidth(image);
	textureHeight := CGImageGetHeight(image);
	bounds := CGRectMake(0, 0, textureWidth, textureHeight);
	bitmapData := GetMem(textureHeight * (textureWidth * 4));
	
	if bitmapData <> nil then
		begin
			colorSpace := CGColorSpaceCreateDeviceRGB;
		  context := CGBitmapContextCreate(bitmapData, textureWidth, textureHeight, 8, 4 * textureWidth, colorSpace, kCGImageAlphaPremultipliedLast);

			if context <> nil then
				begin
					CGContextFlipVertically(context, bounds);
					CGContextClearRect(context, bounds);
					CGContextDrawImage(context, bounds, image);
					
					glGenTextures(1, @result);
					glBindTexture(GL_TEXTURE_2D, result);
					glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
					glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, textureWidth, textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, bitmapData);

					//writeln('generated texture ', result, ' (', textureWidth, 'x', textureHeight,')');
					CGContextRelease(context);
				end;

			FreeMemory(bitmapData);
			CFRelease(colorSpace);
		end;
end;


Regards,
	Ryan Joseph




More information about the fpc-pascal mailing list