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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use glin::Result;
use rin::gl::types::*;
use std::mem;
use glin::buffer::Cast;
use rin::gl;

use rin::math::{Pnt2, pnt2};
use rin::color::consts::*;
use rin::color::*;
use itertools::Itertools;
// type Index = generational_arena::Index;
// type Arena<T> = generational_arena::Arena<T>;

type Index = usize;
type Arena<T> = densevec::DenseVec<T>;

#[derive(Debug, Clone, Copy)]
pub struct BufferRef{
    idx: Index
}

#[derive(Clone, Debug)]
struct Segment {
    range: ::std::ops::Range<usize>,
}

impl Segment{
    fn split(self, offset: usize) -> (Segment, Segment){
        let s1 = Segment{
            range: self.range.start .. self.range.start + offset,
        };

        let s2 = Segment{
            range: self.range.start + offset .. self.range.end,
        };

        (s1, s2)
    }

    fn join(self, other: Segment) -> ::std::result::Result<Segment, (Segment, Segment)>{
        if self.range.end == other.range.start {
            Ok(Segment{
                range: self.range.start .. other.range.end,
            })
        }else if self.range.start == other.range.end {
            Ok(Segment{
                range: other.range.start .. self.range.end,
            })
        }else{
            Err((self, other))
        }
    }

    fn start(&self) -> usize{
        self.range.start
    }

    fn end(&self) -> usize{
        self.range.end
    }

    fn len(&self) -> usize{
        self.range.len()
    }
}

pub trait InternalCreation<B>{
    fn create<C>(gl: &C, initial_size: usize, flags: GLbitfield, target: GLenum) -> Result<B>
    where C: glin::CreationContext;
}

impl InternalCreation<glin::SharedBufferStorage<u8>> for Allocator<glin::SharedBufferStorage<u8>>{
    fn create<C>(gl: &C, initial_size: usize, flags: GLbitfield, _target: GLenum) -> Result<glin::SharedBufferStorage<u8>>
    where C: glin::CreationContext
    {
        gl.new_shared_buffer().create_immutable(initial_size, flags)
    }
}

impl InternalCreation<glin::SharedBuffer<u8>> for Allocator<glin::SharedBuffer<u8>>{
    fn create<C>(gl: &C, initial_size: usize, flags: GLbitfield, target: GLenum) -> Result<glin::SharedBuffer<u8>>
    where C: glin::CreationContext
    {
        gl.new_shared_buffer().create_target(initial_size, flags, target)
    }
}

pub trait Creation<B>{
    fn new<C>(gl: &C, initial_size: usize, flags: GLbitfield, target: GLenum) -> Result<Allocator<B>>
    where C: glin::CreationContext;
}

impl<B, I: InternalCreation<B>> Creation<B> for I{
    fn new<C>(gl: &C, initial_size: usize, flags: GLbitfield, target: GLenum) -> Result<Allocator<B>>
    where C: glin::CreationContext
    {
        let mut segments = Arena::new();
        let free_segment = segments.insert_key_gen(Segment{ range: 0 .. initial_size });
        Ok(Allocator{
            buffer: Self::create(gl, initial_size, flags, target)?,
            segments,
            free_segments: vec![free_segment],
            creation_flags: flags,
            target,
        })
    }
}

pub trait Updater{
    fn update<C, T>(&mut self, gl: &C, buffer: &BufferRef, data: &[T]) -> Result<()>
    where T: 'static,
          C: glin::CreationContext ;
}

impl Updater for Allocator<glin::SharedBufferStorage<u8>>{
    fn update<C, T>(&mut self, gl: &C, buffer: &BufferRef, data: &[T]) -> Result<()>
    where T: 'static,
          C: glin::CreationContext
    {
        let bytes = data.len() * mem::size_of::<T>();
        let segment = &self.segments[buffer.idx];
        if segment.len() != bytes {
            self.reallocate(buffer, gl, bytes)?;
        }

        if self.creation_flags & gl::DYNAMIC_STORAGE_BIT != 0{
            self.buffer(buffer).cast().update(data);
        }else{
            let staging = gl.new_shared_buffer()
                    .immutable_from_data(data, 0)
                    .unwrap();
            let mut buff_t: glin::buffer::Range<T,_,_> = self.buffer(buffer).cast().range(..data.len());
            staging.copy_to(&mut buff_t);
        }

        Ok(())
    }
}

