Struct Texture

Source
#[repr(C)]
pub struct Texture { /* private fields */ }
Expand description

[Image] living on the graphics card that can be used for drawing.

Texture stores pixels that can be drawn, with a sprite for example.

A texture lives in the graphics card memory, therefore it is very fast to draw a texture to a render target, or copy a render target to a texture (the graphics card can access both directly).

Being stored in the graphics card memory has some drawbacks. A texture cannot be manipulated as freely as a [Image], you need to prepare the pixels first and then upload them to the texture in a single operation (see the various update methods below).

Texture makes it easy to convert from/to [Image], but keep in mind that these calls require transfers between the graphics card and the central memory, therefore they are slow operations.

A texture can be loaded from an image, but also directly from a file/memory/stream. The necessary shortcuts are defined so that you don’t need an image first for the most common cases. However, if you want to perform some modifications on the pixels before creating the final texture, you can load your file to a [Image], do whatever you need with the pixels, and then call [Texture::load_from_image].

Since they live in the graphics card memory, the pixels of a texture cannot be accessed without a slow copy first. And they cannot be accessed individually. Therefore, if you need to read the texture’s pixels (like for pixel-perfect collisions), it is recommended to store the collision information separately, for example in an array of booleans.

Like [Image], Texture can handle a unique internal representation of pixels, which is RGBA 32 bits. This means that a pixel must be composed of 8 bits red, green, blue and alpha channels – just like a Color.

Implementations§

Source§

impl Texture

Creation and loading

Source

pub fn create(&mut self, width: u32, height: u32) -> SfResult<()>

Create the texture.

If this function fails, the texture is left unchanged.

Returns whether creation was successful.

Source

pub fn new() -> SfResult<FBox<Texture>>

Creates a new Texture

Source

pub fn load_from_memory(&mut self, mem: &[u8]) -> SfResult<()>

Load texture from memory

The area argument can be used to load only a sub-rectangle of the whole image. If you want the entire image then use a default [IntRect]. If the area rectangle crosses the bounds of the image, it is adjusted to fit the image size.

§Arguments
  • mem - Pointer to the file data in memory
  • area - Area of the image to load
Source

pub fn load_from_file(&mut self, filename: &str) -> SfResult<()>

Load texture from a file

§Arguments
  • filename - Path of the image file to load
Source

pub fn from_file(filename: &str) -> SfResult<FBox<Self>>

Convenience method to easily create and load a Texture from a file.

Examples found in repository?
examples/borrowed-resources.rs (line 24)
12fn main() -> SfResult<()> {
13    example_ensure_right_working_dir();
14
15    let mut window = RenderWindow::new(
16        (800, 600),
17        "Borrowed resources",
18        Style::CLOSE,
19        &Default::default(),
20    )?;
21    window.set_vertical_sync_enabled(true);
22
23    // Create a new texture. (Hey Frank!)
24    let frank = Texture::from_file("frank.jpeg")?;
25
26    // Create a font.
27    let font = Font::from_file("sansation.ttf")?;
28
29    // Create a circle with the Texture.
30    let mut circle = CircleShape::with_texture(&frank);
31    circle.set_radius(70.0);
32    circle.set_position((100.0, 100.0));
33
34    // Create a Sprite.
35    let mut sprite = Sprite::new();
36    // Have it use the same texture as the circle.
37    sprite.set_texture(&frank, true);
38    sprite.set_position((400.0, 300.0));
39    sprite.set_scale(0.5);
40
41    // Create a ConvexShape using the same texture.
42    let mut convex_shape = ConvexShape::with_texture(6, &frank);
43    convex_shape.set_point(0, (400., 100.));
44    convex_shape.set_point(1, (500., 70.));
45    convex_shape.set_point(2, (450., 100.));
46    convex_shape.set_point(3, (580., 150.));
47    convex_shape.set_point(4, (420., 230.));
48    convex_shape.set_point(5, (420., 120.));
49
50    // Create an initialized text using the font.
51    let mut title = Text::new("Borrowed resources example!".into(), &font, 50);
52
53    // Create a second text using the same font.
54    // This time, we create and initialize it separately.
55    let mut second_text = Text::default();
56    second_text.set_string("This text shares the same font with the title!".into());
57    second_text.set_font(&font);
58    second_text.set_fill_color(Color::GREEN);
59    second_text.tf.position = [10.0, 350.0];
60    second_text.set_character_size(20);
61
62    // Create a third text using the same font.
63    let mut third_text = Text::new("This one too!".into(), &font, 20);
64    third_text.tf.position = [300.0, 100.0];
65    third_text.set_fill_color(Color::RED);
66
67    'mainloop: loop {
68        while let Some(event) = window.poll_event() {
69            match event {
70                Event::Closed
71                | Event::KeyPressed {
72                    code: Key::Escape, ..
73                } => break 'mainloop,
74                _ => {}
75            }
76        }
77
78        window.clear(Color::BLACK);
79        let rs = RenderStates::DEFAULT;
80        window.draw_circle_shape(&circle, &rs);
81        window.draw_sprite(&sprite, &rs);
82        window.draw_convex_shape(&convex_shape, &rs);
83        title.draw(&mut *window, &rs);
84        second_text.draw(&mut *window, &rs);
85        third_text.draw(&mut *window, &rs);
86
87        // Little test here for `Shape::points`
88        let mut circ = CircleShape::new(4.0, 30);
89        circ.set_origin(2.0);
90        circ.set_fill_color(Color::YELLOW);
91
92        for p in convex_shape.points() {
93            circ.set_position(p);
94            window.draw_circle_shape(&circ, &RenderStates::DEFAULT);
95        }
96
97        window.display();
98    }
99    Ok(())
100}
Source§

