File: TextureManager.cpp

package info (click to toggle)
sear 0.5.0-5
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 3,408 kB
  • ctags: 2,580
  • sloc: cpp: 14,902; sh: 10,890; makefile: 172
file content (792 lines) | stat: -rw-r--r-- 28,206 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
// This file may be redistributed and modified only under the terms of
// the GNU General Public License (See COPYING for details).
// Copyright (C) 2001 - 2004 Simon Goodall, University of Southampton

// $Id: TextureManager.cpp,v 1.31 2004/07/14 10:10:31 simon Exp $

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "TextureManager.h"

#include <sage/GL.h>
#include <sage/GLU.h>

#include "common/Log.h"
#include "common/Utility.h"

#include "src/System.h"
#include "src/Console.h"

#include "src/FileHandler.h"

#include <unistd.h>

#ifdef WINDOWS
    
int ilogb(double x)
{
    return static_cast<int>(_logb(x));
}
    
#endif

// Default texture maps
#include "default_image.xpm"
#include "default_font.h"


#ifdef USE_MMGR
#include "common/mmgr.h"
  
#endif

#include "Sprite.h"
#include "ImageUtils.h"

#ifdef DEBUG
static const bool debug = true;
#else
static const bool debug = false;
#endif
namespace Sear {

// Config section name
static const std::string SECTION_texture_manager = "texture_manager";
static const std::string SECTION_render = "render";

// config keys
static const std::string KEY_filename = "filename";
static const std::string KEY_path = "path";
static const std::string KEY_clamp = "clamp";
static const std::string KEY_clamp_s = "clamp_s";
static const std::string KEY_clamp_t = "clamp_t";
static const std::string KEY_mipmap = "mipmap";
static const std::string KEY_type = "type";
static const std::string KEY_priority = "priority";
static const std::string KEY_mask = "mask";
static const std::string KEY_min_filter = "min_filter";
static const std::string KEY_mag_filter = "mag_filter";
static const std::string KEY_internal_format = "internal_format";
static const std::string KEY_base_texture_level = "base_texture_level";

// config defaults
static const bool DEFAULT_clamp = false;
static const bool DEFAULT_clamp_s = DEFAULT_clamp;
static const bool DEFAULT_clamp_t = DEFAULT_clamp;
static const bool DEFAULT_mipmap = true;
static const bool DEFAULT_mask = false;
static const unsigned int DEFAULT_min_filter = GL_LINEAR;
static const unsigned int DEFAULT_mag_filter = GL_LINEAR;
//static const unsigned int DEFAULT_mag_filter = GL_NEAREST;

// Filter strings
static const std::string FILTER_NEAREST = "nearest";
static const std::string FILTER_LINEAR = "linear";
static const std::string FILTER_NEAREST_MIPMAP_NEAREST = "nearest_mipmap_nearest";
static const std::string FILTER_NEAREST_MIPMAP_LINEAR = "nearest_mipmap_linear";
static const std::string FILTER_LINEAR_MIPMAP_NEAREST = "linear_mipmap_nearest";
static const std::string FILTER_LINEAR_MIPMAP_LINEAR = "linear_mipmap_linear";

static const std::string CMD_LOAD_TEXTURE_CONFIG = "load_textures";
static const std::string CMD_LOAD_SPRITE_CONFIG = "load_sprites";
static const std::string CMD_SET_TEXTURE_BASE_LEVEL = "set_texture_detail";

// Format strings
static const std::string ALPHA = "alpha";
static const std::string ALPHA4 = "alpha4";
static const std::string ALPHA8 = "alpha8";
static const std::string ALPHA12 = "alpha12";
static const std::string ALPHA16 = "alpha16";

static const std::string LUMINANCE = "luminance";
static const std::string LUMINANCE4 = "luminance4";
static const std::string LUMINANCE8 = "luminance8";
static const std::string LUMINANCE12 = "luminance12";
static const std::string LUMINANCE16 = "luminance16";

static const std::string LUMINANCE_ALPHA = "luminance_alpha";
static const std::string LUMINANCE4_ALPHA4 = "luminance4_alpha4";
static const std::string LUMINANCE6_ALPHA2 = "luminance6_alpha2";
static const std::string LUMINANCE8_ALPHA8 = "luminance8_alpha8";
static const std::string LUMINANCE12_ALPHA4 = "luminance12_alpha4";
static const std::string LUMINANCE12_ALPHA12 = "luminance12_alpha12";
static const std::string LUMINANCE16_ALPHA16 = "luminance16_alpha16";
  
static const std::string INTENSITY = "intensity";
static const std::string INTENSITY4 = "intensity4";
static const std::string INTENSITY8 = "intensity8";
static const std::string INTENSITY12 = "intensity12";
static const std::string INTENSITY16 = "intensity16";

static const std::string RGB = "rgb";
static const std::string R3_G3_B2 = "r3_g3_b2";
static const std::string RGB4 = "rgb4";
static const std::string RGB5 = "rgb5";
static const std::string RGB8 = "rgb8";
static const std::string RGB10 = "rgb10";
static const std::string RGB12 = "rgb12";
static const std::string RGB16 = "rgb16";
static const std::string RGBA = "rgba";
static const std::string RGBA2 = "rgba2";
static const std::string RGBA4 = "rgba4";
static const std::string RGB5_A1 = "rgb5_a1";
static const std::string RGBA8 = "rgba8";
static const std::string RGB10_A2 = "rgb10_a2";
static const std::string RGBA12 = "rgba12";
static const std::string RGBA16 = "rgba16";

// OpenGL Extension flags
bool use_arb_multitexture = false;
bool use_sgis_generate_mipmap = false;
bool use_arb_texture_border_clamp = false;
bool use_ext_texture_filter_anisotropic = false;

TextureManager::TextureManager() :
  m_initialised(false),
  m_initGL(false),
  m_texture_units(1),
  m_baseMipmapLevel(0)
{  
    varconf::Config& cfg(System::instance()->getGeneral());
    cfg.sigsv.connect(SigC::slot(*this, &TextureManager::generalConfigChanged));
}

void TextureManager::init()
{
  if (m_initialised) shutdown();
  if (debug) std::cout << "Initialising TextureManager" << std::endl;

  m_textures.resize(1); // we need to leave texture ID zero free
  m_names.resize(1); // ditto

  m_texture_map.clear();
  
  m_initialised = true;
}

void TextureManager::initGL()
{
  assert((m_initialised == true) && "TextureManager not initialised");
  assert(m_initGL == false);
  
  // Determine available OpenGL extensions
  setupGLExtensions();
  
  // Initialise our current texture cache
  m_last_textures.resize(m_texture_units);
  for (unsigned int i = 0; i < m_last_textures.size(); m_last_textures[i++] = -1);
  // Setup default texture properties
  m_default_texture = createDefaultTexture();
  if (m_default_texture == -1) std::cerr << "Error building default texture" << std::endl;

  // create default font
  m_default_font = createDefaultFont();
  if (m_default_font == -1) std::cerr << "Error building default font" << std::endl;

  m_initGL = true;
}

void TextureManager::shutdown()
{
  if (!m_initialised) return;
  if (debug) std::cout << "TextureManager: Shutdown" << std::endl;

  // Unload all textures
  for (unsigned int i = 1; i < m_textures.size(); ++i) {
    unloadTexture(m_textures[i]);
  }

  m_last_textures.clear();
  m_initialised = false;
}

void TextureManager::readTextureConfig(const std::string &filename) {
  assert((m_initialised == true) && "TextureManager not initialised");
  
  m_texture_config.readFromFile(filename);
}

GLuint TextureManager::loadTexture(const std::string &texture_name) {
  assert((m_initialised == true) && "TextureManager not initialised");
  std::cout << "Loading Texture: " << texture_name << std::endl;
  std::string clean_name = std::string(texture_name);
  
  bool mask = false;
//  std::cout << clean_name << " - " << clean_name.substr(0,5) << " - " << clean_name.substr(5) <<  std::endl;
  if (clean_name.substr(0, 5) == "mask_") {
    mask = true;
    clean_name = clean_name.substr(5);
  }
 
  m_texture_config.clean(clean_name);
  // Check texture is defined
  if (!m_texture_config.find(clean_name)) {
    std::cerr << "Texture " << texture_name << " not defined." << std::endl;
    return 0;
  }
 
  if (!m_texture_config.findItem(clean_name, KEY_filename)) {
    std::cerr << "Texture " << clean_name << " has no filename" << std::endl;
    return 0;
  }

  std::string filename = (std::string)m_texture_config.getItem(clean_name, KEY_filename);
  // Get path to prefix to filename 
  if (m_texture_config.findItem(clean_name, KEY_path)) {
    std::string path = (std::string)m_texture_config.getItem(clean_name, KEY_path);
    filename = path + "/" + filename;
  }
  
  System::instance()->getFileHandler()->expandString(filename);
  SDL_Surface* image = loadImageFromPath(filename);
  if (!image) return 0;
  
  GLuint texture_id = loadTexture(clean_name, image, mask);
  SDL_FreeSurface(image);
  return texture_id;
}

GLuint TextureManager::loadTexture(const std::string &name, SDL_Surface *surface, bool mask)
{
  assert((m_initialised == true) && "TextureManager not initialised");
  // Copy name so we can change it
  std::string texture_name(name);
  m_texture_config.clean(texture_name);
  // If we have requested a mask, filter pixels
/*  bool mask = (bool)m_texture_config.getItem(texture_name, KEY_mask);
  mask = false;
*/  if (mask) {
    // Set all pixels to white. We let the alpha channel do the clipping
    // TODO perhaps define a transparent pixel or threshold to do this
    if (surface->format->BytesPerPixel == 4) {
      for (int i = 0; i < surface->w * surface->h * 4; i += 4) {
        ((unsigned char *)surface->pixels)[i + 0] = (unsigned char)0xff;
        ((unsigned char *)surface->pixels)[i + 1] = (unsigned char)0xff;
        ((unsigned char *)surface->pixels)[i + 2] = (unsigned char)0xff;
      }
    } else {
      for (int i = 0; i < surface->w * surface->h * 3; i += 3) {
        ((unsigned char *)surface->pixels)[i + 0] = (unsigned char)0xff;
        ((unsigned char *)surface->pixels)[i + 1] = (unsigned char)0xff;
        ((unsigned char *)surface->pixels)[i + 2] = (unsigned char)0xff;
      }
    }
  }
// */ 
  // Create open gl texture
  GLuint texture_id;
  glGenTextures(1, &texture_id);
  glBindTexture(GL_TEXTURE_2D, texture_id);
  
  // build image - use mip mapping if requested
  bool mipmap = true;
  if (m_texture_config.findItem(texture_name, KEY_mipmap)) {
    mipmap = (bool)m_texture_config.getItem(texture_name, KEY_mipmap);
  }

  // Set texture filters
  int minFilter = GL_LINEAR;
  if (m_texture_config.findItem(texture_name, KEY_min_filter)) {
    minFilter = getFilter((std::string)m_texture_config.getItem(texture_name, KEY_min_filter));
  } else if (mipmap) {
    minFilter = GL_LINEAR_MIPMAP_LINEAR; // trilinear
  }
  
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);

