Struct pixels::Pixels

source ·
pub struct Pixels { /* private fields */ }
Expand description

Represents a 2D pixel buffer with an explicit image resolution.

See PixelsBuilder for building a customized pixel buffer.

Implementations§

source§

impl Pixels

source

pub fn new<W: HasRawWindowHandle + HasRawDisplayHandle>( width: u32, height: u32, surface_texture: SurfaceTexture<'_, W> ) -> Result<Self, Error>

Create a pixel buffer instance with default options.

Any ratio differences between the pixel buffer texture size and surface texture size will result in a border being added around the pixel buffer texture to maintain an integer scaling ratio.

For instance, a pixel buffer with 320x240 can be scaled to a surface texture with sizes 320x240, 640x480, 960x720, etc. without adding a border because these are exactly 1x, 2x, and 3x scales, respectively.

This method blocks the current thread, making it unusable on Web targets. Use Pixels::new_async for a non-blocking alternative.

Examples
let mut pixels = Pixels::new(320, 240, surface_texture)?;
Errors

Returns an error when a wgpu::Adapter cannot be found.

Panics

Panics when width or height are 0.

source

pub async fn new_async<W: HasRawWindowHandle + HasRawDisplayHandle>( width: u32, height: u32, surface_texture: SurfaceTexture<'_, W> ) -> Result<Self, Error>

Asynchronously create a pixel buffer instance with default options.

See Pixels::new for more information.

Examples
let mut pixels = Pixels::new_async(320, 240, surface_texture).await?;
Errors

Returns an error when a wgpu::Adapter cannot be found.

Panics

Panics when width or height are 0.

source

pub fn clear_color(&mut self, color: Color)

Change the clear color.

Allows customization of the background color and the border drawn for non-integer scale values.

use pixels::wgpu::Color;

let mut pixels = Pixels::new(320, 240, surface_texture)?;

// Set clear color to red.
pixels.clear_color(Color::RED);
source

pub fn adapter(&self) -> &Adapter

Returns a reference of the wgpu adapter used by the crate.

The adapter can be used to retrieve runtime information about the host system or the WGPU backend.

let mut pixels = Pixels::new(320, 240, surface_texture)?;
let adapter = pixels.adapter();
// Do something with the adapter.
source

pub fn resize_buffer( &mut self, width: u32, height: u32 ) -> Result<(), TextureError>

Resize the pixel buffer and zero its contents.

This does not resize the surface upon which the pixel buffer texture is rendered. Use Pixels::resize_surface to change the size of the surface texture.

The pixel buffer will be fit onto the surface texture as best as possible by scaling to the nearest integer, e.g. 2x, 3x, 4x, etc. A border will be added around the pixel buffer texture for non-integer scaling ratios.

Call this method to change the virtual screen resolution. E.g. when you want your pixel buffer to be resized from 640x480 to 800x600.

Errors
source

pub fn resize_surface( &mut self, width: u32, height: u32 ) -> Result<(), TextureError>

Resize the surface upon which the pixel buffer texture is rendered.

This does not resize the pixel buffer. Use Pixels::resize_buffer to change the size of the pixel buffer.

The pixel buffer texture will be fit onto the surface texture as best as possible by scaling to the nearest integer, e.g. 2x, 3x, 4x, etc. A border will be added around the pixel buffer texture for non-integer scaling ratios.

Call this method in response to a resize event from your window manager. The size expected is in physical pixel units. Does nothing when width or height are 0.

Errors
source

pub fn render(&self) -> Result<(), Error>

Draw this pixel buffer to the configured SurfaceTexture.

Errors

Returns an error when wgpu::Surface::get_current_texture fails.

Example
let mut pixels = Pixels::new(320, 240, surface_texture)?;

// Clear the pixel buffer
let frame = pixels.frame_mut();
for pixel in frame.chunks_exact_mut(4) {
    pixel[0] = 0x00; // R
    pixel[1] = 0x00; // G
    pixel[2] = 0x00; // B
    pixel[3] = 0xff; // A
}

// Draw it to the `SurfaceTexture`
pixels.render()?;
source

pub fn render_with<F>(&self, render_function: F) -> Result<(), Error>where F: FnOnce(&mut CommandEncoder, &TextureView, &PixelsContext) -> Result<(), Box<dyn Error + Send + Sync + 'static>>,

Draw this pixel buffer to the configured SurfaceTexture using a custom user-provided render function.

Provides access to a wgpu::CommandEncoder, a wgpu::TextureView from the surface which you can use to render to the screen, and a PixelsContext with all of the internal wgpu context.

The render function must return a Result. This allows fallible render functions to be handled gracefully. The boxed Error will be made available in the Error::UserDefined variant returned by render_with().

Errors

Returns an error when either wgpu::Surface::get_current_texture or the provided render function fails.

Example
let mut pixels = Pixels::new(320, 240, surface_texture)?;

// Clear the pixel buffer
let frame = pixels.frame_mut();
for pixel in frame.chunks_exact_mut(4) {
    pixel[0] = 0x00; // R
    pixel[1] = 0x00; // G
    pixel[2] = 0x00; // B
    pixel[3] = 0xff; // A
}

// Draw it to the `SurfaceTexture`
pixels.render_with(|encoder, render_target, context| {
    context.scaling_renderer.render(encoder, render_target);
    // etc...
    Ok(())
})?;
source

pub fn frame_mut(&mut self) -> &mut [u8]

Get a mutable byte slice for the pixel buffer. The buffer is not cleared for you; it will retain the previous frame’s contents until you clear it yourself.

source

pub fn frame(&self) -> &[u8]

Get an immutable byte slice for the pixel buffer.

This may be useful for operations that must sample the buffer, such as blending pixel colours directly into it.

source

pub fn window_pos_to_pixel( &self, physical_position: (f32, f32) ) -> Result<(usize, usize), (isize, isize)>

Calculate the pixel location from a physical location on the window, dealing with window resizing, scaling, and margins. Takes a physical position (x, y) within the window, and returns a pixel position (x, y).

The location must be given in physical units (for example, winit’s PhysicalLocation)

If the given physical position is outside of the drawing area, this function returns an Err value with the pixel coordinates outside of the screen, using isize instead of usize.

use winit::dpi::PhysicalPosition;

let mut pixels = Pixels::new(320, 240, surface_texture)?;

// A cursor position in physical units
let cursor_position: (f32, f32) = PhysicalPosition::new(0.0, 0.0).into();

// Convert it to a pixel location
let pixel_position: (usize, usize) = pixels.window_pos_to_pixel(cursor_position)
    // Clamp the output to within the screen
    .unwrap_or_else(|pos| pixels.clamp_pixel_pos(pos));
source

pub fn clamp_pixel_pos(&self, pos: (isize, isize)) -> (usize, usize)

Clamp a pixel position to the pixel buffer texture size.

This can be used to clamp the Err value returned by Pixels::window_pos_to_pixel to a position clamped within the drawing area.

let mut pixels = Pixels::new(320, 240, surface_texture)?;

let pixel_pos = pixels.clamp_pixel_pos((-19, 20));
assert_eq!(pixel_pos, (0, 20));

let pixel_pos = pixels.clamp_pixel_pos((11, 3000));
assert_eq!(pixel_pos, (11, 239));
source

pub fn device(&self) -> &Device

Provides access to the internal wgpu::Device.

source

pub fn queue(&self) -> &Queue

Provides access to the internal wgpu::Queue.

source

pub fn texture(&self) -> &Texture

Provides access to the internal source wgpu::Texture.

This is the pre-scaled texture copied from the pixel buffer.

source

pub fn context(&self) -> &PixelsContext

Provides access to the internal PixelsContext.

source

pub fn surface_texture_format(&self) -> TextureFormat

Get the surface texture format.

This texture format may be chosen automatically by the surface. See PixelsBuilder::surface_texture_format for more information.

source

pub fn render_texture_format(&self) -> TextureFormat

Get the render texture format.

See PixelsBuilder::render_texture_format for more information.

Trait Implementations§

source§

impl Debug for Pixels

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Pixels

§

impl Send for Pixels

§

impl Sync for Pixels

§

impl Unpin for Pixels

§

impl !UnwindSafe for Pixels

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> Downcast<T> for T

§

fn downcast(&self) -> &T

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> Upcast<T> for T

§

fn upcast(&self) -> Option<&T>