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).unwrap().as_mut().unwrap()
171 } else {
172 texture_list.textures.push(Some(atlas_texture));
173 texture_list.textures.last_mut().unwrap().as_mut().unwrap()
174 }
175 }
176
177 fn texture(&self, id: AtlasTextureId) -> &MetalAtlasTexture {
178 let textures = match id.kind {
179 crate::AtlasTextureKind::Monochrome => &self.monochrome_textures,
180 crate::AtlasTextureKind::Polychrome => &self.polychrome_textures,
181 };
182 textures[id.index as usize].as_ref().unwrap()
183 }
184}
185
186struct MetalAtlasTexture {
187 id: AtlasTextureId,
188 allocator: BucketedAtlasAllocator,
189 metal_texture: AssertSend<metal::Texture>,
190 live_atlas_keys: u32,
191}
192
193impl MetalAtlasTexture {
194 fn allocate(&mut self, size: Size<DevicePixels>) -> Option<AtlasTile> {
195 let allocation = self.allocator.allocate(size.into())?;
196 let tile = AtlasTile {
197 texture_id: self.id,
198 tile_id: allocation.id.into(),
199 bounds: Bounds {
200 origin: allocation.rectangle.min.into(),
201 size,
202 },
203 padding: 0,
204 };
205 self.live_atlas_keys += 1;
206 Some(tile)
207 }
208
209 fn upload(&self, bounds: Bounds<DevicePixels>, bytes: &[u8]) {
210 let region = metal::MTLRegion::new_2d(
211 bounds.origin.x.into(),
212 bounds.origin.y.into(),
213 bounds.size.width.into(),
214 bounds.size.height.into(),
215 );
216 self.metal_texture.replace_region(
217 region,
218 0,
219 bytes.as_ptr() as *const _,
220 bounds.size.width.to_bytes(self.bytes_per_pixel()) as u64,
221 );
222 }
223
224 fn bytes_per_pixel(&self) -> u8 {
225 use metal::MTLPixelFormat::*;
226 match self.metal_texture.pixel_format() {
227 A8Unorm | R8Unorm => 1,
228 RGBA8Unorm | BGRA8Unorm => 4,
229 _ => unimplemented!(),
230 }
231 }
232
233 fn decrement_ref_count(&mut self) {
234 self.live_atlas_keys -= 1;
235 }
236
237 fn is_unreferenced(&mut self) -> bool {
238 self.live_atlas_keys == 0
239 }
240}
241
242impl From<Size<DevicePixels>> for etagere::Size {
243 fn from(size: Size<DevicePixels>) -> Self {
244 etagere::Size::new(size.width.into(), size.height.into())
245 }
246}
247
248impl From<etagere::Point> for Point<DevicePixels> {
249 fn from(value: etagere::Point) -> Self {
250 Point {
251 x: DevicePixels::from(value.x),
252 y: DevicePixels::from(value.y),
253 }
254 }
255}
256
257impl From<etagere::Size> for Size<DevicePixels> {
258 fn from(size: etagere::Size) -> Self {
259 Size {
260 width: DevicePixels::from(size.width),
261 height: DevicePixels::from(size.height),
262 }
263 }
264}
265
266impl From<etagere::Rectangle> for Bounds<DevicePixels> {
267 fn from(rectangle: etagere::Rectangle) -> Self {
268 Bounds {
269 origin: rectangle.min.into(),
270 size: rectangle.size().into(),
271 }
272 }
273}
274
275#[derive(Deref, DerefMut)]
276struct AssertSend<T>(T);
277
278unsafe impl<T> Send for AssertSend<T> {}