1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
use crate::context::Context;
use super::atlas::*;
use super::*;
#[derive(Default)]
pub struct Entry {
allocated: bool,
/// X coordinate of the image in an atlas.
x: u16,
/// Y coordinate of the image in an atlas.
y: u16,
/// Width of the image.
width: u16,
/// Height of the image.
height: u16,
}
pub struct Atlas {
alloc: AtlasAllocator,
buffer: Vec<u8>,
fresh: bool,
dirty: bool,
}
pub struct ImageCache {
pub entries: Vec<Entry>,
atlas: Atlas,
max_texture_size: u16,
texture: wgpu::Texture,
pub texture_view: wgpu::TextureView,
}
#[inline]
pub fn buffer_size(width: u32, height: u32) -> Option<usize> {
(width as usize)
.checked_add(height as usize)?
.checked_add(4)
}
pub const SIZE: u16 = 2048;
impl ImageCache {
/// Creates a new image cache.
pub fn new(context: &Context) -> Self {
let device = &context.device;
// let max_texture_size = max_texture_size.clamp(1024, 8192);
let max_texture_size = SIZE;
let texture_format = context.get_optimal_texture_format(4); // RGBA
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("rich_text create texture"),
size: wgpu::Extent3d {
width: SIZE as u32,
height: SIZE as u32,
depth_or_array_layers: 1,
},
view_formats: &[],
dimension: wgpu::TextureDimension::D2,
format: texture_format,
usage: wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING,
mip_level_count: 1,
sample_count: 1,
});
let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let alloc = AtlasAllocator::new(max_texture_size, max_texture_size);
// Buffer size depends on texture format
let bytes_per_pixel = if context.supports_f16() { 8 } else { 4 }; // f16 RGBA = 8 bytes, u8 RGBA = 4 bytes
Self {
entries: Vec::new(),
atlas: Atlas {
alloc,
buffer: vec![
0u8;
max_texture_size as usize
* max_texture_size as usize
* bytes_per_pixel
],
fresh: true,
dirty: true,
},
max_texture_size,
texture_view,
texture,
}
}
/// Allocates a new image and optionally fills it with the specified data.
pub fn allocate(&mut self, request: AddImage) -> Option<ImageId> {
let width = request.width;
let height = request.height;
// Reject zero-sized images
if width == 0 || height == 0 {
return None;
}
// Check buffer size
buffer_size(width as u32, height as u32)?;
// Too big to allocate
if !(width <= self.max_texture_size && height <= (self.max_texture_size / 4)) {
return None;
}
let atlas_data = self.atlas.alloc.allocate(width, height);
// if atlas_data.is_none() {
// return None;
// Grow atlas to fit
// self.max_texture_size += SIZE;
// self.atlas.fresh = true;
// self.atlas.dirty = true;
// self.entries.clear();
// println!("{:?}", self.max_texture_size);
// self.atlas.alloc = AtlasAllocator::new(self.max_texture_size, self.max_texture_size);
// self.atlas.buffer = vec![
// 0u8;
// self.max_texture_size as usize * self.max_texture_size as usize * 4
// ];
// atlas_data = self.atlas.alloc.allocate(width, height);
// println!("{:?}", atlas_data);
// if self.max_texture_size > MAX_SIZE {
// println!("should try to grow or reset atlas");
// }
// }
let (x, y) = atlas_data?;
let entry_index = self.entries.len();
self.entries.push(Entry {
allocated: true,
x,
y,
width,
height,
});
if let Some(data) = request.data() {
fill(
x,
y,
width,
height,
data,
self.max_texture_size,
&mut self.atlas.buffer,
);
self.atlas.dirty = true;
}
ImageId::new(entry_index as u32, request.has_alpha)
}
// Evaluate if does make sense to deallocate from atlas and if yes, which case?
// considering that a terminal uses a short/limited of glyphs compared to a wide text editor
// if deallocate an image then is necessary to cleanup cache of draw_layout fn
/// Deallocates the specified image.
#[allow(unused)]
pub fn deallocate(&mut self, image: ImageId) -> Option<()> {
let entry = self.entries.get_mut(image.index())?;
if !entry.allocated {
return None;
}
self.atlas.alloc.deallocate(entry.x, entry.y, entry.width);
entry.allocated = false;
Some(())
}
/// Retrieves the image for the specified handle and updates the epoch.
pub fn get(&self, handle: &ImageId) -> Option<ImageLocation> {
// Empty images have no location (for zero-sized glyphs)
if handle.is_empty() {
return None;
}
let entry = self.entries.get(handle.index())?;
if !entry.allocated {
return None;
}
let s = 1. / self.max_texture_size as f32;
Some(ImageLocation {
min: (entry.x as f32 * s, entry.y as f32 * s),
max: (
(entry.x + entry.width) as f32 * s,
(entry.y + entry.height) as f32 * s,
),
})
}
/// Clears all entries and resets the atlas. Used when fonts change.
pub fn clear_atlas(&mut self) {
// Clear all entries
self.entries.clear();
// Reset the allocator
self.atlas.alloc =
AtlasAllocator::new(self.max_texture_size, self.max_texture_size);
// Clear the buffer
let bytes_per_pixel = self.atlas.buffer.len()
/ (self.max_texture_size as usize * self.max_texture_size as usize);
self.atlas.buffer = vec![
0u8;
self.max_texture_size as usize
* self.max_texture_size as usize
* bytes_per_pixel
];
// Mark as fresh and dirty to trigger texture recreation
self.atlas.fresh = true;
self.atlas.dirty = true;
tracing::info!("Atlas cleared due to font change");
}
/// Returns true if the image is valid.
pub fn is_valid(&self, image: ImageId) -> bool {
// Empty images are always valid (for zero-sized glyphs)
if image.is_empty() {
return true;
}
if let Some(entry) = self.entries.get(image.index()) {
entry.allocated
} else {
false
}
}
/// Updates an image with the specified data.
// pub fn update(&mut self, handle: ImageId, data: &[u8]) -> Option<()> {
// let entry = self.entries.get_mut(handle.index())?;
// if entry.flags & ENTRY_ALLOCATED == 0 {
// return None;
// }
// let atlas = self.atlases.get_mut(entry.owner as usize)?;
// fill(
// entry.x,
// entry.y,
// entry.width,
// entry.height,
// data,
// ATLAS_DIM,
// &mut atlas.buffer,
// 4,
// );
// atlas.dirty = true;
// Some(())
// }
#[inline]
pub fn process_atlases(&mut self, context: &mut Context) {
if !self.atlas.dirty {
return;
}
if self.atlas.fresh {
let texture_size = wgpu::Extent3d {
width: (self.max_texture_size).into(),
height: (self.max_texture_size).into(),
depth_or_array_layers: 1,
};
let new_texture = context.device.create_texture(&wgpu::TextureDescriptor {
size: texture_size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::COPY_DST,
label: Some("rich_text::fresh atlas"),
view_formats: &[],
});
context.queue.write_texture(
// Tells wgpu where to copy the pixel data
wgpu::TexelCopyTextureInfo {
texture: &new_texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
// The actual pixel data
&self.atlas.buffer,
// The layout of the texture
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some((self.max_texture_size * 4).into()),
rows_per_image: Some((self.max_texture_size).into()),
},
texture_size,
);
self.texture = new_texture;
self.texture_view = self
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
} else {
let texture_size = wgpu::Extent3d {
width: (self.max_texture_size).into(),
height: (self.max_texture_size).into(),
depth_or_array_layers: 1,
};
context.queue.write_texture(
// Tells wgpu where to copy the pixel data
wgpu::TexelCopyTextureInfo {
texture: &self.texture,
mip_level: 0,
origin: wgpu::Origin3d { x: 0, y: 0, z: 0 },
aspect: wgpu::TextureAspect::All,
},
// The actual pixel data
&self.atlas.buffer,
// The layout of the texture
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some((self.max_texture_size * 4).into()),
rows_per_image: Some((self.max_texture_size).into()),
},
texture_size,
);
}
self.atlas.fresh = false;
self.atlas.dirty = false;
}
}
fn fill(
x: u16,
y: u16,
width: u16,
_height: u16,
image: &[u8],
target_width: u16,
target: &mut [u8],
) -> Option<()> {
let channels = 4;
let image_pitch = width as usize * channels;
let buffer_pitch = target_width as usize * channels;
let mut offset = y as usize * buffer_pitch + x as usize * channels;
for row in image.chunks(image_pitch) {
let dest = target.get_mut(offset..offset + image_pitch)?;
dest.copy_from_slice(row);
offset += buffer_pitch;
}
Some(())
}