impl Updater for Allocator<glin::SharedBuffer<u8>>{
    fn update<C, T>(&mut self, gl: &C, buffer: &BufferRef, data: &[T]) -> Result<()>
    where T: 'static,
          C: glin::CreationContext
    {
        let bytes = data.len() * mem::size_of::<T>();
        let segment = &self.segments[buffer.idx];
        if segment.len() != bytes {
            self.reallocate(buffer, gl, bytes)?;
        }

        if self.creation_flags & gl::STATIC_DRAW == 0{
            self.buffer(buffer).cast().update(data);
        }else{
            let staging = gl.new_shared_buffer()
                    .immutable_from_data(data, 0)
                    .unwrap();
            let mut buff_t: glin::buffer::Range<T,_,_> = self.buffer(buffer).cast().range(..data.len());
            staging.copy_to(&mut buff_t);
        }
        Ok(())
    }
}

pub struct Allocator<B = glin::SharedBufferStorage<u8>>{
    buffer: B,
    segments: Arena<Segment>,
    free_segments: Vec<Index>,
    creation_flags: GLbitfield,
    target: GLenum,
}

impl Allocator<glin::SharedBufferStorage<u8>>{
    pub fn new_storage<C>(gl: &C, initial_size: usize, flags: GLbitfield, target: GLenum) -> Result<Allocator<glin::SharedBufferStorage<u8>>>
    where C: glin::CreationContext
    {
        let mut segments = Arena::new();
        let free_segment = segments.insert_key_gen(Segment{ range: 0 .. initial_size });
        Ok(Allocator{
            buffer: gl.new_shared_buffer().create_immutable(initial_size, flags)?,
            segments,
            free_segments: vec![free_segment],
            creation_flags: flags,
            target,
        })
    }
}

impl Allocator<glin::SharedBuffer<u8>>{
    pub fn new_buffer<C>(gl: &C, initial_size: usize, flags: GLbitfield, target: GLenum) -> Result<Allocator<glin::SharedBuffer<u8>>>
    where C: glin::CreationContext
    {
        let mut segments = Arena::new();
        let free_segment = segments.insert_key_gen(Segment{ range: 0 .. initial_size });
        Ok(Allocator{
            buffer: gl.new_shared_buffer().create_target(initial_size, flags, target)?,
            segments,
            free_segments: vec![free_segment],
            creation_flags: flags,
            target,
        })
    }
}

