2 Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3 For a list of contributors, see the accompanying CONTRIBUTORS file.
5 This file is part of GtkRadiant.
7 GtkRadiant is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 GtkRadiant is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GtkRadiant; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
24 #include "debugging/debugging.h"
27 #include "itextures.h"
29 #include "preferencesystem.h"
32 #include "texturelib.h"
33 #include "container/hashfunc.h"
34 #include "container/cache.h"
35 #include "generic/callback.h"
40 #include "preferences.h"
46 eTextures_NEAREST = 0,
47 eTextures_NEAREST_MIPMAP_NEAREST = 1,
48 eTextures_NEAREST_MIPMAP_LINEAR = 2,
50 eTextures_LINEAR_MIPMAP_NEAREST = 4,
51 eTextures_LINEAR_MIPMAP_LINEAR = 5,
52 eTextures_MAX_ANISOTROPY = 6,
55 enum TextureCompressionFormat
57 TEXTURECOMPRESSION_NONE = 0,
58 TEXTURECOMPRESSION_RGBA = 1,
59 TEXTURECOMPRESSION_RGBA_S3TC_DXT1 = 2,
60 TEXTURECOMPRESSION_RGBA_S3TC_DXT3 = 3,
61 TEXTURECOMPRESSION_RGBA_S3TC_DXT5 = 4,
64 struct texture_globals_t
67 // texture compression format
68 TextureCompressionFormat m_nTextureCompressionFormat;
72 bool bTextureCompressionSupported; // is texture compression supported by hardware?
73 GLint texture_components;
75 // temporary values that should be initialised only once at run-time
76 bool m_bOpenGLCompressionSupported;
77 bool m_bS3CompressionSupported;
79 texture_globals_t(GLint components) :
80 m_nTextureCompressionFormat(TEXTURECOMPRESSION_NONE),
82 bTextureCompressionSupported(false),
83 texture_components(components),
84 m_bOpenGLCompressionSupported(false),
85 m_bS3CompressionSupported(false)
90 texture_globals_t g_texture_globals(GL_RGBA);
92 void SetTexParameters(ETexturesMode mode)
94 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f);
98 case eTextures_NEAREST:
99 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
100 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
102 case eTextures_NEAREST_MIPMAP_NEAREST:
103 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST );
104 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
106 case eTextures_NEAREST_MIPMAP_LINEAR:
107 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR );
108 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
110 case eTextures_LINEAR:
111 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
112 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
114 case eTextures_LINEAR_MIPMAP_NEAREST:
115 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
116 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
118 case eTextures_LINEAR_MIPMAP_LINEAR:
119 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
120 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
122 case eTextures_MAX_ANISOTROPY:
123 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, QGL_maxTextureAnisotropy());
126 globalOutputStream() << "invalid texture mode\n";
130 ETexturesMode g_texture_mode = eTextures_LINEAR_MIPMAP_LINEAR;
135 byte g_gammatable[256];
136 void ResampleGamma(float fGamma)
141 for (i = 0; i < 256; i++)
145 for (i = 0; i < 256; i++)
147 inf = (int)(255 * pow ( static_cast<double>((i + 0.5) / 255.5) , static_cast<double>(fGamma) ) + 0.5);
152 g_gammatable[i] = inf;
157 inline const int& min_int(const int& left, const int& right)
159 return std::min(left, right);
162 int max_tex_size = 0;
163 const int max_texture_quality = 3;
164 LatchedInt g_Textures_textureQuality(3, "Texture Quality");
166 /// \brief This function does the actual processing of raw RGBA data into a GL texture.
167 /// It will also resample to power-of-two dimensions, generate the mipmaps and adjust gamma.
168 void LoadTextureRGBA(qtexture_t* q, unsigned char* pPixels, int nWidth, int nHeight)
170 static float fGamma = -1;
173 int nCount = nWidth * nHeight;
175 if (fGamma != g_texture_globals.fGamma)
177 fGamma = g_texture_globals.fGamma;
178 ResampleGamma(fGamma);
184 total[0] = total[1] = total[2] = 0.0f;
186 // resample texture gamma according to user settings
187 for (int i = 0; i < (nCount * 4); i += 4)
189 for (int j = 0; j < 3; j++)
191 total[j] += (pPixels + i)[j];
192 byte b = (pPixels + i)[j];
193 (pPixels + i)[j] = g_gammatable[b];
197 q->color[0] = total[0] / (nCount * 255);
198 q->color[1] = total[1] / (nCount * 255);
199 q->color[2] = total[2] / (nCount * 255);
201 glGenTextures (1, &q->texture_number);
203 glBindTexture( GL_TEXTURE_2D, q->texture_number );
205 SetTexParameters(g_texture_mode);
208 while(gl_width < nWidth)
212 while(gl_height < nHeight)
215 bool resampled = false;
216 if (!(gl_width == nWidth && gl_height == nHeight))
219 outpixels = (byte *)malloc(gl_width * gl_height * 4);
220 R_ResampleTexture(pPixels, nWidth, nHeight, outpixels, gl_width, gl_height, 4);
227 int quality_reduction = max_texture_quality - g_Textures_textureQuality.m_value;
228 int target_width = min_int(gl_width >> quality_reduction, max_tex_size);
229 int target_height = min_int(gl_height >> quality_reduction, max_tex_size);
231 while (gl_width > target_width || gl_height > target_height)
233 GL_MipReduce(outpixels, outpixels, gl_width, gl_height, target_width, target_height);
235 if (gl_width > target_width)
237 if (gl_height > target_height)
242 glTexImage2D(GL_TEXTURE_2D, mip++, g_texture_globals.texture_components, gl_width, gl_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, outpixels);
243 while (gl_width > 1 || gl_height > 1)
245 GL_MipReduce(outpixels, outpixels, gl_width, gl_height, 1, 1);
252 glTexImage2D(GL_TEXTURE_2D, mip++, g_texture_globals.texture_components, gl_width, gl_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, outpixels);
255 glBindTexture(GL_TEXTURE_2D, 0);
266 void Texture_InitPalette (byte *pal)
271 byte gammatable[256];
274 gamma = g_texture_globals.fGamma;
278 for (i=0 ; i<256 ; i++)
282 for (i=0 ; i<256 ; i++)
284 inf = (int)(255 * pow ( (i+0.5)/255.5 , gamma ) + 0.5);
293 for (i=0 ; i<256 ; i++)
295 r = gammatable[pal[0]];
296 g = gammatable[pal[1]];
297 b = gammatable[pal[2]];
300 //v = (r<<24) + (g<<16) + (b<<8) + 255;
303 //tex_palette[i] = v;
304 tex_palette[i*3+0] = r;
305 tex_palette[i*3+1] = g;
306 tex_palette[i*3+2] = b;
317 HashTable<CopiedString, CopiedString, HashStringNoCase, StringEqualNoCase> strings;
318 strings["Monkey"] = "bleh";
319 strings["MonkeY"] = "blah";
323 const TestHashtable g_testhashtable;
327 typedef std::pair<LoadImageCallback, CopiedString> TextureKey;
329 void qtexture_realise(qtexture_t& texture, const TextureKey& key)
331 texture.texture_number = 0;
332 if(!string_empty(key.second.c_str()))
334 Image* image = key.first.loadImage(key.second.c_str());
337 LoadTextureRGBA(&texture, image->getRGBAPixels(), image->getWidth(), image->getHeight());
338 texture.surfaceFlags = image->getSurfaceFlags();
339 texture.contentFlags = image->getContentFlags();
340 texture.value = image->getValue();
342 globalOutputStream() << "Loaded Texture: \"" << key.second.c_str() << "\"\n";
343 GlobalOpenGL_debugAssertNoErrors();
347 globalErrorStream() << "Texture load failed: \"" << key.second.c_str() << "\"\n";
352 void qtexture_unrealise(qtexture_t& texture)
354 if(GlobalOpenGL().contextValid && texture.texture_number != 0)
356 glDeleteTextures(1, &texture.texture_number);
357 GlobalOpenGL_debugAssertNoErrors();
361 class TextureKeyEqualNoCase
364 bool operator()(const TextureKey& key, const TextureKey& other) const
366 return key.first == other.first && string_equal_nocase(key.second.c_str(), other.second.c_str());
370 class TextureKeyHashNoCase
373 typedef hash_t hash_type;
374 hash_t operator()(const TextureKey& key) const
376 return hash_combine(string_hash_nocase(key.second.c_str()), pod_hash(key.first));
380 #define DEBUG_TEXTURES 0
382 class TexturesMap : public TexturesCache
384 class TextureConstructor
386 TexturesMap* m_cache;
388 explicit TextureConstructor(TexturesMap* cache)
392 qtexture_t* construct(const TextureKey& key)
394 qtexture_t* texture = new qtexture_t(key.first, key.second.c_str());
395 if(m_cache->realised())
397 qtexture_realise(*texture, key);
401 void destroy(qtexture_t* texture)
403 if(m_cache->realised())
405 qtexture_unrealise(*texture);
411 typedef HashedCache<TextureKey, qtexture_t, TextureKeyHashNoCase, TextureKeyEqualNoCase, TextureConstructor> qtextures_t;
412 qtextures_t m_qtextures;
413 TexturesCacheObserver* m_observer;
414 std::size_t m_unrealised;
417 TexturesMap() : m_qtextures(TextureConstructor(this)), m_observer(0), m_unrealised(1)
420 typedef qtextures_t::iterator iterator;
424 return m_qtextures.begin();
428 return m_qtextures.end();
431 LoadImageCallback defaultLoader() const
433 return LoadImageCallback(0, QERApp_LoadImage);
435 Image* loadImage(const char* name)
437 return defaultLoader().loadImage(name);
439 qtexture_t* capture(const char* name)
441 return capture(defaultLoader(), name);
443 qtexture_t* capture(const LoadImageCallback& loader, const char* name)
446 globalOutputStream() << "textures capture: " << makeQuoted(name) << '\n';
448 return m_qtextures.capture(TextureKey(loader, name)).get();
450 void release(qtexture_t* texture)
453 globalOutputStream() << "textures release: " << makeQuoted(texture->name) << '\n';
455 m_qtextures.release(TextureKey(texture->load, texture->name));
457 void attach(TexturesCacheObserver& observer)
459 ASSERT_MESSAGE(m_observer == 0, "TexturesMap::attach: cannot attach observer");
460 m_observer = &observer;
462 void detach(TexturesCacheObserver& observer)
464 ASSERT_MESSAGE(m_observer == &observer, "TexturesMap::detach: cannot detach observer");
469 if(--m_unrealised == 0)
471 g_texture_globals.bTextureCompressionSupported = false;
473 if(GlobalOpenGL().ARB_texture_compression())
475 g_texture_globals.bTextureCompressionSupported = true;
476 g_texture_globals.m_bOpenGLCompressionSupported = true;
479 if(GlobalOpenGL().EXT_texture_compression_s3tc())
481 g_texture_globals.bTextureCompressionSupported = true;
482 g_texture_globals.m_bS3CompressionSupported = true;
485 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size);
486 if(max_tex_size == 0)
491 for(qtextures_t::iterator i = m_qtextures.begin(); i != m_qtextures.end(); ++i)
493 if(!(*i).value.empty())
495 qtexture_realise(*(*i).value, (*i).key);
500 m_observer->realise();
506 if(++m_unrealised == 1)
510 m_observer->unrealise();
512 for(qtextures_t::iterator i = m_qtextures.begin(); i != m_qtextures.end(); ++i)
514 if(!(*i).value.empty())
516 qtexture_unrealise(*(*i).value);
523 return m_unrealised == 0;
527 TexturesMap* g_texturesmap;
529 TexturesCache& GetTexturesCache()
531 return *g_texturesmap;
535 void Textures_Realise()
537 SetTexParameters(g_texture_mode);
538 g_texturesmap->realise();
541 void Textures_Unrealise()
543 g_texturesmap->unrealise();
547 Callback g_texturesModeChangedNotify;
549 void Textures_setModeChangedNotify(const Callback& notify)
551 g_texturesModeChangedNotify = notify;
554 void Textures_ModeChanged()
556 if(g_texturesmap->realised())
558 SetTexParameters(g_texture_mode);
560 for(TexturesMap::iterator i = g_texturesmap->begin(); i != g_texturesmap->end(); ++i)
562 glBindTexture (GL_TEXTURE_2D, (*i).value->texture_number);
563 SetTexParameters(g_texture_mode);
566 glBindTexture( GL_TEXTURE_2D, 0 );
569 g_texturesModeChangedNotify();
572 void Textures_SetMode(ETexturesMode mode)
574 if(g_texture_mode != mode)
576 g_texture_mode = mode;
578 Textures_ModeChanged();
582 void Textures_setTextureComponents(GLint texture_components)
584 if(g_texture_globals.texture_components != texture_components)
586 Textures_Unrealise();
587 g_texture_globals.texture_components = texture_components;
592 void Textures_UpdateTextureCompressionFormat()
594 GLint texture_components = GL_RGBA;
596 if (g_texture_globals.bTextureCompressionSupported)
598 if(g_texture_globals.m_nTextureCompressionFormat != TEXTURECOMPRESSION_NONE
599 && g_texture_globals.m_nTextureCompressionFormat != TEXTURECOMPRESSION_RGBA
600 && !g_texture_globals.m_bS3CompressionSupported)
602 globalOutputStream() << "OpenGL extension GL_EXT_texture_compression_s3tc not supported by current graphics drivers\n";
603 g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_RGBA; // if this is not supported either, see below
605 if (g_texture_globals.m_nTextureCompressionFormat == TEXTURECOMPRESSION_RGBA && !g_texture_globals.m_bOpenGLCompressionSupported)
607 globalOutputStream() << "OpenGL extension GL_ARB_texture_compression not supported by current graphics drivers\n";
608 g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE;
611 switch (g_texture_globals.m_nTextureCompressionFormat)
613 case (TEXTURECOMPRESSION_NONE):
615 texture_components = GL_RGBA;
618 case (TEXTURECOMPRESSION_RGBA):
620 texture_components = GL_COMPRESSED_RGBA_ARB;
623 case (TEXTURECOMPRESSION_RGBA_S3TC_DXT1):
625 texture_components = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
628 case (TEXTURECOMPRESSION_RGBA_S3TC_DXT3):
630 texture_components = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
633 case (TEXTURECOMPRESSION_RGBA_S3TC_DXT5):
635 texture_components = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
642 texture_components = GL_RGBA;
643 g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE;
646 Textures_setTextureComponents(texture_components);
649 void TextureCompressionImport(TextureCompressionFormat& self, int value)
651 if(!g_texture_globals.m_bOpenGLCompressionSupported
652 && g_texture_globals.m_bS3CompressionSupported
660 self = TEXTURECOMPRESSION_NONE;
663 self = TEXTURECOMPRESSION_RGBA;
666 self = TEXTURECOMPRESSION_RGBA_S3TC_DXT1;
669 self = TEXTURECOMPRESSION_RGBA_S3TC_DXT3;
672 self = TEXTURECOMPRESSION_RGBA_S3TC_DXT5;
675 Textures_UpdateTextureCompressionFormat();
677 typedef ReferenceCaller1<TextureCompressionFormat, int, TextureCompressionImport> TextureCompressionImportCaller;
679 void TextureGammaImport(float& self, float value)
683 Textures_Unrealise();
688 typedef ReferenceCaller1<float, float, TextureGammaImport> TextureGammaImportCaller;
690 void TextureModeImport(ETexturesMode& self, int value)
695 Textures_SetMode(eTextures_NEAREST);
698 Textures_SetMode(eTextures_NEAREST_MIPMAP_NEAREST);
701 Textures_SetMode(eTextures_LINEAR);
704 Textures_SetMode(eTextures_NEAREST_MIPMAP_LINEAR);
707 Textures_SetMode(eTextures_LINEAR_MIPMAP_NEAREST);
710 Textures_SetMode(eTextures_LINEAR_MIPMAP_LINEAR);
713 Textures_SetMode(eTextures_MAX_ANISOTROPY);
716 typedef ReferenceCaller1<ETexturesMode, int, TextureModeImport> TextureModeImportCaller;
718 void TextureModeExport(ETexturesMode& self, const IntImportCallback& importer)
722 case eTextures_NEAREST:
725 case eTextures_NEAREST_MIPMAP_NEAREST:
728 case eTextures_LINEAR:
731 case eTextures_NEAREST_MIPMAP_LINEAR:
734 case eTextures_LINEAR_MIPMAP_NEAREST:
737 case eTextures_LINEAR_MIPMAP_LINEAR:
740 case eTextures_MAX_ANISOTROPY:
747 typedef ReferenceCaller1<ETexturesMode, const IntImportCallback&, TextureModeExport> TextureModeExportCaller;
749 void Textures_constructPreferences(PreferencesPage& page)
752 const char* percentages[] = { "12.5%", "25%", "50%", "100%", };
755 STRING_ARRAY_RANGE(percentages),
756 LatchedIntImportCaller(g_Textures_textureQuality),
757 IntExportCaller(g_Textures_textureQuality.m_latched)
765 FloatImportCallback(TextureGammaImportCaller(g_texture_globals.fGamma)),
766 FloatExportCallback(FloatExportCaller(g_texture_globals.fGamma))
769 const char* texture_mode[] = { "Nearest", "Nearest Mipmap", "Linear", "Bilinear", "Bilinear Mipmap", "Trilinear", "Anisotropy" };
771 "Texture Render Mode",
772 STRING_ARRAY_RANGE(texture_mode),
773 IntImportCallback(TextureModeImportCaller(g_texture_mode)),
774 IntExportCallback(TextureModeExportCaller(g_texture_mode))
778 const char* compression_none[] = { "None" };
779 const char* compression_opengl[] = { "None", "OpenGL ARB" };
780 const char* compression_s3tc[] = { "None", "S3TC DXT1", "S3TC DXT3", "S3TC DXT5" };
781 const char* compression_opengl_s3tc[] = { "None", "OpenGL ARB", "S3TC DXT1", "S3TC DXT3", "S3TC DXT5" };
782 StringArrayRange compression(
783 (g_texture_globals.m_bOpenGLCompressionSupported)
784 ? (g_texture_globals.m_bS3CompressionSupported)
785 ? STRING_ARRAY_RANGE(compression_opengl_s3tc)
786 : STRING_ARRAY_RANGE(compression_opengl)
787 : (g_texture_globals.m_bS3CompressionSupported)
788 ? STRING_ARRAY_RANGE(compression_s3tc)
789 : STRING_ARRAY_RANGE(compression_none)
792 "Hardware Texture Compression",
794 TextureCompressionImportCaller(g_texture_globals.m_nTextureCompressionFormat),
795 IntExportCaller(reinterpret_cast<int&>(g_texture_globals.m_nTextureCompressionFormat))
799 void Textures_constructPage(PreferenceGroup& group)
801 PreferencesPage page(group.createPage("Textures", "Texture Settings"));
802 Textures_constructPreferences(page);
804 void Textures_registerPreferencesPage()
806 PreferencesDialog_addDisplayPage(FreeCaller1<PreferenceGroup&, Textures_constructPage>());
809 void TextureCompression_importString(const char* string)
811 g_texture_globals.m_nTextureCompressionFormat = static_cast<TextureCompressionFormat>(atoi(string));
812 Textures_UpdateTextureCompressionFormat();
814 typedef FreeCaller1<const char*, TextureCompression_importString> TextureCompressionImportStringCaller;
817 void Textures_Construct()
819 g_texturesmap = new TexturesMap;
821 GlobalPreferenceSystem().registerPreference("TextureCompressionFormat", TextureCompressionImportStringCaller(), IntExportStringCaller(reinterpret_cast<int&>(g_texture_globals.m_nTextureCompressionFormat)));
822 GlobalPreferenceSystem().registerPreference("TextureFiltering", IntImportStringCaller(reinterpret_cast<int&>(g_texture_mode)), IntExportStringCaller(reinterpret_cast<int&>(g_texture_mode)));
823 GlobalPreferenceSystem().registerPreference("TextureQuality", IntImportStringCaller(g_Textures_textureQuality.m_latched), IntExportStringCaller(g_Textures_textureQuality.m_latched));
824 GlobalPreferenceSystem().registerPreference("SI_Gamma", FloatImportStringCaller(g_texture_globals.fGamma), FloatExportStringCaller(g_texture_globals.fGamma));
826 g_Textures_textureQuality.useLatched();
828 Textures_registerPreferencesPage();
830 Textures_ModeChanged();
832 void Textures_Destroy()
834 delete g_texturesmap;
838 #include "modulesystem/modulesmap.h"
839 #include "modulesystem/singletonmodule.h"
840 #include "modulesystem/moduleregistry.h"
842 class TexturesDependencies :
843 public GlobalRadiantModuleRef,
844 public GlobalOpenGLModuleRef,
845 public GlobalPreferenceSystemModuleRef
847 ImageModulesRef m_image_modules;
849 TexturesDependencies() :
850 m_image_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("texturetypes"))
853 ImageModules& getImageModules()
855 return m_image_modules.get();
861 TexturesCache* m_textures;
863 typedef TexturesCache Type;
864 STRING_CONSTANT(Name, "*");
868 Textures_Construct();
870 m_textures = &GetTexturesCache();
876 TexturesCache* getTable()
882 typedef SingletonModule<TexturesAPI, TexturesDependencies> TexturesModule;
883 typedef Static<TexturesModule> StaticTexturesModule;
884 StaticRegisterModule staticRegisterTextures(StaticTexturesModule::instance());
886 ImageModules& Textures_getImageModules()
888 return StaticTexturesModule::instance().getDependencies().getImageModules();