Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : *
3 : * Permission is hereby granted, free of charge, to any person obtaining
4 : * a copy of this software and associated documentation files (the
5 : * "Software"), to deal in the Software without restriction, including
6 : * without limitation the rights to use, copy, modify, merge, publish,
7 : * distribute, sublicense, and/or sell copies of the Software, and to
8 : * permit persons to whom the Software is furnished to do so, subject to
9 : * the following conditions:
10 : *
11 : * The above copyright notice and this permission notice shall be included
12 : * in all copies or substantial portions of the Software.
13 : *
14 : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 : * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 : * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 : * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18 : * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19 : * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20 : * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 : */
22 :
23 : /*
24 : * read/write 2d texture files; allows conversion between pixel formats
25 : * and automatic orientation correction.
26 : */
27 :
28 : /**
29 :
30 : Introduction
31 : ------------
32 :
33 : This module allows reading/writing 2d images in various file formats and
34 : encapsulates them in Tex objects.
35 : It supports converting between pixel formats; this is to an extent done
36 : automatically when reading/writing. Provision is also made for flipping
37 : all images to a default orientation.
38 :
39 :
40 : Format Conversion
41 : -----------------
42 :
43 : Image file formats have major differences in their native pixel format:
44 : some store in BGR order, or have rows arranged bottom-up.
45 : We must balance runtime cost/complexity and convenience for the
46 : application (not dumping the entire problem on its lap).
47 : That means rejecting really obscure formats (e.g. right-to-left pixels),
48 : but converting everything else to uncompressed RGB "plain" format
49 : except where noted in enum TexFlags (1).
50 :
51 : Note: conversion is implemented as a pipeline: e.g. "DDS decompress +
52 : vertical flip" would be done by decompressing to RGB (DDS codec) and then
53 : flipping (generic transform). This is in contrast to all<->all
54 : conversion paths: that would be much more complex, if more efficient.
55 :
56 : Since any kind of preprocessing at runtime is undesirable (the absolute
57 : priority is minimizing load time), prefer file formats that are
58 : close to the final pixel format.
59 :
60 : 1) one of the exceptions is S3TC compressed textures. glCompressedTexImage2D
61 : requires these be passed in their original format; decompressing would be
62 : counterproductive. In this and similar cases, TexFlags indicates such
63 : deviations from the plain format.
64 :
65 :
66 : Default Orientation
67 : -------------------
68 :
69 : After loading, all images (except DDS, because its orientation is
70 : indeterminate) are automatically converted to the global row
71 : orientation: top-down or bottom-up, as specified by
72 : tex_set_global_orientation. If that isn't called, the default is top-down
73 : to match Photoshop's DDS output (since this is meant to be the
74 : no-preprocessing-required optimized format).
75 : Reasons to change it might be to speed up loading bottom-up
76 : BMP or TGA images, or to match OpenGL's convention for convenience;
77 : however, be aware of the abovementioned issues with DDS.
78 :
79 : Rationale: it is not expected that this will happen at the renderer layer
80 : (a 'flip all texcoords' flag is too much trouble), so the
81 : application would have to do the same anyway. By taking care of it here,
82 : we unburden the app and save time, since some codecs (e.g. PNG) can
83 : flip for free when loading.
84 :
85 :
86 : Codecs / IO Implementation
87 : --------------------------
88 :
89 : To ease adding support for new formats, they are organized as codecs.
90 : The interface aims to minimize code duplication, so it's organized
91 : following the principle of "Template Method" - this module both
92 : calls into codecs, and provides helper functions that they use.
93 :
94 : IO is done via VFS, but the codecs are decoupled from this and
95 : work with memory buffers. Access to them is endian-safe.
96 :
97 : When "writing", the image is put into an expandable memory region.
98 : This supports external libraries like libpng that do not know the
99 : output size beforehand, but avoids the need for a buffer between
100 : library and IO layer. Read and write are zero-copy.
101 :
102 : **/
103 :
104 : #ifndef INCLUDED_TEX
105 : #define INCLUDED_TEX
106 :
107 : #include "lib/code_annotation.h"
108 : #include "lib/file/vfs/vfs_path.h"
109 : #include "lib/os_path.h"
110 : #include "lib/status.h"
111 :
112 : #include <cstddef>
113 : #include <memory>
114 : #include <vector>
115 :
116 : struct DynArray;
117 :
118 : namespace ERR
119 : {
120 : const Status TEX_UNKNOWN_FORMAT = -120100;
121 : const Status TEX_INCOMPLETE_HEADER = -120101;
122 : const Status TEX_FMT_INVALID = -120102;
123 : const Status TEX_INVALID_COLOR_TYPE = -120103;
124 : const Status TEX_NOT_8BIT_PRECISION = -120104;
125 : const Status TEX_INVALID_LAYOUT = -120105;
126 : const Status TEX_COMPRESSED = -120106;
127 : const Status TEX_INVALID_SIZE = -120107;
128 : }
129 :
130 : namespace WARN
131 : {
132 : const Status TEX_INVALID_DATA = +120108;
133 : }
134 :
135 : namespace INFO
136 : {
137 : const Status TEX_CODEC_CANNOT_HANDLE = +120109;
138 : }
139 :
140 :
141 : /**
142 : * flags describing the pixel format. these are to be interpreted as
143 : * deviations from "plain" format, i.e. uncompressed RGB.
144 : **/
145 : enum TexFlags
146 : {
147 : /**
148 : * flags & TEX_DXT is a field indicating compression.
149 : * if 0, the texture is uncompressed;
150 : * otherwise, it holds the S3TC type: 1,3,5 or DXT1A.
151 : * not converted by default - glCompressedTexImage2D receives
152 : * the compressed data.
153 : **/
154 : TEX_DXT = 0x7, // mask
155 :
156 : /**
157 : * we need a special value for DXT1a to avoid having to consider
158 : * flags & TEX_ALPHA to determine S3TC type.
159 : * the value is arbitrary; do not rely on it!
160 : **/
161 : DXT1A = 7,
162 :
163 : /**
164 : * indicates B and R pixel components are exchanged. depending on
165 : * flags & TEX_ALPHA or bpp, this means either BGR or BGRA.
166 : * not converted by default - it's an acceptable format for OpenGL.
167 : **/
168 : TEX_BGR = 0x08,
169 :
170 : /**
171 : * indicates the image contains an alpha channel. this is set for
172 : * your convenience - there are many formats containing alpha and
173 : * divining this information from them is hard.
174 : * (conversion is not applicable here)
175 : **/
176 : TEX_ALPHA = 0x10,
177 :
178 : /**
179 : * indicates the image is 8bpp greyscale. this is required to
180 : * differentiate between alpha-only and intensity formats.
181 : * not converted by default - it's an acceptable format for OpenGL.
182 : **/
183 : TEX_GREY = 0x20,
184 :
185 : /**
186 : * flags & TEX_ORIENTATION is a field indicating orientation,
187 : * i.e. in what order the pixel rows are stored.
188 : *
189 : * tex_load always sets this to the global orientation
190 : * (and flips the image accordingly to match).
191 : * texture codecs may in intermediate steps during loading set this
192 : * to 0 if they don't know which way around they are (e.g. DDS),
193 : * or to whatever their file contains.
194 : **/
195 : TEX_BOTTOM_UP = 0x40,
196 : TEX_TOP_DOWN = 0x80,
197 : TEX_ORIENTATION = TEX_BOTTOM_UP|TEX_TOP_DOWN, /// mask
198 :
199 : /**
200 : * indicates the image data includes mipmaps. they are stored from lowest
201 : * to highest (1x1), one after the other.
202 : * (conversion is not applicable here)
203 : **/
204 : TEX_MIPMAPS = 0x100,
205 :
206 : TEX_UNDEFINED_FLAGS = ~0x1FF
207 : };
208 :
209 : /**
210 : * Stores all data describing an image.
211 : * TODO: rename to TextureData.
212 : **/
213 24 : class Tex
214 : {
215 : public:
216 : struct MIPLevel
217 : {
218 : // A pointer to the mip level image data (pixels).
219 : std::uint8_t* data;
220 : std::uint32_t dataSize;
221 : std::uint32_t width;
222 : std::uint32_t height;
223 : };
224 :
225 : /**
226 : * file buffer or image data. note: during the course of transforms
227 : * (which may occur when being loaded), this may be replaced with
228 : * a new buffer (e.g. if decompressing file contents).
229 : **/
230 : std::shared_ptr<std::uint8_t> m_Data;
231 :
232 : size_t m_DataSize;
233 :
234 : /**
235 : * offset to image data in file. this is required since
236 : * tex_get_data needs to return the pixels, but data
237 : * returns the actual file buffer. zero-copy load and
238 : * write-back to file is also made possible.
239 : **/
240 : size_t m_Ofs;
241 :
242 : size_t m_Width;
243 : size_t m_Height;
244 : size_t m_Bpp;
245 :
246 : /// see TexFlags and "Format Conversion" in docs.
247 : size_t m_Flags;
248 :
249 24 : ~Tex()
250 : {
251 24 : free();
252 48 : }
253 :
254 : /**
255 : * Is the texture object valid and self-consistent?
256 : *
257 : * @return Status
258 : **/
259 : Status validate() const;
260 :
261 : /**
262 : * free all resources associated with the image and make further
263 : * use of it impossible.
264 : *
265 : * @return Status
266 : **/
267 : void free();
268 :
269 : /**
270 : * decode an in-memory texture file into texture object.
271 : *
272 : * FYI, currently BMP, TGA, JPG, JP2, PNG, DDS are supported - but don't
273 : * rely on this (not all codecs may be included).
274 : *
275 : * @param data Input data.
276 : * @param data_size Its size [bytes].
277 : * @return Status.
278 : **/
279 : Status decode(const std::shared_ptr<std::uint8_t>& data, size_t data_size);
280 :
281 : /**
282 : * encode a texture into a memory buffer in the desired file format.
283 : *
284 : * @param extension (including '.').
285 : * @param da Output memory array. Allocated here; caller must free it
286 : * when no longer needed. Invalid unless function succeeds.
287 : * @return Status
288 : **/
289 : Status encode(const OsPath& extension, DynArray* da);
290 :
291 : /**
292 : * store the given image data into a Tex object; this will be as if
293 : * it had been loaded via tex_load.
294 : *
295 : * rationale: support for in-memory images is necessary for
296 : * emulation of glCompressedTexImage2D and useful overall.
297 : * however, we don't want to provide an alternate interface for each API;
298 : * these would have to be changed whenever fields are added to Tex.
299 : * instead, provide one entry point for specifying images.
300 : * note: since we do not know how \<img\> was allocated, the caller must free
301 : * it themselves (after calling tex_free, which is required regardless of
302 : * alloc type).
303 : *
304 : * we need only add bookkeeping information and "wrap" it in
305 : * our Tex struct, hence the name.
306 : *
307 : * @param w,h Pixel dimensions.
308 : * @param bpp Bits per pixel.
309 : * @param flags TexFlags.
310 : * @param data Img texture data. note: size is calculated from other params.
311 : * @param ofs
312 : * @return Status
313 : **/
314 : Status wrap(size_t w, size_t h, size_t bpp, size_t flags, const std::shared_ptr<std::uint8_t>& data, size_t ofs);
315 :
316 : //
317 : // modify image
318 : //
319 :
320 : /**
321 : * Change the pixel format.
322 : *
323 : * @param transforms TexFlags that are to be flipped.
324 : * @return Status
325 : **/
326 : Status transform(size_t transforms);
327 :
328 : /**
329 : * Change the pixel format (2nd version)
330 : * (note: this is equivalent to Tex::transform(t, t-\>flags^new_flags).
331 : *
332 : * @param new_flags desired new value of TexFlags.
333 : * @return Status
334 : **/
335 : Status transform_to(size_t new_flags);
336 :
337 : //
338 : // return image information
339 : //
340 :
341 : /**
342 : * return a pointer to the image data (pixels), taking into account any
343 : * header(s) that may come before it.
344 : *
345 : * @return pointer to the data.
346 : **/
347 : std::uint8_t* get_data();
348 :
349 6 : const std::vector<MIPLevel>& GetMIPLevels() const { return m_MIPLevels; }
350 :
351 : /**
352 : * return the ARGB value of the 1x1 mipmap level of the texture.
353 : *
354 : * @return ARGB value (or 0 if texture does not have mipmaps)
355 : **/
356 : std::uint32_t get_average_color() const;
357 :
358 : /**
359 : * return total byte size of the image pixels. (including mipmaps!)
360 : * rationale: this is preferable to calculating manually because it's
361 : * less error-prone (e.g. confusing bits_per_pixel with bytes).
362 : *
363 : * @return size [bytes]
364 : **/
365 : size_t img_size() const;
366 :
367 : private:
368 : void UpdateMIPLevels();
369 :
370 : std::vector<MIPLevel> m_MIPLevels;
371 : };
372 :
373 :
374 : /**
375 : * Set the orientation to which all loaded images will
376 : * automatically be converted (excepting file formats that don't specify
377 : * their orientation, i.e. DDS). See "Default Orientation" in docs.
378 : * @param orientation Either TEX_BOTTOM_UP or TEX_TOP_DOWN.
379 : **/
380 : extern void tex_set_global_orientation(int orientation);
381 :
382 :
383 : /**
384 : * special value for levels_to_skip: the callback will only be called
385 : * for the base mipmap level (i.e. 100%)
386 : **/
387 : const int TEX_BASE_LEVEL_ONLY = -1;
388 :
389 : /**
390 : * callback function for each mipmap level.
391 : *
392 : * @param level number; 0 for base level (i.e. 100%), or the first one
393 : * in case some were skipped.
394 : * @param level_w, level_h pixel dimensions (powers of 2, never 0)
395 : * @param level_data the level's texels
396 : * @param level_data_size [bytes]
397 : * @param cbData passed through from tex_util_foreach_mipmap.
398 : **/
399 : typedef void (*MipmapCB)(size_t level, size_t level_w, size_t level_h,
400 : const std::uint8_t* RESTRICT level_data, size_t level_data_size, void* RESTRICT cbData);
401 :
402 : /**
403 : * for a series of mipmaps stored from base to highest, call back for
404 : * each level.
405 : *
406 : * @param w,h Pixel dimensions.
407 : * @param bpp Bits per pixel.
408 : * @param data Series of mipmaps.
409 : * @param levels_to_skip Number of levels (counting from base) to skip, or
410 : * TEX_BASE_LEVEL_ONLY to only call back for the base image.
411 : * Rationale: this avoids needing to special case for images with or
412 : * without mipmaps.
413 : * @param data_padding Minimum pixel dimensions of mipmap levels.
414 : * This is used in S3TC images, where each level is actually stored in
415 : * 4x4 blocks. usually 1 to indicate levels are consecutive.
416 : * @param cb MipmapCB to call.
417 : * @param cbData Extra data to pass to cb.
418 : **/
419 : extern void tex_util_foreach_mipmap(size_t w, size_t h, size_t bpp, const std::uint8_t* data, int levels_to_skip, size_t data_padding, MipmapCB cb, void* RESTRICT cbData);
420 :
421 :
422 : //
423 : // image writing
424 : //
425 :
426 : /**
427 : * Is the file's extension that of a texture format supported by tex_load?
428 : *
429 : * Rationale: tex_load complains if the given file is of an
430 : * unsupported type. this API allows users to preempt that warning
431 : * (by checking the filename themselves), and also provides for e.g.
432 : * enumerating only images in a file picker.
433 : * an alternative might be a flag to suppress warning about invalid files,
434 : * but this is open to misuse.
435 : *
436 : * @param pathname Only the extension (starting with '.') is used. case-insensitive.
437 : * @return bool
438 : **/
439 : extern bool tex_is_known_extension(const VfsPath& pathname);
440 :
441 : /**
442 : * return the minimum header size (i.e. offset to pixel data) of the
443 : * file format corresponding to the filename.
444 : *
445 : * rationale: this can be used to optimize calls to tex_write: when
446 : * allocating the buffer that will hold the image, allocate this much
447 : * extra and pass the pointer as base+hdr_size. this allows writing the
448 : * header directly into the output buffer and makes for zero-copy IO.
449 : *
450 : * @param filename Filename; only the extension (that after '.') is used.
451 : * case-insensitive.
452 : * @return size [bytes] or 0 on error (i.e. no codec found).
453 : **/
454 : extern size_t tex_hdr_size(const VfsPath& filename);
455 :
456 : #endif // INCLUDED_TEX
|