Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #ifndef INCLUDED_TEXTUREMANAGER
19 : #define INCLUDED_TEXTUREMANAGER
20 :
21 : #include "graphics/Texture.h"
22 : #include "lib/code_annotation.h"
23 : #include "lib/file/vfs/vfs.h"
24 : #include "lib/file/vfs/vfs_path.h"
25 : #include "renderer/backend/Format.h"
26 : #include "renderer/backend/Sampler.h"
27 :
28 : #include <cstddef>
29 : #include <cstdint>
30 : #include <memory>
31 :
32 : class CTextureManagerImpl;
33 : class CTextureProperties;
34 : class Tex;
35 : namespace Renderer::Backend { class IDevice; }
36 : namespace Renderer::Backend { class IDeviceCommandContext; }
37 : namespace Renderer::Backend { class ITexture; }
38 :
39 : /**
40 : * Texture manager with asynchronous loading and automatic DDS conversion/compression.
41 : *
42 : * Input textures can be any format. They will be converted to DDS using settings defined
43 : * in files named "texture.xml", in the same directory as the texture and in its parent
44 : * directories. See CTextureConverter for the XML syntax. The DDS file will be cached
45 : * for faster loading in the future.
46 : *
47 : * Typically the graphics code will initialise many textures at the start of the game,
48 : * mostly for off-screen objects, by calling CreateTexture().
49 : * Loading texture data may be very slow (especially if it needs to be converted
50 : * to DDS), and we don't want the game to become unresponsive.
51 : * CreateTexture therefore returns an object immediately, without loading the
52 : * texture. If the object is never used then the data will never be loaded.
53 : *
54 : * Typically, the renderer will call CTexture::Bind() when it wants to use the
55 : * texture. This will trigger the loading of the texture data. If it can be loaded
56 : * quickly (i.e. there is already a cached DDS version), then it will be loaded before
57 : * the function returns, and the texture can be rendered as normal.
58 : *
59 : * If loading will take a long time, then Bind() binds a default placeholder texture
60 : * and starts loading the texture in the background. It will use the correct texture
61 : * when the renderer next calls Bind() after the load has finished.
62 : *
63 : * It is also possible to prefetch textures which are not being rendered yet, but
64 : * are expected to be rendered soon (e.g. for off-screen terrain tiles).
65 : * These will be loaded in the background, when there are no higher-priority textures
66 : * to load.
67 : *
68 : * The same texture file can be safely loaded multiple times with different backend parameters
69 : * (but this should be avoided whenever possible, as it wastes VRAM).
70 : *
71 : * For release packages, DDS files can be precached by appending ".dds" to their name,
72 : * which will be used instead of doing runtime conversion. This means most players should
73 : * never experience the slow asynchronous conversion behaviour.
74 : * These cache files will typically be packed into an archive for faster loading;
75 : * if no archive cache is available then the source file will be converted and stored
76 : * as a loose cache file on the user's disk.
77 : */
78 : class CTextureManager
79 : {
80 : NONCOPYABLE(CTextureManager);
81 :
82 : public:
83 : /**
84 : * Construct texture manager. vfs must be the VFS instance used for all textures
85 : * loaded from this object.
86 : * highQuality is slower and intended for batch-conversion modes.
87 : */
88 : CTextureManager(PIVFS vfs, bool highQuality, Renderer::Backend::IDevice* device);
89 :
90 : ~CTextureManager();
91 :
92 : /**
93 : * Create a texture with the given properties.
94 : * The texture data will not be loaded immediately.
95 : */
96 : CTexturePtr CreateTexture(const CTextureProperties& props);
97 :
98 : /**
99 : * Wraps a backend texture.
100 : */
101 : CTexturePtr WrapBackendTexture(
102 : std::unique_ptr<Renderer::Backend::ITexture> backendTexture);
103 :
104 : /**
105 : * Returns a magenta texture. Use this for highlighting errors
106 : * (e.g. missing terrain textures).
107 : */
108 : const CTexturePtr& GetErrorTexture();
109 :
110 : /**
111 : * Returns a single color RGBA texture with CColor(1.0f, 1.0f, 1.0f, 1.0f).
112 : */
113 : const CTexturePtr& GetWhiteTexture();
114 :
115 : /**
116 : * Returns a single color RGBA texture with CColor(0.0f, 0.0f, 0.0f, 0.0f).
117 : */
118 : const CTexturePtr& GetTransparentTexture();
119 :
120 : /**
121 : * Returns a white RGBA texture with alpha gradient.
122 : */
123 : const CTexturePtr& GetAlphaGradientTexture();
124 :
125 : /**
126 : * Returns a single color RGBA texture cube with CColor(0.0f, 0.0f, 0.0f, 1.0f).
127 : */
128 : const CTexturePtr& GetBlackTextureCube();
129 :
130 : /**
131 : * Work on asynchronous texture loading operations, if any.
132 : * Returns true if it did any work.
133 : * The caller should typically loop this per frame until it returns
134 : * false or exceeds the allocated time for this frame.
135 : */
136 : bool MakeProgress();
137 :
138 : /**
139 : * Work on asynchronous texture uploading operations, if any.
140 : * Returns true if it did any work. Mostly the same as MakeProgress.
141 : */
142 : bool MakeUploadProgress(Renderer::Backend::IDeviceCommandContext* deviceCommandContext);
143 :
144 : /**
145 : * Synchronously converts and compresses and saves the texture,
146 : * and returns the output path (minus a "cache/" prefix). This
147 : * is intended for pre-caching textures in release archives.
148 : * @return true on success
149 : */
150 : bool GenerateCachedTexture(const VfsPath& path, VfsPath& outputPath);
151 :
152 : /**
153 : * @return a cached version of the path
154 : */
155 : VfsPath GetCachedPath(const VfsPath& path) const;
156 :
157 : /**
158 : * Returns true if the given texture exists.
159 : * This tests both for the original and converted filename.
160 : */
161 : bool TextureExists(const VfsPath& path) const;
162 :
163 : /**
164 : * Returns total number of bytes uploaded for all current texture.
165 : */
166 : size_t GetBytesUploaded() const;
167 :
168 : /**
169 : * Should be called on any quality or anisotropic change.
170 : */
171 : void OnQualityChanged();
172 :
173 : private:
174 : CTextureManagerImpl* m;
175 : };
176 :
177 : /**
178 : * Represents the filename and GL parameters of a texture,
179 : * for passing to CTextureManager::CreateTexture.
180 : */
181 277 : class CTextureProperties
182 : {
183 : friend class CTextureManagerImpl;
184 : friend struct TextureCacheCmp;
185 : friend struct TPequal_to;
186 : friend struct TPhash;
187 :
188 : public:
189 : /**
190 : * Use the given texture name, and default GL parameters.
191 : */
192 90 : explicit CTextureProperties(const VfsPath& path)
193 90 : : m_Path(path)
194 : {
195 : }
196 :
197 : CTextureProperties(
198 : const VfsPath& path, const Renderer::Backend::Format formatOverride)
199 : : m_Path(path), m_FormatOverride(formatOverride)
200 : {
201 : }
202 :
203 : /**
204 : * Set sampler address mode.
205 : */
206 0 : void SetAddressMode(const Renderer::Backend::Sampler::AddressMode addressMode)
207 : {
208 0 : m_AddressModeU = m_AddressModeV = addressMode;
209 : }
210 :
211 : /**
212 : * Set sampler address mode separately for different coordinates.
213 : */
214 0 : void SetAddressMode(
215 : const Renderer::Backend::Sampler::AddressMode addressModeU,
216 : const Renderer::Backend::Sampler::AddressMode addressModeV)
217 : {
218 0 : m_AddressModeU = addressModeU;
219 0 : m_AddressModeV = addressModeV;
220 : }
221 :
222 : /**
223 : * The value of max anisotropy is set by options. Though it might make sense
224 : * to add an override.
225 : */
226 0 : void SetAnisotropicFilter(const bool enabled) { m_AnisotropicFilterEnabled = enabled; }
227 :
228 : // TODO: rather than this static definition of texture properties
229 : // (especially anisotropy), maybe we want something that can be more
230 : // easily tweaked in an Options menu? e.g. the caller just specifies
231 : // "terrain texture mode" and we combine it with the user's options.
232 : // That'd let us dynamically change texture properties easily.
233 : //
234 : // enum EQualityMode
235 : // {
236 : // NONE,
237 : // TERRAIN,
238 : // MODEL,
239 : // GUI
240 : // }
241 : // void SetQuality(EQualityMode mode, float anisotropy, float lodbias, int reducemipmaps, ...);
242 : //
243 : // or something a bit like that.
244 :
245 0 : void SetIgnoreQuality(bool ignore) { m_IgnoreQuality = ignore; }
246 :
247 0 : void SetSRGB(const bool sRGB) { m_SRGB = sRGB; }
248 :
249 : private:
250 : // Must update TPhash, TPequal_to when changing these fields
251 : VfsPath m_Path;
252 :
253 : Renderer::Backend::Sampler::AddressMode m_AddressModeU =
254 : Renderer::Backend::Sampler::AddressMode::REPEAT;
255 : Renderer::Backend::Sampler::AddressMode m_AddressModeV =
256 : Renderer::Backend::Sampler::AddressMode::REPEAT;
257 : bool m_AnisotropicFilterEnabled = false;
258 : Renderer::Backend::Format m_FormatOverride =
259 : Renderer::Backend::Format::UNDEFINED;
260 : bool m_IgnoreQuality = false;
261 : bool m_SRGB{false};
262 : };
263 :
264 : /**
265 : * Represents a texture object.
266 : * The texture data may or may not have been loaded yet.
267 : * Before it has been loaded, all operations will act on a default
268 : * 1x1-pixel grey texture instead.
269 : */
270 : class CTexture
271 : {
272 : NONCOPYABLE(CTexture);
273 : public:
274 : ~CTexture();
275 :
276 : /**
277 : * Returns the width (in pixels) of the current texture.
278 : */
279 : size_t GetWidth() const;
280 :
281 : /**
282 : * Returns the height (in pixels) of the current texture.
283 : */
284 : size_t GetHeight() const;
285 :
286 : /**
287 : * Returns whether the current texture has an alpha channel.
288 : */
289 : bool HasAlpha() const;
290 :
291 : /**
292 : * Returns the ARGB value of the lowest mipmap level (i.e. the
293 : * average of the whole texture).
294 : * Returns 0 if the texture has no mipmaps.
295 : */
296 : std::uint32_t GetBaseColor() const;
297 :
298 : /**
299 : * Returns total number of bytes uploaded for this texture.
300 : */
301 : size_t GetUploadedSize() const;
302 :
303 : /**
304 : * Uploads a texture data to a backend texture if successfully loaded.
305 : * If the texture data hasn't been loaded yet, this may wait a short while to
306 : * load it. If loading takes too long then it will return sooner and the data will
307 : * be loaded in a background thread, so this does not guarantee the texture really
308 : * will be uploaded.
309 : */
310 : void UploadBackendTextureIfNeeded(
311 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext);
312 :
313 : /**
314 : * Returns a backend texture if successfully uploaded, else fallback.
315 : */
316 : Renderer::Backend::ITexture* GetBackendTexture();
317 : const Renderer::Backend::ITexture* GetBackendTexture() const;
318 :
319 : /**
320 : * Attempt to load the texture data quickly, as with
321 : * GetUploadedBackendTextureIfNeeded(). Returns whether the texture data is
322 : * currently loaded (but not uploaded).
323 : */
324 : bool TryLoad();
325 :
326 : /**
327 : * Returns whether the texture data is currently loaded.
328 : */
329 12 : bool IsLoaded() const { return m_State == LOADED; }
330 :
331 : /**
332 : * Returns whether the texture data is currently uploaded.
333 : */
334 7 : bool IsUploaded() const { return m_State == UPLOADED; }
335 :
336 : /**
337 : * Activate the prefetching optimisation for this texture.
338 : * Use this if it is likely the texture will be needed in the near future.
339 : * It will be loaded in the background so that it is likely to be ready when
340 : * it is used by Bind().
341 : */
342 : void Prefetch();
343 :
344 : private:
345 : friend class CTextureManagerImpl;
346 : friend class CPredefinedTexture;
347 : friend struct TextureCacheCmp;
348 : friend struct TPequal_to;
349 : friend struct TPhash;
350 :
351 : // Only the texture manager can create these
352 : explicit CTexture(
353 : std::unique_ptr<Renderer::Backend::ITexture> texture,
354 : Renderer::Backend::ITexture* fallback,
355 : const CTextureProperties& props, CTextureManagerImpl* textureManager);
356 :
357 : void ResetBackendTexture(
358 : std::unique_ptr<Renderer::Backend::ITexture> backendTexture,
359 : Renderer::Backend::ITexture* fallbackBackendTexture);
360 :
361 : const CTextureProperties m_Properties;
362 :
363 : std::unique_ptr<Renderer::Backend::ITexture> m_BackendTexture;
364 : // It's possible to m_FallbackBackendTexture references m_BackendTexture.
365 : Renderer::Backend::ITexture* m_FallbackBackendTexture = nullptr;
366 : std::uint32_t m_BaseColor;
367 : std::unique_ptr<Tex> m_TextureData;
368 : size_t m_UploadedSize = 0;
369 : uint32_t m_BaseLevelOffset = 0;
370 :
371 : enum
372 : {
373 : UNLOADED, // loading has not started
374 : PREFETCH_NEEDS_LOADING, // was prefetched; currently waiting to try loading from cache
375 : PREFETCH_NEEDS_CONVERTING, // was prefetched; currently waiting to be sent to the texture converter
376 : PREFETCH_IS_CONVERTING, // was prefetched; currently being processed by the texture converter
377 : HIGH_NEEDS_CONVERTING, // high-priority; currently waiting to be sent to the texture converter
378 : HIGH_IS_CONVERTING, // high-priority; currently being processed by the texture converter
379 : LOADED, // loading texture data has completed (successfully or not)
380 : UPLOADED // uploading to backend has completed (successfully or not)
381 : } m_State;
382 :
383 : CTextureManagerImpl* m_TextureManager;
384 :
385 : // Self-reference to let us recover the CTexturePtr for this object.
386 : // (weak pointer to avoid cycles)
387 : std::weak_ptr<CTexture> m_Self;
388 : };
389 :
390 : #endif // INCLUDED_TEXTUREMANAGER
|