Skip to main content

sui_render_wgpu/
text_policy.rs

1use sui_core::Color;
2
3#[derive(Debug, Clone, Copy, PartialEq)]
4pub struct FeatheringOptions {
5    pub enabled: bool,
6    pub width: f32,
7}
8
9impl Default for FeatheringOptions {
10    fn default() -> Self {
11        Self::new(false, crate::resources::DEFAULT_FEATHER_WIDTH)
12    }
13}
14
15impl FeatheringOptions {
16    pub const fn new(enabled: bool, width: f32) -> Self {
17        Self { enabled, width }
18    }
19
20    pub fn clamped(self) -> Self {
21        Self {
22            enabled: self.enabled,
23            width: self.width.max(0.0),
24        }
25    }
26
27    pub fn effective_width(self) -> f32 {
28        if self.enabled {
29            self.width.max(0.0)
30        } else {
31            0.0
32        }
33    }
34}
35
36pub use sui_scene::TextRenderMode;
37
38/// The renderer's name for [`sui_scene::TextRenderHinting`].
39pub type TextHinting = sui_scene::TextRenderHinting;
40
41/// The renderer's name for [`sui_scene::TextRenderStemDarkening`].
42pub type StemDarkening = sui_scene::TextRenderStemDarkening;
43
44// Share platform calibration between CPU policy evaluation and both shaders.
45macro_rules! text_coverage_parameters {
46    ($gamma:literal, $contrast:literal) => {
47        const PERCEPTUAL_GAMMA: f32 = $gamma;
48        const PERCEPTUAL_CONTRAST: f32 = $contrast;
49        macro_rules! text_coverage_shader_parameters {
50            () => {
51                concat!(
52                    "const TEXT_PERCEPTUAL_GAMMA: f32 = ",
53                    stringify!($gamma),
54                    ";\n",
55                    "const TEXT_PERCEPTUAL_CONTRAST: f32 = ",
56                    stringify!($contrast),
57                    ";\n",
58                )
59            };
60        }
61        pub(crate) use text_coverage_shader_parameters;
62    };
63}
64
65#[cfg(target_os = "linux")]
66text_coverage_parameters!(1.4, 0.5);
67#[cfg(target_os = "android")]
68text_coverage_parameters!(1.4, 0.0);
69#[cfg(not(any(target_os = "linux", target_os = "android")))]
70text_coverage_parameters!(1.8, 0.5);
71
72#[derive(Debug, Clone, Copy, PartialEq, Default)]
73pub enum TextCoveragePolicy {
74    #[default]
75    Perceptual,
76    /// Resolved luminances for the perceptual curve. Prefer `Perceptual` to
77    /// let the renderer resolve these from the text and its solid backdrop.
78    PerceptualLuminance {
79        text: f32,
80        background: f32,
81    },
82    Linear,
83    Gamma(f32),
84    CoverageBoost(f32),
85    TwoCoverageMinusCoverageSq,
86}
87
88impl TextCoveragePolicy {
89    pub fn normalized(self) -> Self {
90        match self {
91            Self::Perceptual => Self::Perceptual,
92            Self::PerceptualLuminance { text, background }
93                if text.is_finite() && background.is_finite() =>
94            {
95                Self::PerceptualLuminance {
96                    text: text.clamp(0.0, 1.0),
97                    background: background.clamp(0.0, 1.0),
98                }
99            }
100            Self::PerceptualLuminance { .. } => Self::Linear,
101            Self::Linear => Self::Linear,
102            Self::Gamma(gamma) if gamma.is_finite() && gamma > 0.0 => Self::Gamma(gamma),
103            Self::Gamma(_) => Self::Linear,
104            Self::CoverageBoost(amount) if amount.is_finite() && amount > 0.0 => {
105                Self::CoverageBoost(amount.clamp(0.0, 1.0))
106            }
107            Self::CoverageBoost(_) => Self::Linear,
108            Self::TwoCoverageMinusCoverageSq => Self::TwoCoverageMinusCoverageSq,
109        }
110    }
111
112    pub fn resolved_for_text_color(self, color: Color) -> Self {
113        self.resolved_for_text_background(color, None)
114    }
115
116    pub(crate) fn resolved_for_text_background(
117        self,
118        color: Color,
119        background: Option<Color>,
120    ) -> Self {
121        match self.normalized() {
122            Self::Perceptual => {
123                if !is_sdr_color(color) || background.is_some_and(|c| !is_sdr_color(c)) {
124                    return Self::Linear;
125                }
126                let text = encoded_srgb_luminance(color);
127                Self::PerceptualLuminance {
128                    text,
129                    background: background.map(encoded_srgb_luminance).unwrap_or(1.0 - text),
130                }
131            }
132            policy => policy,
133        }
134    }
135
136    pub fn apply(self, coverage: f32) -> f32 {
137        let coverage = coverage.clamp(0.0, 1.0);
138        match self.normalized() {
139            Self::Perceptual => perceptual_text_coverage(coverage, 0.0, 1.0),
140            Self::PerceptualLuminance { text, background } => {
141                perceptual_text_coverage(coverage, text, background)
142            }
143            Self::Linear => coverage,
144            Self::Gamma(gamma) => coverage.powf(gamma),
145            Self::CoverageBoost(amount) => apply_coverage_boost(coverage, amount),
146            Self::TwoCoverageMinusCoverageSq => (2.0 * coverage) - (coverage * coverage),
147        }
148    }
149}
150
151pub(crate) fn is_sdr_color(color: Color) -> bool {
152    let c = color.to_linear_srgb();
153    [c.red, c.green, c.blue]
154        .iter()
155        .all(|v| v.is_finite() && (0.0..=1.0).contains(v))
156}
157
158/// Contrast/gamma compensation modeled on Skia's mask-gamma construction,
159/// converted back to coverage for our linear-light framebuffer. The platform
160/// perceptual exponent is independent of the framebuffer transfer function.
161/// Endpoint preservation also keeps glyph padding transparent.
162pub(crate) fn perceptual_text_coverage(coverage: f32, text: f32, background: f32) -> f32 {
163    let c = coverage.clamp(0.0, 1.0);
164    if c == 0.0 || c == 1.0 {
165        return c;
166    }
167    let gamma = PERCEPTUAL_GAMMA;
168    let a = apply_coverage_boost(c, PERCEPTUAL_CONTRAST * background.powf(gamma));
169    let fg = encoded_srgb_to_linear_unit(text);
170    let bg = encoded_srgb_to_linear_unit(background);
171    if (fg - bg).abs() < 1e-4 {
172        return a;
173    }
174    let perceptual = (text.powf(gamma) * a + background.powf(gamma) * (1.0 - a)).powf(1.0 / gamma);
175    ((encoded_srgb_to_linear_unit(perceptual) - bg) / (fg - bg)).clamp(0.0, 1.0)
176}
177
178fn encoded_srgb_to_linear_unit(value: f32) -> f32 {
179    if value <= 0.04045 {
180        value / 12.92
181    } else {
182        ((value + 0.055) / 1.055).powf(2.4)
183    }
184}
185
186/// Chrome/Skia's per-channel sRGB mask correction, followed by conversion of
187/// the resulting encoded-space composite into coverage for our linear target.
188/// Uses the Windows reference contrast of 1.0. This is LCD-only; the portable
189/// grayscale policy keeps its separately calibrated luminance curve.
190#[cfg(test)]
191pub(crate) fn lcd_text_coverage(coverage: f32, text: f32, background: f32) -> f32 {
192    let c = coverage.clamp(0.0, 1.0);
193    if c == 0.0 || c == 1.0 {
194        return c;
195    }
196    let guessed_bg = 1.0 - text;
197    let guessed_linear = encoded_srgb_to_linear_unit(guessed_bg);
198    let foreground_linear = encoded_srgb_to_linear_unit(text);
199    let a = apply_coverage_boost(c, guessed_linear);
200    let encoded_alpha = if (text - guessed_bg).abs() < 1.0 / 256.0 {
201        a
202    } else {
203        (linear_srgb_to_encoded_unit(foreground_linear * a + guessed_linear * (1.0 - a))
204            - guessed_bg)
205            / (text - guessed_bg)
206    }
207    .clamp(0.0, 1.0);
208    let bg = encoded_srgb_to_linear_unit(background);
209    if (foreground_linear - bg).abs() < 1e-4 {
210        return c;
211    }
212    let desired = encoded_srgb_to_linear_unit(background + (text - background) * encoded_alpha);
213    ((desired - bg) / (foreground_linear - bg)).clamp(0.0, 1.0)
214}
215
216pub(crate) fn pack_lcd_background(color: Color) -> f32 {
217    let c = color.to_linear_srgb();
218    let [r, g, b] =
219        [c.red, c.green, c.blue].map(|v| (linear_srgb_to_encoded_unit(v) * 255.0).round() as u32);
220    // Exactly representable as an f32 integer and interpolated flat.
221    ((r << 16) | (g << 8) | b) as f32
222}
223
224pub(crate) fn apply_coverage_boost(coverage: f32, amount: f32) -> f32 {
225    coverage + (coverage * (1.0 - coverage) * amount.clamp(0.0, 1.0))
226}
227
228pub(crate) fn encoded_srgb_luminance(color: Color) -> f32 {
229    let linear = color.to_linear_srgb();
230    let red = linear_srgb_to_encoded_unit(linear.red);
231    let green = linear_srgb_to_encoded_unit(linear.green);
232    let blue = linear_srgb_to_encoded_unit(linear.blue);
233    ((0.2126 * red) + (0.7152 * green) + (0.0722 * blue)).clamp(0.0, 1.0)
234}
235
236pub(crate) fn linear_srgb_to_encoded_unit(channel: f32) -> f32 {
237    let value = channel.clamp(0.0, 1.0);
238    if value <= 0.003_130_8 {
239        value * 12.92
240    } else {
241        (1.055 * value.powf(1.0 / 2.4)) - 0.055
242    }
243}
244
245/// The render mode and subpixel order a window renders text with.
246///
247/// `system_order` is the subpixel order the system antialiases text for on
248/// the window's display, or `None` when the window does not follow the
249/// system. A system that requests RGB/BGR smoothing turns on LCD text at every
250/// scale; an explicit RGB/BGR `order` still chooses the channel order.
251/// Otherwise the configured mode and order stand, so an order alone still does
252/// not select LCD mode.
253pub(crate) fn resolve_window_text_mode(
254    mode: TextRenderMode,
255    order: sui_scene::TextSubpixelOrder,
256    system_order: Option<sui_scene::TextSubpixelOrder>,
257) -> (TextRenderMode, sui_scene::TextSubpixelOrder) {
258    use sui_scene::TextSubpixelOrder;
259    let system_lcd = system_order.filter(|order| *order != TextSubpixelOrder::None);
260    match system_lcd {
261        Some(system) if mode == TextRenderMode::Grayscale => {
262            let order = if order == TextSubpixelOrder::None {
263                system
264            } else {
265                order
266            };
267            (TextRenderMode::LcdSubpixel, order)
268        }
269        _ => (mode, order),
270    }
271}