diff --git a/crates/eframe/src/web/mod.rs b/crates/eframe/src/web/mod.rs index 62b2bdc2..fbf749e0 100644 --- a/crates/eframe/src/web/mod.rs +++ b/crates/eframe/src/web/mod.rs @@ -266,7 +266,7 @@ fn to_image(image: &egui::ColorImage) -> Result { image::RgbaImage::from_raw( image.width() as _, image.height() as _, - bytemuck::cast_slice(&image.pixels).to_vec(), + bytemuck::cast_slice(image.pixels()).to_vec(), ) .ok_or_else(|| "Invalid IconData".to_owned()) } diff --git a/crates/egui-wgpu/src/renderer.rs b/crates/egui-wgpu/src/renderer.rs index 382d8749..1372eddd 100644 --- a/crates/egui-wgpu/src/renderer.rs +++ b/crates/egui-wgpu/src/renderer.rs @@ -652,17 +652,9 @@ impl Renderer { depth_or_array_layers: 1, }; - let data_color32 = match &image_delta.image { - epaint::ImageData::Color(image) => { - assert_eq!( - width as usize * height as usize, - image.pixels.len(), - "Mismatch between texture size and texel count" - ); - Cow::Borrowed(&image.pixels) - } + let data_bytes: &[u8] = match &image_delta.image { + epaint::ImageData::Color(image) => bytemuck::cast_slice(image.pixels()), }; - let data_bytes: &[u8] = bytemuck::cast_slice(data_color32.as_slice()); let queue_write_data_to_texture = |texture, origin| { profiling::scope!("write_texture"); diff --git a/crates/egui-winit/src/clipboard.rs b/crates/egui-winit/src/clipboard.rs index 702e1e54..cddfc4e8 100644 --- a/crates/egui-winit/src/clipboard.rs +++ b/crates/egui-winit/src/clipboard.rs @@ -312,7 +312,7 @@ fn color_image_from_arboard(image: &arboard::ImageData<'_>) -> egui::ColorImage ))] fn arboard_from_color_image(image: &egui::ColorImage) -> arboard::ImageData<'static> { let bytes: Vec = image - .pixels + .pixels() .iter() .flat_map(|color| color.to_srgba_unmultiplied()) .collect(); @@ -418,13 +418,13 @@ mod tests { bytes: std::borrow::Cow::Borrowed(&[255, 0, 0, 255, 255, 255, 255, 128]), }; let color_image = color_image_from_arboard(&image); - assert_eq!(color_image.size, [2, 1]); + assert_eq!(color_image.resolution(), [2, 1]); assert_eq!( - color_image.pixels[0], + color_image.pixels()[0], egui::Color32::from_rgba_unmultiplied(255, 0, 0, 255) ); assert_eq!( - color_image.pixels[1], + color_image.pixels()[1], egui::Color32::from_rgba_unmultiplied(255, 255, 255, 128) ); } diff --git a/crates/egui/src/context.rs b/crates/egui/src/context.rs index 9f6518cd..fa29e008 100644 --- a/crates/egui/src/context.rs +++ b/crates/egui/src/context.rs @@ -3385,7 +3385,7 @@ impl Context { tessellator::Tessellator::new( pixels_per_point, tessellation_options, - texture_atlas.size(), + texture_atlas.resolution(), texture_atlas.prepared_discs(), ) .tessellate_shapes(shapes) @@ -3942,7 +3942,7 @@ impl Context { CollapsingHeader::new("🔠 Font texture") .default_open(false) .show(ui, |ui| { - let font_image_size = self.fonts(|f| f.font_image_size()); + let font_image_size = self.fonts(|f| f.font_image_resolution()); crate::introspection::font_texture_ui(ui, font_image_size); }); @@ -4000,7 +4000,7 @@ impl Context { .min_row_height(max_preview_size.y) .show(ui, |ui| { for (&texture_id, meta) in textures { - let [w, h] = meta.size; + let [w, h] = meta.resolution; let point_size = vec2(w as f32, h as f32) / pixels_per_point; let mut size = point_size; diff --git a/crates/egui/src/load.rs b/crates/egui/src/load.rs index 61508620..b10ad267 100644 --- a/crates/egui/src/load.rs +++ b/crates/egui/src/load.rs @@ -471,10 +471,9 @@ impl SizedTexture { /// Fetch the [id][`SizedTexture::id`] and [size][`SizedTexture::size`] from a [`TextureHandle`]. pub fn from_handle(handle: &TextureHandle) -> Self { - let size = handle.size(); Self { id: handle.id(), - size: Vec2::new(size[0] as f32, size[1] as f32), + size: handle.resolution_vec2(), } } } diff --git a/crates/egui/src/load/texture_loader.rs b/crates/egui/src/load/texture_loader.rs index eb9b4503..38a296a9 100644 --- a/crates/egui/src/load/texture_loader.rs +++ b/crates/egui/src/load/texture_loader.rs @@ -76,7 +76,7 @@ impl TextureLoader for DefaultTextureLoader { match ctx.try_load_image(uri, size_hint)? { ImagePoll::Pending { size } => Ok(TexturePoll::Pending { size }), ImagePoll::Ready { image } => { - let source_size = image.source_size; + let source_size = image.source_size(); let handle = ctx.load_texture(uri, image, texture_options); let texture = SizedTexture::new(handle.id(), source_size); bucket.insert( diff --git a/crates/egui/src/widgets/color_picker.rs b/crates/egui/src/widgets/color_picker.rs index 250b95ae..451f9e7a 100644 --- a/crates/egui/src/widgets/color_picker.rs +++ b/crates/egui/src/widgets/color_picker.rs @@ -61,7 +61,7 @@ fn background_checkers(painter: &Painter, bounds: RoundedRect) { /// Paint a gradient image over the given rounded rect, with an outline. fn paint_gradient(ui: &Ui, id: Id, bounds: RoundedRect, outline: Stroke, image: ColorImage) { let (rect, corner_radius) = bounds.into_parts(); - let [width, height] = image.size; + let [width, height] = image.resolution(); let texture = ui .ctx() .load_texture_cached("color_gradient", id, image, TextureOptions::LINEAR); diff --git a/crates/egui_demo_lib/benches/benchmark.rs b/crates/egui_demo_lib/benches/benchmark.rs index 4d7955ef..033f117c 100644 --- a/crates/egui_demo_lib/benches/benchmark.rs +++ b/crates/egui_demo_lib/benches/benchmark.rs @@ -238,7 +238,7 @@ pub fn criterion_benchmark(c: &mut Criterion) { text_color, wrap_width, ); - let font_image_size = fonts.font_image_size(); + let font_image_size = fonts.font_image_resolution(); let prepared_discs = fonts.texture_atlas().prepared_discs(); let mut tessellator = egui::epaint::Tessellator::new( 1.0, diff --git a/crates/egui_demo_lib/src/demo/tests/tessellation_test.rs b/crates/egui_demo_lib/src/demo/tests/tessellation_test.rs index 40384d50..7f1daad7 100644 --- a/crates/egui_demo_lib/src/demo/tests/tessellation_test.rs +++ b/crates/egui_demo_lib/src/demo/tests/tessellation_test.rs @@ -225,7 +225,7 @@ impl crate::View for TessellationTest { let mut tessellator = epaint::Tessellator::new( 1.0, *tessellation_options, - ui.fonts(|f| f.font_image_size()), + ui.fonts(|f| f.font_image_resolution()), vec![], ); tessellator.tessellate_rect(&shape, &mut mesh); diff --git a/crates/egui_extras/src/loaders/gif_loader.rs b/crates/egui_extras/src/loaders/gif_loader.rs index 3c462ea6..3a31b52e 100644 --- a/crates/egui_extras/src/loaders/gif_loader.rs +++ b/crates/egui_extras/src/loaders/gif_loader.rs @@ -47,9 +47,7 @@ impl AnimatedImage { + self .frames .iter() - .map(|image| { - image.pixels.len() * size_of::() + size_of::() - }) + .map(|image| size_of_val(image.pixels()) + size_of::()) .sum::() } diff --git a/crates/egui_extras/src/loaders/image_loader.rs b/crates/egui_extras/src/loaders/image_loader.rs index 9553a909..d8bfa5ec 100644 --- a/crates/egui_extras/src/loaders/image_loader.rs +++ b/crates/egui_extras/src/loaders/image_loader.rs @@ -1,5 +1,5 @@ use alloc::sync::Arc; -use core::{mem::size_of, task::Poll}; +use core::task::Poll; use egui::{ ColorImage, decode_animated_image_uri, load::{BytesPoll, ImageLoadResult, ImageLoader, ImagePoll, LoadError, SizeHint}, @@ -144,8 +144,7 @@ impl ImageLoader for ImageCrateLoader { } fn byte_size(&self) -> usize { - self.cache - .byte_size(|image| image.pixels.len() * size_of::()) + self.cache.byte_size(|image| size_of_val(image.pixels())) } fn has_pending(&self) -> bool { diff --git a/crates/egui_extras/src/loaders/svg_loader.rs b/crates/egui_extras/src/loaders/svg_loader.rs index f6d22b11..90b8a442 100644 --- a/crates/egui_extras/src/loaders/svg_loader.rs +++ b/crates/egui_extras/src/loaders/svg_loader.rs @@ -1,5 +1,4 @@ use alloc::sync::Arc; -use core::mem::size_of; use ahash::HashMap; @@ -118,7 +117,7 @@ impl ImageLoader for SvgLoader { .values() .flat_map(|bucket| bucket.values()) .map(|entry| match &entry.result { - Ok(image) => image.pixels.len() * size_of::(), + Ok(image) => size_of_val(image.pixels()), Err(err) => err.len(), }) .sum() diff --git a/crates/egui_extras/src/loaders/webp_loader.rs b/crates/egui_extras/src/loaders/webp_loader.rs index ddc10050..b1b47379 100644 --- a/crates/egui_extras/src/loaders/webp_loader.rs +++ b/crates/egui_extras/src/loaders/webp_loader.rs @@ -85,7 +85,7 @@ impl WebP { pub fn byte_len(&self) -> usize { size_of::() + match self { - Self::Static(image) => image.pixels.len() * size_of::(), + Self::Static(image) => size_of_val(image.pixels()), Self::Animated(animation) => animation.byte_len(), } } @@ -103,9 +103,7 @@ impl AnimatedImage { + self .frames .iter() - .map(|image| { - image.pixels.len() * size_of::() + size_of::() - }) + .map(|image| size_of_val(image.pixels()) + size_of::()) .sum::() } diff --git a/crates/egui_extras/src/svg_glyph.rs b/crates/egui_extras/src/svg_glyph.rs index a911eacf..75a3bdb3 100644 --- a/crates/egui_extras/src/svg_glyph.rs +++ b/crates/egui_extras/src/svg_glyph.rs @@ -152,7 +152,7 @@ impl SvgGlyph { let mut image = ColorImage::from_rgba_premultiplied([width, height], pixmap.data()); if !is_color { // The atlas stores coverage for monochrome glyphs, and the tessellator tints them: - for pixel in &mut image.pixels { + for pixel in image.pixels_mut() { *pixel = Color32::from_white_alpha(pixel.a()); } } @@ -252,13 +252,13 @@ mod tests { #[test] fn gray_is_tinted() { let glyph = gray_rect().rasterize(40.0).unwrap(); - assert_eq!(glyph.bitmap.image.size, [20, 40]); + assert_eq!(glyph.bitmap.image.resolution(), [20, 40]); assert!(!glyph.bitmap.is_color); assert!( glyph .bitmap .image - .pixels + .pixels() .iter() .all(|&p| p == Color32::WHITE) ); @@ -270,7 +270,14 @@ mod tests { fn color_is_kept() { let glyph = red_rect().rasterize(40.0).unwrap(); assert!(glyph.bitmap.is_color); - assert!(glyph.bitmap.image.pixels.iter().all(|&p| p == Color32::RED)); + assert!( + glyph + .bitmap + .image + .pixels() + .iter() + .all(|&p| p == Color32::RED) + ); } #[test] @@ -315,7 +322,7 @@ mod tests { .with_baseline_offset(0.25) .rasterize(40.0) .unwrap(); - assert_eq!(glyph.bitmap.image.size, [10, 20]); + assert_eq!(glyph.bitmap.image.resolution(), [10, 20]); assert_eq!(glyph.advance_px, 40.0); assert_eq!( glyph.bitmap.offset_px, diff --git a/crates/egui_glow/src/painter.rs b/crates/egui_glow/src/painter.rs index 8a68de1f..6e14179f 100644 --- a/crates/egui_glow/src/painter.rs +++ b/crates/egui_glow/src/painter.rs @@ -522,15 +522,8 @@ impl Painter { match &delta.image { egui::ImageData::Color(image) => { - assert_eq!( - image.width() * image.height(), - image.pixels.len(), - "Mismatch between texture size and texel count" - ); - - let data: &[u8] = bytemuck::cast_slice(image.pixels.as_ref()); - - self.upload_texture_srgb(delta.pos, image.size, delta.options, data); + let data: &[u8] = bytemuck::cast_slice(image.pixels()); + self.upload_texture_srgb(delta.pos, image.resolution(), delta.options, data); } } } diff --git a/crates/egui_inspection/src/png.rs b/crates/egui_inspection/src/png.rs index fb480d56..0e1912f3 100644 --- a/crates/egui_inspection/src/png.rs +++ b/crates/egui_inspection/src/png.rs @@ -8,7 +8,7 @@ impl EncodedPng { /// # Errors /// When the encoder fails. pub fn from_color_image(image: &egui::ColorImage) -> Result { - let size = [image.size[0] as u32, image.size[1] as u32]; + let size = [image.width() as u32, image.height() as u32]; Self::from_rgba(size, image.as_raw()) } @@ -22,7 +22,7 @@ impl EncodedPng { image: &egui::ColorImage, scale: f32, ) -> Result { - let [w, h] = [image.size[0] as u32, image.size[1] as u32]; + let [w, h] = [image.width() as u32, image.height() as u32]; if scale >= 1.0 || w == 0 || h == 0 { return Self::from_rgba([w, h], image.as_raw()); } diff --git a/crates/egui_kittest/src/recording.rs b/crates/egui_kittest/src/recording.rs index 36198746..16aa119c 100644 --- a/crates/egui_kittest/src/recording.rs +++ b/crates/egui_kittest/src/recording.rs @@ -225,7 +225,7 @@ impl Drop for RecordingPlugin { fn color_image_to_rgba(image: &egui::ColorImage) -> RgbaImage { let pixels = image - .pixels + .pixels() .iter() .flat_map(|pixel| pixel.to_array()) .collect(); diff --git a/crates/egui_kittest/tests/screenshot.rs b/crates/egui_kittest/tests/screenshot.rs index 98e95b18..cf3b2e25 100644 --- a/crates/egui_kittest/tests/screenshot.rs +++ b/crates/egui_kittest/tests/screenshot.rs @@ -35,7 +35,7 @@ fn screenshot_callback() { .expect("Expected the screenshot callback to be invoked"); // The frame was filled with red, so the center pixel should be red. - let center = screenshot.pixels[screenshot.pixels.len() / 2]; + let center = screenshot.pixels()[screenshot.pixels().len() / 2]; assert_eq!(center, Color32::RED, "center pixel should be red"); // The screenshot should match the rendered frame size. diff --git a/crates/epaint/benches/benchmark.rs b/crates/epaint/benches/benchmark.rs index a0bcdb77..3a68050a 100644 --- a/crates/epaint/benches/benchmark.rs +++ b/crates/epaint/benches/benchmark.rs @@ -69,7 +69,7 @@ fn tessellate_circles(c: &mut Criterion) { let options = TessellationOptions::default(); let atlas = TextureAtlas::new([4096, 256], Default::default()); - let font_tex_size = atlas.size(); + let font_tex_size = atlas.resolution(); let prepared_discs = atlas.prepared_discs(); b.iter(|| { diff --git a/crates/epaint/src/image.rs b/crates/epaint/src/image.rs index 1e2f3867..f85ffabd 100644 --- a/crates/epaint/src/image.rs +++ b/crates/epaint/src/image.rs @@ -19,18 +19,27 @@ pub enum ImageData { } impl ImageData { - pub fn size(&self) -> [usize; 2] { + /// Image resolution in texels. + #[inline] + pub fn resolution(&self) -> [usize; 2] { match self { - Self::Color(image) => image.size, + Self::Color(image) => image.resolution, } } - pub fn width(&self) -> usize { - self.size()[0] + #[deprecated = "Renamed 'resolution'"] + pub fn size(&self) -> [usize; 2] { + self.resolution() } + /// Image width in texels. + pub fn width(&self) -> usize { + self.resolution()[0] + } + + /// Image height in texels. pub fn height(&self) -> usize { - self.size()[1] + self.resolution()[1] } pub fn bytes_per_pixel(&self) -> usize { @@ -47,129 +56,127 @@ impl ImageData { #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct ColorImage { /// width, height in texels. - pub size: [usize; 2], + resolution: [usize; 2], - /// Size of the original SVG image (if any), or just the texel size of the image. - pub source_size: Vec2, + /// Size of the original SVG image (if any), or just the texel resolution of the image. + source_size: Vec2, /// The pixels, row by row, from top to bottom. - pub pixels: Vec, + pixels: Vec, } impl ColorImage { - /// Create an image filled with the given color. - pub fn new(size: [usize; 2], pixels: Vec) -> Self { - debug_assert!( - size[0] * size[1] == pixels.len(), - "size: {size:?}, pixels.len(): {}", + /// Create an image from the given pixels, row by row, from top to bottom. + /// + /// Panics if `resolution[0] * resolution[1] != pixels.len()`. + pub fn new(resolution: [usize; 2], pixels: Vec) -> Self { + assert!( + resolution[0] * resolution[1] == pixels.len(), + "resolution: {resolution:?}, pixels.len(): {}", pixels.len() ); Self { - size, - source_size: Vec2::new(size[0] as f32, size[1] as f32), + resolution, + source_size: Vec2::new(resolution[0] as f32, resolution[1] as f32), pixels, } } /// Create an image filled with the given color. - pub fn filled(size: [usize; 2], color: Color32) -> Self { - Self { - size, - source_size: Vec2::new(size[0] as f32, size[1] as f32), - pixels: vec![color; size[0] * size[1]], - } + pub fn filled(resolution: [usize; 2], color: Color32) -> Self { + Self::new(resolution, vec![color; resolution[0] * resolution[1]]) } /// Create a [`ColorImage`] from flat un-multiplied RGBA data. /// /// This is usually what you want to use after having loaded an image file. /// - /// Panics if `size[0] * size[1] * 4 != rgba.len()`. + /// Panics if `resolution[0] * resolution[1] * 4 != rgba.len()`. /// /// ## Example using the [`image`](crates.io/crates/image) crate: /// ``` ignore /// fn load_image_from_path(path: &std::path::Path) -> Result { /// let image = image::io::Reader::open(path)?.decode()?; - /// let size = [image.width() as _, image.height() as _]; + /// let resolution = [image.width() as _, image.height() as _]; /// let image_buffer = image.to_rgba8(); /// let pixels = image_buffer.as_flat_samples(); /// Ok(egui::ColorImage::from_rgba_unmultiplied( - /// size, + /// resolution, /// pixels.as_slice(), /// )) /// } /// /// fn load_image_from_memory(image_data: &[u8]) -> Result { /// let image = image::load_from_memory(image_data)?; - /// let size = [image.width() as _, image.height() as _]; + /// let resolution = [image.width() as _, image.height() as _]; /// let image_buffer = image.to_rgba8(); /// let pixels = image_buffer.as_flat_samples(); /// Ok(ColorImage::from_rgba_unmultiplied( - /// size, + /// resolution, /// pixels.as_slice(), /// )) /// } /// ``` - pub fn from_rgba_unmultiplied(size: [usize; 2], rgba: &[u8]) -> Self { + pub fn from_rgba_unmultiplied(resolution: [usize; 2], rgba: &[u8]) -> Self { assert_eq!( - size[0] * size[1] * 4, + resolution[0] * resolution[1] * 4, rgba.len(), - "size: {:?}, rgba.len(): {}", - size, + "resolution: {:?}, rgba.len(): {}", + resolution, rgba.len() ); let pixels = rgba .chunks_exact(4) .map(|p| Color32::from_rgba_unmultiplied(p[0], p[1], p[2], p[3])) .collect(); - Self::new(size, pixels) + Self::new(resolution, pixels) } - pub fn from_rgba_premultiplied(size: [usize; 2], rgba: &[u8]) -> Self { + pub fn from_rgba_premultiplied(resolution: [usize; 2], rgba: &[u8]) -> Self { assert_eq!( - size[0] * size[1] * 4, + resolution[0] * resolution[1] * 4, rgba.len(), - "size: {:?}, rgba.len(): {}", - size, + "resolution: {:?}, rgba.len(): {}", + resolution, rgba.len() ); let pixels = rgba .chunks_exact(4) .map(|p| Color32::from_rgba_premultiplied(p[0], p[1], p[2], p[3])) .collect(); - Self::new(size, pixels) + Self::new(resolution, pixels) } /// Create a [`ColorImage`] from flat opaque gray data. /// - /// Panics if `size[0] * size[1] != gray.len()`. - pub fn from_gray(size: [usize; 2], gray: &[u8]) -> Self { + /// Panics if `resolution[0] * resolution[1] != gray.len()`. + pub fn from_gray(resolution: [usize; 2], gray: &[u8]) -> Self { assert_eq!( - size[0] * size[1], + resolution[0] * resolution[1], gray.len(), - "size: {:?}, gray.len(): {}", - size, + "resolution: {:?}, gray.len(): {}", + resolution, gray.len() ); let pixels = gray.iter().map(|p| Color32::from_gray(*p)).collect(); - Self::new(size, pixels) + Self::new(resolution, pixels) } /// Alternative method to `from_gray`. /// Create a [`ColorImage`] from iterator over flat opaque gray data. /// - /// Panics if `size[0] * size[1] != gray_iter.len()`. + /// Panics if `resolution[0] * resolution[1] != gray_iter.len()`. #[doc(alias = "from_grey_iter")] - pub fn from_gray_iter(size: [usize; 2], gray_iter: impl Iterator) -> Self { + pub fn from_gray_iter(resolution: [usize; 2], gray_iter: impl Iterator) -> Self { let pixels: Vec<_> = gray_iter.map(Color32::from_gray).collect(); assert_eq!( - size[0] * size[1], + resolution[0] * resolution[1], pixels.len(), - "size: {:?}, pixels.len(): {}", - size, + "resolution: {:?}, pixels.len(): {}", + resolution, pixels.len() ); - Self::new(size, pixels) + Self::new(resolution, pixels) } /// A view of the underlying data as `&[u8]` @@ -189,20 +196,20 @@ impl ColorImage { /// This is what you want to use after having loaded an image file (and if /// you are ignoring the alpha channel - considering it to always be 0xff) /// - /// Panics if `size[0] * size[1] * 3 != rgb.len()`. - pub fn from_rgb(size: [usize; 2], rgb: &[u8]) -> Self { + /// Panics if `resolution[0] * resolution[1] * 3 != rgb.len()`. + pub fn from_rgb(resolution: [usize; 2], rgb: &[u8]) -> Self { assert_eq!( - size[0] * size[1] * 3, + resolution[0] * resolution[1] * 3, rgb.len(), - "size: {:?}, rgb.len(): {}", - size, + "resolution: {:?}, rgb.len(): {}", + resolution, rgb.len() ); let pixels = rgb .chunks_exact(3) .map(|p| Color32::from_rgb(p[0], p[1], p[2])) .collect(); - Self::new(size, pixels) + Self::new(resolution, pixels) } /// An example color image, useful for tests. @@ -229,14 +236,63 @@ impl ColorImage { self } + /// Image resolution in texels. #[inline] - pub fn width(&self) -> usize { - self.size[0] + pub fn resolution(&self) -> [usize; 2] { + self.resolution } + #[deprecated = "Renamed 'resolution'"] + pub fn size(&self) -> [usize; 2] { + self.resolution() + } + + /// Image width in texels. + #[inline] + pub fn width(&self) -> usize { + self.resolution[0] + } + + /// Image height in texels. #[inline] pub fn height(&self) -> usize { - self.size[1] + self.resolution[1] + } + + /// The pixels in the image, row-major. + #[inline] + pub fn pixels(&self) -> &[Color32] { + &self.pixels + } + + /// The pixels in the image, row-major. + #[inline] + pub fn pixels_mut(&mut self) -> &mut [Color32] { + &mut self.pixels + } + + /// Size of the original SVG image (if any), or just the texel resolution of the image. + #[inline] + pub fn source_size(&self) -> Vec2 { + self.source_size + } + + /// Double the height until it is larger than `required_height`, + /// filling new rows with transparent pixels. + /// + /// Returns `true` if the image grew. + pub(crate) fn grow_to_min_height(&mut self, required_height: usize) -> bool { + while required_height >= self.height() { + self.resolution[1] *= 2; + } + + let num_pixels = self.width() * self.height(); + if self.pixels.len() < num_pixels { + self.pixels.resize(num_pixels, Color32::TRANSPARENT); + true + } else { + false + } } /// Create a new image from a patch of the current image. @@ -259,7 +315,7 @@ impl ColorImage { let width = max_x - min_x; let height = max_y - min_y; let mut output = Vec::with_capacity(width * height); - let row_stride = self.size[0]; + let row_stride = self.resolution[0]; for row in min_y..max_y { output.extend_from_slice( @@ -306,7 +362,7 @@ impl core::ops::Index<(usize, usize)> for ColorImage { #[inline] fn index(&self, (x, y): (usize, usize)) -> &Color32 { - let [w, h] = self.size; + let [w, h] = self.resolution; assert!(x < w && y < h, "x: {x}, y: {y}, w: {w}, h: {h}"); &self.pixels[y * w + x] } @@ -315,7 +371,7 @@ impl core::ops::Index<(usize, usize)> for ColorImage { impl core::ops::IndexMut<(usize, usize)> for ColorImage { #[inline] fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut Color32 { - let [w, h] = self.size; + let [w, h] = self.resolution; assert!(x < w && y < h, "x: {x}, y: {y}, w: {w}, h: {h}"); &mut self.pixels[y * w + x] } @@ -338,7 +394,7 @@ impl From> for ImageData { impl core::fmt::Debug for ColorImage { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("ColorImage") - .field("size", &self.size) + .field("resolution", &self.resolution) .field("pixel-count", &self.pixels.len()) .finish_non_exhaustive() } diff --git a/crates/epaint/src/text/fonts.rs b/crates/epaint/src/text/fonts.rs index b5ea20e6..51cf19da 100644 --- a/crates/epaint/src/text/fonts.rs +++ b/crates/epaint/src/text/fonts.rs @@ -229,8 +229,8 @@ impl Fonts { /// Current size of the font image. /// Pass this to [`crate::Tessellator`]. - pub fn font_image_size(&self) -> [usize; 2] { - self.fonts.glyphs.atlas().size() + pub fn font_image_resolution(&self) -> [usize; 2] { + self.fonts.glyphs.atlas().resolution() } /// Do the installed fonts have this glyph? @@ -345,8 +345,8 @@ impl FontsView<'_> { /// Current size of the font image. /// Pass this to [`crate::Tessellator`]. - pub fn font_image_size(&self) -> [usize; 2] { - self.fonts.glyphs.atlas().size() + pub fn font_image_resolution(&self) -> [usize; 2] { + self.fonts.glyphs.atlas().resolution() } /// Width of this character in points. diff --git a/crates/epaint/src/text/glyph_atlas.rs b/crates/epaint/src/text/glyph_atlas.rs index a24c5732..5303ea1c 100644 --- a/crates/epaint/src/text/glyph_atlas.rs +++ b/crates/epaint/src/text/glyph_atlas.rs @@ -388,7 +388,7 @@ impl GlyphAtlas { pixels_per_point: f32, transfer: FontColorTransferFunction, ) -> Option { - let [width, height] = bitmap.image.size; + let [width, height] = bitmap.image.resolution(); if width == 0 || height == 0 || MAX_GLYPH_SIZE < width || MAX_GLYPH_SIZE < height { return None; } diff --git a/crates/epaint/src/texture_atlas.rs b/crates/epaint/src/texture_atlas.rs index b482fe4f..0b8c3c3f 100644 --- a/crates/epaint/src/texture_atlas.rs +++ b/crates/epaint/src/texture_atlas.rs @@ -143,15 +143,15 @@ impl TextureAtlas { &self.options } - pub fn size(&self) -> [usize; 2] { - self.image.size + pub fn resolution(&self) -> [usize; 2] { + self.image.resolution() } /// Returns the locations and sizes of pre-rasterized discs (filled circles) in this atlas. pub fn prepared_discs(&self) -> Vec { - let size = self.size(); - let inv_w = 1.0 / size[0] as f32; - let inv_h = 1.0 / size[1] as f32; + let resolution = self.resolution(); + let inv_w = 1.0 / resolution[0] as f32; + let inv_h = 1.0 / resolution[1] as f32; self.discs .iter() .map(|disc| { @@ -247,7 +247,7 @@ impl TextureAtlas { self.cursor = (0, self.image.height() / 3); // Restart a bit down - the top of the atlas has too many important things in it self.overflowed = true; // this will signal the user that we need to recreate the texture atlas next frame. - } else if resize_to_min_height(&mut self.image, required_height) { + } else if self.image.grow_to_min_height(required_height) { self.dirty = Rectu::EVERYTHING; } @@ -262,18 +262,3 @@ impl TextureAtlas { (pos, &mut self.image) } } - -fn resize_to_min_height(image: &mut ColorImage, required_height: usize) -> bool { - while required_height >= image.height() { - image.size[1] *= 2; // double the height - } - - if image.width() * image.height() > image.pixels.len() { - image - .pixels - .resize(image.width() * image.height(), Color32::TRANSPARENT); - true - } else { - false - } -} diff --git a/crates/epaint/src/texture_handle.rs b/crates/epaint/src/texture_handle.rs index e2049d21..51d6eb3c 100644 --- a/crates/epaint/src/texture_handle.rs +++ b/crates/epaint/src/texture_handle.rs @@ -87,19 +87,29 @@ impl TextureHandle { } /// width x height - pub fn size(&self) -> [usize; 2] { + pub fn resolution(&self) -> [usize; 2] { self.tex_mngr .read() .meta(self.id) - .map_or([0, 0], |tex| tex.size) + .map_or([0, 0], |tex| tex.resolution) + } + + #[deprecated = "Renamed 'resolution'"] + pub fn size(&self) -> [usize; 2] { + self.resolution() } /// width x height - pub fn size_vec2(&self) -> crate::Vec2 { - let [w, h] = self.size(); + pub fn resolution_vec2(&self) -> crate::Vec2 { + let [w, h] = self.resolution(); crate::Vec2::new(w as f32, h as f32) } + #[deprecated = "Renamed 'resolution_vec2'"] + pub fn size_vec2(&self) -> crate::Vec2 { + self.resolution_vec2() + } + /// `width x height x bytes_per_pixel` pub fn byte_size(&self) -> usize { self.tex_mngr @@ -110,7 +120,7 @@ impl TextureHandle { /// width / height pub fn aspect_ratio(&self) -> f32 { - let [w, h] = self.size(); + let [w, h] = self.resolution(); w as f32 / h.at_least(1) as f32 } diff --git a/crates/epaint/src/textures.rs b/crates/epaint/src/textures.rs index 594cada7..2a04bc94 100644 --- a/crates/epaint/src/textures.rs +++ b/crates/epaint/src/textures.rs @@ -37,7 +37,7 @@ impl TextureManager { self.metas.entry(id).or_insert_with(|| TextureMeta { name, - size: image.size(), + resolution: image.resolution(), bytes_per_pixel: image.bytes_per_pixel(), retain_count: 1, options, @@ -53,13 +53,13 @@ impl TextureManager { if let Some(meta) = self.metas.get_mut(&id) { if let Some(pos) = delta.pos { debug_assert!( - pos[0] + delta.image.width() <= meta.size[0] - && pos[1] + delta.image.height() <= meta.size[1], + pos[0] + delta.image.width() <= meta.resolution[0] + && pos[1] + delta.image.height() <= meta.resolution[1], "Partial texture update is outside the bounds of texture {id:?}", ); } else { // whole update - meta.size = delta.image.size(); + meta.resolution = delta.image.resolution(); meta.bytes_per_pixel = delta.image.bytes_per_pixel(); } self.delta.push(id, delta); @@ -132,7 +132,7 @@ pub struct TextureMeta { pub name: String, /// width x height - pub size: [usize; 2], + pub resolution: [usize; 2], /// 4 or 1 pub bytes_per_pixel: usize, @@ -148,7 +148,7 @@ impl TextureMeta { /// Size in bytes. /// width x height x [`Self::bytes_per_pixel`]. pub fn bytes_used(&self) -> usize { - self.size[0] * self.size[1] * self.bytes_per_pixel + self.resolution[0] * self.resolution[1] * self.bytes_per_pixel } } @@ -353,7 +353,7 @@ impl core::fmt::Debug for TexturesDelta { #[expect(clippy::iter_over_hash_type)] for (tex_id, deltas) in &self.set { for delta in deltas { - let size = delta.image.size(); + let size = delta.image.resolution(); if let Some(pos) = delta.pos { write!( string,