2 #include <msp/core/raii.h>
3 #include <msp/gl/extensions/arb_direct_state_access.h>
5 #include "bufferable.h"
12 Bufferable::Bufferable():
17 location_dirty(false),
21 Bufferable::~Bufferable()
26 void Bufferable::use_buffer(Buffer *buf, Bufferable *prev)
28 if(prev && buf!=prev->buffer)
29 throw invalid_argument("Bufferable::use_buffer");
37 prev_in_buffer = prev;
40 next_in_buffer = prev_in_buffer->next_in_buffer;
41 prev_in_buffer->next_in_buffer = this;
45 location_dirty = true;
50 void Bufferable::change_buffer(Buffer *buf)
52 for(Bufferable *b=this; b; b=b->next_in_buffer)
55 b->location_dirty = true;
58 for(Bufferable *b=prev_in_buffer; b; b=b->prev_in_buffer)
61 b->location_dirty = true;
66 unsigned Bufferable::get_required_buffer_size() const
68 const Bufferable *last = this;
69 for(; last->next_in_buffer; last=last->next_in_buffer) ;
70 return last->offset+last->get_data_size();
73 Bufferable::AsyncUpdater *Bufferable::refresh_async() const
75 return dirty ? new AsyncUpdater(*this) : 0;
78 void Bufferable::unlink_from_buffer()
81 prev_in_buffer->next_in_buffer = next_in_buffer;
84 next_in_buffer->prev_in_buffer = prev_in_buffer;
85 next_in_buffer->update_offset();
93 void Bufferable::update_offset()
95 unsigned new_offset = 0;
97 new_offset = prev_in_buffer->offset+prev_in_buffer->get_data_size();
99 unsigned align = get_alignment();
100 new_offset += align-1;
101 new_offset -= new_offset%align;
102 if(new_offset!=offset)
105 location_dirty = true;
110 next_in_buffer->update_offset();
111 else if(buffer && offset+get_data_size()>buffer->get_size())
113 location_dirty = true;
118 void Bufferable::upload_data(char *target) const
120 unsigned data_size = get_data_size();
123 buffer->require_size(offset+data_size);
124 location_changed(buffer, offset, data_size);
125 location_dirty = false;
130 const char *source = reinterpret_cast<const char *>(get_data_pointer());
131 copy(source, source+data_size, target);
134 buffer->sub_data(offset, data_size, get_data_pointer());
139 Bufferable::AsyncUpdater::AsyncUpdater(const Bufferable &b):
142 bufferable.buffer->require_size(bufferable.get_required_buffer_size());
143 mapped_address = reinterpret_cast<char *>(bufferable.buffer->map());
146 Bufferable::AsyncUpdater::~AsyncUpdater()
148 bufferable.buffer->unmap();
151 void Bufferable::AsyncUpdater::upload_data()
153 bufferable.upload_data(mapped_address+bufferable.offset);
154 // Update all bufferables in the same buffer at once
155 for(const Bufferable *b=bufferable.prev_in_buffer; b; b=b->prev_in_buffer)
157 b->upload_data(mapped_address+b->offset);
158 for(const Bufferable *b=bufferable.next_in_buffer; b; b=b->next_in_buffer)
160 b->upload_data(mapped_address+b->offset);