Pyrogenesis HEAD
Pyrogenesis, a RTS Engine
tex.h
Go to the documentation of this file.
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
30Introduction
31------------
32
33This module allows reading/writing 2d images in various file formats and
34encapsulates them in Tex objects.
35It supports converting between pixel formats; this is to an extent done
36automatically when reading/writing. Provision is also made for flipping
37all images to a default orientation.
38
39
40Format Conversion
41-----------------
42
43Image file formats have major differences in their native pixel format:
44some store in BGR order, or have rows arranged bottom-up.
45We must balance runtime cost/complexity and convenience for the
46application (not dumping the entire problem on its lap).
47That means rejecting really obscure formats (e.g. right-to-left pixels),
48but converting everything else to uncompressed RGB "plain" format
49except where noted in enum TexFlags (1).
50
51Note: conversion is implemented as a pipeline: e.g. "DDS decompress +
52vertical flip" would be done by decompressing to RGB (DDS codec) and then
53flipping (generic transform). This is in contrast to all<->all
54conversion paths: that would be much more complex, if more efficient.
55
56Since any kind of preprocessing at runtime is undesirable (the absolute
57priority is minimizing load time), prefer file formats that are
58close to the final pixel format.
59
601) 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
66Default Orientation
67-------------------
68
69After loading, all images (except DDS, because its orientation is
70indeterminate) are automatically converted to the global row
71orientation: top-down or bottom-up, as specified by
72tex_set_global_orientation. If that isn't called, the default is top-down
73to match Photoshop's DDS output (since this is meant to be the
74no-preprocessing-required optimized format).
75Reasons to change it might be to speed up loading bottom-up
76BMP or TGA images, or to match OpenGL's convention for convenience;
77however, be aware of the abovementioned issues with DDS.
78
79Rationale: it is not expected that this will happen at the renderer layer
80(a 'flip all texcoords' flag is too much trouble), so the
81application would have to do the same anyway. By taking care of it here,
82we unburden the app and save time, since some codecs (e.g. PNG) can
83flip for free when loading.
84
85
86Codecs / IO Implementation
87--------------------------
88
89To ease adding support for new formats, they are organized as codecs.
90The interface aims to minimize code duplication, so it's organized
91following the principle of "Template Method" - this module both
92calls into codecs, and provides helper functions that they use.
93
94IO is done via VFS, but the codecs are decoupled from this and
95work with memory buffers. Access to them is endian-safe.
96
97When "writing", the image is put into an expandable memory region.
98This supports external libraries like libpng that do not know the
99output size beforehand, but avoids the need for a buffer between
100library 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"
109#include "lib/os_path.h"
110#include "lib/status.h"
111
112#include <cstddef>
113#include <memory>
114#include <vector>
115
116struct DynArray;
117
118namespace ERR
119{
120 const Status TEX_UNKNOWN_FORMAT = -120100;
122 const Status TEX_FMT_INVALID = -120102;
125 const Status TEX_INVALID_LAYOUT = -120105;
126 const Status TEX_COMPRESSED = -120106;
127 const Status TEX_INVALID_SIZE = -120107;
128}
129
130namespace WARN
131{
132 const Status TEX_INVALID_DATA = +120108;
133}
134
135namespace INFO
136{
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 **/
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 **/
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
208
209/**
210 * Stores all data describing an image.
211 * TODO: rename to TextureData.
212 **/
213class Tex
214{
215public:
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
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
250 {
251 free();
252 }
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 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
367private:
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 **/
380extern 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 **/
387const 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 **/
399typedef 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 **/
419extern 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 **/
439extern 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 **/
454extern size_t tex_hdr_size(const VfsPath& filename);
455
456#endif // INCLUDED_TEX
Definition: path.h:84
Stores all data describing an image.
Definition: tex.h:214
const std::vector< MIPLevel > & GetMIPLevels() const
Definition: tex.h:349
std::shared_ptr< std::uint8_t > m_Data
file buffer or image data.
Definition: tex.h:230
size_t m_DataSize
Definition: tex.h:232
size_t m_Flags
see TexFlags and "Format Conversion" in docs.
Definition: tex.h:247
size_t m_Height
Definition: tex.h:243
Status validate() const
Is the texture object valid and self-consistent?
Definition: tex.cpp:60
size_t img_size() const
return total byte size of the image pixels.
Definition: tex.cpp:681
Status encode(const OsPath &extension, DynArray *da)
encode a texture into a memory buffer in the desired file format.
Definition: tex.cpp:750
std::uint32_t get_average_color() const
return the ARGB value of the 1x1 mipmap level of the texture.
Definition: tex.cpp:636
std::uint8_t * get_data()
return a pointer to the image data (pixels), taking into account any header(s) that may come before i...
Definition: tex.cpp:624
Status decode(const std::shared_ptr< std::uint8_t > &data, size_t data_size)
decode an in-memory texture file into texture object.
Definition: tex.cpp:715
Status transform_to(size_t new_flags)
Change the pixel format (2nd version) (note: this is equivalent to Tex::transform(t,...
Definition: tex.cpp:487
size_t m_Ofs
offset to image data in file.
Definition: tex.h:240
std::vector< MIPLevel > m_MIPLevels
Definition: tex.h:370
~Tex()
Definition: tex.h:249
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)
store the given image data into a Tex object; this will be as if it had been loaded via tex_load.
Definition: tex.cpp:586
void UpdateMIPLevels()
Definition: tex.cpp:777
Status transform(size_t transforms)
Change the pixel format.
Definition: tex.cpp:459
size_t m_Width
Definition: tex.h:242
size_t m_Bpp
Definition: tex.h:244
void free()
free all resources associated with the image and make further use of it impossible.
Definition: tex.cpp:607
#define RESTRICT
Definition: code_annotation.h:267
Definition: debug.h:340
const Status TEX_NOT_8BIT_PRECISION
Definition: tex.h:124
const Status TEX_INVALID_LAYOUT
Definition: tex.h:125
const Status TEX_INVALID_SIZE
Definition: tex.h:127
const Status TEX_UNKNOWN_FORMAT
Definition: tex.h:120
const Status TEX_INVALID_COLOR_TYPE
Definition: tex.h:123
const Status TEX_COMPRESSED
Definition: tex.h:126
const Status TEX_INCOMPLETE_HEADER
Definition: tex.h:121
const Status TEX_FMT_INVALID
Definition: tex.h:122
Definition: debug.h:356
const Status TEX_CODEC_CANNOT_HANDLE
Definition: tex.h:137
Definition: tex.h:131
const Status TEX_INVALID_DATA
Definition: tex.h:132
std::int64_t Status
Error handling system.
Definition: status.h:174
provides a memory range that can be expanded but doesn't waste physical memory or relocate itself.
Definition: dynarray.h:42
Definition: tex.h:217
std::uint32_t height
Definition: tex.h:222
std::uint8_t * data
Definition: tex.h:219
std::uint32_t dataSize
Definition: tex.h:220
std::uint32_t width
Definition: tex.h:221
bool tex_is_known_extension(const VfsPath &pathname)
Is the file's extension that of a texture format supported by tex_load?
Definition: tex.cpp:563
void tex_set_global_orientation(int orientation)
Set the orientation to which all loaded images will automatically be converted (excepting file format...
Definition: tex.cpp:506
TexFlags
flags describing the pixel format.
Definition: tex.h:146
@ TEX_BGR
indicates B and R pixel components are exchanged.
Definition: tex.h:168
@ TEX_ORIENTATION
Definition: tex.h:197
@ TEX_GREY
indicates the image is 8bpp greyscale.
Definition: tex.h:183
@ TEX_MIPMAPS
mask
Definition: tex.h:204
@ TEX_BOTTOM_UP
flags & TEX_ORIENTATION is a field indicating orientation, i.e.
Definition: tex.h:195
@ TEX_UNDEFINED_FLAGS
Definition: tex.h:206
@ TEX_ALPHA
indicates the image contains an alpha channel.
Definition: tex.h:176
@ DXT1A
we need a special value for DXT1a to avoid having to consider flags & TEX_ALPHA to determine S3TC typ...
Definition: tex.h:161
@ TEX_TOP_DOWN
Definition: tex.h:196
@ TEX_DXT
flags & TEX_DXT is a field indicating compression.
Definition: tex.h:154
const int TEX_BASE_LEVEL_ONLY
special value for levels_to_skip: the callback will only be called for the base mipmap level (i....
Definition: tex.h:387
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)
for a series of mipmaps stored from base to highest, call back for each level.
Definition: tex.cpp:131
size_t tex_hdr_size(const VfsPath &filename)
return the minimum header size (i.e.
Definition: tex.cpp:701
void(* MipmapCB)(size_t level, size_t level_w, size_t level_h, const std::uint8_t *RESTRICT level_data, size_t level_data_size, void *RESTRICT cbData)
callback function for each mipmap level.
Definition: tex.h:399