]> git.tdb.fi Git - libs/gl.git/blob - source/texture2d.cpp
Support embedding textures in datafiles
[libs/gl.git] / source / texture2d.cpp
1 /* $Id$
2
3 This file is part of libmspgl
4 Copyright © 2007  Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include "except.h"
9 #include "ilwrap.h"
10 #include "texture2d.h"
11
12 using namespace std;
13
14 namespace Msp {
15 namespace GL {
16
17 Texture2D::Texture2D():
18         width(0),
19         height(0)
20 {
21         target=GL_TEXTURE_2D;
22         bind();
23 }
24
25 void Texture2D::storage(PixelFormat fmt, sizei wd, sizei ht, int brd)
26 {
27         if(width>0)
28                 throw InvalidState("Texture storage may only be specified once");
29         if(wd==0 || ht==0)
30                 throw InvalidParameterValue("Invalid texture dimensions");
31
32         ifmt=fmt;
33         width=wd;
34         height=ht;
35         border=brd;
36 }
37
38 void Texture2D::image(int level, PixelFormat fmt, GLenum type, const void *data)
39 {
40         if(width==0)
41                 throw InvalidState("Texture storage has not been specified");
42
43         maybe_bind();
44
45         glTexImage2D(target, level, ifmt, width, height, border, fmt, type, data);
46 }
47
48 void Texture2D::sub_image(int level, int x, int y, sizei wd, sizei ht, PixelFormat fmt, GLenum type, const void *data)
49 {
50         if(width==0)
51                 throw InvalidState("Texture storage has not been specified");
52
53         maybe_bind();
54
55         glTexSubImage2D(target, level, x, y, wd, ht, fmt, type, data);
56 }
57
58 void Texture2D::load_image(const string &fn)
59 {
60         Image img;
61         img.load_file(fn);
62
63         image(img);
64 }
65
66 void Texture2D::image(const Image &img)
67 {
68         unsigned w=img.get_width();
69         unsigned h=img.get_height();
70         PixelFormat fmt=img.get_format();
71         if(width==0)
72                 storage(fmt, w, h, 0);
73         else if(w!=width || h!=height)
74                 throw IncompatibleData("Image does not match texture storage");
75
76         image(0, fmt, GL_UNSIGNED_BYTE, img.get_data());
77 }
78
79
80 Texture2D::Loader::Loader(Texture2D &t):
81         Texture::Loader(t)
82 {
83         add("image_data", &Loader::image_data);
84 }
85
86 void Texture2D::Loader::image_data(const string &data)
87 {
88         Image img;
89         img.load_lump(data.data(), data.size());
90
91         static_cast<Texture2D &>(tex).image(img);
92 }
93
94 } // namespace GL
95 } // namespace Msp