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
use crate::{
    Bounds, Buffer, BufferLayout, GpuDevice, GpuRenderer, OrderedIndex,
};
use std::ops::Range;

pub struct InstanceDetails {
    pub start: u32,
    pub end: u32,
}

pub type ClippedInstanceDetails = (InstanceDetails, Option<Bounds>);

//This Holds onto all the instances Compressed into a byte array.
pub struct InstanceBuffer<K: BufferLayout> {
    pub unprocessed: Vec<Vec<OrderedIndex>>,
    pub buffers: Vec<Option<InstanceDetails>>,
    pub clipped_buffers: Vec<Vec<ClippedInstanceDetails>>,
    pub buffer: Buffer<K>,
    pub layer_size: usize,
    // this is a calculation of the buffers size when being marked as ready to add into the buffer.
    needed_size: usize,
    is_clipped: bool,
}

impl<K: BufferLayout> InstanceBuffer<K> {
    /// Used to create GpuBuffer from a BufferPass.
    /// Only use this for creating a reusable buffer.
    pub fn create_buffer(
        gpu_device: &GpuDevice,
        data: &[u8],
        layer_size: usize,
    ) -> Self {
        InstanceBuffer {
            unprocessed: Vec::new(),
            buffers: Vec::new(),
            clipped_buffers: Vec::new(),
            buffer: Buffer::new(
                gpu_device,
                data,
                wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
                Some("Instance Buffer"),
            ),
            layer_size: layer_size.max(32),
            needed_size: 0,
            is_clipped: false,
        }
    }

    pub fn add_buffer_store(
        &mut self,
        renderer: &GpuRenderer,
        index: OrderedIndex,
        layer: usize,
    ) {
        if let Some(store) = renderer.get_buffer(index.index) {
            let offset = layer.saturating_add(1);

            if self.unprocessed.len() < offset {
                for i in self.unprocessed.len()..offset {
                    //Push the layer buffer. if this is a layer we are adding data too lets
                    //give it a starting size. this cna be adjusted later for better performance
                    //versus ram usage.
                    self.unprocessed.push(if i == layer {
                        Vec::with_capacity(self.layer_size)
                    } else {
                        Vec::new()
                    });
                }
            }

            self.needed_size += store.store.len();

            if let Some(unprocessed) = self.unprocessed.get_mut(layer) {
                unprocessed.push(index);
            }
        }
    }

    fn buffer_write(
        &self,
        renderer: &mut GpuRenderer,
        buf: &OrderedIndex,
        pos: &mut usize,
        count: &mut u32,
        changed: bool,
    ) {
        let mut write_buffer = false;
        let old_pos = *pos as u64;

        if let Some(store) = renderer.get_buffer_mut(buf.index) {
            let range = *pos..*pos + store.store.len();

            if store.store_pos != range || changed || store.changed {
                store.store_pos = range;
                store.changed = false;
                write_buffer = true
            }

            *pos += store.store.len();
            *count += (store.store.len() / K::stride()) as u32;
        }

        if write_buffer {
            if let Some(store) = renderer.get_buffer(buf.index) {
                self.buffer.write(&renderer.device, &store.store, old_pos);
            }
        }
    }

    pub fn finalize(&mut self, renderer: &mut GpuRenderer) {
        let (mut changed, mut pos, mut count) = (false, 0, 0);

        if self.needed_size > self.buffer.max {
            self.resize(renderer.gpu_device(), self.needed_size / K::stride());
            changed = true;
        }

        self.buffer.count = self.needed_size / K::stride();
        self.buffer.len = self.needed_size;

        for processing in &mut self.unprocessed {
            processing.sort();
        }

        if self.is_clipped {
            for buffer in &mut self.clipped_buffers {
                buffer.clear();
            }

            if self.clipped_buffers.len() < self.unprocessed.len() {
                for _ in self.clipped_buffers.len()..self.unprocessed.len() {
                    self.clipped_buffers.push(Vec::new());
                }
            }
        } else {
            self.buffers.clear();
        }

        for (layer, processing) in self.unprocessed.iter().enumerate() {
            if processing.is_empty() {
                if !self.is_clipped {
                    self.buffers.push(None);
                }
                continue;
            }

            let mut start_pos = count;

            if !self.is_clipped {
                for buf in processing {
                    self.buffer_write(
                        renderer, buf, &mut pos, &mut count, changed,
                    );
                }

                self.buffers.push(Some(InstanceDetails {
                    start: start_pos,
                    end: count,
                }));
            } else {
                for buf in processing {
                    self.buffer_write(
                        renderer, buf, &mut pos, &mut count, changed,
                    );

                    if let Some(buffer) = self.clipped_buffers.get_mut(layer) {
                        buffer.push((
                            InstanceDetails {
                                start: start_pos,
                                end: count,
                            },
                            buf.bounds,
                        ));
                    }

                    start_pos = count;
                }
            }
        }

        self.needed_size = 0;

        for buffer in &mut self.unprocessed {
            buffer.clear()
        }
    }

    //private but resizes the buffer on the GPU when needed.
    fn resize(&mut self, gpu_device: &GpuDevice, capacity: usize) {
        let data = K::with_capacity(capacity, 0);

        self.buffer = Buffer::new(
            gpu_device,
            &data.vertexs,
            wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            Some("Vertex Buffer"),
        );
    }

    /// creates a new pre initlized InstanceBuffer with a default size.
    /// default size is based on the initial InstanceLayout::default_buffer length.
    pub fn new(gpu_device: &GpuDevice, layer_size: usize) -> Self {
        Self::create_buffer(
            gpu_device,
            &K::default_buffer().vertexs,
            layer_size,
        )
    }

    /// Returns the elements count.
    pub fn count(&self) -> u32 {
        self.buffer.count as u32
    }

    /// Returns the elements byte count.
    pub fn len(&self) -> u64 {
        self.buffer.len as u64
    }

    pub fn is_empty(&self) -> bool {
        self.buffer.is_empty()
    }

    /// Returns vertex_buffer's max size in bytes.
    pub fn max(&self) -> usize {
        self.buffer.max
    }

    /// Returns if the buffer is clipped or not to deturmine if you should use
    /// buffers or clipped_buffers.
    pub fn is_clipped(&self) -> bool {
        self.is_clipped
    }

    /// Sets the Buffer into Clipping mode.
    /// This will Produce a clipped_buffers instead of the buffers which
    /// will still be layered but a Vector of individual objects will Exist rather
    /// than a grouped object per layer. Will make it less Efficient but allows Bounds Clipping.
    pub fn set_as_clipped(&mut self) {
        self.is_clipped = true;
    }

    /// Returns buffer's stride.
    pub fn stride(&self) -> usize {
        K::stride()
    }

    /// Returns wgpu::BufferSlice of vertices.
    /// bounds is used to set a specific Range if needed.
    /// If bounds is None then range is 0..vertex_count.
    pub fn instances(&self, bounds: Option<Range<u64>>) -> wgpu::BufferSlice {
        let range = if let Some(bounds) = bounds {
            bounds
        } else {
            0..self.len()
        };

        self.buffer.buffer_slice(range)
    }

    /// Creates a Buffer based on capacity.
    /// Capacity is the amount of objects to initialize for.
    pub fn with_capacity(
        gpu_device: &GpuDevice,
        capacity: usize,
        layer_size: usize,
    ) -> Self {
        Self::create_buffer(
            gpu_device,
            &K::with_capacity(capacity, 0).vertexs,
            layer_size,
        )
    }
}