Enum bevy::render::texture::ImageSampler

pub enum ImageSampler {
    Default,
    Descriptor(ImageSamplerDescriptor),
}
Expand description

Used in Image, this determines what image sampler to use when rendering. The default setting, ImageSampler::Default, will read the sampler from the ImagePlugin at setup. Setting this to ImageSampler::Descriptor will override the global default descriptor for this Image.

Variants§

§

Default

Default image sampler, derived from the ImagePlugin setup.

§

Descriptor(ImageSamplerDescriptor)

Custom sampler for this image which will override global default.

Implementations§

§

impl ImageSampler

pub fn linear() -> ImageSampler

Returns an image sampler with ImageFilterMode::Linear min and mag filters

Examples found in repository?
examples/2d/texture_atlas.rs (line 65)
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
fn setup(
    mut commands: Commands,
    rpg_sprite_handles: Res<RpgSpriteFolder>,
    asset_server: Res<AssetServer>,
    mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,
    loaded_folders: Res<Assets<LoadedFolder>>,
    mut textures: ResMut<Assets<Image>>,
) {
    let loaded_folder = loaded_folders.get(&rpg_sprite_handles.0).unwrap();

    // create texture atlases with different padding and sampling

    let (texture_atlas_linear, linear_texture) = create_texture_atlas(
        loaded_folder,
        None,
        Some(ImageSampler::linear()),
        &mut textures,
    );
    let atlas_linear_handle = texture_atlases.add(texture_atlas_linear.clone());

    let (texture_atlas_nearest, nearest_texture) = create_texture_atlas(
        loaded_folder,
        None,
        Some(ImageSampler::nearest()),
        &mut textures,
    );
    let atlas_nearest_handle = texture_atlases.add(texture_atlas_nearest);

    let (texture_atlas_linear_padded, linear_padded_texture) = create_texture_atlas(
        loaded_folder,
        Some(UVec2::new(6, 6)),
        Some(ImageSampler::linear()),
        &mut textures,
    );
    let atlas_linear_padded_handle = texture_atlases.add(texture_atlas_linear_padded.clone());

    let (texture_atlas_nearest_padded, nearest_padded_texture) = create_texture_atlas(
        loaded_folder,
        Some(UVec2::new(6, 6)),
        Some(ImageSampler::nearest()),
        &mut textures,
    );
    let atlas_nearest_padded_handle = texture_atlases.add(texture_atlas_nearest_padded);

    // setup 2d scene
    commands.spawn(Camera2dBundle::default());

    // padded textures are to the right, unpadded to the left

    // draw unpadded texture atlas
    commands.spawn(SpriteBundle {
        texture: linear_texture.clone(),
        transform: Transform {
            translation: Vec3::new(-250.0, -130.0, 0.0),
            scale: Vec3::splat(0.8),
            ..default()
        },
        ..default()
    });

    // draw padded texture atlas
    commands.spawn(SpriteBundle {
        texture: linear_padded_texture.clone(),
        transform: Transform {
            translation: Vec3::new(250.0, -130.0, 0.0),
            scale: Vec3::splat(0.8),
            ..default()
        },
        ..default()
    });

    let font = asset_server.load("fonts/FiraSans-Bold.ttf");

    // padding label text style
    let text_style: TextStyle = TextStyle {
        font: font.clone(),
        font_size: 50.0,
        ..default()
    };

    // labels to indicate padding

    // No padding
    create_label(
        &mut commands,
        (-250.0, 330.0, 0.0),
        "No padding",
        text_style.clone(),
    );

    // Padding
    create_label(&mut commands, (250.0, 330.0, 0.0), "Padding", text_style);

    // get handle to a sprite to render
    let vendor_handle: Handle<Image> = asset_server
        .get_handle("textures/rpg/chars/vendor/generic-rpg-vendor.png")
        .unwrap();

    // get index of the sprite in the texture atlas, this is used to render the sprite
    // the index is the same for all the texture atlases, since they are created from the same folder
    let vendor_index = texture_atlas_linear
        .get_texture_index(&vendor_handle)
        .unwrap();

    // configuration array to render sprites through iteration
    let configurations: [(&str, Handle<TextureAtlasLayout>, Handle<Image>, f32); 4] = [
        ("Linear", atlas_linear_handle, linear_texture, -350.0),
        ("Nearest", atlas_nearest_handle, nearest_texture, -150.0),
        (
            "Linear",
            atlas_linear_padded_handle,
            linear_padded_texture,
            150.0,
        ),
        (
            "Nearest",
            atlas_nearest_padded_handle,
            nearest_padded_texture,
            350.0,
        ),
    ];

    // label text style
    let sampling_label_style = TextStyle {
        font,
        font_size: 30.0,
        ..default()
    };

    let base_y = 170.0; // y position of the sprites

    for (sampling, atlas_handle, image_handle, x) in configurations {
        // render a sprite from the texture_atlas
        create_sprite_from_atlas(
            &mut commands,
            (x, base_y, 0.0),
            vendor_index,
            atlas_handle,
            image_handle,
        );

        // render a label to indicate the sampling setting
        create_label(
            &mut commands,
            (x, base_y + 110.0, 0.0), // offset to y position of the sprite
            sampling,
            sampling_label_style.clone(),
        );
    }
}

