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:
1 parent
e3288b96ac
commit
e90396ff28
7 files changed
+326
-162
No files matched your search
+4
-5
@@ -88,11 +88,10 @@ impl App {
|
||||
|
||||
let stage_output = self.stage.frame()?;
|
||||
|
||||
if let Some(font_image_delta) = self.fonts.borrow_mut().font_atlas_delta() {
|
||||
self.texture_manager
|
||||
.borrow()
|
||||
.update_font_texture(font_image_delta);
|
||||
}
|
||||
let font_image_delta = self.fonts.borrow_mut().font_atlas_delta();
|
||||
self.texture_manager
|
||||
.borrow()
|
||||
.update_font_texture(font_image_delta);
|
||||
|
||||
let textures_delta = self.texture_manager.borrow().take_delta();
|
||||
|
||||
|
||||
+1
-1
@@ -100,7 +100,7 @@ impl Fonts {
|
||||
}
|
||||
|
||||
/// 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()
|
||||
}
|
||||
|
||||
|
||||
+70
-27
@@ -5,7 +5,7 @@ use crate::{
|
||||
dpi::PhysicalSize,
|
||||
math::{Point, Rect, Scale, Size},
|
||||
renderer::{
|
||||
image::{DataOrder, ImageData, ImageDelta},
|
||||
image::{DataOrder, ImageData, ImageDelta, MipStrategy, PartialDeltaOrigin},
|
||||
textures::TextureOptions,
|
||||
},
|
||||
uv::{UvRect, UvSpace},
|
||||
@@ -25,9 +25,11 @@ pub struct AllocatedGlyph<'a> {
|
||||
|
||||
struct Layer {
|
||||
image: RgbaImage,
|
||||
// position of next allocation
|
||||
/// Position of next allocation
|
||||
cursor: FontAtlasPoint,
|
||||
current_row_height: u32,
|
||||
/// Dirty region
|
||||
dirty: FontAtlasRect,
|
||||
}
|
||||
|
||||
pub struct FontAtlas {
|
||||
@@ -35,11 +37,10 @@ pub struct FontAtlas {
|
||||
// maximum amount of layers
|
||||
max_layers: u32,
|
||||
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
|
||||
to_uv: Scale<f32, FontAtlasSpace, UvSpace>,
|
||||
/// Set when a full texture upload is required
|
||||
needs_full_update: bool,
|
||||
}
|
||||
|
||||
impl FontAtlas {
|
||||
@@ -48,8 +49,8 @@ impl FontAtlas {
|
||||
layer_size: Size::new(layer_size, layer_size),
|
||||
max_layers,
|
||||
layers: Vec::new(),
|
||||
dirty: false,
|
||||
to_uv: Scale::new(1.0 / layer_size as f32),
|
||||
needs_full_update: false,
|
||||
};
|
||||
|
||||
atlas.push_layer();
|
||||
@@ -63,7 +64,11 @@ impl FontAtlas {
|
||||
image: RgbaImage::new(self.layer_size.width, self.layer_size.height),
|
||||
cursor: FontAtlasPoint::zero(),
|
||||
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.
|
||||
@@ -108,11 +113,13 @@ impl FontAtlas {
|
||||
layer.current_row_height = layer.current_row_height.max(requested_size.height);
|
||||
let pos = layer.cursor;
|
||||
layer.cursor.x += requested_size.width + PADDING;
|
||||
self.dirty = true;
|
||||
|
||||
let glyph_rect = FontAtlasRect::from_origin_and_size(pos, requested_size);
|
||||
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 {
|
||||
sub_image: layer.image.sub_image(
|
||||
pos.x,
|
||||
@@ -125,31 +132,67 @@ impl FontAtlas {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_delta(&mut self) -> Option<ImageDelta> {
|
||||
if !std::mem::replace(&mut self.dirty, false) {
|
||||
return None;
|
||||
pub fn take_delta(&mut self) -> Vec<ImageDelta> {
|
||||
// first check if full update is required
|
||||
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(
|
||||
self.layers.len() * (self.layer_size.width * self.layer_size.height * 4) as usize,
|
||||
);
|
||||
// add partial update for each dirty layer
|
||||
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 {
|
||||
bytes.extend_from_slice(layer.image.as_raw());
|
||||
let bytes = layer
|
||||
.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(
|
||||
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,
|
||||
))
|
||||
partial_updates
|
||||
}
|
||||
|
||||
pub fn write_mask(
|
||||
|
||||
@@ -201,6 +201,7 @@ unsafe extern "C-unwind" fn image_handle_load(state: *mut ffi::lua_State) -> c_i
|
||||
|
||||
// Flags
|
||||
let mut is_async = false;
|
||||
let mut generate_mipmaps = false;
|
||||
let mut options = TextureOptions::LINEAR_REPEAT;
|
||||
|
||||
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;
|
||||
}
|
||||
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,
|
||||
options,
|
||||
is_async,
|
||||
generate_mipmaps,
|
||||
);
|
||||
}
|
||||
None => {
|
||||
if let Ok(texture_handle) = ctx
|
||||
.texture_manager
|
||||
.borrow()
|
||||
.load_texture(path, options, is_async)
|
||||
if let Ok(texture_handle) =
|
||||
ctx.texture_manager
|
||||
.borrow()
|
||||
.load_texture(path, options, is_async, generate_mipmaps)
|
||||
{
|
||||
handle.texture = Some(texture_handle);
|
||||
}
|
||||
|
||||
+120
-89
@@ -3,7 +3,7 @@ use crate::{
|
||||
dpi::{LogicalPoint, LogicalRect, LogicalSize, PhysicalRect, PhysicalSize, ScaleFactor},
|
||||
math::Point,
|
||||
renderer::{
|
||||
image::ImageData,
|
||||
image::{ImageData, MipStrategy},
|
||||
textures::{TextureId, TextureOptions, TexturesDelta},
|
||||
},
|
||||
util::calculate_hash,
|
||||
@@ -15,7 +15,7 @@ use std::{
|
||||
num::{NonZeroU32, NonZeroU64},
|
||||
ops::Range,
|
||||
};
|
||||
use wgpu::util::DeviceExt;
|
||||
use wgpu::{Origin3d, util::DeviceExt};
|
||||
|
||||
pub mod image;
|
||||
mod mipmap;
|
||||
@@ -325,80 +325,119 @@ impl Renderer {
|
||||
) {
|
||||
profiling::scope!("update_textures");
|
||||
|
||||
if !textures_delta.update.is_empty() {
|
||||
self.batch_bind_group_cache.clear();
|
||||
}
|
||||
|
||||
for (id, image_delta) in &textures_delta.update {
|
||||
let ImageData {
|
||||
format,
|
||||
width,
|
||||
height,
|
||||
array_layers,
|
||||
mipmap_count,
|
||||
data_order,
|
||||
ref bytes,
|
||||
} = image_delta.image;
|
||||
match image_delta {
|
||||
image::ImageDelta::Full {
|
||||
image,
|
||||
options,
|
||||
mip_strategy,
|
||||
} => {
|
||||
let ImageData {
|
||||
format,
|
||||
width,
|
||||
height,
|
||||
array_layers,
|
||||
mipmap_count,
|
||||
data_order,
|
||||
bytes,
|
||||
} = image;
|
||||
|
||||
let size = wgpu::Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: array_layers,
|
||||
};
|
||||
let size = wgpu::Extent3d {
|
||||
width: *width,
|
||||
height: *height,
|
||||
depth_or_array_layers: *array_layers,
|
||||
};
|
||||
|
||||
// only generate mipmaps for uncompressed images that don't already have mipmaps
|
||||
let gen_mipmaps = image_delta.options.generate_mipmaps
|
||||
&& mipmap_count.get() == 1
|
||||
&& !format.is_compressed();
|
||||
let gen_mipmaps = matches!(mip_strategy, MipStrategy::GenerateOnUpload);
|
||||
|
||||
let mip_level_count = if gen_mipmaps {
|
||||
size.max_mips(wgpu::TextureDimension::D2)
|
||||
} else {
|
||||
mipmap_count.get()
|
||||
};
|
||||
let mip_level_count = if gen_mipmaps {
|
||||
size.max_mips(wgpu::TextureDimension::D2)
|
||||
} else {
|
||||
mipmap_count.get()
|
||||
};
|
||||
|
||||
let label_str = format!("texture_{id:?}");
|
||||
let label = Some(label_str.as_str());
|
||||
let label_str = format!("texture_{id:?}");
|
||||
let label = Some(label_str.as_str());
|
||||
|
||||
let texture = create_texture_with_data(
|
||||
device,
|
||||
queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
label,
|
||||
size,
|
||||
mip_level_count,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[format.add_srgb_suffix()],
|
||||
},
|
||||
data_order.into(),
|
||||
bytes,
|
||||
gen_mipmaps,
|
||||
);
|
||||
let texture = create_texture_with_data(
|
||||
device,
|
||||
queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
label,
|
||||
size,
|
||||
mip_level_count,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: *format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING
|
||||
| wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[format.add_srgb_suffix()],
|
||||
},
|
||||
(*data_order).into(),
|
||||
bytes,
|
||||
gen_mipmaps,
|
||||
);
|
||||
|
||||
if gen_mipmaps {
|
||||
mipmap::generate_mipmap_chain(queue, &texture, bytes);
|
||||
if gen_mipmaps {
|
||||
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],
|
||||
skip_mipmaps: bool,
|
||||
) -> wgpu::Texture {
|
||||
// Implicitly add the COPY_DST usage
|
||||
// implicitly add the COPY_DST usage
|
||||
let mut desc = desc.to_owned();
|
||||
desc.usage |= wgpu::TextureUsages::COPY_DST;
|
||||
let texture = device.create_texture(&desc);
|
||||
|
||||
// Will return None only if it's a combined depth-stencil format
|
||||
// If so, default to 4, validation will fail later anyway since the depth or stencil
|
||||
// aspect needs to be written to individually
|
||||
// will return None only if it's a combined depth-stencil format. if so, default to 4,
|
||||
// validation will fail later anyway since the depth or stencil aspect needs to be written to
|
||||
// individually
|
||||
let block_size = desc.format.block_copy_size(None).unwrap_or(4);
|
||||
let (block_width, block_height) = desc.format.block_dimensions();
|
||||
let layer_iterations = desc.array_layer_count();
|
||||
|
||||
let outer_iteration;
|
||||
let inner_iteration;
|
||||
match order {
|
||||
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 (outer_iteration, inner_iteration) = match order {
|
||||
wgpu::wgt::TextureDataOrder::LayerMajor => (layer_iterations, desc.mip_level_count),
|
||||
wgpu::wgt::TextureDataOrder::MipMajor => (desc.mip_level_count, layer_iterations),
|
||||
};
|
||||
|
||||
let mut binary_offset = 0;
|
||||
for outer in 0..outer_iteration {
|
||||
@@ -646,13 +677,13 @@ fn create_texture_with_data(
|
||||
mip_size.depth_or_array_layers = 1;
|
||||
}
|
||||
|
||||
// When uploading mips of compressed textures and the mip is supposed to be
|
||||
// a size that isn't a multiple of the block size, the mip needs to be uploaded
|
||||
// as its "physical size" which is the size rounded up to the nearest block size.
|
||||
// when uploading mips of compressed textures and the mip is supposed to be a size that
|
||||
// isn't a multiple of the block size, the mip needs to be uploaded as its "physical
|
||||
// size" which is the size rounded up to the nearest block size.
|
||||
let mip_physical = mip_size.physical_size(desc.format);
|
||||
|
||||
// All these calculations are performed on the physical size as that's the
|
||||
// data that exists in the buffer.
|
||||
// all these calculations are performed on the physical size as that's the data that
|
||||
// exists in the buffer.
|
||||
let width_blocks = mip_physical.width / block_width;
|
||||
let height_blocks = mip_physical.height / block_height;
|
||||
|
||||
|
||||
+72
-6
@@ -2,17 +2,83 @@ use crate::{color::Srgba, renderer::textures::TextureOptions};
|
||||
use image::{DynamicImage, RgbaImage};
|
||||
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)]
|
||||
pub struct ImageDelta {
|
||||
pub image: ImageData,
|
||||
pub options: TextureOptions,
|
||||
pub enum ImageDelta {
|
||||
/// Creates a whole new texture.
|
||||
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 {
|
||||
pub fn new<I: Into<ImageData>>(image: I, options: TextureOptions) -> Self {
|
||||
Self {
|
||||
image: image.into(),
|
||||
pub fn full<I: Into<ImageData>>(
|
||||
image: I,
|
||||
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,
|
||||
mip_strategy,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn partial<I: Into<ImageData>>(image: I, origin: PartialDeltaOrigin) -> Self {
|
||||
Self::Partial {
|
||||
image: image.into(),
|
||||
origin,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+52
-29
@@ -5,7 +5,7 @@ use anyhow::bail;
|
||||
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
renderer::image::{ImageData, ImageDelta, load_image_file},
|
||||
renderer::image::{ImageData, ImageDelta, MipStrategy, load_image_file},
|
||||
worker_pool::WorkerPool,
|
||||
};
|
||||
|
||||
@@ -80,10 +80,18 @@ struct TextureRegistry {
|
||||
|
||||
impl TextureRegistry {
|
||||
/// 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;
|
||||
self.next_id += 1;
|
||||
|
||||
let mip_strategy = MipStrategy::resolve(&image, generate_mipmaps);
|
||||
|
||||
self.meta_data.insert(
|
||||
id,
|
||||
TextureMetaData {
|
||||
@@ -96,7 +104,7 @@ impl TextureRegistry {
|
||||
|
||||
self.delta
|
||||
.update
|
||||
.push((id, ImageDelta::new(image, options)));
|
||||
.push((id, ImageDelta::full(image, options, mip_strategy)));
|
||||
|
||||
id
|
||||
}
|
||||
@@ -122,9 +130,11 @@ impl TextureRegistry {
|
||||
/// Assigns a new image to an existing texture.
|
||||
pub fn set(&mut self, id: TextureId, delta: ImageDelta) {
|
||||
if let Some(meta_data) = self.meta_data.get_mut(&id) {
|
||||
meta_data.size = [delta.image.width as usize, delta.image.height as usize];
|
||||
// discard all old enqueued deltas
|
||||
self.delta.update.retain(|(x, _)| x != &id);
|
||||
if let ImageDelta::Full { image, .. } = &delta {
|
||||
meta_data.size = [image.width as usize, image.height as usize];
|
||||
// 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));
|
||||
} else {
|
||||
// the handle may have been dropped while the async load was in flight.
|
||||
@@ -181,6 +191,7 @@ enum LoadResult {
|
||||
id: TextureId,
|
||||
image: ImageData,
|
||||
options: TextureOptions,
|
||||
generate_mipmaps: bool,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -199,8 +210,9 @@ impl TextureManager {
|
||||
// allocate default texture (id: 0) for font atlas
|
||||
manager.alloc(
|
||||
"font_atlas_texture".into(),
|
||||
ImageData::from_solid_color([0, 0], Srgba::TRANSPARENT),
|
||||
ImageData::from_solid_color([1, 1], Srgba::WHITE),
|
||||
TextureOptions::default(),
|
||||
false,
|
||||
);
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
@@ -214,8 +226,10 @@ impl TextureManager {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn update_font_texture(&self, delta: ImageDelta) {
|
||||
self.manager.borrow_mut().set(TextureId::default(), delta);
|
||||
pub fn update_font_texture(&self, delta: Vec<ImageDelta>) {
|
||||
delta.into_iter().for_each(|d| {
|
||||
self.manager.borrow_mut().set(TextureId::default(), d);
|
||||
});
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -229,6 +243,7 @@ impl TextureManager {
|
||||
image_path: String,
|
||||
options: TextureOptions,
|
||||
is_async: bool,
|
||||
generate_mipmaps: bool,
|
||||
) -> anyhow::Result<TextureHandle> {
|
||||
profiling::scope!("load_texture");
|
||||
|
||||
@@ -242,7 +257,12 @@ impl TextureManager {
|
||||
self.worker_pool
|
||||
.execute(move || match load_image_file(Path::new(&image_path)) {
|
||||
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}"),
|
||||
});
|
||||
@@ -251,7 +271,12 @@ impl TextureManager {
|
||||
} else {
|
||||
match load_image_file(Path::new(&image_path)) {
|
||||
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))
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -268,6 +293,7 @@ impl TextureManager {
|
||||
image_path: String,
|
||||
options: TextureOptions,
|
||||
is_async: bool,
|
||||
generate_mipmaps: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
if is_async {
|
||||
let tx = self.results_tx.clone();
|
||||
@@ -278,19 +304,21 @@ impl TextureManager {
|
||||
id: texture_id,
|
||||
image,
|
||||
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 {
|
||||
match load_image_file(Path::new(&image_path)) {
|
||||
Ok(image) => {
|
||||
let mip_strategy = MipStrategy::resolve(&image, generate_mipmaps);
|
||||
self.manager
|
||||
.borrow_mut()
|
||||
.set(texture_id, ImageDelta::new(image, options));
|
||||
.set(texture_id, ImageDelta::full(image, options, mip_strategy));
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("Unable to load image fron {image_path}: {e}");
|
||||
log::warn!("Unable to load image from {image_path}: {e}");
|
||||
bail!(e);
|
||||
}
|
||||
}
|
||||
@@ -302,19 +330,25 @@ impl TextureManager {
|
||||
/// Drains completed async image loads and assigns them to textures
|
||||
fn apply_pending_loads(&self) {
|
||||
let mut manager = self.manager.borrow_mut();
|
||||
while let Ok(LoadResult::Loaded { id, image, options }) = self.results_rx.try_recv() {
|
||||
manager.set(id, ImageDelta::new(image, options));
|
||||
while let Ok(LoadResult::Loaded {
|
||||
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 magnification: wgpu::FilterMode,
|
||||
pub minification: wgpu::FilterMode,
|
||||
pub wrap_mode: wgpu::AddressMode,
|
||||
pub mipmap_mode: wgpu::MipmapFilterMode,
|
||||
pub generate_mipmaps: bool,
|
||||
}
|
||||
|
||||
impl TextureOptions {
|
||||
@@ -323,7 +357,6 @@ impl TextureOptions {
|
||||
minification: wgpu::FilterMode::Linear,
|
||||
wrap_mode: wgpu::AddressMode::Repeat,
|
||||
mipmap_mode: wgpu::MipmapFilterMode::Linear,
|
||||
generate_mipmaps: false,
|
||||
};
|
||||
|
||||
pub const LINEAR: Self = Self {
|
||||
@@ -331,7 +364,6 @@ impl TextureOptions {
|
||||
minification: wgpu::FilterMode::Linear,
|
||||
wrap_mode: wgpu::AddressMode::ClampToEdge,
|
||||
mipmap_mode: wgpu::MipmapFilterMode::Linear,
|
||||
generate_mipmaps: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -340,12 +372,3 @@ impl Default for TextureOptions {
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user