4 #include "bufferable.h"
11 Bufferable::Bufferable():
19 Bufferable::~Bufferable()
24 void Bufferable::use_buffer(Buffer *buf, Bufferable *prev)
26 if(prev && buf!=prev->buffer)
27 throw invalid_argument("Bufferable::use_buffer");
35 prev_in_buffer = prev;
38 next_in_buffer = prev_in_buffer->next_in_buffer;
39 prev_in_buffer->next_in_buffer = this;
47 Bufferable::AsyncUpdater *Bufferable::refresh_async() const
49 return dirty ? new AsyncUpdater(*this) : 0;
52 void Bufferable::unlink_from_buffer()
55 prev_in_buffer->next_in_buffer = next_in_buffer;
58 next_in_buffer->prev_in_buffer = prev_in_buffer;
59 next_in_buffer->update_offset();
66 void Bufferable::update_offset()
68 unsigned new_offset = 0;
70 new_offset = prev_in_buffer->offset+prev_in_buffer->get_data_size();
72 unsigned align = get_alignment();
73 new_offset += align-1;
74 new_offset -= new_offset%align;
75 if(new_offset!=offset)
83 next_in_buffer->update_offset();
85 /* Do not resize the buffer here, as more bufferables may be added before
86 the buffer is actually used. */
89 bool Bufferable::resize_buffer() const
91 if(offset+get_data_size()>=buffer->get_size())
93 const Bufferable *last = this;
94 for(; last->next_in_buffer; last=last->next_in_buffer) ;
96 unsigned total_size = last->offset+last->get_data_size();
98 if(total_size>buffer->get_size())
100 buffer->data(total_size, 0);
108 void Bufferable::update_buffer() const
110 BindRestore bind(buffer, buffer->get_type());
113 /* Resizing the buffer invalidates its contents. Non-dirty data may
114 be in use, so reupload it. */
115 for(const Bufferable *b=prev_in_buffer; b; b=b->prev_in_buffer)
118 for(const Bufferable *b=next_in_buffer; b; b=b->next_in_buffer)
127 void Bufferable::upload_data(char *target) const
131 const char *source = reinterpret_cast<const char *>(get_data_pointer());
132 copy(source, source+get_data_size(), target);
135 buffer->sub_data(offset, get_data_size(), get_data_pointer());
139 Bufferable::AsyncUpdater::AsyncUpdater(const Bufferable &b):
142 buffer_resized = bufferable.resize_buffer();
143 mapped_address = reinterpret_cast<char *>(bufferable.buffer->map(WRITE_ONLY));
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)
156 if(b->dirty || buffer_resized)
158 b->upload_data(mapped_address+b->offset);
161 for(const Bufferable *b=bufferable.next_in_buffer; b; b=b->next_in_buffer)
162 if(b->dirty || buffer_resized)
164 b->upload_data(mapped_address+b->offset);