pub fn nearest() -> ImageSampler

Returns an image sampler with ImageFilterMode::Nearest min and mag filters

Examples found in repository?
examples/asset/asset_settings.rs (line 69)
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
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    // Without any .meta file specifying settings, the default sampler [ImagePlugin::default()] is used for loading images.
    // If you are using a very small image and rendering it larger like seen here, the default linear filtering will result in a blurry image.
    // Useful note: The default sampler specified by the ImagePlugin is *not* the same as the default implementation of sampler. This is why
    // everything uses linear by default but if you look at the default of sampler, it uses nearest.
    commands.spawn(SpriteBundle {
        texture: asset_server.load("bevy_pixel_dark.png"),
        sprite: Sprite {
            custom_size: Some(Vec2 { x: 160.0, y: 120.0 }),
            ..Default::default()
        },
        transform: Transform::from_xyz(-100.0, 0.0, 0.0),
        ..Default::default()
    });

    // When a .meta file is added with the same name as the asset and a '.meta' extension
    // you can (and must) specify all fields of the asset loader's settings for that
    // particular asset, in this case [ImageLoaderSettings]. Take a look at
    // examples/asset/files/bevy_pixel_dark_with_meta.png.meta
    // for the format and you'll notice, the only non-default option is setting Nearest
    // filtering. This tends to work much better for pixel art assets.
    // A good reference when filling this out is to check out [ImageLoaderSettings::default()]
    // and follow to the default implementation of each fields type.
    // https://docs.rs/bevy/latest/bevy/render/texture/struct.ImageLoaderSettings.html#
    commands.spawn(SpriteBundle {
        texture: asset_server.load("bevy_pixel_dark_with_meta.png"),
        sprite: Sprite {
            custom_size: Some(Vec2 { x: 160.0, y: 120.0 }),
            ..Default::default()
        },
        transform: Transform::from_xyz(100.0, 0.0, 0.0),
        ..Default::default()
    });

    // Another option is to use the AssetServers load_with_settings function.
    // With this you can specify the same settings upon loading your asset with a
    // couple of differences. A big one is that you aren't required to set *every*
    // setting, just modify the ones that you need. It works by passing in a function
    // (in this case an anonymous closure) that takes a reference to the settings type
    // that is then modified in the function.
    // Do note that if you want to load the same asset with different settings, the
    // settings changes from any loads after the first of the same asset will be ignored.
    // This is why this one loads a differently named copy of the asset instead of using
    // same one as without a .meta file.
    commands.spawn(SpriteBundle {
        texture: asset_server.load_with_settings(
            "bevy_pixel_dark_with_settings.png",
            |settings: &mut ImageLoaderSettings| {
                settings.sampler = ImageSampler::nearest();
            },
        ),
        sprite: Sprite {
            custom_size: Some(Vec2 { x: 160.0, y: 120.0 }),
            ..Default::default()
        },
        transform: Transform::from_xyz(0.0, 150.0, 0.0),
        ..Default::default()
    });

    commands.spawn(Camera2dBundle::default());
}
More examples
Hide additional examples
examples/2d/texture_atlas.rs (line 73)
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
fn setup(
    mut commands: Commands,
    rpg_sprite_handles: Res<RpgSpriteFolder>,
    asset_server: Res<AssetServer>,
    mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,
    loaded_folders: Res<Assets<LoadedFolder>>,
    mut textures: ResMut<Assets<Image>>,
) {
    let loaded_folder = loaded_folders.get(&rpg_sprite_handles.0).unwrap();

    // create texture atlases with different padding and sampling

    let (texture_atlas_linear, linear_texture) = create_texture_atlas(
        loaded_folder,
        None,
        Some(ImageSampler::linear()),
        &mut textures,
    );
    let atlas_linear_handle = texture_atlases.add(texture_atlas_linear.clone());

    let (texture_atlas_nearest, nearest_texture) = create_texture_atlas(
        loaded_folder,
        None,
        Some(ImageSampler::nearest()),
        &mut textures,
    );
    let atlas_nearest_handle = texture_atlases.add(texture_atlas_nearest);

    let (texture_atlas_linear_padded, linear_padded_texture) = create_texture_atlas(
        loaded_folder,
        Some(UVec2::new(6, 6)),
        Some(ImageSampler::linear()),
        &mut textures,
    );
    let atlas_linear_padded_handle = texture_atlases.add(texture_atlas_linear_padded.clone());

    let (texture_atlas_nearest_padded, nearest_padded_texture) = create_texture_atlas(
        loaded_folder,
        Some(UVec2::new(6, 6)),
        Some(ImageSampler::nearest()),
        &mut textures,
    );
    let atlas_nearest_padded_handle = texture_atlases.add(texture_atlas_nearest_padded);

    // setup 2d scene
    commands.spawn(Camera2dBundle::default());

    // padded textures are to the right, unpadded to the left

    // draw unpadded texture atlas
    commands.spawn(SpriteBundle {
        texture: linear_texture.clone(),
        transform: Transform {
            translation: Vec3::new(-250.0, -130.0, 0.0),
            scale: Vec3::splat(0.8),
            ..default()
        },
        ..default()
    });

    // draw padded texture atlas
    commands.spawn(SpriteBundle {
        texture: linear_padded_texture.clone(),
        transform: Transform {
            translation: Vec3::new(250.0, -130.0, 0.0),
            scale: Vec3::splat(0.8),
            ..default()
        },
        ..default()
    });

    let font = asset_server.load("fonts/FiraSans-Bold.ttf");

    // padding label text style
    let text_style: TextStyle = TextStyle {
        font: font.clone(),
        font_size: 50.0,
        ..default()
    };

    // labels to indicate padding

    // No padding
    create_label(
        &mut commands,
        (-250.0, 330.0, 0.0),
        "No padding",
        text_style.clone(),
    );

    // Padding
    create_label(&mut commands, (250.0, 330.0, 0.0), "Padding", text_style);

    // get handle to a sprite to render
    let vendor_handle: Handle<Image> = asset_server
        .get_handle("textures/rpg/chars/vendor/generic-rpg-vendor.png")
        .unwrap();

    // get index of the sprite in the texture atlas, this is used to render the sprite
    // the index is the same for all the texture atlases, since they are created from the same folder
    let vendor_index = texture_atlas_linear
        .get_texture_index(&vendor_handle)
        .unwrap();

    // configuration array to render sprites through iteration
    let configurations: [(&str, Handle<TextureAtlasLayout>, Handle<Image>, f32); 4] = [
        ("Linear", atlas_linear_handle, linear_texture, -350.0),
        ("Nearest", atlas_nearest_handle, nearest_texture, -150.0),
        (
            "Linear",
            atlas_linear_padded_handle,
            linear_padded_texture,
            150.0,
        ),
        (
            "Nearest",
            atlas_nearest_padded_handle,
            nearest_padded_texture,
            350.0,
        ),
    ];

    // label text style
    let sampling_label_style = TextStyle {
        font,
        font_size: 30.0,
        ..default()
    };

    let base_y = 170.0; // y position of the sprites

    for (sampling, atlas_handle, image_handle, x) in configurations {
        // render a sprite from the texture_atlas
        create_sprite_from_atlas(
            &mut commands,
            (x, base_y, 0.0),
            vendor_index,
            atlas_handle,
            image_handle,
        );

        // render a label to indicate the sampling setting
        create_label(
            &mut commands,
            (x, base_y + 110.0, 0.0), // offset to y position of the sprite
            sampling,
            sampling_label_style.clone(),
        );
    }
}