  if (m_texture_config.findItem(texture_name, KEY_mag_filter)) {
    int filter = getFilter((std::string) m_texture_config.getItem(texture_name, KEY_mag_filter));
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter);
  } else {
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, DEFAULT_mag_filter);
  }

// Set clamp or repeat
  bool clamp = DEFAULT_clamp;
  bool clamp_s = DEFAULT_clamp_s;
  bool clamp_t = DEFAULT_clamp_t;
  if (m_texture_config.findItem(texture_name, KEY_clamp)) {
    clamp_s = clamp_t = clamp = (bool)m_texture_config.getItem(texture_name, KEY_clamp);
  }
  if (m_texture_config.findItem(texture_name, KEY_clamp_s)) {
    clamp_s = (bool)m_texture_config.getItem(texture_name, KEY_clamp_s);
  }
  if (m_texture_config.findItem(texture_name, KEY_clamp_t)) {

    clamp_t = (bool)m_texture_config.getItem(texture_name, KEY_clamp_t);
  }

  if (clamp_s) {
    if (use_arb_texture_border_clamp) {
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    } else {
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    }
  } else {
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  }

  if (clamp_t) {
    if (use_arb_texture_border_clamp) {
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);    
    } else {
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    }
  } else {
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  }
  // Check to see if anisotropic filtering is available
  if (use_ext_texture_filter_anisotropic) {
    GLfloat largest_supported_anisotropy;
    glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &largest_supported_anisotropy);
    glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, &largest_supported_anisotropy);
  }


  // Taken from Apogee
  int format, fmt;
  int bpp = surface->format->BitsPerPixel;
                                                                                
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
    if (surface->format->Rshift > surface->format->Bshift) {
#else // SDL_BYTEORDER == SDL_LIL_ENDIAN
    if (surface->format->Rshift < surface->format->Bshift) {
#endif // SDL_BYTEORDER == SDL_LIL_ENDIAN
        format = (bpp == 24) ? GL_BGR_EXT : GL_BGRA_EXT;
    } else {
        format = (bpp == 24) ? GL_RGB : GL_RGBA;
    }
    
    if (bpp == 8) format = GL_ALPHA;
    
    if (m_texture_config.findItem(texture_name, KEY_internal_format)) {
      fmt = getFormat((std::string)m_texture_config.getItem(texture_name, KEY_internal_format));
    } else {
        switch (bpp) {
        case 32:    fmt = GL_RGB5_A1; break;
        case 24:    fmt = GL_RGB5; break;
        case 8:     fmt = GL_ALPHA; break; // GL_LUMINANCE?
        default:
            std::cerr << "unsupported image depth" << std::endl;
            fmt = GL_RGB5_A1; break; // Set default
        }
    }
  
  if (mipmap) {
    if (m_baseMipmapLevel == 0)
        glTexImage2D(GL_TEXTURE_2D, 0, fmt, surface->w, surface->h, 0, format, GL_UNSIGNED_BYTE, surface->pixels);
    
    SDL_Surface* mip = surface;
    int max = ilogb(std::max(surface->w, surface->h));
    
    /* mipmap generation loop. This is pretty straight forward, one 
    complication is we need to free previous mipmaps, but not free the
    original surface (level 0), becuase that will be freed by the caller. */
    for (int level = 1; level <= max; ++level) {
        SDL_Surface* newMip = mipmapSurface(mip);
        if (!newMip) {
            std::cerr << "failed to created mipmap at level " << (level + 1) << std::endl;
            break;
        }
        
        if (mip != surface) SDL_FreeSurface(mip);
        mip = newMip;
        
        if (level >= m_baseMipmapLevel) {
            /* the -m_baseMipmapLevel term here is because ATI drivers seem
            to break if level zero isn't defined. So we shift all the mipmaps
            down if baseMipmapLevel > 0 */
            glTexImage2D(GL_TEXTURE_2D, level - m_baseMipmapLevel, fmt, mip->w, mip->h, 0, format, GL_UNSIGNED_BYTE, mip->pixels);
            GLenum er;
            if ((er = glGetError()) != 0) {
                std::cerr << "Texture \"" << texture_name
                          << "\" failed to load with error: "
                          << gluErrorString(er)
                          << std::endl << std::flush;
            }

        }
    } // of mipmap generation loop
    
    // don't leak the final mipmap
    if (mip != surface) SDL_FreeSurface(mip);
  } else {
    glTexImage2D(GL_TEXTURE_2D, 0, fmt, surface->w, surface->h, 0, format, GL_UNSIGNED_BYTE, surface->pixels);
  }

  // Set texture priority if requested
  if (m_texture_config.findItem(texture_name, KEY_priority)) {
    float priority = (double)m_texture_config.getItem(texture_name, KEY_priority);
    glPrioritizeTextures(1, &texture_id, &priority);
  }
  
  return texture_id;
}


