Add support for partial GPU texture updates

Mainly used for font atlas changes. Each glyph allocation now only
triggers a partial texture update instead of creating a full new
texture.
This commit is contained in:
meehl committed 2026-09-01 10:17:34 +02:00
1 parent e3288b96ac
commit e90396ff28
7 files changed
+326 -162

No files matched your search

+4 -5
View File
@@ -88,11 +88,10 @@ impl App {
let stage_output = self.stage.frame()?; let stage_output = self.stage.frame()?;
if let Some(font_image_delta) = self.fonts.borrow_mut().font_atlas_delta() { let font_image_delta = self.fonts.borrow_mut().font_atlas_delta();
self.texture_manager self.texture_manager
.borrow() .borrow()
.update_font_texture(font_image_delta); .update_font_texture(font_image_delta);
}
let textures_delta = self.texture_manager.borrow().take_delta(); let textures_delta = self.texture_manager.borrow().take_delta();
+1 -1
View File
@@ -100,7 +100,7 @@ impl Fonts {
} }
/// Gets changes to the font atlas texture since last call. /// Gets changes to the font atlas texture since last call.
pub fn font_atlas_delta(&mut self) -> Option<ImageDelta> { pub fn font_atlas_delta(&mut self) -> Vec<ImageDelta> {
self.atlas.take_delta() self.atlas.take_delta()
} }
+70 -27
View File
@@ -5,7 +5,7 @@ use crate::{
dpi::PhysicalSize, dpi::PhysicalSize,
math::{Point, Rect, Scale, Size}, math::{Point, Rect, Scale, Size},
renderer::{ renderer::{
image::{DataOrder, ImageData, ImageDelta}, image::{DataOrder, ImageData, ImageDelta, MipStrategy, PartialDeltaOrigin},
textures::TextureOptions, textures::TextureOptions,
}, },
uv::{UvRect, UvSpace}, uv::{UvRect, UvSpace},
@@ -25,9 +25,11 @@ pub struct AllocatedGlyph<'a> {
struct Layer { struct Layer {
image: RgbaImage, image: RgbaImage,
// position of next allocation /// Position of next allocation
cursor: FontAtlasPoint, cursor: FontAtlasPoint,
current_row_height: u32, current_row_height: u32,
/// Dirty region
dirty: FontAtlasRect,
} }
pub struct FontAtlas { pub struct FontAtlas {
@@ -35,11 +37,10 @@ pub struct FontAtlas {
// maximum amount of layers // maximum amount of layers
max_layers: u32, max_layers: u32,
layers: Vec<Layer>, layers: Vec<Layer>,
// atlas has been altered and needs to be reuploaded to the GPU
// TODO: only mark changed regions as dirty and perform partial texture update
dirty: bool,
// used to convert to normalized UV coordinates // used to convert to normalized UV coordinates
to_uv: Scale<f32, FontAtlasSpace, UvSpace>, to_uv: Scale<f32, FontAtlasSpace, UvSpace>,
/// Set when a full texture upload is required
needs_full_update: bool,
} }
impl FontAtlas { impl FontAtlas {
@@ -48,8 +49,8 @@ impl FontAtlas {
layer_size: Size::new(layer_size, layer_size), layer_size: Size::new(layer_size, layer_size),
max_layers, max_layers,
layers: Vec::new(), layers: Vec::new(),
dirty: false,
to_uv: Scale::new(1.0 / layer_size as f32), to_uv: Scale::new(1.0 / layer_size as f32),
needs_full_update: false,
}; };
atlas.push_layer(); atlas.push_layer();
@@ -63,7 +64,11 @@ impl FontAtlas {
image: RgbaImage::new(self.layer_size.width, self.layer_size.height), image: RgbaImage::new(self.layer_size.width, self.layer_size.height),
cursor: FontAtlasPoint::zero(), cursor: FontAtlasPoint::zero(),
current_row_height: 0, current_row_height: 0,
dirty: FontAtlasRect::zero(),
}); });
// adding a new layer requires a full texture re-allocation
self.needs_full_update = true;
} }
/// Initializes the atlas. /// Initializes the atlas.
@@ -108,11 +113,13 @@ impl FontAtlas {
layer.current_row_height = layer.current_row_height.max(requested_size.height); layer.current_row_height = layer.current_row_height.max(requested_size.height);
let pos = layer.cursor; let pos = layer.cursor;
layer.cursor.x += requested_size.width + PADDING; layer.cursor.x += requested_size.width + PADDING;
self.dirty = true;
let glyph_rect = FontAtlasRect::from_origin_and_size(pos, requested_size); let glyph_rect = FontAtlasRect::from_origin_and_size(pos, requested_size);
let uv = self.to_uv.transform_box2d(&glyph_rect.cast()); let uv = self.to_uv.transform_box2d(&glyph_rect.cast());
// extend dirty region to include new glyph allocation
layer.dirty = layer.dirty.union(&glyph_rect);
AllocatedGlyph { AllocatedGlyph {
sub_image: layer.image.sub_image( sub_image: layer.image.sub_image(
pos.x, pos.x,
@@ -125,31 +132,67 @@ impl FontAtlas {
} }
} }
pub fn take_delta(&mut self) -> Option<ImageDelta> { pub fn take_delta(&mut self) -> Vec<ImageDelta> {
if !std::mem::replace(&mut self.dirty, false) { // first check if full update is required
return None; if std::mem::replace(&mut self.needs_full_update, false) {
let mut bytes = Vec::with_capacity(
self.layers.len() * (self.layer_size.width * self.layer_size.height * 4) as usize,
);
for layer in &mut self.layers {
bytes.extend_from_slice(layer.image.as_raw());
// reset layer's dirty region since we're doing a full update anyway
layer.dirty = FontAtlasRect::zero();
}
return vec![ImageDelta::full(
ImageData {
format: wgpu::TextureFormat::Rgba8Unorm,
width: self.layer_size.width,
height: self.layer_size.height,
array_layers: self.layers.len() as u32,
mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"),
data_order: DataOrder::default(),
bytes,
},
TextureOptions::LINEAR,
MipStrategy::None,
)];
} }
let mut bytes = Vec::with_capacity( // add partial update for each dirty layer
self.layers.len() * (self.layer_size.width * self.layer_size.height * 4) as usize, let mut partial_updates = Vec::new();
); for (i, layer) in self.layers.iter_mut().enumerate() {
let dirty = std::mem::replace(&mut layer.dirty, FontAtlasRect::zero());
if dirty.is_empty() {
continue;
}
for layer in &self.layers { let bytes = layer
bytes.extend_from_slice(layer.image.as_raw()); .image
.sub_image(dirty.min.x, dirty.min.y, dirty.width(), dirty.height())
.to_image()
.into_vec();
partial_updates.push(ImageDelta::partial(
ImageData {
format: wgpu::TextureFormat::Rgba8Unorm,
width: dirty.width(),
height: dirty.height(),
array_layers: 1,
mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"),
data_order: DataOrder::default(),
bytes,
},
PartialDeltaOrigin {
x: dirty.min.x,
y: dirty.min.y,
layer: i as u32,
},
));
} }
Some(ImageDelta::new( partial_updates
ImageData {
format: wgpu::TextureFormat::Rgba8Unorm,
width: self.layer_size.width,
height: self.layer_size.height,
array_layers: self.layers.len() as u32,
mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"),
data_order: DataOrder::default(),
bytes,
},
TextureOptions::LINEAR,
))
} }
pub fn write_mask( pub fn write_mask(
+7 -5
View File
@@ -201,6 +201,7 @@ unsafe extern "C-unwind" fn image_handle_load(state: *mut ffi::lua_State) -> c_i
// Flags // Flags
let mut is_async = false; let mut is_async = false;
let mut generate_mipmaps = false;
let mut options = TextureOptions::LINEAR_REPEAT; let mut options = TextureOptions::LINEAR_REPEAT;
let nargs = unsafe { ffi::lua_gettop(state) }; let nargs = unsafe { ffi::lua_gettop(state) };
@@ -230,7 +231,7 @@ unsafe extern "C-unwind" fn image_handle_load(state: *mut ffi::lua_State) -> c_i
is_async = true; is_async = true;
} }
b"MIPMAP" => { b"MIPMAP" => {
options.generate_mipmaps = true; generate_mipmaps = true;
} }
_ => {} _ => {}
} }
@@ -250,13 +251,14 @@ unsafe extern "C-unwind" fn image_handle_load(state: *mut ffi::lua_State) -> c_i
path, path,
options, options,
is_async, is_async,
generate_mipmaps,
); );
} }
None => { None => {
if let Ok(texture_handle) = ctx if let Ok(texture_handle) =
.texture_manager ctx.texture_manager
.borrow() .borrow()
.load_texture(path, options, is_async) .load_texture(path, options, is_async, generate_mipmaps)
{ {
handle.texture = Some(texture_handle); handle.texture = Some(texture_handle);
} }
+120 -89
View File
@@ -3,7 +3,7 @@ use crate::{
dpi::{LogicalPoint, LogicalRect, LogicalSize, PhysicalRect, PhysicalSize, ScaleFactor}, dpi::{LogicalPoint, LogicalRect, LogicalSize, PhysicalRect, PhysicalSize, ScaleFactor},
math::Point, math::Point,
renderer::{ renderer::{
image::ImageData, image::{ImageData, MipStrategy},
textures::{TextureId, TextureOptions, TexturesDelta}, textures::{TextureId, TextureOptions, TexturesDelta},
}, },
util::calculate_hash, util::calculate_hash,
@@ -15,7 +15,7 @@ use std::{
num::{NonZeroU32, NonZeroU64}, num::{NonZeroU32, NonZeroU64},
ops::Range, ops::Range,
}; };
use wgpu::util::DeviceExt; use wgpu::{Origin3d, util::DeviceExt};
pub mod image; pub mod image;
mod mipmap; mod mipmap;
@@ -325,80 +325,119 @@ impl Renderer {
) { ) {
profiling::scope!("update_textures"); profiling::scope!("update_textures");
if !textures_delta.update.is_empty() {
self.batch_bind_group_cache.clear();
}
for (id, image_delta) in &textures_delta.update { for (id, image_delta) in &textures_delta.update {
let ImageData { match image_delta {
format, image::ImageDelta::Full {
width, image,
height, options,
array_layers, mip_strategy,
mipmap_count, } => {
data_order, let ImageData {
ref bytes, format,
} = image_delta.image; width,
height,
array_layers,
mipmap_count,
data_order,
bytes,
} = image;
let size = wgpu::Extent3d { let size = wgpu::Extent3d {
width, width: *width,
height, height: *height,
depth_or_array_layers: array_layers, depth_or_array_layers: *array_layers,
}; };
// only generate mipmaps for uncompressed images that don't already have mipmaps let gen_mipmaps = matches!(mip_strategy, MipStrategy::GenerateOnUpload);
let gen_mipmaps = image_delta.options.generate_mipmaps
&& mipmap_count.get() == 1
&& !format.is_compressed();
let mip_level_count = if gen_mipmaps { let mip_level_count = if gen_mipmaps {
size.max_mips(wgpu::TextureDimension::D2) size.max_mips(wgpu::TextureDimension::D2)
} else { } else {
mipmap_count.get() mipmap_count.get()
}; };
let label_str = format!("texture_{id:?}"); let label_str = format!("texture_{id:?}");
let label = Some(label_str.as_str()); let label = Some(label_str.as_str());
let texture = create_texture_with_data( let texture = create_texture_with_data(
device, device,
queue, queue,
&wgpu::TextureDescriptor { &wgpu::TextureDescriptor {
label, label,
size, size,
mip_level_count, mip_level_count,
sample_count: 1, sample_count: 1,
dimension: wgpu::TextureDimension::D2, dimension: wgpu::TextureDimension::D2,
format, format: *format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, usage: wgpu::TextureUsages::TEXTURE_BINDING
view_formats: &[format.add_srgb_suffix()], | wgpu::TextureUsages::COPY_DST,
}, view_formats: &[format.add_srgb_suffix()],
data_order.into(), },
bytes, (*data_order).into(),
gen_mipmaps, bytes,
); gen_mipmaps,
);
if gen_mipmaps { if gen_mipmaps {
mipmap::generate_mipmap_chain(queue, &texture, bytes); mipmap::generate_mipmap_chain(queue, &texture, bytes);
}
let view = texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
self.samplers
.entry(*options)
.or_insert_with(|| create_sampler(*options, device));
self.textures.insert(
*id,
TextureEntry {
texture,
view,
options: *options,
},
);
self.batch_bind_group_cache.clear();
}
image::ImageDelta::Partial {
image: source,
origin,
} => {
let destination = self.textures.get(id).expect("Texture is allocated");
let size = wgpu::Extent3d {
width: source.width,
height: source.height,
depth_or_array_layers: 1,
};
let origin = Origin3d {
x: origin.x,
y: origin.y,
z: origin.layer,
};
// NOTE: this doesn't handle mipmaps or formats other than RBGA
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &destination.texture,
mip_level: 0,
origin,
aspect: wgpu::wgt::TextureAspect::All,
},
&source.bytes,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(4 * source.width),
rows_per_image: Some(source.height),
},
size,
);
}
} }
let view = texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
self.samplers
.entry(image_delta.options)
.or_insert_with(|| create_sampler(image_delta.options, device));
self.textures.insert(
*id,
TextureEntry {
texture,
view,
options: image_delta.options,
},
);
} }
} }
@@ -607,30 +646,22 @@ fn create_texture_with_data(
data: &[u8], data: &[u8],
skip_mipmaps: bool, skip_mipmaps: bool,
) -> wgpu::Texture { ) -> wgpu::Texture {
// Implicitly add the COPY_DST usage // implicitly add the COPY_DST usage
let mut desc = desc.to_owned(); let mut desc = desc.to_owned();
desc.usage |= wgpu::TextureUsages::COPY_DST; desc.usage |= wgpu::TextureUsages::COPY_DST;
let texture = device.create_texture(&desc); let texture = device.create_texture(&desc);
// Will return None only if it's a combined depth-stencil format // will return None only if it's a combined depth-stencil format. if so, default to 4,
// If so, default to 4, validation will fail later anyway since the depth or stencil // validation will fail later anyway since the depth or stencil aspect needs to be written to
// aspect needs to be written to individually // individually
let block_size = desc.format.block_copy_size(None).unwrap_or(4); let block_size = desc.format.block_copy_size(None).unwrap_or(4);
let (block_width, block_height) = desc.format.block_dimensions(); let (block_width, block_height) = desc.format.block_dimensions();
let layer_iterations = desc.array_layer_count(); let layer_iterations = desc.array_layer_count();
let outer_iteration; let (outer_iteration, inner_iteration) = match order {
let inner_iteration; wgpu::wgt::TextureDataOrder::LayerMajor => (layer_iterations, desc.mip_level_count),
match order { wgpu::wgt::TextureDataOrder::MipMajor => (desc.mip_level_count, layer_iterations),
wgpu::wgt::TextureDataOrder::LayerMajor => { };
outer_iteration = layer_iterations;
inner_iteration = desc.mip_level_count;
}
wgpu::wgt::TextureDataOrder::MipMajor => {
outer_iteration = desc.mip_level_count;
inner_iteration = layer_iterations;
}
}
let mut binary_offset = 0; let mut binary_offset = 0;
for outer in 0..outer_iteration { for outer in 0..outer_iteration {
@@ -646,13 +677,13 @@ fn create_texture_with_data(
mip_size.depth_or_array_layers = 1; mip_size.depth_or_array_layers = 1;
} }
// When uploading mips of compressed textures and the mip is supposed to be // when uploading mips of compressed textures and the mip is supposed to be a size that
// a size that isn't a multiple of the block size, the mip needs to be uploaded // isn't a multiple of the block size, the mip needs to be uploaded as its "physical
// as its "physical size" which is the size rounded up to the nearest block size. // size" which is the size rounded up to the nearest block size.
let mip_physical = mip_size.physical_size(desc.format); let mip_physical = mip_size.physical_size(desc.format);
// All these calculations are performed on the physical size as that's the // all these calculations are performed on the physical size as that's the data that
// data that exists in the buffer. // exists in the buffer.
let width_blocks = mip_physical.width / block_width; let width_blocks = mip_physical.width / block_width;
let height_blocks = mip_physical.height / block_height; let height_blocks = mip_physical.height / block_height;
+72 -6
View File
@@ -2,17 +2,83 @@ use crate::{color::Srgba, renderer::textures::TextureOptions};
use image::{DynamicImage, RgbaImage}; use image::{DynamicImage, RgbaImage};
use std::{io::Read, num::NonZeroU32, path::Path}; use std::{io::Read, num::NonZeroU32, path::Path};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MipStrategy {
/// Single mip level.
None,
/// Generate mip chain from mip 0 on upload.
GenerateOnUpload,
/// Upload as is. Used when `ImageData` already contains a full mip chain (e.g. when loaded from DDS).
Provided,
}
impl MipStrategy {
/// Resolves to a `MipStrategy` based on the actual `ImageData` and the callers request to
/// generate a mip chain if possible.
pub fn resolve(image: &ImageData, generate_if_possible: bool) -> Self {
if image.mipmap_count.get() > 1 {
Self::Provided
} else if generate_if_possible && !image.format.is_compressed() {
Self::GenerateOnUpload
} else {
Self::None
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct PartialDeltaOrigin {
pub x: u32,
pub y: u32,
pub layer: u32,
}
/// Represents the change to a GPU texture.
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub struct ImageDelta { pub enum ImageDelta {
pub image: ImageData, /// Creates a whole new texture.
pub options: TextureOptions, Full {
image: ImageData,
options: TextureOptions,
mip_strategy: MipStrategy,
},
/// Updates a sub-region starting at `origin` of an existing texture.
Partial {
image: ImageData,
origin: PartialDeltaOrigin,
},
} }
impl ImageDelta { impl ImageDelta {
pub fn new<I: Into<ImageData>>(image: I, options: TextureOptions) -> Self { pub fn full<I: Into<ImageData>>(
Self { image: I,
image: image.into(), options: TextureOptions,
mip_strategy: MipStrategy,
) -> Self {
let image = image.into();
debug_assert!(
match mip_strategy {
MipStrategy::None => true,
MipStrategy::GenerateOnUpload => {
image.mipmap_count.get() == 1 && !image.format.is_compressed()
}
MipStrategy::Provided => image.mipmap_count.get() > 1,
},
"MipStrategy inconsistent with image data"
);
Self::Full {
image,
options, options,
mip_strategy,
}
}
pub fn partial<I: Into<ImageData>>(image: I, origin: PartialDeltaOrigin) -> Self {
Self::Partial {
image: image.into(),
origin,
} }
} }
} }
+52 -29
View File
@@ -5,7 +5,7 @@ use anyhow::bail;
use crate::{ use crate::{
color::Srgba, color::Srgba,
renderer::image::{ImageData, ImageDelta, load_image_file}, renderer::image::{ImageData, ImageDelta, MipStrategy, load_image_file},
worker_pool::WorkerPool, worker_pool::WorkerPool,
}; };
@@ -80,10 +80,18 @@ struct TextureRegistry {
impl TextureRegistry { impl TextureRegistry {
/// Allocates a new Texture. /// Allocates a new Texture.
pub fn alloc(&mut self, name: String, image: ImageData, options: TextureOptions) -> TextureId { pub fn alloc(
&mut self,
name: String,
image: ImageData,
options: TextureOptions,
generate_mipmaps: bool,
) -> TextureId {
let id = self.next_id; let id = self.next_id;
self.next_id += 1; self.next_id += 1;
let mip_strategy = MipStrategy::resolve(&image, generate_mipmaps);
self.meta_data.insert( self.meta_data.insert(
id, id,
TextureMetaData { TextureMetaData {
@@ -96,7 +104,7 @@ impl TextureRegistry {
self.delta self.delta
.update .update
.push((id, ImageDelta::new(image, options))); .push((id, ImageDelta::full(image, options, mip_strategy)));
id id
} }
@@ -122,9 +130,11 @@ impl TextureRegistry {
/// Assigns a new image to an existing texture. /// Assigns a new image to an existing texture.
pub fn set(&mut self, id: TextureId, delta: ImageDelta) { pub fn set(&mut self, id: TextureId, delta: ImageDelta) {
if let Some(meta_data) = self.meta_data.get_mut(&id) { if let Some(meta_data) = self.meta_data.get_mut(&id) {
meta_data.size = [delta.image.width as usize, delta.image.height as usize]; if let ImageDelta::Full { image, .. } = &delta {
// discard all old enqueued deltas meta_data.size = [image.width as usize, image.height as usize];
self.delta.update.retain(|(x, _)| x != &id); // discard all old enqueued deltas since we're doing a full update
self.delta.update.retain(|(x, _)| x != &id);
}
self.delta.update.push((id, delta)); self.delta.update.push((id, delta));
} else { } else {
// the handle may have been dropped while the async load was in flight. // the handle may have been dropped while the async load was in flight.
@@ -181,6 +191,7 @@ enum LoadResult {
id: TextureId, id: TextureId,
image: ImageData, image: ImageData,
options: TextureOptions, options: TextureOptions,
generate_mipmaps: bool,
}, },
} }
@@ -199,8 +210,9 @@ impl TextureManager {
// allocate default texture (id: 0) for font atlas // allocate default texture (id: 0) for font atlas
manager.alloc( manager.alloc(
"font_atlas_texture".into(), "font_atlas_texture".into(),
ImageData::from_solid_color([0, 0], Srgba::TRANSPARENT), ImageData::from_solid_color([1, 1], Srgba::WHITE),
TextureOptions::default(), TextureOptions::default(),
false,
); );
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
@@ -214,8 +226,10 @@ impl TextureManager {
} }
#[inline] #[inline]
pub fn update_font_texture(&self, delta: ImageDelta) { pub fn update_font_texture(&self, delta: Vec<ImageDelta>) {
self.manager.borrow_mut().set(TextureId::default(), delta); delta.into_iter().for_each(|d| {
self.manager.borrow_mut().set(TextureId::default(), d);
});
} }
#[inline] #[inline]
@@ -229,6 +243,7 @@ impl TextureManager {
image_path: String, image_path: String,
options: TextureOptions, options: TextureOptions,
is_async: bool, is_async: bool,
generate_mipmaps: bool,
) -> anyhow::Result<TextureHandle> { ) -> anyhow::Result<TextureHandle> {
profiling::scope!("load_texture"); profiling::scope!("load_texture");
@@ -242,7 +257,12 @@ impl TextureManager {
self.worker_pool self.worker_pool
.execute(move || match load_image_file(Path::new(&image_path)) { .execute(move || match load_image_file(Path::new(&image_path)) {
Ok(image) => { Ok(image) => {
let _ = tx.send(LoadResult::Loaded { id, image, options }); let _ = tx.send(LoadResult::Loaded {
id,
image,
options,
generate_mipmaps,
});
} }
Err(e) => log::warn!("Unable to load image from {image_path}: {e}"), Err(e) => log::warn!("Unable to load image from {image_path}: {e}"),
}); });
@@ -251,7 +271,12 @@ impl TextureManager {
} else { } else {
match load_image_file(Path::new(&image_path)) { match load_image_file(Path::new(&image_path)) {
Ok(image) => { Ok(image) => {
let id = self.manager.borrow_mut().alloc(image_path, image, options); let id = self.manager.borrow_mut().alloc(
image_path,
image,
options,
generate_mipmaps,
);
Ok(TextureHandle::new(Rc::clone(&self.manager), id)) Ok(TextureHandle::new(Rc::clone(&self.manager), id))
} }
Err(e) => { Err(e) => {
@@ -268,6 +293,7 @@ impl TextureManager {
image_path: String, image_path: String,
options: TextureOptions, options: TextureOptions,
is_async: bool, is_async: bool,
generate_mipmaps: bool,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
if is_async { if is_async {
let tx = self.results_tx.clone(); let tx = self.results_tx.clone();
@@ -278,19 +304,21 @@ impl TextureManager {
id: texture_id, id: texture_id,
image, image,
options, options,
generate_mipmaps,
}); });
} }
Err(e) => log::warn!("Unable to load image fron {image_path}: {e}"), Err(e) => log::warn!("Unable to load image from {image_path}: {e}"),
}); });
} else { } else {
match load_image_file(Path::new(&image_path)) { match load_image_file(Path::new(&image_path)) {
Ok(image) => { Ok(image) => {
let mip_strategy = MipStrategy::resolve(&image, generate_mipmaps);
self.manager self.manager
.borrow_mut() .borrow_mut()
.set(texture_id, ImageDelta::new(image, options)); .set(texture_id, ImageDelta::full(image, options, mip_strategy));
} }
Err(e) => { Err(e) => {
log::warn!("Unable to load image fron {image_path}: {e}"); log::warn!("Unable to load image from {image_path}: {e}");
bail!(e); bail!(e);
} }
} }
@@ -302,19 +330,25 @@ impl TextureManager {
/// Drains completed async image loads and assigns them to textures /// Drains completed async image loads and assigns them to textures
fn apply_pending_loads(&self) { fn apply_pending_loads(&self) {
let mut manager = self.manager.borrow_mut(); let mut manager = self.manager.borrow_mut();
while let Ok(LoadResult::Loaded { id, image, options }) = self.results_rx.try_recv() { while let Ok(LoadResult::Loaded {
manager.set(id, ImageDelta::new(image, options)); id,
image,
options,
generate_mipmaps,
}) = self.results_rx.try_recv()
{
let mip_strategy = MipStrategy::resolve(&image, generate_mipmaps);
manager.set(id, ImageDelta::full(image, options, mip_strategy));
} }
} }
} }
#[derive(Copy, Clone, Debug, PartialEq, Eq)] #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct TextureOptions { pub struct TextureOptions {
pub magnification: wgpu::FilterMode, pub magnification: wgpu::FilterMode,
pub minification: wgpu::FilterMode, pub minification: wgpu::FilterMode,
pub wrap_mode: wgpu::AddressMode, pub wrap_mode: wgpu::AddressMode,
pub mipmap_mode: wgpu::MipmapFilterMode, pub mipmap_mode: wgpu::MipmapFilterMode,
pub generate_mipmaps: bool,
} }
impl TextureOptions { impl TextureOptions {
@@ -323,7 +357,6 @@ impl TextureOptions {
minification: wgpu::FilterMode::Linear, minification: wgpu::FilterMode::Linear,
wrap_mode: wgpu::AddressMode::Repeat, wrap_mode: wgpu::AddressMode::Repeat,
mipmap_mode: wgpu::MipmapFilterMode::Linear, mipmap_mode: wgpu::MipmapFilterMode::Linear,
generate_mipmaps: false,
}; };
pub const LINEAR: Self = Self { pub const LINEAR: Self = Self {
@@ -331,7 +364,6 @@ impl TextureOptions {
minification: wgpu::FilterMode::Linear, minification: wgpu::FilterMode::Linear,
wrap_mode: wgpu::AddressMode::ClampToEdge, wrap_mode: wgpu::AddressMode::ClampToEdge,
mipmap_mode: wgpu::MipmapFilterMode::Linear, mipmap_mode: wgpu::MipmapFilterMode::Linear,
generate_mipmaps: false,
}; };
} }
@@ -340,12 +372,3 @@ impl Default for TextureOptions {
Self::LINEAR Self::LINEAR
} }
} }
impl std::hash::Hash for TextureOptions {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.magnification.hash(state);
self.minification.hash(state);
self.wrap_mode.hash(state);
self.mipmap_mode.hash(state);
}
}