1 #include <msp/gl/extensions/arb_vertex_array_object.h>
2 #include <msp/gl/extensions/arb_vertex_shader.h>
23 Mesh::Mesh(const VertexFormat &f):
38 glDeleteVertexArrays(1, &vao_id);
47 void Mesh::use_buffers(bool b)
49 defer_buffers = false;
54 vertices.use_buffer(0);
62 void Mesh::create_buffers()
64 defer_buffers = false;
67 vbuf = new Buffer(ARRAY_BUFFER);
68 vertices.use_buffer(vbuf);
71 ibuf = new Buffer(ELEMENT_ARRAY_BUFFER);
73 if(ARB_vertex_array_object && !vao_id)
74 glGenVertexArrays(1, &vao_id);
77 void Mesh::setup_vao() const
79 Bind bind_vbuf(vbuf, ARRAY_BUFFER);
81 const VertexFormat &fmt = vertices.get_format();
82 unsigned stride = get_stride(fmt)*sizeof(float);
84 for(const unsigned char *c=fmt.begin(); c!=fmt.end(); ++c)
86 unsigned t = get_component_type(*c);
87 if(t>=get_component_type(ATTRIB1))
88 t -= get_component_type(ATTRIB1);
89 unsigned sz = get_component_size(*c);
91 glVertexAttribPointer(t, 4, GL_UNSIGNED_BYTE, true, stride, ptr);
93 glVertexAttribPointer(t, sz, GL_FLOAT, false, stride, ptr);
94 glEnableVertexAttribArray(t);
97 glBindBuffer(ELEMENT_ARRAY_BUFFER, ibuf->get_id());
102 unsigned Mesh::get_n_vertices() const
104 return vertices.size();
107 float *Mesh::modify_vertex(unsigned i)
109 return vertices.modify(i);
112 void Mesh::add_batch(const Batch &b)
118 if(!batches.empty() && batches.back().can_append(b.get_type()))
119 batches.back().append(b);
122 Batch *prev = (batches.empty() ? 0 : &batches.back());
123 batches.push_back(b);
125 batches.back().use_buffer(ibuf, prev);
129 void Mesh::set_winding(const WindingTest *w)
134 void Mesh::draw() const
136 const Mesh *cur = current();
138 throw invalid_operation("Mesh::draw");
142 Bind bind_ibuf(ibuf, ELEMENT_ARRAY_BUFFER);
143 Bind bind_winding(winding);
145 for(list<Batch>::const_iterator i=batches.begin(); i!=batches.end(); ++i)
149 void Mesh::draw(Renderer &renderer) const
151 renderer.set_mesh(this);
152 renderer.set_element_buffer(ibuf);
153 renderer.set_winding_test(winding);
155 for(list<Batch>::const_iterator i=batches.begin(); i!=batches.end(); ++i)
159 void Mesh::bind() const
161 /* If VAOs are not supported, vao_id is zero and set_current won't get
162 called. Thus unbind won't try to call a null function either. */
165 else if(set_current(this))
167 glBindVertexArray(vao_id);
177 glBindVertexArray(0);
181 Mesh::Loader::Loader(Mesh &m):
182 DataFile::ObjectLoader<Mesh>(m)
184 add("batch", &Loader::batch);
185 add("vertices", &Loader::vertices);
186 add("winding", &Loader::winding);
189 void Mesh::Loader::vertices(const vector<VertexComponent> &c)
192 throw invalid_argument("No vertex components");
195 for(vector<VertexComponent>::const_iterator i=c.begin(); i!=c.end(); ++i)
197 obj.vertices.reset(fmt);
199 load_sub(obj.vertices);
202 void Mesh::Loader::batch(PrimitiveType p)
209 void Mesh::Loader::winding(FaceWinding w)
212 obj.winding = &WindingTest::clockwise();
213 else if(w==COUNTERCLOCKWISE)
214 obj.winding = &WindingTest::counterclockwise();