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
349
use std::fmt::Debug;
use std::ops::Div;
use std::sync::{Arc, PoisonError, RwLock};

use alot::{LotId, Lots};
use etagere::{Allocation, BucketedAtlasAllocator};
use figures::units::UPx;
use figures::{IntoSigned, IntoUnsigned, Point, Px2D, Rect, Size, UPx2D};

use crate::pipeline::{PreparedGraphic, Vertex};
use crate::{sealed, CanRenderTo, Graphics, Kludgine, KludgineGraphics, Texture, TextureSource};

fn atlas_usages() -> wgpu::TextureUsages {
    wgpu::TextureUsages::TEXTURE_BINDING
        | wgpu::TextureUsages::COPY_DST
        | wgpu::TextureUsages::COPY_SRC
}

/// A collection of multiple textures, managed as a single texture on the GPU.
/// This type is often called an atlas.
///
/// The collection is currently fixed-size and will panic when an allocation
/// fails. In the future, this type will dynamically grow as more textures are
/// added to it.
///
/// In general, this type should primarly be used with similarly-sized graphics,
/// otherwise the packing may be inefficient. For example, packing many images
/// that are multiples of 32px wide/tall will be very efficient. Interally, this
/// type is used for caching rendered glyphs on the GPU.
#[derive(Clone)]
pub struct TextureCollection {
    format: wgpu::TextureFormat,
    filter_mode: wgpu::FilterMode,
    data: Arc<RwLock<Data>>,
}

struct Data {
    rects: BucketedAtlasAllocator,
    texture: Texture,
    textures: Lots<Allocation>,
}

impl TextureCollection {
    pub(crate) fn new_generic(
        initial_size: Size<UPx>,
        format: wgpu::TextureFormat,
        filter_mode: wgpu::FilterMode,
        graphics: &impl KludgineGraphics,
    ) -> Self {
        let texture = Texture::new_generic(
            graphics,
            1,
            initial_size,
            format,
            atlas_usages(),
            filter_mode,
        );

        let initial_size = initial_size.into_signed();
        Self {
            format,
            filter_mode,
            data: Arc::new(RwLock::new(Data {
                rects: BucketedAtlasAllocator::new(etagere::euclid::Size2D::new(
                    initial_size.width.into(),
                    initial_size.height.into(),
                )),
                texture,
                textures: Lots::new(),
            })),
        }
    }

    /// Returns a new atlas of the given size and format.
    #[must_use]
    pub fn new(
        initial_size: Size<UPx>,
        format: wgpu::TextureFormat,
        filter_mode: wgpu::FilterMode,
        graphics: &Graphics<'_>,
    ) -> Self {
        Self::new_generic(initial_size, format, filter_mode, graphics)
    }

    /// Pushes image data to a specific region of the texture.
    ///
    /// The data format must match the format of the texture, and must be sized
    /// exactly according to the `data_layout` and `size` and format.
    ///
    /// The returned [`CollectedTexture`] will automatically free the space it
    /// occupies when the last instance is dropped.
    pub fn push_texture(
        &mut self,
        data: &[u8],
        data_layout: wgpu::ImageDataLayout,
        size: Size<UPx>,
        graphics: &Graphics<'_>,
    ) -> CollectedTexture {
        self.push_texture_generic(data, data_layout, size, graphics)
    }

    pub(crate) fn push_texture_generic(
        &mut self,
        data: &[u8],
        data_layout: wgpu::ImageDataLayout,
        size: Size<UPx>,
        graphics: &impl KludgineGraphics,
    ) -> CollectedTexture {
        let mut this = self.data.write().unwrap_or_else(PoisonError::into_inner);
        let signed_size = size.into_signed();
        let allocation = loop {
            if let Some(allocation) = this.rects.allocate(etagere::euclid::Size2D::new(
                signed_size.width.into(),
                signed_size.height.into(),
            )) {
                break allocation;
            }

            let new_size = this.texture.size * 2;
            let new_texture = Texture::new_generic(
                graphics,
                1,
                new_size,
                self.format,
                atlas_usages(),
                self.filter_mode,
            );
            let mut commands = graphics
                .device()
                .create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
            commands.copy_texture_to_texture(
                this.texture.data.wgpu.as_image_copy(),
                new_texture.data.wgpu.as_image_copy(),
                this.texture.size.into(),
            );
            graphics.queue().submit([commands.finish()]);

            this.rects.grow(etagere::euclid::Size2D::new(
                new_size.width.into_signed().get(),
                new_size.height.into_signed().get(),
            ));
            this.texture = new_texture;
        };

        let region = Rect::new(
            Point::px(allocation.rectangle.min.x, allocation.rectangle.min.y).into_unsigned(),
            size,
        );

        graphics.queue().write_texture(
            wgpu::ImageCopyTexture {
                texture: &this.texture.data.wgpu,
                mip_level: 0,
                origin: region.origin.into(),
                aspect: wgpu::TextureAspect::All,
            },
            data,
            data_layout,
            size.into(),
        );
        CollectedTexture {
            collection: self.clone(),
            id: Arc::new(this.textures.push(allocation)),
            region,
        }
    }

