Grow internal packer and re-upload glyphs automatically

This commit is contained in:
Héctor Ramón Jiménez 2023-06-15 18:23:36 +02:00 committed by Josh Groves
parent a74ce29c1a
commit f64771c2c3
5 changed files with 86 additions and 30 deletions

View file

@ -9,7 +9,7 @@ license = "MIT OR Apache-2.0 OR Zlib"
[dependencies] [dependencies]
wgpu = "0.16" wgpu = "0.16"
etagere = "0.2.6" etagere = { git = "https://github.com/hecrj/etagere.git", rev = "4ee873d5c412d31237cd51efdcfdc7a0afd1953b" }
cosmic-text = "0.8" cosmic-text = "0.8"
lru = "0.9" lru = "0.9"

View file

@ -1,4 +1,3 @@
use crate::ContentType;
use std::{ use std::{
error::Error, error::Error,
fmt::{self, Display, Formatter}, fmt::{self, Display, Formatter},
@ -7,7 +6,7 @@ use std::{
/// An error that occurred while preparing text for rendering. /// An error that occurred while preparing text for rendering.
#[derive(Clone, Copy, Debug, Eq, PartialEq)] #[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PrepareError { pub enum PrepareError {
AtlasFull(ContentType), AtlasFull,
} }
impl Display for PrepareError { impl Display for PrepareError {

View file

@ -10,9 +10,10 @@ mod text_render;
pub use error::{PrepareError, RenderError}; pub use error::{PrepareError, RenderError};
pub use text_atlas::{ColorMode, TextAtlas}; pub use text_atlas::{ColorMode, TextAtlas};
pub use text_render::ContentType;
pub use text_render::TextRenderer; pub use text_render::TextRenderer;
use text_render::ContentType;
// Re-export all top-level types from `cosmic-text` for convenience. // Re-export all top-level types from `cosmic-text` for convenience.
pub use cosmic_text::{ pub use cosmic_text::{
self, fontdb, Action, Affinity, Attrs, AttrsList, AttrsOwned, Buffer, BufferLine, CacheKey, self, fontdb, Action, Affinity, Attrs, AttrsList, AttrsOwned, Buffer, BufferLine, CacheKey,

View file

@ -1,4 +1,7 @@
use crate::{text_render::ContentType, CacheKey, GlyphDetails, GlyphToRender, Params, Resolution}; use crate::{
text_render::ContentType, CacheKey, FontSystem, GlyphDetails, GlyphToRender, GpuCacheStatus,
Params, Resolution, SwashCache,
};
use etagere::{size2, Allocation, BucketedAtlasAllocator}; use etagere::{size2, Allocation, BucketedAtlasAllocator};
use lru::LruCache; use lru::LruCache;
use std::{borrow::Cow, collections::HashSet, mem::size_of, num::NonZeroU64, sync::Arc}; use std::{borrow::Cow, collections::HashSet, mem::size_of, num::NonZeroU64, sync::Arc};
@ -6,11 +9,12 @@ use wgpu::{
BindGroup, BindGroupDescriptor, BindGroupEntry, BindGroupLayout, BindGroupLayoutEntry, BindGroup, BindGroupDescriptor, BindGroupEntry, BindGroupLayout, BindGroupLayoutEntry,
BindingResource, BindingType, BlendState, Buffer, BufferBindingType, BufferDescriptor, BindingResource, BindingType, BlendState, Buffer, BufferBindingType, BufferDescriptor,
BufferUsages, ColorTargetState, ColorWrites, DepthStencilState, Device, Extent3d, FilterMode, BufferUsages, ColorTargetState, ColorWrites, DepthStencilState, Device, Extent3d, FilterMode,
FragmentState, MultisampleState, PipelineLayout, PipelineLayoutDescriptor, PrimitiveState, FragmentState, ImageCopyTexture, ImageDataLayout, MultisampleState, Origin3d, PipelineLayout,
Queue, RenderPipeline, RenderPipelineDescriptor, Sampler, SamplerBindingType, PipelineLayoutDescriptor, PrimitiveState, Queue, RenderPipeline, RenderPipelineDescriptor,
SamplerDescriptor, ShaderModule, ShaderModuleDescriptor, ShaderSource, ShaderStages, Texture, Sampler, SamplerBindingType, SamplerDescriptor, ShaderModule, ShaderModuleDescriptor,
TextureDescriptor, TextureDimension, TextureFormat, TextureSampleType, TextureUsages, ShaderSource, ShaderStages, Texture, TextureAspect, TextureDescriptor, TextureDimension,
TextureView, TextureViewDescriptor, TextureViewDimension, VertexFormat, VertexState, TextureFormat, TextureSampleType, TextureUsages, TextureView, TextureViewDescriptor,
TextureViewDimension, VertexFormat, VertexState,
}; };
#[allow(dead_code)] #[allow(dead_code)]
@ -78,20 +82,19 @@ impl InnerAtlas {
} }
// Try to free least recently used allocation // Try to free least recently used allocation
let (_, mut value) = self.glyph_cache.peek_lru()?; let (mut key, mut value) = self.glyph_cache.peek_lru()?;
while value.atlas_id.is_none() { while value.atlas_id.is_none() {
let _ = self.glyph_cache.pop_lru(); let _ = self.glyph_cache.pop_lru();
(_, value) = self.glyph_cache.peek_lru()?; (key, value) = self.glyph_cache.peek_lru()?;
} }
let (key, value) = self.glyph_cache.pop_lru().unwrap();
if self.glyphs_in_use.contains(&key) { if self.glyphs_in_use.contains(&key) {
return None; return None;
} }
let (_, value) = self.glyph_cache.pop_lru().unwrap();
self.packer.deallocate(value.atlas_id.unwrap()); self.packer.deallocate(value.atlas_id.unwrap());
} }
} }
@ -110,7 +113,13 @@ impl InnerAtlas {
self.glyphs_in_use.insert(glyph); self.glyphs_in_use.insert(glyph);
} }
pub(crate) fn grow(&mut self, device: &wgpu::Device) -> bool { pub(crate) fn grow(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
font_system: &mut FontSystem,
cache: &mut SwashCache,
) -> bool {
if self.size >= self.max_texture_dimension_2d { if self.size >= self.max_texture_dimension_2d {
return false; return false;
} }
@ -118,7 +127,7 @@ impl InnerAtlas {
// TODO: Better resizing logic (?) // TODO: Better resizing logic (?)
let new_size = (self.size + Self::INITIAL_SIZE).min(self.max_texture_dimension_2d); let new_size = (self.size + Self::INITIAL_SIZE).min(self.max_texture_dimension_2d);
self.packer = BucketedAtlasAllocator::new(size2(new_size as i32, new_size as i32)); self.packer.grow(size2(new_size as i32, new_size as i32));
// Create a texture to use for our atlas // Create a texture to use for our atlas
self.texture = device.create_texture(&TextureDescriptor { self.texture = device.create_texture(&TextureDescriptor {
@ -136,12 +145,46 @@ impl InnerAtlas {
view_formats: &[], view_formats: &[],
}); });
// Re-upload glyphs
for (&cache_key, glyph) in &self.glyph_cache {
let (x, y) = match glyph.gpu_cache {
GpuCacheStatus::InAtlas { x, y, .. } => (x, y),
GpuCacheStatus::SkipRasterization => continue,
};
let image = cache.get_image_uncached(font_system, cache_key).unwrap();
let width = image.placement.width as usize;
let height = image.placement.height as usize;
queue.write_texture(
ImageCopyTexture {
texture: &self.texture,
mip_level: 0,
origin: Origin3d {
x: x as u32,
y: y as u32,
z: 0,
},
aspect: TextureAspect::All,
},
&image.data,
ImageDataLayout {
offset: 0,
bytes_per_row: Some(width as u32 * self.kind.num_channels() as u32),
rows_per_image: None,
},
Extent3d {
width: width as u32,
height: height as u32,
depth_or_array_layers: 1,
},
);
}
self.texture_view = self.texture.create_view(&TextureViewDescriptor::default()); self.texture_view = self.texture.create_view(&TextureViewDescriptor::default());
self.size = new_size; self.size = new_size;
self.glyph_cache.clear();
self.glyphs_in_use.clear();
true true
} }
@ -406,18 +449,24 @@ impl TextAtlas {
self.color_atlas.trim(); self.color_atlas.trim();
} }
pub fn grow(&mut self, device: &wgpu::Device, content_type: ContentType) -> bool { pub(crate) fn grow(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
font_system: &mut FontSystem,
cache: &mut SwashCache,
content_type: ContentType,
) -> bool {
let did_grow = match content_type { let did_grow = match content_type {
ContentType::Mask => self.mask_atlas.grow(device), ContentType::Mask => self.mask_atlas.grow(device, queue, font_system, cache),
ContentType::Color => self.color_atlas.grow(device), ContentType::Color => self.color_atlas.grow(device, queue, font_system, cache),
}; };
if did_grow { if did_grow {
self.rebind(device); self.rebind(device);
true
} else {
false
} }
did_grow
} }
pub(crate) fn glyph(&self, glyph: &CacheKey) -> Option<&GlyphDetails> { pub(crate) fn glyph(&self, glyph: &CacheKey) -> Option<&GlyphDetails> {

View file

@ -118,13 +118,20 @@ impl TextRenderer {
let should_rasterize = width > 0 && height > 0; let should_rasterize = width > 0 && height > 0;
let (gpu_cache, atlas_id, inner) = if should_rasterize { let (gpu_cache, atlas_id, inner) = if should_rasterize {
let inner = atlas.inner_for_content_mut(content_type); let mut inner = atlas.inner_for_content_mut(content_type);
// Find a position in the packer // Find a position in the packer
let allocation = match inner.try_allocate(width, height) { let allocation = loop {
Some(a) => a, match inner.try_allocate(width, height) {
Some(a) => break a,
None => { None => {
return Err(PrepareError::AtlasFull(content_type)); if !atlas.grow(device, queue, font_system, cache, content_type)
{
return Err(PrepareError::AtlasFull);
}
inner = atlas.inner_for_content_mut(content_type);
}
} }
}; };
let atlas_min = allocation.rectangle.min; let atlas_min = allocation.rectangle.min;