void TextureManager::unloadTexture(const std::string &texture_name)
{
  assert((m_initialised == true) && "TextureManager not initialised");
  unsigned int texture_id = m_texture_map[texture_name];
  unloadTexture(m_textures[texture_id]);
  m_textures[texture_id] = 0;
  m_texture_map[texture_name] = 0;
}

void TextureManager::unloadTexture(GLuint texture_id) {
  assert((m_initialised == true) && "TextureManager not initialised");
  if (glIsTexture(texture_id)) glDeleteTextures(1, &texture_id);
}

void TextureManager::switchTexture(TextureID texture_id) {
  assert((m_initialised == true) && "TextureManager not initialised");
  if (texture_id == m_last_textures[0]) return;
  GLuint to = m_textures[texture_id];
  if (to == 0) {
    m_texture_config.clean(m_names[texture_id]);
    to = loadTexture(m_names[texture_id]);
    if (to == 0) {
      std::cerr << "Cannot find " << m_names[texture_id] << " ID " << texture_id <<  std::endl;
      to = m_textures[m_default_texture];
    }
    m_textures[texture_id] = to;
  }
  glBindTexture(GL_TEXTURE_2D, to);
  m_last_textures[0] = texture_id;  
}

void TextureManager::switchTexture(unsigned int texture_unit, TextureID texture_id) {
  assert((m_initialised == true) && "TextureManager not initialised");
  if (texture_id == m_last_textures[texture_unit]) return;
//  if (texture_id == -1) texture_id = m_default_texture;
  if (!use_arb_multitexture) return switchTexture(texture_id);
  if ((int)texture_unit >= m_texture_units) return; // Check we have enough texture units
  GLuint to = (texture_id == -1) ? (m_textures[m_default_texture]) : (m_textures[texture_id]);
  if (to == 0) {
    to = loadTexture(m_names[texture_id]);
    if (to == 0) {
      std::cerr << "Cannot find " << m_names[texture_id] << std::endl;
      to = m_textures[m_default_texture];
    }
    m_textures[texture_id] = to;
  }
  glActiveTextureARB(GL_TEXTURE0_ARB + texture_unit);
  glBindTexture(GL_TEXTURE_2D, to);
  m_last_textures[texture_unit] = to;
  // Make sure we are at texture unit 0
  glActiveTextureARB(GL_TEXTURE0_ARB);
}