impl<B> Allocator<B>
where B: glin::BufferRange<u8> +
         Clone +
         glin::buffer::WithBackend +
         glin::buffer::WithBackendMut +
         glin::buffer::MapRange<u8>,
      Self: InternalCreation<B>
{

    pub fn reallocate<C>(&mut self, buffer: &BufferRef, gl: &C, len: usize) -> Result<()>
    where C: glin::CreationContext
    {
        let segment = &self.segments[buffer.idx];
        if segment.len() == len {
            return Ok(());
        }else if segment.len() > len {
            let (s1, s2) = segment.clone().split(len);
            self.segments[buffer.idx] = s1;
            if let Some(contiguous_idx) = self.free_segments.iter()
                .find(|idx| self.segments[**idx].start() == s2.end())
            {
                let contiguous = &mut self.segments[*contiguous_idx];
                *contiguous = s2.join(contiguous.clone()).unwrap();
            }else{
                let idx = self.segments.insert_key_gen(s2);
                self.free_segments.push(idx);
            }
            Ok(())
        }else{
            if let Some((free_pos, next_idx)) = self.free_segments.iter().enumerate()
                .find(|(_free_pos, idx)| self.segments[**idx].start() == segment.end() ||
                                        self.segments[**idx].end() == segment.start())
            {
                let diff = segment.len() as isize + self.segments[*next_idx].len() as isize - len as isize;
                if diff == 0 {
                    let next = self.segments.remove(*next_idx).unwrap();
                    self.segments[buffer.idx] = self.segments[buffer.idx].clone().join(next).unwrap();
                    self.free_segments.remove(free_pos);
                    return Ok(());
                }else if diff > 0{
                    if self.segments[*next_idx].start() >= self.segments[buffer.idx].start(){
                        let diff = self.segments[*next_idx].len() - diff as usize;
                        let (s1, s2) = self.segments[*next_idx].clone().split(diff);
                        self.segments[buffer.idx] = self.segments[buffer.idx].clone().join(s1).unwrap();
                        self.segments[*next_idx] = s2;
                        return Ok(())
                    }else{
                        let (s1, s2) = self.segments[*next_idx].clone().split(diff as usize);
                        self.segments[buffer.idx] = s2.join(self.segments[buffer.idx].clone()).unwrap();
                        self.segments[*next_idx] = s1;
                        return Ok(())
                    }
                }
            }

            // self.free(BufferRef{idx: buffer.idx});
            let start = self.segments[buffer.idx].start();
            let end = self.segments[buffer.idx].end();
            if let Some(contiguous_idx) = self.free_segments.iter()
                .find(|idx| self.segments[**idx].start() == end)
            {
                self.segments[*contiguous_idx].range.start = start;
                self.segments[buffer.idx].range.end = start;
            }

            let new_buffer = self._allocate(gl, len, Some(buffer.idx))?;
            assert_eq!(buffer.idx, new_buffer.idx);

            Ok(())
        }
    }

    pub fn allocate<C>(&mut self, gl: &C, len: usize) -> Result<BufferRef>
    where C: glin::CreationContext
    {
        self._allocate(gl, len, None)
    }

    fn _allocate<C>(&mut self, gl: &C, len: usize, replace_segment: Option<usize>) -> Result<BufferRef>
    where C: glin::CreationContext
    {
        // println!("Allocating {}", len);
        let free_segment = self.free_segments.iter().enumerate().filter_map(|(pos, idx)| {
            let segment = &self.segments[*idx];
            if segment.len() >= len {
                Some((pos, *idx, segment))
            }else{
                None
            }
        }).min_by_key(|(_pos, _idx, segment)| {
            segment.len()
        });

        if let Some((free_pos, segment_idx, free_segment)) = free_segment{
            // println!("Found free segment with {} at {}", free_segment.len(), free_segment.start());
            if free_segment.len() == len {
                // println!("Exact len, just using free segment");
                self.free_segments.remove(free_pos);
                if let Some(replace_segment) = replace_segment {
                    self.segments.swap(replace_segment, segment_idx);
                    Ok(BufferRef{
                        idx: replace_segment
                    })
                }else{
                    Ok(BufferRef{
                        idx: segment_idx
                    })
                }
            }else{
                // println!("Non exact len, splitting free segment");
                let (s1, s2) = free_segment.clone().split(len);
                if let Some(contiguous_idx) = self.free_segments.iter()
                    .find(|idx| self.segments[**idx].start() == s2.end())
                {
                    let contiguous = &mut self.segments[*contiguous_idx];
                    // println!("Found segment contiguous to remainder at {}, joining", contiguous.start());
                    *contiguous = s2.join(contiguous.clone()).unwrap();
                    // println!("Joined remanider and contiguous {} .. {}", contiguous.start(), contiguous.end());
                    self.free_segments.remove(free_pos);
                    if let Some(replace_segment) = replace_segment {
                        self.segments.swap(replace_segment, segment_idx);
                        Ok(BufferRef{
                            idx: replace_segment
                        })
                    }else{
                        Ok(BufferRef{
                            idx: segment_idx
                        })
                    }
                }else{
                    // println!("Not found any contiguous, just inserting remainder {} .. {} as free", s2.start(), s2.end());
                    self.segments[segment_idx] = s2;
                    if let Some(replace_segment) = replace_segment {
                        self.segments[replace_segment] = s1;
                        Ok(BufferRef{
                            idx: replace_segment
                        })
                    }else{
                        let idx = self.segments.insert_key_gen(s1);
                        Ok(BufferRef{
                            idx
                        })
                    }
                }
            }
        }else{
            // let new_capacity = next;
            let prev_capacity = self.buffer.capacity();
            if let Some(segment_at_end_idx) = self.free_segments.iter()
                .find(|idx| self.segments[**idx].end() == prev_capacity)
            {
                let last_segment = self.segments[*segment_at_end_idx].len();
                let needs = prev_capacity - last_segment + len;

                #[cfg(feature="gl_allocator_exponential")]
                let new_capacity = {
                    let mut new_capacity = prev_capacity as f32 * 1.5;
                    while new_capacity < needs as f32 {
                        new_capacity *= 1.5;
                    }
                    new_capacity as usize
                };

                #[cfg(not(feature="gl_allocator_exponential"))]
                let new_capacity = needs;

                let new_buffer = Self::create(gl, new_capacity, self.creation_flags, self.target)
                    .map_err(|err| glin::Error::with_cause(err.kind(), "Error reallocating buffer", err))?;
                self.buffer.copy_to(&mut new_buffer.clone().into_range(..self.buffer.len()));
                self.buffer = new_buffer;

                self.segments[*segment_at_end_idx].range.end = new_capacity;
                // println!("Found free last segment expanding to {} and retrying", self.segments[*segment_at_end_idx].len());
                self._allocate(gl, len, replace_segment)
            }else{
                let needs = prev_capacity + len;

                #[cfg(feature="gl_allocator_exponential")]
                let new_capacity = {
                    let mut new_capacity = prev_capacity as f32 * 1.5;
                    while new_capacity < needs as f32 {
                        new_capacity *= 1.5;
                    }
                    new_capacity as usize
                };

                #[cfg(not(feature="gl_allocator_exponential"))]
                let new_capacity = needs;

                let new_buffer = Self::create(gl, new_capacity, self.creation_flags, self.target)
                    .map_err(|err| glin::Error::with_cause(err.kind(), "Error reallocating buffer", err))?;
                self.buffer.copy_to(&mut new_buffer.clone().into_range(..self.buffer.len()));
                self.buffer = new_buffer;
                let segment = Segment{
                    range: prev_capacity .. needs,
                };
                if let Some(replace_segment) = replace_segment {
                    self.segments[replace_segment] = segment;
                    Ok(BufferRef{
                        idx: replace_segment
                    })
                }else{
                    let idx = self.segments.insert_key_gen(segment);
                    // println!("Expanded main buffer to {} and returning new segment", new_capacity);
                    Ok(BufferRef{
                        idx
                    })
                }
            }
        }
    }

    pub fn from_data<C, T>(&mut self, gl: &C, data: &[T]) -> Result<BufferRef>
    where C: glin::CreationContext,
          T: 'static,
          Self: Updater,
    {
        let bytes = data.len() * mem::size_of::<T>();
        let mut buffer = self.allocate(gl, bytes)?;
        self.update_range(gl, &mut buffer, data)?;
        Ok(buffer)
    }

    pub fn buffer(&self, bufferref: &BufferRef) -> glin::buffer::Range<u8, B, B>{
        let segment = &self.segments[bufferref.idx];
        self.buffer.clone().into_range(segment.range.clone())
    }

    pub fn full_buffer(&self) -> &B{
        &self.buffer
    }

    pub fn update_range<C, T>(&mut self, gl: &C, bufferref: &BufferRef, data: &[T]) -> Result<()>
    where T: 'static,
          C: glin::CreationContext,
          Self: Updater,
    {
        self.update(gl, bufferref, data)
    }

    pub fn free(&mut self, bufferref: BufferRef){
        let end = self.segments[bufferref.idx].end();
        if let Some(contiguous_idx) = self.free_segments.iter()
            .find(|idx| self.segments[**idx].start() == end)
        {
            let segment = self.segments.remove(bufferref.idx).unwrap();
            let contiguous = &mut self.segments[*contiguous_idx];
            *contiguous = segment.join(contiguous.clone()).unwrap();
        }else{
            self.free_segments.push(bufferref.idx)
        }
    }

    pub fn gl_debug(&self, gl: &gl::Renderer, pos: &Pnt2, w: f32, h: f32){
        let gl = gl.with_properties(&[
            gl::Property::Blend(true),
    		gl::Property::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA),
        ]);
        let total_capacity = self.buffer.capacity();
        gl.draw_rectangle_fill(pos, w, h, &rgba!(&GRAY, 0.5));
        for (idx, segment) in self.segments.iter().sorted_by_key(|(_, segment)| segment.start()) {
            let free = self.free_segments.iter().find(|free| **free == idx).is_some();
            let segment_color = if free { rgba!(&WHITE, 0.1) } else { rgba!(&WHITE, 0.8) };
            let segment_x = pos.x + segment.start() as f32 / total_capacity as f32 * w;
            let segment_w = segment.len() as f32 / total_capacity as f32 * w;
            let segment_pos = pnt2(segment_x, pos.y);
            gl.draw_rectangle_fill(&segment_pos, segment_w, h, &segment_color);
            gl.draw_rectangle_lines(&segment_pos, segment_w, h, &BLACK);

            let text = format!("{}: {}", idx, human(segment.len()));
            if text.len() * 8 < segment_w as usize{
                let text_x = segment_x + segment_w / 2. - (text.len() * 8 / 2) as f32;
                gl.draw_bitmap_string(&text, text_x, pos.y + h / 2. + 4., &BLACK);
            }else{
                let text = format!("{}", idx);
                if text.len() * 8 < segment_w as usize{
                    let text_x = segment_x + segment_w / 2. - (text.len() * 8 / 2) as f32;
                    gl.draw_bitmap_string(&text, text_x, pos.y + h / 2. + 4., &BLACK);
                }
            }
        }
    }
}


pub fn human(bytes: usize) -> String{
    if bytes < 1024 {
        bytes.to_string() + "b"
    }else if bytes < 1024 * 1024{
        format!("{:#.01}Kb", bytes as f32 / 1024 as f32)
    }else if bytes < 1024 * 1024 * 1024{
        format!("{:#.03}Mb", bytes as f32 / (1024 * 1024) as f32)
    }else{
        format!("{:#.03}Gb", bytes as f32 / (1024 * 1024 * 1024) as f32)
    }
}