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,
54 enum TextureCompressionFormat
56 TEXTURECOMPRESSION_NONE = 0,
57 TEXTURECOMPRESSION_RGBA = 1,
58 TEXTURECOMPRESSION_RGBA_S3TC_DXT1 = 2,
59 TEXTURECOMPRESSION_RGBA_S3TC_DXT3 = 3,
60 TEXTURECOMPRESSION_RGBA_S3TC_DXT5 = 4,
63 struct texture_globals_t
66 // texture compression format
67 TextureCompressionFormat m_nTextureCompressionFormat;
71 bool bTextureCompressionSupported; // is texture compression supported by hardware?
72 GLint texture_components;
74 // temporary values that should be initialised only once at run-time
75 bool m_bOpenGLCompressionSupported;
76 bool m_bS3CompressionSupported;
78 texture_globals_t(GLint components) :
79 m_nTextureCompressionFormat(TEXTURECOMPRESSION_NONE),
81 bTextureCompressionSupported(false),
82 texture_components(components),
83 m_bOpenGLCompressionSupported(false),
84 m_bS3CompressionSupported(false)
89 texture_globals_t g_texture_globals(GL_RGBA);
91 void SetTexParameters(ETexturesMode mode)
95 case eTextures_NEAREST:
96 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
97 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
99 case eTextures_NEAREST_MIPMAP_NEAREST:
100 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST );
101 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
103 case eTextures_NEAREST_MIPMAP_LINEAR:
104 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR );
105 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
107 case eTextures_LINEAR:
108 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
109 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
111 case eTextures_LINEAR_MIPMAP_NEAREST:
112 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
113 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
115 case eTextures_LINEAR_MIPMAP_LINEAR:
116 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
117 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
120 globalOutputStream() << "invalid texture mode\n";
124 ETexturesMode g_texture_mode = eTextures_LINEAR_MIPMAP_LINEAR;
129 byte g_gammatable[256];
130 void ResampleGamma(float fGamma)
135 for (i = 0; i < 256; i++)
139 for (i = 0; i < 256; i++)
141 inf = (int)(255 * pow ( static_cast<double>((i + 0.5) / 255.5) , static_cast<double>(fGamma) ) + 0.5);
146 g_gammatable[i] = inf;
151 inline const int& min_int(const int& left, const int& right)
153 return std::min(left, right);
156 int max_tex_size = 0;
157 const int max_texture_quality = 3;
158 LatchedInt g_Textures_textureQuality(3, "Texture Quality");
160 /// \brief This function does the actual processing of raw RGBA data into a GL texture.
161 /// It will also resample to power-of-two dimensions, generate the mipmaps and adjust gamma.
162 void LoadTextureRGBA(qtexture_t* q, unsigned char* pPixels, int nWidth, int nHeight)
164 static float fGamma = -1;
167 int nCount = nWidth * nHeight;
169 if (fGamma != g_texture_globals.fGamma)
171 fGamma = g_texture_globals.fGamma;
172 ResampleGamma(fGamma);
178 total[0] = total[1] = total[2] = 0.0f;
180 // resample texture gamma according to user settings
181 for (int i = 0; i < (nCount * 4); i += 4)
183 for (int j = 0; j < 3; j++)
185 total[j] += (pPixels + i)[j];
186 byte b = (pPixels + i)[j];
187 (pPixels + i)[j] = g_gammatable[b];
191 q->color[0] = total[0] / (nCount * 255);
192 q->color[1] = total[1] / (nCount * 255);
193 q->color[2] = total[2] / (nCount * 255);
195 glGenTextures (1, &q->texture_number);
197 glBindTexture( GL_TEXTURE_2D, q->texture_number );
199 SetTexParameters(g_texture_mode);
202 while(gl_width < nWidth)
206 while(gl_height < nHeight)
209 bool resampled = false;
210 if (!(gl_width == nWidth && gl_height == nHeight))
213 outpixels = (byte *)malloc(gl_width * gl_height * 4);
214 R_ResampleTexture(pPixels, nWidth, nHeight, outpixels, gl_width, gl_height, 4);
221 int quality_reduction = max_texture_quality - g_Textures_textureQuality.m_value;
222 int target_width = min_int(gl_width >> quality_reduction, max_tex_size);
223 int target_height = min_int(gl_height >> quality_reduction, max_tex_size);
225 while (gl_width > target_width || gl_height > target_height)
227 GL_MipReduce(outpixels, outpixels, gl_width, gl_height, target_width, target_height);
229 if (gl_width > target_width)
231 if (gl_height > target_height)
236 glTexImage2D(GL_TEXTURE_2D, mip++, g_texture_globals.texture_components, gl_width, gl_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, outpixels);
237 while (gl_width > 1 || gl_height > 1)
239 GL_MipReduce(outpixels, outpixels, gl_width, gl_height, 1, 1);
246 glTexImage2D(GL_TEXTURE_2D, mip++, g_texture_globals.texture_components, gl_width, gl_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, outpixels);
249 glBindTexture(GL_TEXTURE_2D, 0);
260 void Texture_InitPalette (byte *pal)
265 byte gammatable[256];
268 gamma = g_texture_globals.fGamma;
272 for (i=0 ; i<256 ; i++)
276 for (i=0 ; i<256 ; i++)
278 inf = (int)(255 * pow ( (i+0.5)/255.5 , gamma ) + 0.5);
287 for (i=0 ; i<256 ; i++)
289 r = gammatable[pal[0]];
290 g = gammatable[pal[1]];
291 b = gammatable[pal[2]];
294 //v = (r<<24) + (g<<16) + (b<<8) + 255;
297 //tex_palette[i] = v;
298 tex_palette[i*3+0] = r;
299 tex_palette[i*3+1] = g;
300 tex_palette[i*3+2] = b;
311 HashTable<CopiedString, CopiedString, HashStringNoCase, StringEqualNoCase> strings;
312 strings["Monkey"] = "bleh";
313 strings["MonkeY"] = "blah";
317 const TestHashtable g_testhashtable;
321 typedef std::pair<LoadImageCallback, CopiedString> TextureKey;
323 void qtexture_realise(qtexture_t& texture, const TextureKey& key)
325 texture.texture_number = 0;
326 if(!string_empty(key.second.c_str()))
328 Image* image = key.first.loadImage(key.second.c_str());
331 LoadTextureRGBA(&texture, image->getRGBAPixels(), image->getWidth(), image->getHeight());
332 texture.surfaceFlags = image->getSurfaceFlags();
333 texture.contentFlags = image->getContentFlags();
334 texture.value = image->getValue();
336 globalOutputStream() << "Loaded Texture: \"" << key.second.c_str() << "\"\n";
337 GlobalOpenGL_debugAssertNoErrors();
341 globalErrorStream() << "Texture load failed: \"" << key.second.c_str() << "\"\n";
346 void qtexture_unrealise(qtexture_t& texture)
348 if(GlobalOpenGL().contextValid && texture.texture_number != 0)
350 glDeleteTextures(1, &texture.texture_number);
351 GlobalOpenGL_debugAssertNoErrors();
355 class TextureKeyEqualNoCase
358 bool operator()(const TextureKey& key, const TextureKey& other) const
360 return key.first == other.first && string_equal_nocase(key.second.c_str(), other.second.c_str());
364 class TextureKeyHashNoCase
367 typedef hash_t hash_type;
368 hash_t operator()(const TextureKey& key) const
370 return hash_combine(string_hash_nocase(key.second.c_str()), pod_hash(key.first));
374 #define DEBUG_TEXTURES 0
376 class TexturesMap : public TexturesCache
378 class TextureConstructor
380 TexturesMap* m_cache;
382 explicit TextureConstructor(TexturesMap* cache)
386 qtexture_t* construct(const TextureKey& key)
388 qtexture_t* texture = new qtexture_t(key.first, key.second.c_str());
389 if(m_cache->realised())
391 qtexture_realise(*texture, key);
395 void destroy(qtexture_t* texture)
397 if(m_cache->realised())
399 qtexture_unrealise(*texture);
405 typedef HashedCache<TextureKey, qtexture_t, TextureKeyHashNoCase, TextureKeyEqualNoCase, TextureConstructor> qtextures_t;
406 qtextures_t m_qtextures;
407 TexturesCacheObserver* m_observer;
408 std::size_t m_unrealised;
411 TexturesMap() : m_qtextures(TextureConstructor(this)), m_observer(0), m_unrealised(1)
414 typedef qtextures_t::iterator iterator;
418 return m_qtextures.begin();
422 return m_qtextures.end();
425 LoadImageCallback defaultLoader() const
427 return LoadImageCallback(0, QERApp_LoadImage);
429 Image* loadImage(const char* name)
431 return defaultLoader().loadImage(name);
433 qtexture_t* capture(const char* name)
435 return capture(defaultLoader(), name);
437 qtexture_t* capture(const LoadImageCallback& loader, const char* name)
440 globalOutputStream() << "textures capture: " << makeQuoted(name) << '\n';
442 return m_qtextures.capture(TextureKey(loader, name)).get();
444 void release(qtexture_t* texture)
447 globalOutputStream() << "textures release: " << makeQuoted(texture->name) << '\n';
449 m_qtextures.release(TextureKey(texture->load, texture->name));
451 void attach(TexturesCacheObserver& observer)
453 ASSERT_MESSAGE(m_observer == 0, "TexturesMap::attach: cannot attach observer");
454 m_observer = &observer;
456 void detach(TexturesCacheObserver& observer)
458 ASSERT_MESSAGE(m_observer == &observer, "TexturesMap::detach: cannot detach observer");
463 if(--m_unrealised == 0)
465 g_texture_globals.bTextureCompressionSupported = false;
467 if(GlobalOpenGL().ARB_texture_compression())
469 g_texture_globals.bTextureCompressionSupported = true;
470 g_texture_globals.m_bOpenGLCompressionSupported = true;
473 if(GlobalOpenGL().EXT_texture_compression_s3tc())
475 g_texture_globals.bTextureCompressionSupported = true;
476 g_texture_globals.m_bS3CompressionSupported = true;
479 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size);
480 if(max_tex_size == 0)
485 for(qtextures_t::iterator i = m_qtextures.begin(); i != m_qtextures.end(); ++i)
487 if(!(*i).value.empty())
489 qtexture_realise(*(*i).value, (*i).key);
494 m_observer->realise();
500 if(++m_unrealised == 1)
504 m_observer->unrealise();
506 for(qtextures_t::iterator i = m_qtextures.begin(); i != m_qtextures.end(); ++i)
508 if(!(*i).value.empty())
510 qtexture_unrealise(*(*i).value);
517 return m_unrealised == 0;
521 TexturesMap* g_texturesmap;
523 TexturesCache& GetTexturesCache()
525 return *g_texturesmap;
529 void Textures_Realise()
531 SetTexParameters(g_texture_mode);
532 g_texturesmap->realise();
535 void Textures_Unrealise()
537 g_texturesmap->unrealise();
541 Callback g_texturesModeChangedNotify;
543 void Textures_setModeChangedNotify(const Callback& notify)
545 g_texturesModeChangedNotify = notify;
548 void Textures_ModeChanged()
550 if(g_texturesmap->realised())
552 SetTexParameters(g_texture_mode);
554 for(TexturesMap::iterator i = g_texturesmap->begin(); i != g_texturesmap->end(); ++i)
556 glBindTexture (GL_TEXTURE_2D, (*i).value->texture_number);
557 SetTexParameters(g_texture_mode);
560 glBindTexture( GL_TEXTURE_2D, 0 );
563 g_texturesModeChangedNotify();
566 void Textures_SetMode(ETexturesMode mode)
568 if(g_texture_mode != mode)
570 g_texture_mode = mode;
572 Textures_ModeChanged();
576 void Textures_setTextureComponents(GLint texture_components)
578 if(g_texture_globals.texture_components != texture_components)
580 Textures_Unrealise();
581 g_texture_globals.texture_components = texture_components;
586 void Textures_UpdateTextureCompressionFormat()
588 GLint texture_components = GL_RGBA;
590 if (g_texture_globals.bTextureCompressionSupported)
592 if(g_texture_globals.m_nTextureCompressionFormat != TEXTURECOMPRESSION_NONE
593 && g_texture_globals.m_nTextureCompressionFormat != TEXTURECOMPRESSION_RGBA
594 && !g_texture_globals.m_bS3CompressionSupported)
596 globalOutputStream() << "OpenGL extension GL_EXT_texture_compression_s3tc not supported by current graphics drivers\n";
597 g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_RGBA; // if this is not supported either, see below
599 if (g_texture_globals.m_nTextureCompressionFormat == TEXTURECOMPRESSION_RGBA && !g_texture_globals.m_bOpenGLCompressionSupported)
601 globalOutputStream() << "OpenGL extension GL_ARB_texture_compression not supported by current graphics drivers\n";
602 g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE;
605 switch (g_texture_globals.m_nTextureCompressionFormat)
607 case (TEXTURECOMPRESSION_NONE):
609 texture_components = GL_RGBA;
612 case (TEXTURECOMPRESSION_RGBA):
614 texture_components = GL_COMPRESSED_RGBA_ARB;
617 case (TEXTURECOMPRESSION_RGBA_S3TC_DXT1):
619 texture_components = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
622 case (TEXTURECOMPRESSION_RGBA_S3TC_DXT3):
624 texture_components = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
627 case (TEXTURECOMPRESSION_RGBA_S3TC_DXT5):
629 texture_components = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
636 texture_components = GL_RGBA;
637 g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE;
640 Textures_setTextureComponents(texture_components);
643 void TextureCompressionImport(TextureCompressionFormat& self, int value)
645 if(!g_texture_globals.m_bOpenGLCompressionSupported
646 && g_texture_globals.m_bS3CompressionSupported
654 self = TEXTURECOMPRESSION_NONE;
657 self = TEXTURECOMPRESSION_RGBA;
660 self = TEXTURECOMPRESSION_RGBA_S3TC_DXT1;
663 self = TEXTURECOMPRESSION_RGBA_S3TC_DXT3;
666 self = TEXTURECOMPRESSION_RGBA_S3TC_DXT5;
669 Textures_UpdateTextureCompressionFormat();
671 typedef ReferenceCaller1<TextureCompressionFormat, int, TextureCompressionImport> TextureCompressionImportCaller;
673 void TextureGammaImport(float& self, float value)
677 Textures_Unrealise();
682 typedef ReferenceCaller1<float, float, TextureGammaImport> TextureGammaImportCaller;
684 void TextureModeImport(ETexturesMode& self, int value)
689 Textures_SetMode(eTextures_NEAREST);
692 Textures_SetMode(eTextures_NEAREST_MIPMAP_NEAREST);
695 Textures_SetMode(eTextures_LINEAR);
698 Textures_SetMode(eTextures_NEAREST_MIPMAP_LINEAR);
701 Textures_SetMode(eTextures_LINEAR_MIPMAP_NEAREST);
704 Textures_SetMode(eTextures_LINEAR_MIPMAP_LINEAR);
708 typedef ReferenceCaller1<ETexturesMode, int, TextureModeImport> TextureModeImportCaller;
710 void TextureModeExport(ETexturesMode& self, const IntImportCallback& importer)
714 case eTextures_NEAREST:
717 case eTextures_NEAREST_MIPMAP_NEAREST:
720 case eTextures_LINEAR:
723 case eTextures_NEAREST_MIPMAP_LINEAR:
726 case eTextures_LINEAR_MIPMAP_NEAREST:
729 case eTextures_LINEAR_MIPMAP_LINEAR:
736 typedef ReferenceCaller1<ETexturesMode, const IntImportCallback&, TextureModeExport> TextureModeExportCaller;
738 void Textures_constructPreferences(PreferencesPage& page)
741 const char* percentages[] = { "12.5%", "25%", "50%", "100%", };
744 STRING_ARRAY_RANGE(percentages),
745 LatchedIntImportCaller(g_Textures_textureQuality),
746 IntExportCaller(g_Textures_textureQuality.m_latched)
754 FloatImportCallback(TextureGammaImportCaller(g_texture_globals.fGamma)),
755 FloatExportCallback(FloatExportCaller(g_texture_globals.fGamma))
758 const char* texture_mode[] = { "Nearest", "Nearest Mipmap", "Linear", "Bilinear", "Bilinear Mipmap", "Trilinear" };
760 "Texture Render Mode",
761 STRING_ARRAY_RANGE(texture_mode),
762 IntImportCallback(TextureModeImportCaller(g_texture_mode)),
763 IntExportCallback(TextureModeExportCaller(g_texture_mode))
767 const char* compression_none[] = { "None" };
768 const char* compression_opengl[] = { "None", "OpenGL ARB" };
769 const char* compression_s3tc[] = { "None", "S3TC DXT1", "S3TC DXT3", "S3TC DXT5" };
770 const char* compression_opengl_s3tc[] = { "None", "OpenGL ARB", "S3TC DXT1", "S3TC DXT3", "S3TC DXT5" };
771 StringArrayRange compression(
772 (g_texture_globals.m_bOpenGLCompressionSupported)
773 ? (g_texture_globals.m_bS3CompressionSupported)
774 ? STRING_ARRAY_RANGE(compression_opengl_s3tc)
775 : STRING_ARRAY_RANGE(compression_opengl)
776 : (g_texture_globals.m_bS3CompressionSupported)
777 ? STRING_ARRAY_RANGE(compression_s3tc)
778 : STRING_ARRAY_RANGE(compression_none)
781 "Hardware Texture Compression",
783 TextureCompressionImportCaller(g_texture_globals.m_nTextureCompressionFormat),
784 IntExportCaller(reinterpret_cast<int&>(g_texture_globals.m_nTextureCompressionFormat))
788 void Textures_constructPage(PreferenceGroup& group)
790 PreferencesPage page(group.createPage("Textures", "Texture Settings"));
791 Textures_constructPreferences(page);
793 void Textures_registerPreferencesPage()
795 PreferencesDialog_addDisplayPage(FreeCaller1<PreferenceGroup&, Textures_constructPage>());
798 void TextureCompression_importString(const char* string)
800 g_texture_globals.m_nTextureCompressionFormat = static_cast<TextureCompressionFormat>(atoi(string));
801 Textures_UpdateTextureCompressionFormat();
803 typedef FreeCaller1<const char*, TextureCompression_importString> TextureCompressionImportStringCaller;
806 void Textures_Construct()
808 g_texturesmap = new TexturesMap;
810 GlobalPreferenceSystem().registerPreference("TextureCompressionFormat", TextureCompressionImportStringCaller(), IntExportStringCaller(reinterpret_cast<int&>(g_texture_globals.m_nTextureCompressionFormat)));
811 GlobalPreferenceSystem().registerPreference("TextureFiltering", IntImportStringCaller(reinterpret_cast<int&>(g_texture_mode)), IntExportStringCaller(reinterpret_cast<int&>(g_texture_mode)));
812 GlobalPreferenceSystem().registerPreference("TextureQuality", IntImportStringCaller(g_Textures_textureQuality.m_latched), IntExportStringCaller(g_Textures_textureQuality.m_latched));
813 GlobalPreferenceSystem().registerPreference("SI_Gamma", FloatImportStringCaller(g_texture_globals.fGamma), FloatExportStringCaller(g_texture_globals.fGamma));
815 g_Textures_textureQuality.useLatched();
817 Textures_registerPreferencesPage();
819 Textures_ModeChanged();
821 void Textures_Destroy()
823 delete g_texturesmap;
827 #include "modulesystem/modulesmap.h"
828 #include "modulesystem/singletonmodule.h"
829 #include "modulesystem/moduleregistry.h"
831 class TexturesDependencies :
832 public GlobalRadiantModuleRef,
833 public GlobalOpenGLModuleRef,
834 public GlobalPreferenceSystemModuleRef
836 ImageModulesRef m_image_modules;
838 TexturesDependencies() :
839 m_image_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("texturetypes"))
842 ImageModules& getImageModules()
844 return m_image_modules.get();
850 TexturesCache* m_textures;
852 typedef TexturesCache Type;
853 STRING_CONSTANT(Name, "*");
857 Textures_Construct();
859 m_textures = &GetTexturesCache();
865 TexturesCache* getTable()
871 typedef SingletonModule<TexturesAPI, TexturesDependencies> TexturesModule;
872 typedef Static<TexturesModule> StaticTexturesModule;
873 StaticRegisterModule staticRegisterTextures(StaticTexturesModule::instance());
875 ImageModules& Textures_getImageModules()
877 return StaticTexturesModule::instance().getDependencies().getImageModules();