impl Texture

Query properties

Source

pub fn size(&self) -> Vector2u

Return the size of the texture

Return the Size in pixels

Source

pub fn maximum_size() -> u32

Get the maximum texture size allowed

Return the maximum size allowed for textures, in pixels

Source

pub fn is_smooth(&self) -> bool

Tell whether the smooth filter is enabled or not for a texture

Return true if smoothing is enabled, false if it is disabled

Source

pub fn is_repeated(&self) -> bool

Tell whether a texture is repeated or not

Return frue if repeat mode is enabled, false if it is disabled

Source

pub fn is_srgb(&self) -> bool

Tell whether the texture source is converted from sRGB or not.

Source§

impl Texture

Set properties

Source

pub fn set_smooth(&mut self, smooth: bool)

Enable or disable the smooth filter on a texture

§Arguments
  • smooth - true to enable smoothing, false to disable it
Source

pub fn set_repeated(&mut self, repeated: bool)

Enable or disable repeating for a texture

epeating is involved when using texture coordinates outside the texture rectangle [0, 0, width, height]. In this case, if repeat mode is enabled, the whole texture will be repeated as many times as needed to reach the coordinate (for example, if the X texture coordinate is 3 * width, the texture will be repeated 3 times). If repeat mode is disabled, the “extra space” will instead be filled with border pixels. Warning: on very old graphics cards, white pixels may appear when the texture is repeated. With such cards, repeat mode can be used reliably only if the texture has power-of-two dimensions (such as 256x128). Repeating is disabled by default.

§Arguments
  • repeated - true to repeat the texture, false to disable repeating
Source

pub fn set_srgb(&mut self, srgb: bool)

Enable or disable conversion from sRGB.

When providing texture data from an image file or memory, it can either be stored in a linear color space or an sRGB color space. Most digital images account for gamma correction already, so they would need to be “uncorrected” back to linear color space before being processed by the hardware. The hardware can automatically convert it from the sRGB color space to a linear color space when it gets sampled. When the rendered image gets output to the final framebuffer, it gets converted back to sRGB.

After enabling or disabling sRGB conversion, make sure to reload the texture data in order for the setting to take effect.

This option is only useful in conjunction with an sRGB capable framebuffer. This can be requested during window creation.

Source§

impl Texture

OpenGL interop

Source

pub fn native_handle(&self) -> u32

Get the underlying OpenGL handle of the texture.

You shouldn’t need to use this function, unless you have very specific stuff to implement that SFML doesn’t support, or implement a temporary workaround until a bug is fixed.

Source

pub fn bind(&self)

Bind a texture for rendering

This function is not part of the graphics API, it mustn’t be used when drawing SFML entities. It must be used only if you mix Texture with OpenGL code.

Source§

impl Texture

Copying and updating

Source

pub unsafe fn update_from_window(&mut self, window: &Window, x: u32, y: u32)

Update a part of the texture from the contents of a window.

This function does nothing if either the texture or the window was not previously created.

§Safety

No additional check is performed on the size of the window, passing an invalid combination of window size and offset will lead to an undefined behavior.

Source

pub unsafe fn update_from_render_window( &mut self, render_window: &RenderWindow, x: u32, y: u32, )

Update a part of the texture from the contents of a render window.

This function does nothing if either the texture or the window was not previously created.

§Safety

No additional check is performed on the size of the window, passing an invalid combination of window size and offset will lead to an undefined behavior.

Source

pub unsafe fn update_from_texture(&mut self, texture: &Texture, x: u32, y: u32)

Update a part of this texture from another texture.

This function does nothing if either texture was not previously created.

§Safety

No additional check is performed on the size of the texture, passing an invalid combination of texture size and offset will lead to an undefined behavior.

Source

pub fn update_from_pixels( &mut self, pixels: &[u8], width: u32, height: u32, x: u32, y: u32, )

Update a part of the texture from an array of pixels.

The size of the pixel array must match the width and height arguments, and it must contain 32-bits RGBA pixels.

This function does nothing if the texture was not previously created.

§Panics

Panics the provided parameters would result in out of bounds access.

Source

pub fn swap(&mut self, other: &mut Texture)

Swap the contents of this texture with those of another.

Source§

impl Texture

Mipmapping

Source

pub fn generate_mipmap(&mut self) -> SfResult<()>

Generate a mipmap using the current texture data.

Mipmaps are pre-computed chains of optimized textures. Each level of texture in a mipmap is generated by halving each of the previous level’s dimensions. This is done until the final level has the size of 1x1. The textures generated in this process may make use of more advanced filters which might improve the visual quality of textures when they are applied to objects much smaller than they are. This is known as minification. Because fewer texels (texture elements) have to be sampled from when heavily minified, usage of mipmaps can also improve rendering performance in certain scenarios.

Mipmap generation relies on the necessary OpenGL extension being available. If it is unavailable or generation fails due to another reason, this function will return false. Mipmap data is only valid from the time it is generated until the next time the base level image is modified, at which point this function will have to be called again to regenerate it.

Trait Implementations§

Source§

impl Debug for Texture

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Drop for Texture

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl ToOwned for Texture

Source§

type Owned = FBox<Texture>

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> Self::Owned

Creates owned data from borrowed data, usually by cloning. Read more
1.63.0 · Source§

fn clone_into(&self, target: &mut Self::Owned)

Uses borrowed data to replace owned data, usually by cloning. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where 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 T
where U: Into<T>,

Source§

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 T
where U: TryFrom<T>,

Source§

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.