3 This file is part of libmspgl
4 Copyright © 2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
9 #include <msp/core/error.h>
10 #include "texture2d.h"
17 Texture2D::Texture2D()
23 Uploads an image into the texture. Direct wrapper for glTexImage2D.
25 void Texture2D::image(int level, int ifmt, sizei wd, sizei ht, int border, GLenum fmt, GLenum type, void *data)
29 glTexImage2D(target, level, ifmt, wd, ht, border, fmt, type, data);
35 Uploads an image into the texture, with a simpler interface.
37 void Texture2D::image(int level, sizei wd, sizei ht, TextureFormat tfmt, void *data)
45 case LUMINANCE8: ifmt=GL_LUMINANCE; fmt=GL_LUMINANCE; type=GL_UNSIGNED_BYTE; break;
46 case LUMINANCE8_ALPHA8: ifmt=GL_LUMINANCE_ALPHA; fmt=GL_LUMINANCE_ALPHA; type=GL_UNSIGNED_BYTE; break;
47 case RGB8: ifmt=GL_RGB; fmt=GL_RGB; type=GL_UNSIGNED_BYTE; break;
48 case RGBA8: ifmt=GL_RGBA; fmt=GL_RGBA; type=GL_UNSIGNED_INT_8_8_8_8_REV; break;
49 case BGR8: ifmt=GL_RGB; fmt=GL_BGR; type=GL_UNSIGNED_BYTE; break;
50 case BGRA8: ifmt=GL_RGBA; fmt=GL_BGRA; type=GL_UNSIGNED_INT_8_8_8_8_REV; break;
51 default: throw InvalidParameterValue("Invalid texture format");
54 image(level, ifmt, wd, ht, 0, fmt, type, data);
58 Loads an image from a file and uploads it into the texture. Currently assumes
59 the file to be a PNG image.
61 void Texture2D::image(const string &fn)
63 FILE *file=fopen(fn.c_str(), "r");
64 if(!file) throw Exception("Couldn't open "+fn);
67 fread(sig, 8, 1, file);
68 if(png_sig_cmp((png_byte *)sig, 0, 8))
69 throw Exception("Not a PNG image");
71 png_struct *pngs=png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
72 png_info *pngi=png_create_info_struct(pngs);
74 if(setjmp(png_jmpbuf(pngs)))
76 png_destroy_read_struct(&pngs, &pngi, 0);
78 throw Exception("PNG error");
80 png_init_io(pngs, file);
81 png_set_sig_bytes(pngs, 8);
83 png_read_info(pngs, pngi);
85 unsigned wd=png_get_image_width(pngs, pngi);
86 unsigned ht=png_get_image_height(pngs, pngi);
87 unsigned depth=png_get_bit_depth(pngs, pngi);
88 unsigned ctype=png_get_color_type(pngs, pngi);
90 if(ctype==PNG_COLOR_TYPE_PALETTE || depth<8)
92 png_destroy_read_struct(&pngs, &pngi, 0);
94 throw Exception("Invalid color type or bit depth");
98 png_set_strip_16(pngs);
105 case PNG_COLOR_TYPE_GRAY: fmt=LUMINANCE8; planes=1; break;
106 case PNG_COLOR_TYPE_GRAY_ALPHA: fmt=LUMINANCE8_ALPHA8; planes=2; break;
107 case PNG_COLOR_TYPE_RGB: fmt=RGB8; planes=3; break;
108 case PNG_COLOR_TYPE_RGB_ALPHA: fmt=RGBA8; planes=4; break;
109 default: throw Exception("Invalid color type");
112 png_byte *data=new png_byte[wd*ht*planes];
113 png_byte *row_ptrs[ht];
114 for(unsigned i=0; i<ht; ++i)
115 row_ptrs[i]=data+(ht-1-i)*wd*planes;
117 png_read_image(pngs, row_ptrs);
119 image(0, wd, ht, fmt, data);
122 png_destroy_read_struct(&pngs, &pngi, 0);