void TextureManager::generalConfigChanged(const std::string &section, const std::string &key, varconf::Config &config)
{
    assert((m_initialised == true) && "TextureManager not initialised");

    if (section != "graphics") return;
    
    if (key == KEY_base_texture_level) {
        m_baseMipmapLevel = config.getItem(section, key);
        std::cout << "set base mipmap level to " << m_baseMipmapLevel << std::endl;
        
        // restart stuff as necessary
        if (m_initGL)
            invalidate();
    }
}


int TextureManager::getFilter(const std::string &filter_name) {
  int filter = -1;
  if (filter_name == FILTER_NEAREST) filter = GL_NEAREST;
  else if (filter_name == FILTER_LINEAR) filter = GL_LINEAR;
  else if (filter_name == FILTER_NEAREST_MIPMAP_NEAREST) filter = GL_NEAREST_MIPMAP_NEAREST;
  else if (filter_name == FILTER_NEAREST_MIPMAP_LINEAR) filter = GL_NEAREST_MIPMAP_LINEAR;
  else if (filter_name == FILTER_LINEAR_MIPMAP_NEAREST) filter = GL_LINEAR_MIPMAP_NEAREST;
  else if (filter_name == FILTER_LINEAR_MIPMAP_LINEAR) filter = GL_LINEAR_MIPMAP_LINEAR;
  assert (filter != -1);
  return filter;
}

