Implement growing logic for TextAtlas

The `TextAtlas` will have an initial size of `256` (we could make this
configurable) and `try_allocate` will keep track of the glyphs in use
in the current frame, returning `None` when the LRU glyph is in use.

In that case, `TextRenderer::prepare` will return
`PrepareError::AtlasFull` with the `ContentType` of the atlas that is
full. The user of the library can then call `TextAtlas::grow` with the
provided `ContentType` to obtain a bigger atlas (by `256`).

A `TextAtlas::grow` call clears the whole atlas and, as a result, all of
the `prepare` calls need to be repeated in a frame until they all
succeed. Overall, the atlas will rarely need to grow and so the calls
will not need to be repated often.

Finally, the user needs to call `TextAtlas::trim` at the end of the
frame. This allows us to clear the glyphs in use collection in the atlas. Maybe
there is a better way to model this in an API that forces the user to
trim the atlas (e.g. make `trim` return a new type and changing `prepare` and `render` to take that type instead).
This commit is contained in:
Héctor Ramón Jiménez 2023-02-08 23:08:37 +01:00 committed by Josh Groves
parent d20643702f
commit a74ce29c1a
5 changed files with 159 additions and 59 deletions

View file

@ -1,16 +1,16 @@
use crate::{text_render::ContentType, CacheKey, GlyphDetails, GlyphToRender, Params, Resolution};
use etagere::{size2, Allocation, BucketedAtlasAllocator};
use lru::LruCache;
use std::{borrow::Cow, mem::size_of, num::NonZeroU64, sync::Arc};
use std::{borrow::Cow, collections::HashSet, mem::size_of, num::NonZeroU64, sync::Arc};
use wgpu::{
BindGroup, BindGroupDescriptor, BindGroupEntry, BindGroupLayoutEntry, BindingResource,
BindingType, BlendState, Buffer, BufferBindingType, BufferDescriptor, BufferUsages,
ColorTargetState, ColorWrites, DepthStencilState, Device, Extent3d, FilterMode, FragmentState,
MultisampleState, PipelineLayout, PipelineLayoutDescriptor, PrimitiveState, Queue,
RenderPipeline, RenderPipelineDescriptor, SamplerBindingType, SamplerDescriptor, ShaderModule,
ShaderModuleDescriptor, ShaderSource, ShaderStages, Texture, TextureDescriptor,
TextureDimension, TextureFormat, TextureSampleType, TextureUsages, TextureView,
TextureViewDescriptor, TextureViewDimension, VertexFormat, VertexState,
BindGroup, BindGroupDescriptor, BindGroupEntry, BindGroupLayout, BindGroupLayoutEntry,
BindingResource, BindingType, BlendState, Buffer, BufferBindingType, BufferDescriptor,
BufferUsages, ColorTargetState, ColorWrites, DepthStencilState, Device, Extent3d, FilterMode,
FragmentState, MultisampleState, PipelineLayout, PipelineLayoutDescriptor, PrimitiveState,
Queue, RenderPipeline, RenderPipelineDescriptor, Sampler, SamplerBindingType,
SamplerDescriptor, ShaderModule, ShaderModuleDescriptor, ShaderSource, ShaderStages, Texture,
TextureDescriptor, TextureDimension, TextureFormat, TextureSampleType, TextureUsages,
TextureView, TextureViewDescriptor, TextureViewDimension, VertexFormat, VertexState,
};
#[allow(dead_code)]
@ -19,25 +19,27 @@ pub(crate) struct InnerAtlas {
pub texture: Texture,
pub texture_view: TextureView,
pub packer: BucketedAtlasAllocator,
pub width: u32,
pub height: u32,
pub size: u32,
pub glyph_cache: LruCache<CacheKey, GlyphDetails>,
pub glyphs_in_use: HashSet<CacheKey>,
pub max_texture_dimension_2d: u32,
}
impl InnerAtlas {
const INITIAL_SIZE: u32 = 256;
fn new(device: &Device, _queue: &Queue, kind: Kind) -> Self {
let max_texture_dimension_2d = device.limits().max_texture_dimension_2d;
let width = max_texture_dimension_2d;
let height = max_texture_dimension_2d;
let size = Self::INITIAL_SIZE.min(max_texture_dimension_2d);
let packer = BucketedAtlasAllocator::new(size2(width as i32, height as i32));
let packer = BucketedAtlasAllocator::new(size2(size as i32, size as i32));
// Create a texture to use for our atlas
let texture = device.create_texture(&TextureDescriptor {
label: Some("glyphon atlas"),
size: Extent3d {
width,
height,
width: size,
height: size,
depth_or_array_layers: 1,
},
mip_level_count: 1,
@ -51,15 +53,17 @@ impl InnerAtlas {
let texture_view = texture.create_view(&TextureViewDescriptor::default());
let glyph_cache = LruCache::unbounded();
let glyphs_in_use = HashSet::new();
Self {
kind,
texture,
texture_view,
packer,
width,
height,
size,
glyph_cache,
glyphs_in_use,
max_texture_dimension_2d,
}
}
@ -68,20 +72,82 @@ impl InnerAtlas {
loop {
let allocation = self.packer.allocate(size);
if allocation.is_some() {
return allocation;
}
// Try to free least recently used allocation
let (_, value) = self.glyph_cache.pop_lru()?;
self.packer
.deallocate(value.atlas_id.expect("cache corrupt"));
let (_, mut value) = self.glyph_cache.peek_lru()?;
while value.atlas_id.is_none() {
let _ = self.glyph_cache.pop_lru();
(_, value) = self.glyph_cache.peek_lru()?;
}
let (key, value) = self.glyph_cache.pop_lru().unwrap();
if self.glyphs_in_use.contains(&key) {
return None;
}
self.packer.deallocate(value.atlas_id.unwrap());
}
}
pub fn num_channels(&self) -> usize {
self.kind.num_channels()
}
pub(crate) fn promote(&mut self, glyph: CacheKey) {
self.glyph_cache.promote(&glyph);
self.glyphs_in_use.insert(glyph);
}
pub(crate) fn put(&mut self, glyph: CacheKey, details: GlyphDetails) {
self.glyph_cache.put(glyph, details);
self.glyphs_in_use.insert(glyph);
}
pub(crate) fn grow(&mut self, device: &wgpu::Device) -> bool {
if self.size >= self.max_texture_dimension_2d {
return false;
}
// TODO: Better resizing logic (?)
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));
// Create a texture to use for our atlas
self.texture = device.create_texture(&TextureDescriptor {
label: Some("glyphon atlas"),
size: Extent3d {
width: new_size,
height: new_size,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: self.kind.texture_format(),
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST,
view_formats: &[],
});
self.texture_view = self.texture.create_view(&TextureViewDescriptor::default());
self.size = new_size;
self.glyph_cache.clear();
self.glyphs_in_use.clear();
true
}
fn trim(&mut self) {
self.glyphs_in_use.clear();
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@ -145,6 +211,8 @@ pub struct TextAtlas {
Arc<RenderPipeline>,
)>,
pub(crate) bind_group: Arc<BindGroup>,
pub(crate) bind_group_layout: BindGroupLayout,
pub(crate) sampler: Sampler,
pub(crate) color_atlas: InnerAtlas,
pub(crate) mask_atlas: InnerAtlas,
pub(crate) pipeline_layout: PipelineLayout,
@ -322,6 +390,8 @@ impl TextAtlas {
params_buffer,
cached_pipelines: Vec::new(),
bind_group,
bind_group_layout,
sampler,
color_atlas,
mask_atlas,
pipeline_layout,
@ -331,8 +401,23 @@ impl TextAtlas {
}
}
pub(crate) fn contains_cached_glyph(&self, glyph: &CacheKey) -> bool {
self.mask_atlas.glyph_cache.contains(glyph) || self.color_atlas.glyph_cache.contains(glyph)
pub fn trim(&mut self) {
self.mask_atlas.trim();
self.color_atlas.trim();
}
pub fn grow(&mut self, device: &wgpu::Device, content_type: ContentType) -> bool {
let did_grow = match content_type {
ContentType::Mask => self.mask_atlas.grow(device),
ContentType::Color => self.color_atlas.grow(device),
};
if did_grow {
self.rebind(device);
true
} else {
false
}
}
pub(crate) fn glyph(&self, glyph: &CacheKey) -> Option<&GlyphDetails> {
@ -388,4 +473,29 @@ impl TextAtlas {
pipeline
})
}
fn rebind(&mut self, device: &wgpu::Device) {
self.bind_group = Arc::new(device.create_bind_group(&BindGroupDescriptor {
layout: &self.bind_group_layout,
entries: &[
BindGroupEntry {
binding: 0,
resource: self.params_buffer.as_entire_binding(),
},
BindGroupEntry {
binding: 1,
resource: BindingResource::TextureView(&self.color_atlas.texture_view),
},
BindGroupEntry {
binding: 2,
resource: BindingResource::TextureView(&self.mask_atlas.texture_view),
},
BindGroupEntry {
binding: 3,
resource: BindingResource::Sampler(&self.sampler),
},
],
label: Some("glyphon bind group"),
}));
}
}