Skip to main content

dear_imgui_rs/texture/
format.rs

1use crate::sys;
2
3pub(super) fn texture_format_bytes_per_pixel(format: TextureFormat) -> usize {
4    match format {
5        TextureFormat::RGBA32 => 4,
6        TextureFormat::Alpha8 => 1,
7    }
8}
9
10pub(super) fn texture_format_bytes_per_pixel_i32(format: TextureFormat) -> i32 {
11    i32::try_from(texture_format_bytes_per_pixel(format))
12        .expect("texture format bytes per pixel exceeded i32 range")
13}
14
15/// Texture format supported by Dear ImGui
16#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
17#[repr(i32)]
18pub enum TextureFormat {
19    /// 4 components per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight * 4
20    RGBA32 = sys::ImTextureFormat_RGBA32 as i32,
21    /// 1 component per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight
22    Alpha8 = sys::ImTextureFormat_Alpha8 as i32,
23}
24
25impl From<sys::ImTextureFormat> for TextureFormat {
26    fn from(format: sys::ImTextureFormat) -> Self {
27        match format {
28            sys::ImTextureFormat_RGBA32 => TextureFormat::RGBA32,
29            sys::ImTextureFormat_Alpha8 => TextureFormat::Alpha8,
30            _ => TextureFormat::RGBA32, // Default fallback
31        }
32    }
33}
34
35impl From<TextureFormat> for sys::ImTextureFormat {
36    fn from(format: TextureFormat) -> Self {
37        format as sys::ImTextureFormat
38    }
39}
40
41/// Get the number of bytes per pixel for a texture format
42pub fn get_format_bytes_per_pixel(format: TextureFormat) -> usize {
43    texture_format_bytes_per_pixel(format)
44}
45
46/// Get the name of a texture format (for debugging)
47pub fn get_format_name(format: TextureFormat) -> &'static str {
48    unsafe {
49        let ptr = sys::igImTextureDataGetFormatName(format.into());
50        if ptr.is_null() {
51            "Unknown"
52        } else {
53            std::ffi::CStr::from_ptr(ptr).to_str().unwrap_or("Invalid")
54        }
55    }
56}