void TextureManager::setupGLExtensions()
{
  assert((m_initialised == true) && "TextureManager not initialised");
  
  // Get number of texture units
  // We write to a tempory as m_texture_units is a uint
  GLint tex_units;
  glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &tex_units);
  m_texture_units = tex_units;
  
  if (debug) std::cout << m_texture_units << " texture units" << std::endl;
  
  use_arb_multitexture = sage_ext[GL_ARB_MULTITEXTURE];
  if (debug && use_arb_multitexture) std::cout << "Using arb_multitexture" << std::endl;
  
  use_sgis_generate_mipmap = sage_ext[GL_SGIS_GENERATE_MIPMAP];
  if (debug && use_sgis_generate_mipmap) std::cout << "Using GL_SGIS_GENERATE_MIPMAP" << std::endl;
  
  use_ext_texture_filter_anisotropic = sage_ext[GL_EXT_TEXTURE_FILTER_ANISOTROPIC];
  use_arb_texture_border_clamp = true;//sage_ext[GL_ARB_TEXTURE_BORDER_CLAMP];

}

void TextureManager::setScale(float scale_x, float scale_y) {
  assert((m_initialised == true) && "TextureManager not initialised");
  glMatrixMode(GL_TEXTURE);
  glLoadIdentity();
  glScalef(scale_x, scale_y, 1.0f);
  glMatrixMode(GL_MODELVIEW);
}

