-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathformat.rs
More file actions
91 lines (80 loc) · 2.64 KB
/
format.rs
File metadata and controls
91 lines (80 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use crate::{Format, Rect, SoftBufferError};
use std::num::NonZeroU32;
pub struct ConvertFormat {
buffer: Vec<u32>,
buffer_presented: bool,
size: Option<(NonZeroU32, NonZeroU32)>,
in_fmt: Format,
out_fmt: Format,
}
impl ConvertFormat {
pub fn new(in_fmt: Format, out_fmt: Format) -> Result<Self, SoftBufferError> {
// TODO select out_fmt from native_formats?
Ok(Self {
buffer: Vec::new(),
buffer_presented: false,
size: None,
in_fmt,
out_fmt,
})
}
pub fn pixels(&self) -> &[u32] {
&self.buffer
}
pub fn pixels_mut(&mut self) -> &mut [u32] {
&mut self.buffer
}
pub fn resize(&mut self, width: NonZeroU32, height: NonZeroU32) {
if self.size == Some((width, height)) {
return;
}
self.size = Some((width, height));
self.buffer_presented = false;
self.buffer
.resize((u32::from(width) * u32::from(height)) as usize, 0);
}
pub fn age(&self) -> u8 {
if self.buffer_presented {
1
} else {
0
}
}
// Can only damage be copied? Need to track damage for multiple buffers? if backend uses
pub fn present(&self, outputs: &mut [u32], damage: &[Rect]) {
assert_eq!(outputs.len(), self.buffer.len());
convert_format(self.in_fmt, &self.buffer, self.out_fmt, outputs);
self.buffer_presented;
}
}
fn convert_pixels<F: FnMut([u8; 4]) -> [u8; 4]>(inputs: &[u32], outputs: &mut [u32], mut cb: F) {
for (input, output) in inputs.iter().zip(outputs.iter_mut()) {
*output = u32::from_ne_bytes(cb(input.to_ne_bytes()));
}
}
// Convert between BGR* and RGB*
#[inline(always)]
fn swap_rb(mut bytes: [u8; 4]) -> [u8; 4] {
bytes.swap(0, 2);
bytes
}
// Convert ***X to ***A format by setting alpha to 255
#[inline(always)]
fn set_opaque(mut bytes: [u8; 4]) -> [u8; 4] {
bytes[3] = 255;
bytes
}
fn convert_format(in_fmt: Format, inputs: &[u32], out_fmt: Format, outputs: &mut [u32]) {
use Format::*;
match (in_fmt, out_fmt) {
(RGBA, RGBA) | (RGBX, RGBX) | (BGRA, BGRA) | (BGRX, BGRX) => {
outputs.copy_from_slice(inputs)
}
(RGBX, RGBA) | (BGRX, BGRA) => convert_pixels(inputs, outputs, set_opaque),
(RGBX, BGRX) | (RGBA, BGRA) | (BGRX, RGBX) | (BGRA, RGBA) => {
convert_pixels(inputs, outputs, swap_rb)
}
(RGBX, BGRA) | (BGRX, RGBA) => convert_pixels(inputs, outputs, |x| set_opaque(swap_rb(x))),
(RGBA | BGRA, RGBX | BGRX) => unimplemented!("can't convert alpha to non-alpha format"),
}
}