    /// Pushes an image to this collection.
    ///
    /// The returned [`CollectedTexture`] will automatically free the space it
    /// occupies when the last instance is dropped.
    ///
    /// # Panics
    ///
    /// Currently this only supports uploading to Rgba8 formatted textures.
    #[cfg(feature = "image")]
    pub fn push_image(
        &mut self,
        image: &image::DynamicImage,
        graphics: &Graphics<'_>,
    ) -> CollectedTexture {
        assert!(matches!(
            self.format,
            wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Rgba8UnormSrgb
        ));
        // TODO this isn't correct for all texture formats, but there's limited
        // conversion format support for the image crate. We will have to create
        // our own conversion formats for other texture formats, or we could add
        // a generic paramter to TextureCollection to determine its texture
        // format, allowing this function to only be present on types that we
        // can convert to using the image crate.
        let image = image.to_rgba8();
        self.push_texture(
            image.as_raw(),
            wgpu::ImageDataLayout {
                offset: 0,
                bytes_per_row: Some(image.width() * 4),
                rows_per_image: None,
            },
            Size::upx(image.width(), image.height()),
            graphics,
        )
    }

    /// Returns the current size of the underlying texture.
    pub fn size(&self) -> Size<UPx> {
        let data = self.data.read().unwrap_or_else(PoisonError::into_inner);
        data.texture.size()
    }

    fn free(&mut self, id: LotId) {
        let mut data = self.data.write().unwrap_or_else(PoisonError::into_inner);
        let allocation = data.textures.remove(id).expect("invalid texture free");
        data.rects.deallocate(allocation.id);
    }

    fn prepare<Unit>(
        &self,
        src: Rect<UPx>,
        dest: Rect<Unit>,
        graphics: &Graphics<'_>,
    ) -> PreparedGraphic<Unit>
    where
        Unit: figures::Unit + Div<i32, Output = Unit>,
        Vertex<Unit>: bytemuck::Pod,
    {
        let data = self.data.read().unwrap_or_else(PoisonError::into_inner);
        data.texture.prepare_partial(src, dest, graphics)
    }

    /// Returns a [`PreparedGraphic`] for the entire texture.
    ///
    /// This is primarily a debugging tool, as generally the
    /// [`CollectedTexture`]s are rendered instead.
    pub fn prepare_entire_colection<Unit>(
        &self,
        dest: Rect<Unit>,
        graphics: &Graphics<'_>,
    ) -> PreparedGraphic<Unit>
    where
        Unit: figures::Unit,
        Vertex<Unit>: bytemuck::Pod,
    {
        let data = self.data.read().unwrap_or_else(PoisonError::into_inner);
        data.texture.prepare(dest, graphics)
    }

    /// Returns the format of the texture backing this collection.
    #[must_use]
    pub const fn format(&self) -> wgpu::TextureFormat {
        self.format
    }
}

impl CanRenderTo for TextureCollection {
    fn can_render_to(&self, kludgine: &Kludgine) -> bool {
        self.data
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .texture
            .can_render_to(kludgine)
    }
}

impl TextureSource for TextureCollection {}

impl sealed::TextureSource for TextureCollection {
    fn bind_group(&self, graphics: &impl sealed::KludgineGraphics) -> Arc<wgpu::BindGroup> {
        let data = self.data.read().unwrap_or_else(PoisonError::into_inner);
        data.texture.bind_group(graphics)
    }

    fn id(&self) -> sealed::TextureId {
        let data = self.data.read().unwrap_or_else(PoisonError::into_inner);
        data.texture.id()
    }

    fn is_mask(&self) -> bool {
        let data = self.data.read().unwrap_or_else(PoisonError::into_inner);
        data.texture.is_mask()
    }

    fn default_rect(&self) -> Rect<UPx> {
        let data = self.data.read().unwrap_or_else(PoisonError::into_inner);
        data.texture.default_rect()
    }
}

/// A texture that is contained within a [`TextureCollection`].
#[derive(Clone)]
pub struct CollectedTexture {
    collection: TextureCollection,
    id: Arc<LotId>,
    pub(crate) region: Rect<UPx>,
}

impl Debug for CollectedTexture {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CollectedTexture")
            .field("id", &self.id)
            .field("region", &self.region)
            .finish_non_exhaustive()
    }
}

impl CollectedTexture {
    /// Returns a [`PreparedGraphic`] that renders this texture at `dest`.
    pub fn prepare<Unit>(&self, dest: Rect<Unit>, graphics: &Graphics<'_>) -> PreparedGraphic<Unit>
    where
        Unit: figures::Unit + Div<i32, Output = Unit>,
        Vertex<Unit>: bytemuck::Pod,
    {
        self.collection.prepare(self.region, dest, graphics)
    }
}

impl Drop for CollectedTexture {
    fn drop(&mut self) {
        if Arc::strong_count(&self.id) == 1 {
            self.collection.free(*self.id);
        }
    }
}

impl CanRenderTo for CollectedTexture {
    fn can_render_to(&self, kludgine: &Kludgine) -> bool {
        self.collection.can_render_to(kludgine)
    }
}

impl TextureSource for CollectedTexture {}

impl sealed::TextureSource for CollectedTexture {
    fn bind_group(&self, graphics: &impl sealed::KludgineGraphics) -> Arc<wgpu::BindGroup> {
        self.collection.bind_group(graphics)
    }

    fn id(&self) -> sealed::TextureId {
        self.collection.id()
    }

    fn is_mask(&self) -> bool {
        self.collection.is_mask()
    }

    fn default_rect(&self) -> Rect<UPx> {
        self.region
    }
}