void TextureManager::setScale(unsigned int texture_unit, float scale_x, float scale_y) {
  assert((m_initialised == true) && "TextureManager not initialised");
  glActiveTextureARB(GL_TEXTURE0_ARB + texture_unit);
  glMatrixMode(GL_TEXTURE);
  glLoadIdentity();
  glScalef(scale_x, scale_y, 1.0f);
  glMatrixMode(GL_MODELVIEW);
  glActiveTextureARB(GL_TEXTURE0_ARB);
}

TextureID TextureManager::createDefaultTexture() {
  assert((m_initialised == true) && "TextureManager not initialised");
  std::string texture_name = "default_texture";
  // Load texture into memory
  /*
  m_texture_config.setItem(texture_name, KEY_mask, false);
  m_texture_config.setItem(texture_name, KEY_min_filter, FILTER_LINEAR);
  m_texture_config.setItem(texture_name, KEY_mag_filter, FILTER_LINEAR);
  m_texture_config.setItem(texture_name, KEY_clamp, false);
  m_texture_config.setItem(texture_name, KEY_mipmap, false);
  
  SDL_Surface *surface = IMG_ReadXPMFromArray(default_image_xpm);
 
  if (!surface) {
    std::cerr << "Error loading default texture" << std::endl;
    return -1;
  }
  TextureObject texture = loadTexture(texture_name, surface);
  //  Free image
  SDL_FreeSurface(surface);
  */
  unsigned int width, height;
  GLuint texture;
  glGenTextures(1, &texture);
  unsigned char *data = xpm_to_image((const char**)default_image_xpm, width, height);

  glBindTexture(GL_TEXTURE_2D, texture);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
  delete []data;

  TextureID texId = requestTextureID(texture_name, false);
  m_textures[texId] = texture;
  return texId;
}

