directx_atlas.rs

  1use collections::FxHashMap;
  2use etagere::BucketedAtlasAllocator;
  3use parking_lot::Mutex;
  4use windows::Win32::Graphics::{
  5    Direct3D11::{
  6        D3D11_BIND_SHADER_RESOURCE, D3D11_BOX, D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT,
  7        ID3D11Device, ID3D11DeviceContext, ID3D11ShaderResourceView, ID3D11Texture2D,
  8    },
  9    Dxgi::Common::*,
 10};
 11
 12use gpui::{
 13    AtlasKey, AtlasTextureId, AtlasTextureKind, AtlasTextureList, AtlasTile, Bounds, DevicePixels,
 14    PlatformAtlas, Point, Size,
 15};
 16
 17pub(crate) struct DirectXAtlas(Mutex<DirectXAtlasState>);
 18
 19struct DirectXAtlasState {
 20    device: ID3D11Device,
 21    device_context: ID3D11DeviceContext,
 22    monochrome_textures: AtlasTextureList<DirectXAtlasTexture>,
 23    polychrome_textures: AtlasTextureList<DirectXAtlasTexture>,
 24    subpixel_textures: AtlasTextureList<DirectXAtlasTexture>,
 25    tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
 26}
 27
 28struct DirectXAtlasTexture {
 29    id: AtlasTextureId,
 30    bytes_per_pixel: u32,
 31    allocator: BucketedAtlasAllocator,
 32    texture: ID3D11Texture2D,
 33    view: [Option<ID3D11ShaderResourceView>; 1],
 34    live_atlas_keys: u32,
 35}
 36
 37impl DirectXAtlas {
 38    pub(crate) fn new(device: &ID3D11Device, device_context: &ID3D11DeviceContext) -> Self {
 39        DirectXAtlas(Mutex::new(DirectXAtlasState {
 40            device: device.clone(),
 41            device_context: device_context.clone(),
 42            monochrome_textures: Default::default(),
 43            polychrome_textures: Default::default(),
 44            subpixel_textures: Default::default(),
 45            tiles_by_key: Default::default(),
 46        }))
 47    }
 48
 49    pub(crate) fn get_texture_view(
 50        &self,
 51        id: AtlasTextureId,
 52    ) -> [Option<ID3D11ShaderResourceView>; 1] {
 53        let lock = self.0.lock();
 54        let tex = lock.texture(id);
 55        tex.view.clone()
 56    }
 57
 58    pub(crate) fn handle_device_lost(
 59        &self,
 60        device: &ID3D11Device,
 61        device_context: &ID3D11DeviceContext,
 62    ) {
 63        let mut lock = self.0.lock();
 64        lock.device = device.clone();
 65        lock.device_context = device_context.clone();
 66        lock.monochrome_textures = AtlasTextureList::default();
 67        lock.polychrome_textures = AtlasTextureList::default();
 68        lock.subpixel_textures = AtlasTextureList::default();
 69        lock.tiles_by_key.clear();
 70    }
 71}
 72
 73impl PlatformAtlas for DirectXAtlas {
 74    fn get_or_insert_with<'a>(
 75        &self,
 76        key: &AtlasKey,
 77        build: &mut dyn FnMut() -> anyhow::Result<
 78            Option<(Size<DevicePixels>, std::borrow::Cow<'a, [u8]>)>,
 79        >,
 80    ) -> anyhow::Result<Option<AtlasTile>> {
 81        let mut lock = self.0.lock();
 82        if let Some(tile) = lock.tiles_by_key.get(key) {
 83            Ok(Some(tile.clone()))
 84        } else {
 85            let Some((size, bytes)) = build()? else {
 86                return Ok(None);
 87            };
 88            let tile = lock
 89                .allocate(size, key.texture_kind())
 90                .ok_or_else(|| anyhow::anyhow!("failed to allocate"))?;
 91            let texture = lock.texture(tile.texture_id);
 92            texture.upload(&lock.device_context, tile.bounds, &bytes);
 93            lock.tiles_by_key.insert(key.clone(), tile.clone());
 94            Ok(Some(tile))
 95        }
 96    }
 97
 98    fn remove(&self, key: &AtlasKey) {
 99        let mut lock = self.0.lock();
100
101        let Some(id) = lock.tiles_by_key.remove(key).map(|tile| tile.texture_id) else {
102            return;
103        };
104
105        let textures = match id.kind {
106            AtlasTextureKind::Monochrome => &mut lock.monochrome_textures,
107            AtlasTextureKind::Polychrome => &mut lock.polychrome_textures,
108            AtlasTextureKind::Subpixel => &mut lock.subpixel_textures,
109        };
110
111        let Some(texture_slot) = textures.textures.get_mut(id.index as usize) else {
112            return;
113        };
114
115        if let Some(mut texture) = texture_slot.take() {
116            texture.decrement_ref_count();
117            if texture.is_unreferenced() {
118                textures.free_list.push(texture.id.index as usize);
119            } else {
120                *texture_slot = Some(texture);
121            }
122        }
123    }
124}
125
126impl DirectXAtlasState {
127    fn allocate(
128        &mut self,
129        size: Size<DevicePixels>,
130        texture_kind: AtlasTextureKind,
131    ) -> Option<AtlasTile> {
132        {
133            let textures = match texture_kind {
134                AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
135                AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
136                AtlasTextureKind::Subpixel => &mut self.subpixel_textures,
137            };
138
139            if let Some(tile) = textures
140                .iter_mut()
141                .rev()
142                .find_map(|texture| texture.allocate(size))
143            {
144                return Some(tile);
145            }
146        }
147
148        let texture = self.push_texture(size, texture_kind)?;
149        texture.allocate(size)
150    }
151
152    fn push_texture(
153        &mut self,
154        min_size: Size<DevicePixels>,
155        kind: AtlasTextureKind,
156    ) -> Option<&mut DirectXAtlasTexture> {
157        const DEFAULT_ATLAS_SIZE: Size<DevicePixels> = Size {
158            width: DevicePixels(1024),
159            height: DevicePixels(1024),
160        };
161        // Max texture size for DirectX. See:
162        // https://learn.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-resources-limits
163        const MAX_ATLAS_SIZE: Size<DevicePixels> = Size {
164            width: DevicePixels(16384),
165            height: DevicePixels(16384),
166        };
167        let size = min_size.min(&MAX_ATLAS_SIZE).max(&DEFAULT_ATLAS_SIZE);
168        let pixel_format;
169        let bind_flag;
170        let bytes_per_pixel;
171        match kind {
172            AtlasTextureKind::Monochrome => {
173                pixel_format = DXGI_FORMAT_R8_UNORM;
174                bind_flag = D3D11_BIND_SHADER_RESOURCE;
175                bytes_per_pixel = 1;
176            }
177            AtlasTextureKind::Polychrome => {
178                pixel_format = DXGI_FORMAT_B8G8R8A8_UNORM;
179                bind_flag = D3D11_BIND_SHADER_RESOURCE;
180                bytes_per_pixel = 4;
181            }
182            AtlasTextureKind::Subpixel => {
183                pixel_format = DXGI_FORMAT_R8G8B8A8_UNORM;
184                bind_flag = D3D11_BIND_SHADER_RESOURCE;
185                bytes_per_pixel = 4;
186            }
187        }
188        let texture_desc = D3D11_TEXTURE2D_DESC {
189            Width: size.width.0 as u32,
190            Height: size.height.0 as u32,
191            MipLevels: 1,
192            ArraySize: 1,
193            Format: pixel_format,
194            SampleDesc: DXGI_SAMPLE_DESC {
195                Count: 1,
196                Quality: 0,
197            },
198            Usage: D3D11_USAGE_DEFAULT,
199            BindFlags: bind_flag.0 as u32,
200            CPUAccessFlags: 0,
201            MiscFlags: 0,
202        };
203        let mut texture: Option<ID3D11Texture2D> = None;
204        unsafe {
205            // This only returns None if the device is lost, which we will recreate later.
206            // So it's ok to return None here.
207            self.device
208                .CreateTexture2D(&texture_desc, None, Some(&mut texture))
209                .ok()?;
210        }
211        let texture = texture.unwrap();
212
213        let texture_list = match kind {
214            AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
215            AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
216            AtlasTextureKind::Subpixel => &mut self.subpixel_textures,
217        };
218        let index = texture_list.free_list.pop();
219        let view = unsafe {
220            let mut view = None;
221            self.device
222                .CreateShaderResourceView(&texture, None, Some(&mut view))
223                .ok()?;
224            [view]
225        };
226        let atlas_texture = DirectXAtlasTexture {
227            id: AtlasTextureId {
228                index: index.unwrap_or(texture_list.textures.len()) as u32,
229                kind,
230            },
231            bytes_per_pixel,
232            allocator: etagere::BucketedAtlasAllocator::new(device_size_to_etagere(size)),
233            texture,
234            view,
235            live_atlas_keys: 0,
236        };
237        if let Some(ix) = index {
238            texture_list.textures[ix] = Some(atlas_texture);
239            texture_list.textures.get_mut(ix).unwrap().as_mut()
240        } else {
241            texture_list.textures.push(Some(atlas_texture));
242            texture_list.textures.last_mut().unwrap().as_mut()
243        }
244    }
245
246    fn texture(&self, id: AtlasTextureId) -> &DirectXAtlasTexture {
247        match id.kind {
248            AtlasTextureKind::Monochrome => &self.monochrome_textures[id.index as usize]
249                .as_ref()
250                .unwrap(),
251            AtlasTextureKind::Polychrome => &self.polychrome_textures[id.index as usize]
252                .as_ref()
253                .unwrap(),
254            AtlasTextureKind::Subpixel => {
255                &self.subpixel_textures[id.index as usize].as_ref().unwrap()
256            }
257        }
258    }
259}
260
261impl DirectXAtlasTexture {
262    fn allocate(&mut self, size: Size<DevicePixels>) -> Option<AtlasTile> {
263        let allocation = self.allocator.allocate(device_size_to_etagere(size))?;
264        let tile = AtlasTile {
265            texture_id: self.id,
266            tile_id: allocation.id.into(),
267            bounds: Bounds {
268                origin: etagere_point_to_device(allocation.rectangle.min),
269                size,
270            },
271            padding: 0,
272        };
273        self.live_atlas_keys += 1;
274        Some(tile)
275    }
276
277    fn upload(
278        &self,
279        device_context: &ID3D11DeviceContext,
280        bounds: Bounds<DevicePixels>,
281        bytes: &[u8],
282    ) {
283        unsafe {
284            device_context.UpdateSubresource(
285                &self.texture,
286                0,
287                Some(&D3D11_BOX {
288                    left: bounds.left().0 as u32,
289                    top: bounds.top().0 as u32,
290                    front: 0,
291                    right: bounds.right().0 as u32,
292                    bottom: bounds.bottom().0 as u32,
293                    back: 1,
294                }),
295                bytes.as_ptr() as _,
296                bounds.size.width.to_bytes(self.bytes_per_pixel as u8),
297                0,
298            );
299        }
300    }
301
302    fn decrement_ref_count(&mut self) {
303        self.live_atlas_keys -= 1;
304    }
305
306    fn is_unreferenced(&mut self) -> bool {
307        self.live_atlas_keys == 0
308    }
309}
310
311fn device_size_to_etagere(size: Size<DevicePixels>) -> etagere::Size {
312    etagere::Size::new(size.width.into(), size.height.into())
313}
314
315fn etagere_point_to_device(value: etagere::Point) -> Point<DevicePixels> {
316    Point {
317        x: DevicePixels::from(value.x),
318        y: DevicePixels::from(value.y),
319    }
320}