Skip to main content

cotis_wgpu/
color.rs

1//! Color conversion between cotis and wgpu representations.
2//!
3//! Cotis [`cotis_defaults::colors::Color`] stores each channel as `f32` in the `0..=255`
4//! range. This module normalizes channels to `0.0..=1.0` for GPU use.
5//!
6//! **Alpha handling differs by consumer:**
7//!
8//! - [`cotis_color_to_ui_color`] — RGB only; used by the UI geometry pipeline, which forces
9//!   opaque fragments in the WGSL shader.
10//! - [`cotis_color_to_wgpu`] — full RGBA; suitable for swapchain clear colors and
11//!   [`crate::renderer::CotisWgpuRenderer::set_background`].
12//! - Text rendering converts cotis colors to glyphon `Color` with rounded `u8` channels,
13//!   preserving alpha.
14
15use cotis_defaults::colors::Color;
16
17use crate::pipeline::UIColor;
18
19/// Converts a cotis RGBA color (0..255 per channel) into normalized GPU color components.
20///
21/// Alpha is omitted because the UI geometry shader outputs opaque fragments.
22///
23/// # Examples
24///
25/// ```
26/// use cotis_defaults::colors::Color;
27/// use cotis_wgpu::color::cotis_color_to_ui_color;
28///
29/// let ui = cotis_color_to_ui_color(Color::rgba(255.0, 255.0, 255.0, 255.0));
30/// assert!((ui.r - 1.0).abs() < f32::EPSILON);
31/// assert!((ui.g - 1.0).abs() < f32::EPSILON);
32/// assert!((ui.b - 1.0).abs() < f32::EPSILON);
33/// ```
34pub fn cotis_color_to_ui_color(color: Color) -> UIColor {
35    UIColor {
36        r: color.r / 255.0,
37        g: color.g / 255.0,
38        b: color.b / 255.0,
39    }
40}
41
42/// Converts a cotis RGBA color into a wgpu clear/present color (0.0..=1.0 per channel).
43///
44/// Use this when setting the swapchain background via
45/// [`crate::renderer::CotisWgpuRenderer::set_background`] or during renderer construction.
46pub fn cotis_color_to_wgpu(color: Color) -> wgpu::Color {
47    wgpu::Color {
48        r: (color.r / 255.0) as f64,
49        g: (color.g / 255.0) as f64,
50        b: (color.b / 255.0) as f64,
51        a: (color.a / 255.0) as f64,
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn converts_cotis_white_to_unit_rgb() {
61        let ui = cotis_color_to_ui_color(Color::rgba(255.0, 255.0, 255.0, 255.0));
62        assert!((ui.r - 1.0).abs() < f32::EPSILON);
63        assert!((ui.g - 1.0).abs() < f32::EPSILON);
64        assert!((ui.b - 1.0).abs() < f32::EPSILON);
65    }
66}