TextureID TextureManager::createDefaultFont() {
  assert((m_initialised == true) && "TextureManager not initialised");
  std::string texture_name = "default_font";
/*
  m_texture_config.setItem(texture_name, KEY_mask, false);
  m_texture_config.setItem(texture_name, KEY_min_filter, FILTER_LINEAR);
  m_texture_config.setItem(texture_name, KEY_mag_filter, FILTER_LINEAR);
  m_texture_config.setItem(texture_name, KEY_clamp, true);
  m_texture_config.setItem(texture_name, KEY_mipmap, false);
 
  // Load texture into memory
  SDL_Surface *surface = IMG_ReadXPMFromArray(default_font_xpm);
  if (!surface) {
    std::cerr << "Error loading default font" << std::endl;
    return -1;
  }
  TextureObject texture = loadTexture(texture_name, surface);
  // Free image
  SDL_FreeSurface(surface);

*/

  GLuint texture;
#if 0

  unsigned int width, height;

  unsigned char *data = xpm_to_image((const char**)default_font_xpm, width, height);
  glGenTextures(1, &texture);

  glBindTexture(GL_TEXTURE_2D, texture);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
  GLfloat priority = 1.0f;
  glPrioritizeTextures(1, &texture, &priority);
  
  delete [] data;
#else
  glGenTextures(1, &texture);
  glBindTexture(GL_TEXTURE_2D, texture);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  glTexImage2D(GL_TEXTURE_2D, 0, texture_font_internalFormat,
               texture_font_width, texture_font_height, 0,
               texture_font_format, GL_UNSIGNED_BYTE, texture_font_pixels);
  if (glGetError() != 0) {
      std::cerr << "Failed to load font texture" << std::endl << std::flush;
  }
  GLfloat priority = 1.0f;
  glPrioritizeTextures(1, &texture, &priority);

#endif

  TextureID texId = requestTextureID(texture_name, false);
  m_textures[texId] = texture;
  return texId;
}


void TextureManager::registerCommands(Console *console) {
  assert((m_initialised == true) && "TextureManager not initialised");
  if (debug) std::cout << "Registering commands" << std::endl;
  console->registerCommand(CMD_LOAD_TEXTURE_CONFIG, this);
  console->registerCommand(CMD_LOAD_SPRITE_CONFIG, this);
  console->registerCommand(CMD_SET_TEXTURE_BASE_LEVEL, this);
}

void TextureManager::runCommand(const std::string &command, const std::string &arguments) {
  assert((m_initialised == true) && "TextureManager not initialised");
  if (command == CMD_LOAD_TEXTURE_CONFIG) {
    std::string a = arguments;
    System::instance()->getFileHandler()->expandString(a);
    readTextureConfig(a);
  }
  
  if (command == CMD_LOAD_SPRITE_CONFIG) {
    std::string a = arguments;
    System::instance()->getFileHandler()->expandString(a);
    std::cout << "reading sprite config at " << a << std::endl;
    m_spriteConfig.readFromFile(a);
  }
  
  if (command == CMD_SET_TEXTURE_BASE_LEVEL) {
    int level = strtol(arguments.c_str(), NULL, 0);
    if ((level < 0) || (level > 10)) {
        std::cerr << CMD_SET_TEXTURE_BASE_LEVEL << " specified bad level: " << level << std::endl;
        return;
    }
    
    varconf::Config& cfg(System::instance()->getGeneral());
    cfg.setItem("graphics", KEY_base_texture_level, level);
  }

}

void TextureManager::invalidate()
{
  assert((m_initialised == true) && "TextureManager not initialised");
  assert(m_initGL);
  
  // TODO unload textures first.
  for (unsigned int i = 0; i < m_textures.size(); i++) {
    // Unload texture if its still valid
    if (glIsTexture(m_textures[i])) {
      glDeleteTextures(1, &m_textures[i]);
    }
    m_textures[i] = 0;
  }

  for (SpriteInstanceMap::iterator S=m_sprites.begin(); S != m_sprites.end(); ++S) {
    S->second->invalidate();
  }

  // Determine available OpenGL extensions
  setupGLExtensions();
  
  // Initialise our current texture cache
  for (unsigned int i = 0; i < m_last_textures.size(); m_last_textures[i++] = -1);
  // Setup default texture properties
  m_default_texture = createDefaultTexture();
  if (m_default_texture == -1) std::cerr << "Error building default texture" << std::endl;

  // create default font
  m_default_font = createDefaultFont();
  if (m_default_font == -1) std::cerr << "Error building default font" << std::endl;
}

