1use crate::{
2 AtlasKey, AtlasTextureId, AtlasTextureKind, AtlasTile, Bounds, DevicePixels, PlatformAtlas,
3 Point, Size,
4};
5use anyhow::Result;
6use blade_graphics as gpu;
7use blade_util::{BufferBelt, BufferBeltDescriptor};
8use collections::FxHashMap;
9use etagere::BucketedAtlasAllocator;
10use parking_lot::Mutex;
11use std::{borrow::Cow, ops, sync::Arc};
12
13pub(crate) const PATH_TEXTURE_FORMAT: gpu::TextureFormat = gpu::TextureFormat::R16Float;
14
15pub(crate) struct BladeAtlas(Mutex<BladeAtlasState>);
16
17struct PendingUpload {
18 id: AtlasTextureId,
19 bounds: Bounds<DevicePixels>,
20 data: gpu::BufferPiece,
21}
22
23struct BladeAtlasState {
24 gpu: Arc<gpu::Context>,
25 upload_belt: BufferBelt,
26 storage: BladeAtlasStorage,
27 tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
28 initializations: Vec<AtlasTextureId>,
29 uploads: Vec<PendingUpload>,
30}
31
32#[cfg(gles)]
33unsafe impl Send for BladeAtlasState {}
34
35impl BladeAtlasState {
36 fn destroy(&mut self) {
37 self.storage.destroy(&self.gpu);
38 self.upload_belt.destroy(&self.gpu);
39 }
40}
41
42pub struct BladeTextureInfo {
43 pub size: gpu::Extent,
44 pub raw_view: gpu::TextureView,
45}
46
47impl BladeAtlas {
48 pub(crate) fn new(gpu: &Arc<gpu::Context>) -> Self {
49 BladeAtlas(Mutex::new(BladeAtlasState {
50 gpu: Arc::clone(gpu),
51 upload_belt: BufferBelt::new(BufferBeltDescriptor {
52 memory: gpu::Memory::Upload,
53 min_chunk_size: 0x10000,
54 alignment: 64, // Vulkan `optimalBufferCopyOffsetAlignment` on Intel XE
55 }),
56 storage: BladeAtlasStorage::default(),
57 tiles_by_key: Default::default(),
58 initializations: Vec::new(),
59 uploads: Vec::new(),
60 }))
61 }
62
63 pub(crate) fn destroy(&self) {
64 self.0.lock().destroy();
65 }
66
67 pub(crate) fn clear_textures(&self, texture_kind: AtlasTextureKind) {
68 let mut lock = self.0.lock();
69 let textures = &mut lock.storage[texture_kind];
70 for texture in textures {
71 texture.clear();
72 }
73 }
74
75 /// Allocate a rectangle and make it available for rendering immediately (without waiting for `before_frame`)
76 pub fn allocate_for_rendering(
77 &self,
78 size: Size<DevicePixels>,
79 texture_kind: AtlasTextureKind,
80 gpu_encoder: &mut gpu::CommandEncoder,
81 ) -> AtlasTile {
82 let mut lock = self.0.lock();
83 let tile = lock.allocate(size, texture_kind);
84 lock.flush_initializations(gpu_encoder);
85 tile
86 }
87
88 pub fn before_frame(&self, gpu_encoder: &mut gpu::CommandEncoder) {
89 let mut lock = self.0.lock();
90 lock.flush(gpu_encoder);
91 }
92
93 pub fn after_frame(&self, sync_point: &gpu::SyncPoint) {
94 let mut lock = self.0.lock();
95 lock.upload_belt.flush(sync_point);
96 }
97
98 pub fn get_texture_info(&self, id: AtlasTextureId) -> BladeTextureInfo {
99 let lock = self.0.lock();
100 let texture = &lock.storage[id];
101 let size = texture.allocator.size();
102 BladeTextureInfo {
103 size: gpu::Extent {
104 width: size.width as u32,
105 height: size.height as u32,
106 depth: 1,
107 },
108 raw_view: texture.raw_view,
109 }
110 }
111}
112
113impl PlatformAtlas for BladeAtlas {
114 fn get_or_insert_with<'a>(
115 &self,
116 key: &AtlasKey,
117 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
118 ) -> Result<Option<AtlasTile>> {
119 let mut lock = self.0.lock();
120 if let Some(tile) = lock.tiles_by_key.get(key) {
121 Ok(Some(tile.clone()))
122 } else {
123 profiling::scope!("new tile");
124 let Some((size, bytes)) = build()? else {
125 return Ok(None);
126 };
127 let tile = lock.allocate(size, key.texture_kind());
128 lock.upload_texture(tile.texture_id, tile.bounds, &bytes);
129 lock.tiles_by_key.insert(key.clone(), tile.clone());
130 Ok(Some(tile))
131 }
132 }
133}
134
135impl BladeAtlasState {
136 fn allocate(&mut self, size: Size<DevicePixels>, texture_kind: AtlasTextureKind) -> AtlasTile {
137 let textures = &mut self.storage[texture_kind];
138 textures
139 .iter_mut()
140 .rev()
141 .find_map(|texture| texture.allocate(size))
142 .unwrap_or_else(|| {
143 let texture = self.push_texture(size, texture_kind);
144 texture.allocate(size).unwrap()
145 })
146 }
147
148 fn push_texture(
149 &mut self,
150 min_size: Size<DevicePixels>,
151 kind: AtlasTextureKind,
152 ) -> &mut BladeAtlasTexture {
153 const DEFAULT_ATLAS_SIZE: Size<DevicePixels> = Size {
154 width: DevicePixels(1024),
155 height: DevicePixels(1024),
156 };
157
158 let size = min_size.max(&DEFAULT_ATLAS_SIZE);
159 let format;
160 let usage;
161 match kind {
162 AtlasTextureKind::Monochrome => {
163 format = gpu::TextureFormat::R8Unorm;
164 usage = gpu::TextureUsage::COPY | gpu::TextureUsage::RESOURCE;
165 }
166 AtlasTextureKind::Polychrome => {
167 format = gpu::TextureFormat::Bgra8UnormSrgb;
168 usage = gpu::TextureUsage::COPY | gpu::TextureUsage::RESOURCE;
169 }
170 AtlasTextureKind::Path => {
171 format = PATH_TEXTURE_FORMAT;
172 usage = gpu::TextureUsage::COPY
173 | gpu::TextureUsage::RESOURCE
174 | gpu::TextureUsage::TARGET;
175 }
176 }
177
178 let raw = self.gpu.create_texture(gpu::TextureDesc {
179 name: "atlas",
180 format,
181 size: gpu::Extent {
182 width: size.width.into(),
183 height: size.height.into(),
184 depth: 1,
185 },
186 array_layer_count: 1,
187 mip_level_count: 1,
188 dimension: gpu::TextureDimension::D2,
189 usage,
190 });
191 let raw_view = self.gpu.create_texture_view(
192 raw,
193 gpu::TextureViewDesc {
194 name: "",
195 format,
196 dimension: gpu::ViewDimension::D2,
197 subresources: &Default::default(),
198 },
199 );
200
201 let textures = &mut self.storage[kind];
202 let atlas_texture = BladeAtlasTexture {
203 id: AtlasTextureId {
204 index: textures.len() as u32,
205 kind,
206 },
207 allocator: etagere::BucketedAtlasAllocator::new(size.into()),
208 format,
209 raw,
210 raw_view,
211 };
212
213 self.initializations.push(atlas_texture.id);
214 textures.push(atlas_texture);
215 textures.last_mut().unwrap()
216 }
217
218 fn upload_texture(&mut self, id: AtlasTextureId, bounds: Bounds<DevicePixels>, bytes: &[u8]) {
219 let data = self.upload_belt.alloc_bytes(bytes, &self.gpu);
220 self.uploads.push(PendingUpload { id, bounds, data });
221 }
222
223 fn flush_initializations(&mut self, encoder: &mut gpu::CommandEncoder) {
224 for id in self.initializations.drain(..) {
225 let texture = &self.storage[id];
226 encoder.init_texture(texture.raw);
227 }
228 }
229
230 fn flush(&mut self, encoder: &mut gpu::CommandEncoder) {
231 self.flush_initializations(encoder);
232
233 let mut transfers = encoder.transfer();
234 for upload in self.uploads.drain(..) {
235 let texture = &self.storage[upload.id];
236 transfers.copy_buffer_to_texture(
237 upload.data,
238 upload.bounds.size.width.to_bytes(texture.bytes_per_pixel()),
239 gpu::TexturePiece {
240 texture: texture.raw,
241 mip_level: 0,
242 array_layer: 0,
243 origin: [
244 upload.bounds.origin.x.into(),
245 upload.bounds.origin.y.into(),
246 0,
247 ],
248 },
249 gpu::Extent {
250 width: upload.bounds.size.width.into(),
251 height: upload.bounds.size.height.into(),
252 depth: 1,
253 },
254 );
255 }
256 }
257}
258
259#[derive(Default)]
260struct BladeAtlasStorage {
261 monochrome_textures: Vec<BladeAtlasTexture>,
262 polychrome_textures: Vec<BladeAtlasTexture>,
263 path_textures: Vec<BladeAtlasTexture>,
264}
265
266impl ops::Index<AtlasTextureKind> for BladeAtlasStorage {
267 type Output = Vec<BladeAtlasTexture>;
268 fn index(&self, kind: AtlasTextureKind) -> &Self::Output {
269 match kind {
270 crate::AtlasTextureKind::Monochrome => &self.monochrome_textures,
271 crate::AtlasTextureKind::Polychrome => &self.polychrome_textures,
272 crate::AtlasTextureKind::Path => &self.path_textures,
273 }
274 }
275}
276
277impl ops::IndexMut<AtlasTextureKind> for BladeAtlasStorage {
278 fn index_mut(&mut self, kind: AtlasTextureKind) -> &mut Self::Output {
279 match kind {
280 crate::AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
281 crate::AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
282 crate::AtlasTextureKind::Path => &mut self.path_textures,
283 }
284 }
285}
286
287impl ops::Index<AtlasTextureId> for BladeAtlasStorage {
288 type Output = BladeAtlasTexture;
289 fn index(&self, id: AtlasTextureId) -> &Self::Output {
290 let textures = match id.kind {
291 crate::AtlasTextureKind::Monochrome => &self.monochrome_textures,
292 crate::AtlasTextureKind::Polychrome => &self.polychrome_textures,
293 crate::AtlasTextureKind::Path => &self.path_textures,
294 };
295 &textures[id.index as usize]
296 }
297}
298
299impl BladeAtlasStorage {
300 fn destroy(&mut self, gpu: &gpu::Context) {
301 for mut texture in self.monochrome_textures.drain(..) {
302 texture.destroy(gpu);
303 }
304 for mut texture in self.polychrome_textures.drain(..) {
305 texture.destroy(gpu);
306 }
307 for mut texture in self.path_textures.drain(..) {
308 texture.destroy(gpu);
309 }
310 }
311}
312
313struct BladeAtlasTexture {
314 id: AtlasTextureId,
315 allocator: BucketedAtlasAllocator,
316 raw: gpu::Texture,
317 raw_view: gpu::TextureView,
318 format: gpu::TextureFormat,
319}
320
321impl BladeAtlasTexture {
322 fn clear(&mut self) {
323 self.allocator.clear();
324 }
325
326 fn allocate(&mut self, size: Size<DevicePixels>) -> Option<AtlasTile> {
327 let allocation = self.allocator.allocate(size.into())?;
328 let tile = AtlasTile {
329 texture_id: self.id,
330 tile_id: allocation.id.into(),
331 padding: 0,
332 bounds: Bounds {
333 origin: allocation.rectangle.min.into(),
334 size,
335 },
336 };
337 Some(tile)
338 }
339
340 fn destroy(&mut self, gpu: &gpu::Context) {
341 gpu.destroy_texture(self.raw);
342 gpu.destroy_texture_view(self.raw_view);
343 }
344
345 fn bytes_per_pixel(&self) -> u8 {
346 self.format.block_info().size
347 }
348}
349
350impl From<Size<DevicePixels>> for etagere::Size {
351 fn from(size: Size<DevicePixels>) -> Self {
352 etagere::Size::new(size.width.into(), size.height.into())
353 }
354}
355
356impl From<etagere::Point> for Point<DevicePixels> {
357 fn from(value: etagere::Point) -> Self {
358 Point {
359 x: DevicePixels::from(value.x),
360 y: DevicePixels::from(value.y),
361 }
362 }
363}
364
365impl From<etagere::Size> for Size<DevicePixels> {
366 fn from(size: etagere::Size) -> Self {
367 Size {
368 width: DevicePixels::from(size.width),
369 height: DevicePixels::from(size.height),
370 }
371 }
372}
373
374impl From<etagere::Rectangle> for Bounds<DevicePixels> {
375 fn from(rectangle: etagere::Rectangle) -> Self {
376 Bounds {
377 origin: rectangle.min.into(),
378 size: rectangle.size().into(),
379 }
380 }
381}