metal_atlas.rs

  1use crate::{
  2    AtlasKey, AtlasTextureId, AtlasTextureKind, AtlasTile, Bounds, DevicePixels, PlatformAtlas,
  3    Point, Size, platform::AtlasTextureList,
  4};
  5use anyhow::{Context as _, Result};
  6use collections::FxHashMap;
  7use derive_more::{Deref, DerefMut};
  8use etagere::BucketedAtlasAllocator;
  9use metal::Device;
 10use parking_lot::Mutex;
 11use std::borrow::Cow;
 12
 13pub(crate) struct MetalAtlas(Mutex<MetalAtlasState>);
 14
 15impl MetalAtlas {
 16    pub(crate) fn new(device: Device) -> Self {
 17        MetalAtlas(Mutex::new(MetalAtlasState {
 18            device: AssertSend(device),
 19            monochrome_textures: Default::default(),
 20            polychrome_textures: Default::default(),
 21            tiles_by_key: Default::default(),
 22        }))
 23    }
 24
 25    pub(crate) fn metal_texture(&self, id: AtlasTextureId) -> metal::Texture {
 26        self.0.lock().texture(id).metal_texture.clone()
 27    }
 28}
 29
 30struct MetalAtlasState {
 31    device: AssertSend<Device>,
 32    monochrome_textures: AtlasTextureList<MetalAtlasTexture>,
 33    polychrome_textures: AtlasTextureList<MetalAtlasTexture>,
 34    tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
 35}
 36
 37impl PlatformAtlas for MetalAtlas {
 38    fn get_or_insert_with<'a>(
 39        &self,
 40        key: &AtlasKey,
 41        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
 42    ) -> Result<Option<AtlasTile>> {
 43        let mut lock = self.0.lock();
 44        if let Some(tile) = lock.tiles_by_key.get(key) {
 45            Ok(Some(tile.clone()))
 46        } else {
 47            let Some((size, bytes)) = build()? else {
 48                return Ok(None);
 49            };
 50            let tile = lock
 51                .allocate(size, key.texture_kind())
 52                .context("failed to allocate")?;
 53            let texture = lock.texture(tile.texture_id);
 54            texture.upload(tile.bounds, &bytes);
 55            lock.tiles_by_key.insert(key.clone(), tile.clone());
 56            Ok(Some(tile))
 57        }
 58    }
 59
 60    fn remove(&self, key: &AtlasKey) {
 61        let mut lock = self.0.lock();
 62        let Some(id) = lock.tiles_by_key.get(key).map(|v| v.texture_id) else {
 63            return;
 64        };
 65
 66        let textures = match id.kind {
 67            AtlasTextureKind::Monochrome => &mut lock.monochrome_textures,
 68            AtlasTextureKind::Polychrome => &mut lock.polychrome_textures,
 69        };
 70
 71        let Some(texture_slot) = textures
 72            .textures
 73            .iter_mut()
 74            .find(|texture| texture.as_ref().is_some_and(|v| v.id == id))
 75        else {
 76            return;
 77        };
 78
 79        if let Some(mut texture) = texture_slot.take() {
 80            texture.decrement_ref_count();
 81
 82            if texture.is_unreferenced() {
 83                textures.free_list.push(id.index as usize);
 84                lock.tiles_by_key.remove(key);
 85            } else {
 86                *texture_slot = Some(texture);
 87            }
 88        }
 89    }
 90}
 91
 92impl MetalAtlasState {
 93    fn allocate(
 94        &mut self,
 95        size: Size<DevicePixels>,
 96        texture_kind: AtlasTextureKind,
 97    ) -> Option<AtlasTile> {
 98        {
 99            let textures = match texture_kind {
100                AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
101                AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
102            };
103
104            if let Some(tile) = textures
105                .iter_mut()
106                .rev()
107                .find_map(|texture| texture.allocate(size))
108            {
109                return Some(tile);
110            }
111        }
112
113        let texture = self.push_texture(size, texture_kind);
114        texture.allocate(size)
115    }
116
117    fn push_texture(
118        &mut self,
119        min_size: Size<DevicePixels>,
120        kind: AtlasTextureKind,
121    ) -> &mut MetalAtlasTexture {
122        const DEFAULT_ATLAS_SIZE: Size<DevicePixels> = Size {
123            width: DevicePixels(1024),
124            height: DevicePixels(1024),
125        };
126        // Max texture size on all modern Apple GPUs. Anything bigger than that crashes in validateWithDevice.
127        const MAX_ATLAS_SIZE: Size<DevicePixels> = Size {
128            width: DevicePixels(16384),
129            height: DevicePixels(16384),
130        };
131        let size = min_size.min(&MAX_ATLAS_SIZE).max(&DEFAULT_ATLAS_SIZE);
132        let texture_descriptor = metal::TextureDescriptor::new();
133        texture_descriptor.set_width(size.width.into());
134        texture_descriptor.set_height(size.height.into());
135        let pixel_format;
136        let usage;
137        match kind {
138            AtlasTextureKind::Monochrome => {
139                pixel_format = metal::MTLPixelFormat::A8Unorm;
140                usage = metal::MTLTextureUsage::ShaderRead;
141            }
142            AtlasTextureKind::Polychrome => {
143                pixel_format = metal::MTLPixelFormat::BGRA8Unorm;
144                usage = metal::MTLTextureUsage::ShaderRead;
145            }
146        }
147        texture_descriptor.set_pixel_format(pixel_format);
148        texture_descriptor.set_usage(usage);
149        let metal_texture = self.device.new_texture(&texture_descriptor);
150
151        let texture_list = match kind {
152            AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
153            AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
154        };
155
156        let index = texture_list.free_list.pop();
157
158        let atlas_texture = MetalAtlasTexture {
159            id: AtlasTextureId {
160                index: index.unwrap_or(texture_list.textures.len()) as u32,
161                kind,
162            },
163            allocator: etagere::BucketedAtlasAllocator::new(size.into()),
164            metal_texture: AssertSend(metal_texture),
165            live_atlas_keys: 0,
166        };
167
168        if let Some(ix) = index {
169            texture_list.textures[ix] = Some(atlas_texture);
170            texture_list.textures.get_mut(ix)
171        } else {
172            texture_list.textures.push(Some(atlas_texture));
173            texture_list.textures.last_mut()
174        }
175        .unwrap()
176        .as_mut()
177        .unwrap()
178    }
179
180    fn texture(&self, id: AtlasTextureId) -> &MetalAtlasTexture {
181        let textures = match id.kind {
182            crate::AtlasTextureKind::Monochrome => &self.monochrome_textures,
183            crate::AtlasTextureKind::Polychrome => &self.polychrome_textures,
184        };
185        textures[id.index as usize].as_ref().unwrap()
186    }
187}
188
189struct MetalAtlasTexture {
190    id: AtlasTextureId,
191    allocator: BucketedAtlasAllocator,
192    metal_texture: AssertSend<metal::Texture>,
193    live_atlas_keys: u32,
194}
195
196impl MetalAtlasTexture {
197    fn allocate(&mut self, size: Size<DevicePixels>) -> Option<AtlasTile> {
198        let allocation = self.allocator.allocate(size.into())?;
199        let tile = AtlasTile {
200            texture_id: self.id,
201            tile_id: allocation.id.into(),
202            bounds: Bounds {
203                origin: allocation.rectangle.min.into(),
204                size,
205            },
206            padding: 0,
207        };
208        self.live_atlas_keys += 1;
209        Some(tile)
210    }
211
212    fn upload(&self, bounds: Bounds<DevicePixels>, bytes: &[u8]) {
213        let region = metal::MTLRegion::new_2d(
214            bounds.origin.x.into(),
215            bounds.origin.y.into(),
216            bounds.size.width.into(),
217            bounds.size.height.into(),
218        );
219        self.metal_texture.replace_region(
220            region,
221            0,
222            bytes.as_ptr() as *const _,
223            bounds.size.width.to_bytes(self.bytes_per_pixel()) as u64,
224        );
225    }
226
227    fn bytes_per_pixel(&self) -> u8 {
228        use metal::MTLPixelFormat::*;
229        match self.metal_texture.pixel_format() {
230            A8Unorm | R8Unorm => 1,
231            RGBA8Unorm | BGRA8Unorm => 4,
232            _ => unimplemented!(),
233        }
234    }
235
236    const fn decrement_ref_count(&mut self) {
237        self.live_atlas_keys -= 1;
238    }
239
240    const fn is_unreferenced(&mut self) -> bool {
241        self.live_atlas_keys == 0
242    }
243}
244
245impl From<Size<DevicePixels>> for etagere::Size {
246    fn from(size: Size<DevicePixels>) -> Self {
247        etagere::Size::new(size.width.into(), size.height.into())
248    }
249}
250
251impl From<etagere::Point> for Point<DevicePixels> {
252    fn from(value: etagere::Point) -> Self {
253        Point {
254            x: DevicePixels::from(value.x),
255            y: DevicePixels::from(value.y),
256        }
257    }
258}
259
260impl From<etagere::Size> for Size<DevicePixels> {
261    fn from(size: etagere::Size) -> Self {
262        Size {
263            width: DevicePixels::from(size.width),
264            height: DevicePixels::from(size.height),
265        }
266    }
267}
268
269impl From<etagere::Rectangle> for Bounds<DevicePixels> {
270    fn from(rectangle: etagere::Rectangle) -> Self {
271        Bounds {
272            origin: rectangle.min.into(),
273            size: rectangle.size().into(),
274        }
275    }
276}
277
278#[derive(Deref, DerefMut)]
279struct AssertSend<T>(T);
280
281unsafe impl<T> Send for AssertSend<T> {}