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 g_texturesmap->realise();
540 void Textures_Unrealise()
542 g_texturesmap->unrealise();
546 Callback g_texturesModeChangedNotify;
548 void Textures_setModeChangedNotify(const Callback& notify)
550 g_texturesModeChangedNotify = notify;
553 void Textures_ModeChanged()
555 if(g_texturesmap->realised())
557 SetTexParameters(g_texture_mode);
559 for(TexturesMap::iterator i = g_texturesmap->begin(); i != g_texturesmap->end(); ++i)
561 glBindTexture (GL_TEXTURE_2D, (*i).value->texture_number);
562 SetTexParameters(g_texture_mode);
565 glBindTexture( GL_TEXTURE_2D, 0 );
567 g_texturesModeChangedNotify();
570 void Textures_SetMode(ETexturesMode mode)
572 if(g_texture_mode != mode)
574 g_texture_mode = mode;
576 Textures_ModeChanged();
580 void Textures_setTextureComponents(GLint texture_components)
582 if(g_texture_globals.texture_components != texture_components)
584 Textures_Unrealise();
585 g_texture_globals.texture_components = texture_components;
590 void Textures_UpdateTextureCompressionFormat()
592 GLint texture_components = GL_RGBA;
594 if(!g_texturesmap->realised())
596 texture_components = g_texture_globals.m_nTextureCompressionFormat;
597 if(texture_components == TEXTURECOMPRESSION_NONE)
598 texture_components = GL_RGBA;
602 if (g_texture_globals.bTextureCompressionSupported)
604 if(g_texture_globals.m_nTextureCompressionFormat != TEXTURECOMPRESSION_NONE
605 && g_texture_globals.m_nTextureCompressionFormat != TEXTURECOMPRESSION_RGBA
606 && !g_texture_globals.m_bS3CompressionSupported)
608 globalOutputStream() << "OpenGL extension GL_EXT_texture_compression_s3tc not supported by current graphics drivers\n";
609 g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_RGBA; // if this is not supported either, see below
611 if (g_texture_globals.m_nTextureCompressionFormat == TEXTURECOMPRESSION_RGBA && !g_texture_globals.m_bOpenGLCompressionSupported)
613 globalOutputStream() << "OpenGL extension GL_ARB_texture_compression not supported by current graphics drivers\n";
614 g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE;
617 switch (g_texture_globals.m_nTextureCompressionFormat)
619 case (TEXTURECOMPRESSION_NONE):
621 texture_components = GL_RGBA;
624 case (TEXTURECOMPRESSION_RGBA):
626 texture_components = GL_COMPRESSED_RGBA_ARB;
629 case (TEXTURECOMPRESSION_RGBA_S3TC_DXT1):
631 texture_components = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
634 case (TEXTURECOMPRESSION_RGBA_S3TC_DXT3):
636 texture_components = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
639 case (TEXTURECOMPRESSION_RGBA_S3TC_DXT5):
641 texture_components = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
648 texture_components = GL_RGBA;
649 g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE;
653 Textures_setTextureComponents(texture_components);
656 void TextureCompressionImport(TextureCompressionFormat& self, int value)
658 if(!g_texture_globals.m_bOpenGLCompressionSupported
659 && g_texture_globals.m_bS3CompressionSupported
667 self = TEXTURECOMPRESSION_NONE;
670 self = TEXTURECOMPRESSION_RGBA;
673 self = TEXTURECOMPRESSION_RGBA_S3TC_DXT1;
676 self = TEXTURECOMPRESSION_RGBA_S3TC_DXT3;
679 self = TEXTURECOMPRESSION_RGBA_S3TC_DXT5;
682 Textures_UpdateTextureCompressionFormat();
684 typedef ReferenceCaller1<TextureCompressionFormat, int, TextureCompressionImport> TextureCompressionImportCaller;
686 void TextureGammaImport(float& self, float value)
690 Textures_Unrealise();
695 typedef ReferenceCaller1<float, float, TextureGammaImport> TextureGammaImportCaller;
697 void TextureModeImport(ETexturesMode& self, int value)
702 Textures_SetMode(eTextures_NEAREST);
705 Textures_SetMode(eTextures_NEAREST_MIPMAP_NEAREST);
708 Textures_SetMode(eTextures_LINEAR);
711 Textures_SetMode(eTextures_NEAREST_MIPMAP_LINEAR);
714 Textures_SetMode(eTextures_LINEAR_MIPMAP_NEAREST);
717 Textures_SetMode(eTextures_LINEAR_MIPMAP_LINEAR);
720 Textures_SetMode(eTextures_MAX_ANISOTROPY);
723 typedef ReferenceCaller1<ETexturesMode, int, TextureModeImport> TextureModeImportCaller;
725 void TextureModeExport(ETexturesMode& self, const IntImportCallback& importer)
729 case eTextures_NEAREST:
732 case eTextures_NEAREST_MIPMAP_NEAREST:
735 case eTextures_LINEAR:
738 case eTextures_NEAREST_MIPMAP_LINEAR:
741 case eTextures_LINEAR_MIPMAP_NEAREST:
744 case eTextures_LINEAR_MIPMAP_LINEAR:
747 case eTextures_MAX_ANISOTROPY:
754 typedef ReferenceCaller1<ETexturesMode, const IntImportCallback&, TextureModeExport> TextureModeExportCaller;
756 void Textures_constructPreferences(PreferencesPage& page)
759 const char* percentages[] = { "12.5%", "25%", "50%", "100%", };
762 STRING_ARRAY_RANGE(percentages),
763 LatchedIntImportCaller(g_Textures_textureQuality),
764 IntExportCaller(g_Textures_textureQuality.m_latched)
772 FloatImportCallback(TextureGammaImportCaller(g_texture_globals.fGamma)),
773 FloatExportCallback(FloatExportCaller(g_texture_globals.fGamma))
776 const char* texture_mode[] = { "Nearest", "Nearest Mipmap", "Linear", "Bilinear", "Bilinear Mipmap", "Trilinear", "Anisotropy" };
778 "Texture Render Mode",
779 STRING_ARRAY_RANGE(texture_mode),
780 IntImportCallback(TextureModeImportCaller(g_texture_mode)),
781 IntExportCallback(TextureModeExportCaller(g_texture_mode))
785 const char* compression_none[] = { "None" };
786 const char* compression_opengl[] = { "None", "OpenGL ARB" };
787 const char* compression_s3tc[] = { "None", "S3TC DXT1", "S3TC DXT3", "S3TC DXT5" };
788 const char* compression_opengl_s3tc[] = { "None", "OpenGL ARB", "S3TC DXT1", "S3TC DXT3", "S3TC DXT5" };
789 StringArrayRange compression(
790 (g_texture_globals.m_bOpenGLCompressionSupported)
791 ? (g_texture_globals.m_bS3CompressionSupported)
792 ? STRING_ARRAY_RANGE(compression_opengl_s3tc)
793 : STRING_ARRAY_RANGE(compression_opengl)
794 : (g_texture_globals.m_bS3CompressionSupported)
795 ? STRING_ARRAY_RANGE(compression_s3tc)
796 : STRING_ARRAY_RANGE(compression_none)
799 "Hardware Texture Compression",
801 TextureCompressionImportCaller(g_texture_globals.m_nTextureCompressionFormat),
802 IntExportCaller(reinterpret_cast<int&>(g_texture_globals.m_nTextureCompressionFormat))
806 void Textures_constructPage(PreferenceGroup& group)
808 PreferencesPage page(group.createPage("Textures", "Texture Settings"));
809 Textures_constructPreferences(page);
811 void Textures_registerPreferencesPage()
813 PreferencesDialog_addDisplayPage(FreeCaller1<PreferenceGroup&, Textures_constructPage>());
816 void TextureCompression_importString(const char* string)
818 g_texture_globals.m_nTextureCompressionFormat = static_cast<TextureCompressionFormat>(atoi(string));
819 Textures_UpdateTextureCompressionFormat();
821 typedef FreeCaller1<const char*, TextureCompression_importString> TextureCompressionImportStringCaller;
824 void Textures_Construct()
826 g_texturesmap = new TexturesMap;
828 GlobalPreferenceSystem().registerPreference("TextureCompressionFormat", TextureCompressionImportStringCaller(), IntExportStringCaller(reinterpret_cast<int&>(g_texture_globals.m_nTextureCompressionFormat)));
829 GlobalPreferenceSystem().registerPreference("TextureFiltering", IntImportStringCaller(reinterpret_cast<int&>(g_texture_mode)), IntExportStringCaller(reinterpret_cast<int&>(g_texture_mode)));
830 GlobalPreferenceSystem().registerPreference("TextureQuality", IntImportStringCaller(g_Textures_textureQuality.m_latched), IntExportStringCaller(g_Textures_textureQuality.m_latched));
831 GlobalPreferenceSystem().registerPreference("SI_Gamma", FloatImportStringCaller(g_texture_globals.fGamma), FloatExportStringCaller(g_texture_globals.fGamma));
833 g_Textures_textureQuality.useLatched();
835 Textures_registerPreferencesPage();
837 Textures_ModeChanged();
839 void Textures_Destroy()
841 delete g_texturesmap;
845 #include "modulesystem/modulesmap.h"
846 #include "modulesystem/singletonmodule.h"
847 #include "modulesystem/moduleregistry.h"
849 class TexturesDependencies :
850 public GlobalRadiantModuleRef,
851 public GlobalOpenGLModuleRef,
852 public GlobalPreferenceSystemModuleRef
854 ImageModulesRef m_image_modules;
856 TexturesDependencies() :
857 m_image_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("texturetypes"))
860 ImageModules& getImageModules()
862 return m_image_modules.get();
868 TexturesCache* m_textures;
870 typedef TexturesCache Type;
871 STRING_CONSTANT(Name, "*");
875 Textures_Construct();
877 m_textures = &GetTexturesCache();
883 TexturesCache* getTable()
889 typedef SingletonModule<TexturesAPI, TexturesDependencies> TexturesModule;
890 typedef Static<TexturesModule> StaticTexturesModule;
891 StaticRegisterModule staticRegisterTextures(StaticTexturesModule::instance());
893 ImageModules& Textures_getImageModules()
895 return StaticTexturesModule::instance().getDependencies().getImageModules();