GLint TextureManager::getFormat(const std::string &fmt) {
  if (fmt == ALPHA) return GL_ALPHA;
  if (fmt == ALPHA4) return GL_ALPHA4;
  if (fmt == ALPHA8) return GL_ALPHA8;
  if (fmt == ALPHA12) return GL_ALPHA12;
  if (fmt == ALPHA16) return GL_ALPHA16;

  if (fmt == LUMINANCE) return GL_LUMINANCE;
  if (fmt == LUMINANCE4) return GL_LUMINANCE4;
  if (fmt == LUMINANCE8) return GL_LUMINANCE8;
  if (fmt == LUMINANCE12) return GL_LUMINANCE12;
  if (fmt == LUMINANCE16) return GL_LUMINANCE16;

  if (fmt == LUMINANCE_ALPHA) return GL_LUMINANCE_ALPHA;
  if (fmt == LUMINANCE4_ALPHA4) return GL_LUMINANCE4_ALPHA4;
  if (fmt == LUMINANCE6_ALPHA2) return GL_LUMINANCE6_ALPHA2;
  if (fmt == LUMINANCE8_ALPHA8) return GL_LUMINANCE8_ALPHA8;
  if (fmt == LUMINANCE12_ALPHA4) return GL_LUMINANCE12_ALPHA4;
  if (fmt == LUMINANCE12_ALPHA12) return GL_LUMINANCE12_ALPHA12;
  if (fmt == LUMINANCE16_ALPHA16) return GL_LUMINANCE16_ALPHA16;
  
  if (fmt == INTENSITY) return GL_INTENSITY;
  if (fmt == INTENSITY4) return GL_INTENSITY4;
  if (fmt == INTENSITY8) return GL_INTENSITY8;
  if (fmt == INTENSITY12) return GL_INTENSITY12;
  if (fmt == INTENSITY16) return GL_INTENSITY16;

  if (fmt == RGB) return GL_RGB;
  if (fmt == R3_G3_B2) return GL_R3_G3_B2;
  if (fmt == RGB4) return GL_RGB4;
  if (fmt == RGB5) return GL_RGB5;
  if (fmt == RGB8) return GL_RGB8;
  if (fmt == RGB10) return GL_RGB10;
  if (fmt == RGB12) return GL_RGB12;
  if (fmt == RGB16) return GL_RGB16;
  if (fmt == RGBA) return GL_RGBA;
  if (fmt == RGBA2) return GL_RGBA2;
  if (fmt == RGBA4) return GL_RGBA4;
  if (fmt == RGB5_A1) return GL_RGB5_A1;
  if (fmt == RGBA8) return GL_RGBA8;
  if (fmt == RGB10_A2) return GL_RGB10_A2;
  if (fmt == RGBA12) return GL_RGBA12;
  if (fmt == RGBA16) return GL_RGBA16;
  assert(0);
  return 0;
}

SpriteData* TextureManager::getSpriteData(const std::string& name)
{
    assert(m_initialised);
    assert(!name.empty());
    
    SpriteInstanceMap::iterator S = m_sprites.find(name);
    if (S == m_sprites.end())
    {
        SpriteData* sd = new SpriteData(name);
        S = m_sprites.insert(S, SpriteInstanceMap::value_type(name, sd));
    }
    
    return S->second;
}

void TextureManager::clearLastTexture(unsigned int index)
{
    m_last_textures[index] = -1;
}

} /* namespace Sear */