Trait Implementations§

§

impl Clone for ImageSampler

§

fn clone(&self) -> ImageSampler

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for ImageSampler

§

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

Formats the value using the given formatter. Read more
§

impl Default for ImageSampler

§

fn default() -> ImageSampler

Returns the “default value” for a type. Read more
§

impl<'de> Deserialize<'de> for ImageSampler

§

fn deserialize<__D>( __deserializer: __D, ) -> Result<ImageSampler, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
§

impl Serialize for ImageSampler

§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. 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
§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
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
§

impl<T> Downcast<T> for T

§

fn downcast(&self) -> &T

§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<S> FromSample<S> for S

§

fn from_sample_(s: S) -> S

§

impl<T> FromWorld for T
where T: Default,

§

fn from_world(_world: &mut World) -> T

Creates Self using data from the given World.
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

§

fn into_sample(self) -> T

§

impl<T> NoneValue for T
where T: Default,

§

type NoneType = T

§

fn null_value() -> T

The none-equivalent value.
§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> Serialize for T
where T: Serialize + ?Sized,

source§

fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>

source§

fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

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

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

§

fn to_sample_(self) -> U

source§

impl<T, U> TryFrom<U> for T
where 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 T
where 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> TypeData for T
where T: 'static + Send + Sync + Clone,

§

fn clone_type_data(&self) -> Box<dyn TypeData>

§

impl<T> Upcast<T> for T

§

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

§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
§

impl<T> ConditionalSend for T
where T: Send,

source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

§

impl<T> Settings for T
where T: 'static + Send + Sync,

§

impl<T> WasmNotSend for T
where T: Send,

§

impl<T> WasmNotSendSync for T
where T: WasmNotSend + WasmNotSync,

§

impl<T> WasmNotSync for T
where T: Sync,