Path: blob/main/crates/bevy_sprite/src/texture_slice/mod.rs
6600 views
mod border_rect;1mod slicer;23use bevy_math::{Rect, Vec2};4pub use border_rect::BorderRect;5pub use slicer::{SliceScaleMode, TextureSlicer};67/// Single texture slice, representing a texture rect to draw in a given area8#[derive(Debug, Clone, PartialEq)]9pub struct TextureSlice {10/// texture area to draw11pub texture_rect: Rect,12/// slice draw size13pub draw_size: Vec2,14/// offset of the slice15pub offset: Vec2,16}1718impl TextureSlice {19/// Transforms the given slice in a collection of tiled subdivisions.20///21/// # Arguments22///23/// * `stretch_value` - The slice will repeat when the ratio between the *drawing dimensions* of texture and the24/// *original texture size* (rect) are above `stretch_value`.25/// * `tile_x` - should the slice be tiled horizontally26/// * `tile_y` - should the slice be tiled vertically27#[must_use]28pub fn tiled(self, stretch_value: f32, (tile_x, tile_y): (bool, bool)) -> Vec<Self> {29if !tile_x && !tile_y {30return vec![self];31}32let stretch_value = stretch_value.max(0.001);33let rect_size = self.texture_rect.size();34// Each tile expected size35let expected_size = Vec2::new(36if tile_x {37// No slice should be less than 1 pixel wide38(rect_size.x * stretch_value).max(1.0)39} else {40self.draw_size.x41},42if tile_y {43// No slice should be less than 1 pixel high44(rect_size.y * stretch_value).max(1.0)45} else {46self.draw_size.y47},48)49.min(self.draw_size);50let mut slices = Vec::new();51let base_offset = Vec2::new(52-self.draw_size.x / 2.0,53self.draw_size.y / 2.0, // Start from top54);55let mut offset = base_offset;5657let mut remaining_columns = self.draw_size.y;58while remaining_columns > 0.0 {59let size_y = expected_size.y.min(remaining_columns);60offset.x = base_offset.x;61offset.y -= size_y / 2.0;62let mut remaining_rows = self.draw_size.x;63while remaining_rows > 0.0 {64let size_x = expected_size.x.min(remaining_rows);65offset.x += size_x / 2.0;66let draw_size = Vec2::new(size_x, size_y);67let delta = draw_size / expected_size;68slices.push(Self {69texture_rect: Rect {70min: self.texture_rect.min,71max: self.texture_rect.min + self.texture_rect.size() * delta,72},73draw_size,74offset: self.offset + offset,75});76offset.x += size_x / 2.0;77remaining_rows -= size_x;78}79offset.y -= size_y / 2.0;80remaining_columns -= size_y;81}82if slices.len() > 1_000 {83tracing::warn!("One of your tiled textures has generated {} slices. You might want to use higher stretch values to avoid a great performance cost", slices.len());84}85slices86}87}888990