Skip to content

Commit 80cdb1b

Browse files
authored
Add example of converting alpha mode in place before presenting (#362)
1 parent 92cd76a commit 80cdb1b

1 file changed

Lines changed: 45 additions & 1 deletion

File tree

src/lib.rs

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -481,7 +481,7 @@ impl Buffer<'_> {
481481
/// }
482482
/// }
483483
///
484-
/// buffer.present();
484+
/// buffer.present().unwrap();
485485
/// ```
486486
#[inline]
487487
pub fn data_u8(&mut self) -> &mut [u8] {
@@ -698,6 +698,50 @@ pub enum AlphaMode {
698698
///
699699
/// - Android, macOS/iOS, DRM/KMS, Orbital, Wayland, Windows, X11: Supported.
700700
/// - Web: Cannot be supported in a zero-copy manner.
701+
///
702+
/// # Example
703+
///
704+
/// Write to the buffer as-if it had [`AlphaMode::Ignored`], and convert afterwards if
705+
/// necessary (in case the buffer only supports `AlphaMode::Opaque`).
706+
///
707+
/// ```no_run
708+
/// use softbuffer::{AlphaMode, Pixel};
709+
///
710+
/// # let surface: softbuffer::Surface<
711+
/// # std::sync::Arc<dyn raw_window_handle::HasDisplayHandle>,
712+
/// # std::sync::Arc<dyn raw_window_handle::HasWindowHandle>,
713+
/// # > = todo!();
714+
/// # let width = std::num::NonZero::new(1).unwrap();
715+
/// # let height = std::num::NonZero::new(1).unwrap();
716+
///
717+
/// // At startup:
718+
/// if surface.supports_alpha_mode(AlphaMode::Ignored) {
719+
/// surface.configure(width, height, AlphaMode::Ignored).unwrap();
720+
/// } else {
721+
/// surface.configure(width, height, AlphaMode::Opaque).unwrap();
722+
/// }
723+
///
724+
/// // Each draw:
725+
/// let buffer = surface.next_buffer().unwrap();
726+
///
727+
/// for row in buffer.pixel_rows() {
728+
/// for pixel in row {
729+
/// // Write red pixels with an arbitrary alpha value.
730+
/// *pixel = Pixel::new_rgba(0xff, 0x00, 0x00, 0x7f);
731+
/// }
732+
/// }
733+
///
734+
/// // Convert the alpha mode of the buffer in place.
735+
/// if buffer.alpha_mode() == AlphaMode::Opaque {
736+
/// for pixel in buffer.pixels() {
737+
/// // TODO: SIMD-optimize this somehow? Or maybe autovectorization is good enough?
738+
/// pixel.a = 0xff;
739+
/// }
740+
/// }
741+
///
742+
/// // Alpha value is ignored, either by compositor or by us above.
743+
/// buffer.present().unwrap();
744+
/// ```
701745
Ignored,
702746
/// The non-alpha channels are expected to already have been multiplied by the alpha channel.
703747
///

0 commit comments

Comments
 (0)