2 #include <msp/core/raii.h>
3 #include <msp/gl/extensions/arb_direct_state_access.h>
6 #include "bufferable.h"
13 Bufferable::Bufferable():
18 location_dirty(false),
22 Bufferable::~Bufferable()
27 void Bufferable::use_buffer(Buffer *buf, Bufferable *prev)
29 if(prev && buf!=prev->buffer)
30 throw invalid_argument("Bufferable::use_buffer");
38 prev_in_buffer = prev;
41 next_in_buffer = prev_in_buffer->next_in_buffer;
42 prev_in_buffer->next_in_buffer = this;
46 location_dirty = true;
51 void Bufferable::change_buffer(Buffer *buf)
53 for(Bufferable *b=this; b; b=b->next_in_buffer)
56 b->location_dirty = true;
59 for(Bufferable *b=prev_in_buffer; b; b=b->prev_in_buffer)
62 b->location_dirty = true;
67 unsigned Bufferable::get_required_buffer_size() const
69 const Bufferable *last = this;
70 for(; last->next_in_buffer; last=last->next_in_buffer) ;
71 return last->offset+last->get_data_size();
74 Bufferable::AsyncUpdater *Bufferable::refresh_async() const
76 return dirty ? new AsyncUpdater(*this) : 0;
79 void Bufferable::unlink_from_buffer()
82 prev_in_buffer->next_in_buffer = next_in_buffer;
85 next_in_buffer->prev_in_buffer = prev_in_buffer;
86 next_in_buffer->update_offset();
94 void Bufferable::update_offset()
96 unsigned new_offset = 0;
98 new_offset = prev_in_buffer->offset+prev_in_buffer->get_data_size();
100 unsigned align = get_alignment();
101 new_offset += align-1;
102 new_offset -= new_offset%align;
103 if(new_offset!=offset)
106 location_dirty = true;
111 next_in_buffer->update_offset();
112 else if(buffer && offset+get_data_size()>buffer->get_size())
114 location_dirty = true;
119 void Bufferable::upload_data(char *target) const
121 unsigned data_size = get_data_size();
124 buffer->require_size(offset+data_size);
125 location_changed(buffer, offset, data_size);
126 location_dirty = false;
131 const char *source = reinterpret_cast<const char *>(get_data_pointer());
132 copy(source, source+data_size, target);
135 buffer->sub_data(offset, data_size, get_data_pointer());
140 Bufferable::AsyncUpdater::AsyncUpdater(const Bufferable &b):
143 bufferable.buffer->require_size(bufferable.get_required_buffer_size());
144 mapped_address = reinterpret_cast<char *>(bufferable.buffer->map());
147 Bufferable::AsyncUpdater::~AsyncUpdater()
149 bufferable.buffer->unmap();
152 void Bufferable::AsyncUpdater::upload_data()
154 bufferable.upload_data(mapped_address+bufferable.offset);
155 // Update all bufferables in the same buffer at once
156 for(const Bufferable *b=bufferable.prev_in_buffer; b; b=b->prev_in_buffer)
158 b->upload_data(mapped_address+b->offset);
159 for(const Bufferable *b=bufferable.next_in_buffer; b; b=b->next_in_buffer)
161 b->upload_data(mapped_address+b->offset);