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
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Buffer-layout-specific traits for user-defined behavior.
//!
//! [`Layout`]'s job is to split a buffer into sub-slices that will then be distributed to tile to
//! be rendered, and to write color data to these sub-slices.

use std::fmt;

use rayon::prelude::*;

mod slice_cache;
pub use slice_cache::{Chunks, Ref, Slice, SliceCache, Span};

use crate::consts;

/// Listener that gets called after every write to the buffer. Its main use is to flush freshly
/// written memory slices.
pub trait Flusher: fmt::Debug + Send + Sync {
    /// Called after `slice` was written to.
    fn flush(&self, slice: &mut [u8]);
}

/// A fill that the [`Layout`] uses to write to tiles.
pub enum TileFill<'c> {
    /// Fill tile with a solid color.
    Solid([u8; 4]),
    /// Fill tile with provided colors buffer. They are provided in [column-major] order.
    ///
    /// [column-major]: https://en.wikipedia.org/wiki/Row-_and_column-major_order
    Full(&'c [[u8; 4]]),
}

/// A buffer's layout description.
///
/// Implementors are supposed to cache sub-slices between uses provided they are being used with
/// exactly the same buffer. This is achieved by storing a [`SliceCache`] in every layout
/// implementation.
pub trait Layout {
    /// Width in pixels.
    ///
    /// # Examples
    ///
    /// ```
    /// # use forma_render::cpu::buffer::layout::{Layout, LinearLayout};
    /// let layout = LinearLayout::new(2, 3 * 4, 4);
    ///
    /// assert_eq!(layout.width(), 2);
    /// ```
    fn width(&self) -> usize;

    /// Height in pixels.
    ///
    /// # Examples
    ///
    /// ```
    /// # use forma_render::cpu::buffer::layout::{Layout, LinearLayout};
    /// let layout = LinearLayout::new(2, 3 * 4, 4);
    ///
    /// assert_eq!(layout.height(), 4);
    /// ```
    fn height(&self) -> usize;

    /// Number of buffer sub-slices that will be passes to [`Layout::write`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use forma_render::{
    /// #     cpu::buffer::{layout::{Layout, LinearLayout}}, consts::cpu::TILE_HEIGHT,
    /// # };
    /// let layout = LinearLayout::new(2, 3 * 4, 4);
    ///
    /// assert_eq!(layout.slices_per_tile(), TILE_HEIGHT);
    /// ```
    fn slices_per_tile(&self) -> usize;

    /// Returns self-stored sub-slices of `buffer` which are stored in a [`SliceCache`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use forma_render::cpu::buffer::layout::{Layout, LinearLayout};
    /// let mut buffer = [
    ///     [1; 4], [2; 4], [3; 4],
    ///     [4; 4], [5; 4], [6; 4],
    /// ].concat();
    /// let mut layout = LinearLayout::new(2, 3 * 4, 2);
    /// let slices = layout.slices(&mut buffer);
    ///
    /// assert_eq!(&*slices[0], &[[1; 4], [2; 4]].concat());
    /// assert_eq!(&*slices[1], &[[4; 4], [5; 4]].concat());
    /// ```
    fn slices<'l, 'b>(&'l mut self, buffer: &'b mut [u8]) -> Ref<'l, [Slice<'b, u8>]>;

    /// Writes `fill` to `slices`, optionally calling the `flusher`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use forma_render::cpu::buffer::layout::{Layout, LinearLayout, TileFill};
    /// let mut buffer = [
    ///     [1; 4], [2; 4], [3; 4],
    ///     [4; 4], [5; 4], [6; 4],
    /// ].concat();
    /// let mut layout = LinearLayout::new(2, 3 * 4, 2);
    ///
    /// LinearLayout::write(&mut *layout.slices(&mut buffer), None, TileFill::Solid([0; 4]));
    ///
    /// assert_eq!(buffer, [
    ///     [0; 4], [0; 4], [3; 4],
    ///     [0; 4], [0; 4], [6; 4],
    /// ].concat());
    fn write(slices: &mut [Slice<'_, u8>], flusher: Option<&dyn Flusher>, fill: TileFill<'_>);

    /// Width in tiles.
    ///
    /// # Examples
    ///
    /// ```
    /// # use forma_render::{
    /// #     cpu::buffer::{layout::{Layout, LinearLayout}},
    /// #     consts::cpu::{TILE_HEIGHT, TILE_WIDTH},
    /// # };
    /// let layout = LinearLayout::new(2 * TILE_WIDTH, 3 * TILE_WIDTH * 4, 4 * TILE_HEIGHT);
    ///
    /// assert_eq!(layout.width_in_tiles(), 2);
    /// ```
    #[inline]
    fn width_in_tiles(&self) -> usize {
        (self.width() + consts::cpu::TILE_WIDTH - 1) >> consts::cpu::TILE_WIDTH_SHIFT
    }

    /// Height in tiles.
    ///
    /// # Examples
    ///
    /// ```
    /// # use forma_render::{
    /// #     cpu::buffer::{layout::{Layout, LinearLayout}},
    /// #     consts::cpu::{TILE_HEIGHT, TILE_WIDTH},
    /// # };
    /// let layout = LinearLayout::new(2 * TILE_WIDTH, 3 * TILE_WIDTH * 4, 4 * TILE_HEIGHT);
    ///
    /// assert_eq!(layout.height_in_tiles(), 4);
    /// ```
    #[inline]
    fn height_in_tiles(&self) -> usize {
        (self.height() + consts::cpu::TILE_HEIGHT - 1) >> consts::cpu::TILE_HEIGHT_SHIFT
    }
}

