textpsys

diff src/image.cc @ 0:a4ffd9e6984c

initial commit
author John Tsiombikas <nuclear@member.fsf.org>
date Wed, 19 Aug 2015 09:13:48 +0300
parents
children
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/image.cc	Wed Aug 19 09:13:48 2015 +0300
     1.3 @@ -0,0 +1,89 @@
     1.4 +#include <string.h>
     1.5 +#include <math.h>
     1.6 +#include "opengl.h"
     1.7 +#include "image.h"
     1.8 +
     1.9 +static unsigned int next_pow2(unsigned int x);
    1.10 +
    1.11 +Image::Image()
    1.12 +{
    1.13 +	width = height = 0;
    1.14 +	tex_width = tex_height = 0;
    1.15 +	pixels = 0;
    1.16 +	texture = 0;
    1.17 +	own_pixels = 0;
    1.18 +}
    1.19 +
    1.20 +Image::~Image()
    1.21 +{
    1.22 +	destroy();
    1.23 +}
    1.24 +
    1.25 +void Image::create(int xsz, int ysz, unsigned char *pix)
    1.26 +{
    1.27 +	destroy();
    1.28 +
    1.29 +	pixels = own_pixels = new unsigned char[xsz * ysz * 3];
    1.30 +	if(pix) {
    1.31 +		memcpy(pixels, pix, xsz * ysz * 3);
    1.32 +	} else {
    1.33 +		memset(pixels, 0, xsz * ysz * 3);
    1.34 +	}
    1.35 +	width = xsz;
    1.36 +	height = ysz;
    1.37 +}
    1.38 +
    1.39 +void Image::destroy()
    1.40 +{
    1.41 +	if(texture) {
    1.42 +		glDeleteTextures(1, &texture);
    1.43 +		texture = 0;
    1.44 +	}
    1.45 +
    1.46 +	delete [] own_pixels;
    1.47 +	own_pixels = pixels = 0;
    1.48 +
    1.49 +	width = height = tex_width = tex_height = 0;
    1.50 +}
    1.51 +
    1.52 +unsigned int Image::gen_texture()
    1.53 +{
    1.54 +	if(!pixels || !width || !height) {
    1.55 +		return 0;
    1.56 +	}
    1.57 +
    1.58 +	if(!texture) {
    1.59 +		glGenTextures(1, &texture);
    1.60 +		glBindTexture(GL_TEXTURE_2D, texture);
    1.61 +		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    1.62 +		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    1.63 +		glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
    1.64 +	} else {
    1.65 +		glBindTexture(GL_TEXTURE_2D, texture);
    1.66 +	}
    1.67 +
    1.68 +	tex_width = next_pow2(width);
    1.69 +	tex_height = next_pow2(height);
    1.70 +
    1.71 +	if(tex_width == width && tex_height == height) {
    1.72 +		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tex_width, tex_height, 0,
    1.73 +				GL_RGB, GL_UNSIGNED_BYTE, pixels);
    1.74 +	} else {
    1.75 +		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tex_width, tex_height, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
    1.76 +		glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height,
    1.77 +				GL_RGB, GL_UNSIGNED_BYTE, pixels);
    1.78 +	}
    1.79 +
    1.80 +	return texture;
    1.81 +}
    1.82 +
    1.83 +static unsigned int next_pow2(unsigned int x)
    1.84 +{
    1.85 +	--x;
    1.86 +	x |= x >> 1;
    1.87 +	x |= x >> 2;
    1.88 +	x |= x >> 4;
    1.89 +	x |= x >> 8;
    1.90 +	x |= x >> 16;
    1.91 +	return x + 1;
    1.92 +}