Skip to main content

fbsurface/
ops.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Low-level 32-bit pixel primitives.
24//!
25//! [`Canvas`](crate::Canvas) is generic over [`PixelOps`], so a kernel build
26//! monomorphises to the SSE2/AVX2 backend and a host test instantiates
27//! [`ScalarOps`]. There is no `dyn` dispatch on the hot path and no
28//! `alloc`-backed trait object.
29//!
30//! Every public drawing call enters [`PixelOps::guard`] first. The kernel
31//! adapter returns an [`FpuGuard`](../strat9_kernel) that preserves the
32//! caller's SSE state; the scalar backend returns a zero-sized guard. The
33//! invariant therefore lives in the API instead of in the memory of each
34//! caller, which is where it used to live (each `fill_rect` opened with
35//! `let _fpu = FpuGuard::save();` by convention).
36
37/// Marker for the RAII value returned by [`PixelOps::guard`].
38pub trait PixelGuard {}
39
40/// The default no-op guard, used by [`ScalarOps`].
41#[derive(Clone, Copy, Debug, Default)]
42pub struct NoGuard;
43
44impl PixelGuard for NoGuard {}
45
46/// Raw 32-bit pixel operations.
47///
48/// # Safety contract
49///
50/// Implementations may assume, for every method, that:
51///
52/// - `dst` points to `count` writable `u32` values;
53/// - `src` points to `count` readable `u32` values;
54/// - the two ranges do not overlap.
55///
56/// The methods stay `unsafe fn` even though the trait is safe: constructing
57/// a bad implementation is harmless as long as every call site upholds the
58/// contract, and [`Canvas`](crate::Canvas) is the only caller.
59pub trait PixelOps {
60    /// RAII state saved around a drawing call (FPU/SSE registers in the
61    /// kernel, nothing on the host).
62    type Guard: PixelGuard;
63
64    /// Acquire the guard. Kept separate from the operations so the compiler
65    /// can drop it at the end of the drawing call.
66    fn guard(&self) -> Self::Guard;
67
68    /// Fill `count` pixels with `color`.
69    ///
70    /// # Safety
71    /// See the trait-level contract.
72    unsafe fn fill(&self, dst: *mut u32, color: u32, count: usize);
73
74    /// Copy `count` pixels from `src` to `dst`.
75    ///
76    /// # Safety
77    /// See the trait-level contract.
78    unsafe fn blit(&self, dst: *mut u32, src: *const u32, count: usize);
79
80    /// Blend `src` over `dst` with a constant `alpha` (0 = keep dst,
81    /// 255 = take src), channel by channel including the top byte.
82    ///
83    /// # Safety
84    /// See the trait-level contract.
85    unsafe fn blend(&self, dst: *mut u32, src: *const u32, alpha: u8, count: usize);
86
87    /// Non-temporal variant of [`Self::fill`], for write-combining memory.
88    ///
89    /// # Safety
90    /// See the trait-level contract, plus: `dst` must be write-combining
91    /// memory, and the caller must issue a fence before the result is read.
92    unsafe fn fill_nt(&self, dst: *mut u32, color: u32, count: usize);
93
94    /// Non-temporal variant of [`Self::blit`].
95    ///
96    /// # Safety
97    /// See [`Self::fill_nt`].
98    unsafe fn blit_nt(&self, dst: *mut u32, src: *const u32, count: usize);
99}
100
101/// Portable scalar backend. This is the reference implementation used by
102/// host tests; it is also correct on any architecture.
103#[derive(Clone, Copy, Debug, Default)]
104pub struct ScalarOps;
105
106impl PixelOps for ScalarOps {
107    type Guard = NoGuard;
108
109    #[inline]
110    fn guard(&self) -> NoGuard {
111        NoGuard
112    }
113
114    unsafe fn fill(&self, dst: *mut u32, color: u32, count: usize) {
115        for i in 0..count {
116            // Unaligned-safe: a 24 bpp surface may hand us a byte-aligned
117            // base, and a caller-provided buffer is only 1-byte aligned by
118            // type.
119            unsafe { dst.add(i).write_unaligned(color) };
120        }
121    }
122
123    unsafe fn blit(&self, dst: *mut u32, src: *const u32, count: usize) {
124        for i in 0..count {
125            let px = unsafe { src.add(i).read_unaligned() };
126            unsafe { dst.add(i).write_unaligned(px) };
127        }
128    }
129
130    unsafe fn blend(&self, dst: *mut u32, src: *const u32, alpha: u8, count: usize) {
131        let a = alpha as u32;
132        let inv = 255 - a;
133        for i in 0..count {
134            let d = unsafe { dst.add(i).read_unaligned() };
135            let s = unsafe { src.add(i).read_unaligned() };
136            unsafe { dst.add(i).write_unaligned(blend_word(d, s, a, inv)) };
137        }
138    }
139
140    unsafe fn fill_nt(&self, dst: *mut u32, color: u32, count: usize) {
141        unsafe { self.fill(dst, color, count) }
142    }
143
144    unsafe fn blit_nt(&self, dst: *mut u32, src: *const u32, count: usize) {
145        unsafe { self.blit(dst, src, count) }
146    }
147}
148
149/// Blend two packed 32-bit words byte by byte.
150///
151/// `a` is the source weight (`0..=255`), `inv == 255 - a`. The `/255` is
152/// the exact rounding form used by the SSE2 path, so the scalar fallback
153/// and the vector path agree on every byte.
154#[inline]
155pub fn blend_word(d: u32, s: u32, a: u32, inv: u32) -> u32 {
156    let mut out = 0u32;
157    let mut shift = 0;
158    while shift < 32 {
159        let db = (d >> shift) & 0xFF;
160        let sb = (s >> shift) & 0xFF;
161        let x = sb * a + db * inv;
162        let byte = (x + (x >> 8) + 1) >> 8;
163        out |= (byte & 0xFF) << shift;
164        shift += 8;
165    }
166    out
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn fill_and_blit_round_trip() {
175        let mut dst = [0u32; 8];
176        let src = [1u32, 2, 3, 4];
177        unsafe {
178            ScalarOps.fill(dst.as_mut_ptr(), 0xABCD_EF01, 4);
179            assert_eq!(&dst[..4], &[0xABCD_EF01; 4]);
180            ScalarOps.blit(dst.as_mut_ptr(), src.as_ptr(), 4);
181        }
182        assert_eq!(&dst[..4], &src);
183    }
184
185    #[test]
186    fn blend_endpoints_are_exact() {
187        let d = 0x0011_2233;
188        let s = 0xFF44_5566;
189        assert_eq!(blend_word(d, s, 0, 255), d);
190        // alpha 255 gives src, except the rounding of the exact /255 form:
191        // (s*255 + 255) >> 8 is s for every byte.
192        assert_eq!(blend_word(d, s, 255, 0), s);
193    }
194
195    #[test]
196    fn blend_half_way_is_symmetric() {
197        let a = 0;
198        let b = 0xFF;
199        let mid = blend_word(a, b, 127, 128);
200        assert_eq!(mid & 0xFF, 127);
201        let back = blend_word(b, a, 127, 128);
202        assert_eq!(back & 0xFF, 128);
203    }
204
205    #[test]
206    fn blend_never_exceeds_a_byte() {
207        for alpha in 0..=255u32 {
208            let out = blend_word(0xFFFF_FFFF, 0xFFFF_FFFF, alpha, 255 - alpha);
209            assert_eq!(out, 0xFFFF_FFFF);
210        }
211    }
212}