/// A linear buffer layout where each optionally strided pixel row of an image is saved
/// sequentially into the buffer.
#[derive(Debug)]
pub struct LinearLayout {
    cache: SliceCache,
    width: usize,
    width_stride: usize,
    height: usize,
}

impl LinearLayout {
    /// Creates a new linear layout from `width`, `width_stride` (in bytes) and `height`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use forma_render::cpu::buffer::layout::{Layout, LinearLayout};
    /// let layout = LinearLayout::new(2, 3 * 4, 4);
    ///
    /// assert_eq!(layout.width(), 2);
    /// ```
    #[inline]
    pub fn new(width: usize, width_stride: usize, height: usize) -> Self {
        assert!(
            width * 4 <= width_stride,
            "width exceeds width stride: {} * 4 > {}",
            width,
            width_stride
        );

        let cache = SliceCache::new(width_stride * height, move |buffer| {
            let mut layout: Vec<_> = buffer
                .chunks(width_stride)
                .enumerate()
                .flat_map(|(tile_y, row)| {
                    row.slice(..width * 4)
                        .unwrap()
                        .chunks(consts::cpu::TILE_WIDTH * 4)
                        .enumerate()
                        .map(move |(tile_x, slice)| {
                            let tile_y = tile_y >> consts::cpu::TILE_HEIGHT_SHIFT;
                            (tile_x, tile_y, slice)
                        })
                })
                .collect();
            layout.par_sort_by_key(|&(tile_x, tile_y, _)| (tile_y, tile_x));

            layout.into_iter().map(|(_, _, slice)| slice).collect()
        });

        LinearLayout {
            cache,
            width,
            width_stride,
            height,
        }
    }
}

impl Layout for LinearLayout {
    #[inline]
    fn width(&self) -> usize {
        self.width
    }

    #[inline]
    fn height(&self) -> usize {
        self.height
    }

    #[inline]
    fn slices_per_tile(&self) -> usize {
        consts::cpu::TILE_HEIGHT
    }

    #[inline]
    fn slices<'l, 'b>(&'l mut self, buffer: &'b mut [u8]) -> Ref<'l, [Slice<'b, u8>]> {
        assert!(
            self.width <= buffer.len(),
            "width exceeds buffer length: {} > {}",
            self.width,
            buffer.len()
        );
        assert!(
            self.width_stride <= buffer.len(),
            "width_stride exceeds buffer length: {} > {}",
            self.width_stride,
            buffer.len(),
        );
        assert!(
            self.height * self.width_stride <= buffer.len(),
            "height * width_stride exceeds buffer length: {} > {}",
            self.height * self.width_stride,
            buffer.len(),
        );

        self.cache.access(buffer).unwrap()
    }

    #[inline]
    fn write(slices: &mut [Slice<'_, u8>], flusher: Option<&dyn Flusher>, fill: TileFill<'_>) {
        let tiles_len = slices.len();
        match fill {
            TileFill::Solid(solid) => {
                for row in slices.iter_mut().take(tiles_len) {
                    for color in row.chunks_exact_mut(4) {
                        color.copy_from_slice(&solid);
                    }
                }
            }
            TileFill::Full(colors) => {
                for (y, row) in slices.iter_mut().enumerate().take(tiles_len) {
                    for (x, color) in row.chunks_exact_mut(4).enumerate() {
                        color.copy_from_slice(&colors[x * consts::cpu::TILE_HEIGHT + y]);
                    }
                }
            }
        }

        if let Some(flusher) = flusher {
            for row in slices.iter_mut().take(tiles_len) {
                flusher.flush(
                    if let Some(subslice) = row.get_mut(..consts::cpu::TILE_WIDTH * 4) {
                        subslice
                    } else {
                        row
                    },
                );
            }
        }
    }
}