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 : #include "precompiled.h"
19 :
20 : #include "TextureConverter.h"
21 :
22 : #include "lib/alignment.h"
23 : #include "lib/allocators/shared_ptr.h"
24 : #include "lib/debug.h"
25 : #include "lib/path.h"
26 : #include "lib/regex.h"
27 : #include "lib/status.h"
28 : #include "lib/tex/tex.h"
29 : #include "maths/MD5.h"
30 : #include "ps/CLogger.h"
31 : #include "ps/CStr.h"
32 : #include "ps/Errors.h"
33 : #include "ps/Future.h"
34 : #include "ps/Profiler2.h"
35 : #include "ps/TaskManager.h"
36 : #include "ps/Util.h"
37 : #include "ps/XMB/XMBData.h"
38 : #include "ps/XMB/XMBStorage.h"
39 : #include "ps/XML/Xeromyces.h"
40 :
41 : #include <bit>
42 : #include <cstring>
43 : #include <utility>
44 :
45 : #if CONFIG2_NVTT
46 :
47 : #include "nvtt/nvtt.h"
48 :
49 : // We assume NVTT is recent enough to support the alpha flag in the DXT1a format. If users try to use an
50 : // old version of NVTT, the game will crash when trying to decode dds files generated by NVTT.
51 : //
52 : // The support was added upstream in https://github.com/castano/nvidia-texture-tools/commit/782a127071895f538c1ae49925a6e15687e3c966
53 : // so, in theory, 2.0.7 and newer should be enough, but all 2.0.x releases define NVTT_VERSION as 200, so
54 : // we can't distinguish them. NVTT_VERSION is 201 in all development versions of the 2.0.x era, so we also
55 : // have to exclude that value.
56 : #if !defined NVTT_VERSION || NVTT_VERSION == 200 || NVTT_VERSION == 201
57 : #error Please use NVTT 2.1.0 or newer. \
58 : If your system does not provide it, you should use the bundled version by NOT passing --with-system-nvtt to premake.
59 : #endif
60 :
61 : namespace
62 : {
63 :
64 : // Completely arbitrary constant - there is some main-thread cost to loading textures and the textures
65 : // use a lot of memory, so probably should not be too high.
66 : // Note that some results in the result queue may already be ready.
67 : constexpr size_t MAX_QUEUE_SIZE_FOR_OPTIMAL_UTILIZATION{12};
68 :
69 : /**
70 : * Output handler to collect NVTT's output into a simplistic buffer.
71 : */
72 6 : struct BufferOutputHandler : public nvtt::OutputHandler
73 : {
74 : std::vector<std::uint8_t> buffer;
75 :
76 39 : virtual void beginImage(int /*size*/, int /*width*/, int /*height*/, int /*depth*/, int /*face*/,
77 : int /*miplevel*/)
78 : {
79 39 : }
80 :
81 45 : virtual bool writeData(const void* data, int size)
82 : {
83 45 : size_t off = buffer.size();
84 45 : buffer.resize(off + size);
85 45 : memcpy(&buffer[off], data, size);
86 45 : return true;
87 : }
88 :
89 39 : virtual void endImage()
90 : {
91 39 : }
92 : };
93 :
94 : /**
95 : * Arguments to the asynchronous task.
96 : */
97 : struct ConversionRequest
98 : {
99 : VfsPath dest;
100 : CTexturePtr texture;
101 : nvtt::InputOptions inputOptions;
102 : nvtt::CompressionOptions compressionOptions;
103 : nvtt::OutputOptions outputOptions;
104 : };
105 :
106 : } // anonymous namespace
107 :
108 : /**
109 : * Response from the asynchronous task.
110 : */
111 6 : struct CTextureConverter::ConversionResult
112 : {
113 : VfsPath dest;
114 : CTexturePtr texture;
115 : BufferOutputHandler output;
116 : bool ret; // true if the conversion succeeded
117 : };
118 :
119 : #endif // CONFIG2_NVTT
120 :
121 11 : void CTextureConverter::Settings::Hash(MD5& hash)
122 : {
123 11 : hash.Update(reinterpret_cast<const std::uint8_t*>(&format), sizeof(format));
124 11 : hash.Update(reinterpret_cast<const std::uint8_t*>(&mipmap), sizeof(mipmap));
125 11 : hash.Update(reinterpret_cast<const std::uint8_t*>(&normal), sizeof(normal));
126 11 : hash.Update(reinterpret_cast<const std::uint8_t*>(&alpha), sizeof(alpha));
127 11 : hash.Update(reinterpret_cast<const std::uint8_t*>(&filter), sizeof(filter));
128 11 : hash.Update(reinterpret_cast<const std::uint8_t*>(&kaiserWidth), sizeof(kaiserWidth));
129 11 : hash.Update(reinterpret_cast<const std::uint8_t*>(&kaiserAlpha), sizeof(kaiserAlpha));
130 11 : hash.Update(reinterpret_cast<const std::uint8_t*>(&kaiserStretch), sizeof(kaiserStretch));
131 11 : }
132 :
133 0 : CTextureConverter::SettingsFile* CTextureConverter::LoadSettings(const VfsPath& path) const
134 : {
135 0 : CXeromyces XeroFile;
136 0 : if (XeroFile.Load(m_VFS, path, "texture") != PSRETURN_OK)
137 : return NULL;
138 :
139 : // Define all the elements used in the XML file
140 : #define EL(x) int el_##x = XeroFile.GetElementID(#x)
141 : #define AT(x) int at_##x = XeroFile.GetAttributeID(#x)
142 0 : EL(textures);
143 0 : EL(file);
144 0 : AT(pattern);
145 0 : AT(format);
146 0 : AT(mipmap);
147 0 : AT(normal);
148 0 : AT(alpha);
149 0 : AT(filter);
150 0 : AT(kaiserwidth);
151 0 : AT(kaiseralpha);
152 0 : AT(kaiserstretch);
153 : #undef AT
154 : #undef EL
155 :
156 0 : XMBElement root = XeroFile.GetRoot();
157 :
158 0 : if (root.GetNodeName() != el_textures)
159 : {
160 0 : LOGERROR("Invalid texture settings file \"{}\" (unrecognized root element)", path.string8());
161 0 : return NULL;
162 : }
163 :
164 0 : std::unique_ptr<SettingsFile> settings = std::make_unique<SettingsFile>();
165 :
166 0 : for (XMBElement child : root.GetChildNodes())
167 : {
168 0 : if (child.GetNodeName() == el_file)
169 : {
170 0 : Match p;
171 :
172 0 : for (XMBAttribute attr : child.GetAttributes())
173 : {
174 0 : if (attr.Name == at_pattern)
175 : {
176 0 : p.pattern = attr.Value.FromUTF8();
177 : }
178 0 : else if (attr.Name == at_format)
179 : {
180 0 : CStr v(attr.Value);
181 0 : if (v == "dxt1")
182 0 : p.settings.format = FMT_DXT1;
183 0 : else if (v == "dxt3")
184 0 : p.settings.format = FMT_DXT3;
185 0 : else if (v == "dxt5")
186 0 : p.settings.format = FMT_DXT5;
187 0 : else if (v == "rgba")
188 0 : p.settings.format = FMT_RGBA;
189 0 : else if (v == "alpha")
190 0 : p.settings.format = FMT_ALPHA;
191 : else
192 0 : LOGERROR("Invalid attribute value <file format='{}'>", v);
193 0 : }
194 0 : else if (attr.Name == at_mipmap)
195 : {
196 0 : CStr v(attr.Value);
197 0 : if (v == "true")
198 0 : p.settings.mipmap = MIP_TRUE;
199 0 : else if (v == "false")
200 0 : p.settings.mipmap = MIP_FALSE;
201 : else
202 0 : LOGERROR("Invalid attribute value <file mipmap='{}'>", v);
203 0 : }
204 0 : else if (attr.Name == at_normal)
205 : {
206 0 : CStr v(attr.Value);
207 0 : if (v == "true")
208 0 : p.settings.normal = NORMAL_TRUE;
209 0 : else if (v == "false")
210 0 : p.settings.normal = NORMAL_FALSE;
211 : else
212 0 : LOGERROR("Invalid attribute value <file normal='{}'>", v);
213 0 : }
214 0 : else if (attr.Name == at_alpha)
215 : {
216 0 : CStr v(attr.Value);
217 0 : if (v == "none")
218 0 : p.settings.alpha = ALPHA_NONE;
219 0 : else if (v == "player")
220 0 : p.settings.alpha = ALPHA_PLAYER;
221 0 : else if (v == "transparency")
222 0 : p.settings.alpha = ALPHA_TRANSPARENCY;
223 : else
224 0 : LOGERROR("Invalid attribute value <file alpha='{}'>", v);
225 0 : }
226 0 : else if (attr.Name == at_filter)
227 : {
228 0 : CStr v(attr.Value);
229 0 : if (v == "box")
230 0 : p.settings.filter = FILTER_BOX;
231 0 : else if (v == "triangle")
232 0 : p.settings.filter = FILTER_TRIANGLE;
233 0 : else if (v == "kaiser")
234 0 : p.settings.filter = FILTER_KAISER;
235 : else
236 0 : LOGERROR("Invalid attribute value <file filter='{}'>", v);
237 0 : }
238 0 : else if (attr.Name == at_kaiserwidth)
239 : {
240 0 : p.settings.kaiserWidth = CStr(attr.Value).ToFloat();
241 : }
242 0 : else if (attr.Name == at_kaiseralpha)
243 : {
244 0 : p.settings.kaiserAlpha = CStr(attr.Value).ToFloat();
245 : }
246 0 : else if (attr.Name == at_kaiserstretch)
247 : {
248 0 : p.settings.kaiserStretch = CStr(attr.Value).ToFloat();
249 : }
250 : else
251 : {
252 0 : LOGERROR("Invalid attribute name <file {}='...'>",
253 : XeroFile.GetAttributeString(attr.Name));
254 : }
255 0 : }
256 :
257 0 : settings->patterns.push_back(p);
258 0 : }
259 : }
260 :
261 0 : return settings.release();
262 0 : }
263 :
264 18 : CTextureConverter::Settings CTextureConverter::ComputeSettings(const std::wstring& filename, const std::vector<SettingsFile*>& settingsFiles) const
265 : {
266 : // Set sensible defaults
267 18 : Settings settings;
268 18 : settings.format = FMT_DXT1;
269 18 : settings.mipmap = MIP_TRUE;
270 18 : settings.normal = NORMAL_FALSE;
271 18 : settings.alpha = ALPHA_NONE;
272 18 : settings.filter = FILTER_BOX;
273 18 : settings.kaiserWidth = 3.f;
274 18 : settings.kaiserAlpha = 4.f;
275 18 : settings.kaiserStretch = 1.f;
276 :
277 18 : for (size_t i = 0; i < settingsFiles.size(); ++i)
278 : {
279 0 : for (size_t j = 0; j < settingsFiles[i]->patterns.size(); ++j)
280 : {
281 0 : Match p = settingsFiles[i]->patterns[j];
282 :
283 : // Check that the pattern matches the texture file
284 0 : if (!match_wildcard(filename.c_str(), p.pattern.c_str()))
285 0 : continue;
286 :
287 0 : if (p.settings.format != FMT_UNSPECIFIED)
288 0 : settings.format = p.settings.format;
289 :
290 0 : if (p.settings.mipmap != MIP_UNSPECIFIED)
291 0 : settings.mipmap = p.settings.mipmap;
292 :
293 0 : if (p.settings.normal != NORMAL_UNSPECIFIED)
294 0 : settings.normal = p.settings.normal;
295 :
296 0 : if (p.settings.alpha != ALPHA_UNSPECIFIED)
297 0 : settings.alpha = p.settings.alpha;
298 :
299 0 : if (p.settings.filter != FILTER_UNSPECIFIED)
300 0 : settings.filter = p.settings.filter;
301 :
302 0 : if (p.settings.kaiserWidth != -1.f)
303 0 : settings.kaiserWidth = p.settings.kaiserWidth;
304 :
305 0 : if (p.settings.kaiserAlpha != -1.f)
306 0 : settings.kaiserAlpha = p.settings.kaiserAlpha;
307 :
308 0 : if (p.settings.kaiserStretch != -1.f)
309 0 : settings.kaiserStretch = p.settings.kaiserStretch;
310 0 : }
311 : }
312 :
313 18 : return settings;
314 : }
315 :
316 15 : CTextureConverter::CTextureConverter(PIVFS vfs, bool highQuality) :
317 15 : m_VFS(vfs), m_HighQuality(highQuality)
318 : {
319 : #if CONFIG2_NVTT
320 : // Verify that we are running with at least the version we were compiled with,
321 : // to avoid bugs caused by ABI changes
322 15 : ENSURE(nvtt::version() >= NVTT_VERSION);
323 : #endif // CONFIG2_NVTT
324 15 : }
325 :
326 15 : CTextureConverter::~CTextureConverter() = default;
327 :
328 7 : bool CTextureConverter::ConvertTexture(const CTexturePtr& texture, const VfsPath& src, const VfsPath& dest, const Settings& settings)
329 : {
330 7 : std::shared_ptr<std::uint8_t> file;
331 7 : size_t fileSize;
332 7 : if (m_VFS->LoadFile(src, file, fileSize) < 0)
333 : {
334 0 : LOGERROR("Failed to load texture \"{}\"", src.string8());
335 0 : return false;
336 : }
337 :
338 7 : Tex tex;
339 7 : const Status decodeStatus = tex.decode(file, fileSize);
340 7 : if (decodeStatus != INFO::OK)
341 : {
342 0 : LOGERROR("Failed to decode texture \"{}\" {}", src.string8(),
343 : GetStatusAsString(decodeStatus));
344 0 : return false;
345 : }
346 :
347 7 : if (!std::has_single_bit(tex.m_Width) || !std::has_single_bit(tex.m_Height))
348 : {
349 3 : LOGERROR("Texture to convert \"{}\" should have width and height be power of two: {}x{}",
350 : src.string8(), tex.m_Width, tex.m_Height);
351 1 : return false;
352 : }
353 :
354 : // Check whether there's any alpha channel
355 6 : bool hasAlpha = ((tex.m_Flags & TEX_ALPHA) != 0);
356 :
357 6 : if (settings.format == FMT_ALPHA)
358 : {
359 : // Convert to uncompressed 8-bit with no mipmaps
360 0 : if (tex.transform_to((tex.m_Flags | TEX_GREY) & ~(TEX_DXT | TEX_MIPMAPS | TEX_ALPHA)) < 0)
361 : {
362 0 : LOGERROR("Failed to transform texture \"{}\"", src.string8());
363 0 : return false;
364 : }
365 : }
366 : else
367 : {
368 : // Convert to uncompressed BGRA with no mipmaps
369 6 : if (tex.transform_to((tex.m_Flags | TEX_BGR | TEX_ALPHA) & ~(TEX_DXT | TEX_MIPMAPS)) < 0)
370 : {
371 0 : LOGERROR("Failed to transform texture \"{}\"", src.string8());
372 0 : return false;
373 : }
374 : }
375 :
376 : // Check if the texture has all alpha=255, so we can automatically
377 : // switch from DXT3/DXT5 to DXT1 with no loss
378 6 : if (hasAlpha)
379 : {
380 4 : hasAlpha = false;
381 4 : std::uint8_t* data = tex.get_data();
382 4 : for (size_t i = 0; i < tex.m_Width * tex.m_Height; ++i)
383 : {
384 4 : if (data[i*4+3] != 0xFF)
385 : {
386 : hasAlpha = true;
387 : break;
388 : }
389 : }
390 : }
391 :
392 : #if CONFIG2_NVTT
393 :
394 6 : std::unique_ptr<ConversionRequest> request = std::make_unique<ConversionRequest>();
395 6 : request->dest = dest;
396 6 : request->texture = texture;
397 :
398 : // Apply the chosen settings:
399 :
400 6 : request->inputOptions.setMipmapGeneration(settings.mipmap == MIP_TRUE);
401 :
402 6 : if (settings.alpha == ALPHA_TRANSPARENCY)
403 0 : request->inputOptions.setAlphaMode(nvtt::AlphaMode_Transparency);
404 : else
405 6 : request->inputOptions.setAlphaMode(nvtt::AlphaMode_None);
406 :
407 6 : if (settings.format == FMT_RGBA)
408 : {
409 0 : request->compressionOptions.setFormat(nvtt::Format_RGBA);
410 : // Change the default component order (see tex_dds.cpp decode_pf)
411 0 : request->compressionOptions.setPixelFormat(32, 0xFF, 0xFF00, 0xFF0000, 0xFF000000u);
412 : }
413 6 : else if (settings.format == FMT_ALPHA)
414 : {
415 0 : request->compressionOptions.setFormat(nvtt::Format_RGBA);
416 0 : request->compressionOptions.setPixelFormat(8, 0x00, 0x00, 0x00, 0xFF);
417 : }
418 6 : else if (!hasAlpha)
419 : {
420 : // if no alpha channel then there's no point using DXT3 or DXT5
421 2 : request->compressionOptions.setFormat(nvtt::Format_DXT1);
422 : }
423 4 : else if (settings.format == FMT_DXT1)
424 : {
425 4 : request->compressionOptions.setFormat(nvtt::Format_DXT1a);
426 : }
427 0 : else if (settings.format == FMT_DXT3)
428 : {
429 0 : request->compressionOptions.setFormat(nvtt::Format_DXT3);
430 : }
431 0 : else if (settings.format == FMT_DXT5)
432 : {
433 0 : request->compressionOptions.setFormat(nvtt::Format_DXT5);
434 : }
435 :
436 6 : if (settings.filter == FILTER_BOX)
437 6 : request->inputOptions.setMipmapFilter(nvtt::MipmapFilter_Box);
438 0 : else if (settings.filter == FILTER_TRIANGLE)
439 0 : request->inputOptions.setMipmapFilter(nvtt::MipmapFilter_Triangle);
440 0 : else if (settings.filter == FILTER_KAISER)
441 0 : request->inputOptions.setMipmapFilter(nvtt::MipmapFilter_Kaiser);
442 :
443 6 : if (settings.normal == NORMAL_TRUE)
444 0 : request->inputOptions.setNormalMap(true);
445 :
446 6 : request->inputOptions.setKaiserParameters(settings.kaiserWidth, settings.kaiserAlpha, settings.kaiserStretch);
447 :
448 6 : request->inputOptions.setWrapMode(nvtt::WrapMode_Mirror); // TODO: should this be configurable?
449 :
450 12 : request->compressionOptions.setQuality(m_HighQuality ? nvtt::Quality_Production : nvtt::Quality_Fastest);
451 :
452 : // TODO: normal maps, gamma, etc
453 :
454 : // Load the texture data
455 6 : request->inputOptions.setTextureLayout(nvtt::TextureType_2D, tex.m_Width, tex.m_Height);
456 6 : if (tex.m_Bpp == 32)
457 : {
458 6 : request->inputOptions.setMipmapData(tex.get_data(), tex.m_Width, tex.m_Height);
459 : }
460 : else // bpp == 8
461 : {
462 : // NVTT requires 32-bit input data, so convert
463 0 : const std::uint8_t* input = tex.get_data();
464 0 : std::uint8_t* rgba = new std::uint8_t[tex.m_Width * tex.m_Height * 4];
465 : std::uint8_t* p = rgba;
466 0 : for (size_t i = 0; i < tex.m_Width * tex.m_Height; i++)
467 : {
468 0 : p[0] = p[1] = p[2] = p[3] = *input++;
469 0 : p += 4;
470 : }
471 0 : request->inputOptions.setMipmapData(rgba, tex.m_Width, tex.m_Height);
472 0 : delete[] rgba;
473 : }
474 :
475 24 : m_ResultQueue.push({g_TaskManager, [request = std::move(request)]
476 : {
477 6 : PROFILE2("compress");
478 : // Set up the result object
479 6 : std::unique_ptr<ConversionResult> result = std::make_unique<ConversionResult>();
480 6 : result->dest = request->dest;
481 6 : result->texture = request->texture;
482 :
483 6 : request->outputOptions.setOutputHandler(&result->output);
484 :
485 : // Perform the compression
486 6 : nvtt::Compressor compressor;
487 6 : result->ret = compressor.process(request->inputOptions, request->compressionOptions,
488 6 : request->outputOptions);
489 :
490 12 : return result;
491 12 : }, Threading::TaskPriority::LOW});
492 :
493 6 : return true;
494 :
495 : #else // CONFIG2_NVTT
496 : LOGERROR("Failed to convert texture \"{}\" (NVTT not available)", src.string8());
497 : return false;
498 : #endif // !CONFIG2_NVTT
499 20 : }
500 :
501 13 : bool CTextureConverter::Poll(CTexturePtr& texture, VfsPath& dest, bool& ok)
502 : {
503 : #if CONFIG2_NVTT
504 13 : if (m_ResultQueue.empty() || !m_ResultQueue.front().IsDone())
505 : {
506 : // no work to do
507 7 : return false;
508 : }
509 :
510 6 : std::unique_ptr<ConversionResult> result = m_ResultQueue.front().Get();
511 6 : m_ResultQueue.pop();
512 :
513 6 : if (!result->ret)
514 : {
515 : // conversion had failed
516 0 : ok = false;
517 0 : return true;
518 : }
519 :
520 : // Move output into a correctly-aligned buffer
521 6 : size_t size = result->output.buffer.size();
522 6 : std::shared_ptr<std::uint8_t> file;
523 6 : AllocateAligned(file, size, maxSectorSize);
524 6 : memcpy(file.get(), &result->output.buffer[0], size);
525 6 : if (m_VFS->CreateFile(result->dest, {file.get(), size}) < 0)
526 : {
527 : // error writing file
528 0 : ok = false;
529 0 : return true;
530 : }
531 :
532 : // Succeeded in converting texture
533 6 : texture = result->texture;
534 6 : dest = result->dest;
535 6 : ok = true;
536 6 : return true;
537 :
538 : #else // CONFIG2_NVTT
539 : return false;
540 : #endif // !CONFIG2_NVTT
541 6 : }
542 :
543 6 : bool CTextureConverter::IsBusy() const
544 : {
545 : #if CONFIG2_NVTT
546 6 : return m_ResultQueue.size() >= MAX_QUEUE_SIZE_FOR_OPTIMAL_UTILIZATION;
547 : #else // CONFIG2_NVTT
548 : return false;
549 : #endif // !CONFIG2_NVTT
550 : }
|