]> git.tdb.fi Git - libs/gl.git/blob - source/program.cpp
Rework ProgramData to do less unnecessary work
[libs/gl.git] / source / program.cpp
1 #include <algorithm>
2 #include <cstring>
3 #include <set>
4 #include <msp/core/hash.h>
5 #include <msp/core/maputils.h>
6 #include <msp/gl/extensions/arb_shader_objects.h>
7 #include <msp/gl/extensions/arb_uniform_buffer_object.h>
8 #include <msp/gl/extensions/arb_vertex_shader.h>
9 #include <msp/gl/extensions/ext_gpu_shader4.h>
10 #include <msp/strings/format.h>
11 #include "buffer.h"
12 #include "error.h"
13 #include "misc.h"
14 #include "program.h"
15 #include "shader.h"
16
17 using namespace std;
18
19 namespace Msp {
20 namespace GL {
21
22 Program::Program()
23 {
24         init();
25 }
26
27 Program::Program(const ProgramBuilder::StandardFeatures &features)
28 {
29         init();
30
31         ProgramBuilder builder(features);
32         builder.add_shaders(*this);
33         link();
34 }
35
36 Program::Program(const string &vert, const string &frag)
37 {
38         init();
39
40         attach_shader_owned(new VertexShader(vert));
41         attach_shader_owned(new FragmentShader(frag));
42         link();
43 }
44
45 void Program::init()
46 {
47         static Require _req(ARB_shader_objects);
48
49         linked = false;
50         id = glCreateProgram();
51 }
52
53 Program::~Program()
54 {
55         for(ShaderList::iterator i=owned_data.begin(); i!=owned_data.end(); ++i)
56                 delete *i;
57         glDeleteProgram(id);
58 }
59
60 void Program::attach_shader(Shader &shader)
61 {
62         if(find(shaders.begin(), shaders.end(), &shader)==shaders.end())
63         {
64                 glAttachShader(id, shader.get_id());
65                 shaders.push_back(&shader);
66         }
67 }
68
69 void Program::attach_shader_owned(Shader *shader)
70 {
71         attach_shader(*shader);
72         if(find(owned_data.begin(), owned_data.end(), shader)==owned_data.end())
73                 owned_data.push_back(shader);
74 }
75
76 void Program::detach_shader(Shader &shader)
77 {
78         ShaderList::iterator i = remove(shaders.begin(), shaders.end(), &shader);
79         if(i!=shaders.end())
80         {
81                 shaders.erase(i, shaders.end());
82                 glDetachShader(id, shader.get_id());
83         }
84 }
85
86 void Program::bind_attribute(unsigned index, const string &name)
87 {
88         static Require _req(ARB_vertex_shader);
89         glBindAttribLocation(id, index, name.c_str());
90 }
91
92 void Program::bind_attribute(VertexComponent comp, const string &name)
93 {
94         bind_attribute(get_component_type(comp), name);
95 }
96
97 void Program::bind_fragment_data(unsigned index, const string &name)
98 {
99         static Require _req(EXT_gpu_shader4);
100         glBindFragDataLocation(id, index, name.c_str());
101 }
102
103 void Program::link()
104 {
105         for(ShaderList::iterator i=shaders.begin(); i!=shaders.end(); ++i)
106                 if(!(*i)->is_compiled())
107                         (*i)->compile();
108
109         uniforms.clear();
110         legacy_vars = false;
111
112         glLinkProgram(id);
113         linked = get_program_i(id, GL_LINK_STATUS);
114         if(!linked)
115                 throw compile_error(get_info_log());
116
117         unsigned count = get_program_i(id, GL_ACTIVE_UNIFORMS);
118         vector<UniformInfo *> uniforms_by_index(count);
119         for(unsigned i=0; i<count; ++i)
120         {
121                 char name[128];
122                 int len = 0;
123                 int size;
124                 GLenum type;
125                 glGetActiveUniform(id, i, sizeof(name), &len, &size, &type, name);
126                 if(len && strncmp(name, "gl_", 3))
127                 {
128                         /* Some implementations report the first element of a uniform array,
129                         others report just the name of the array itself. */
130                         if(len>3 && !strcmp(name+len-3, "[0]"))
131                                 name[len-3] = 0;
132
133                         UniformInfo &info = uniforms[name];
134                         info.block = 0;
135                         info.name = name;
136                         info.size = size;
137                         info.array_stride = 0;
138                         info.matrix_stride = 0;
139                         info.type = type;
140                         uniforms_by_index[i] = &info;
141                 }
142                 else
143                         legacy_vars = true;
144         }
145
146         count = get_program_i(id, GL_ACTIVE_ATTRIBUTES);
147         for(unsigned i=0; i<count; ++i)
148         {
149                 char name[128];
150                 int len = 0;
151                 int size;
152                 GLenum type;
153                 glGetActiveAttrib(id, i, sizeof(name), &len, &size, &type, name);
154                 if(len && !strncmp(name, "gl_", 3))
155                         legacy_vars = true;
156         }
157
158         if(ARB_uniform_buffer_object)
159         {
160                 uniform_blocks.clear();
161
162                 std::set<unsigned> used_bind_points;
163                 count = get_program_i(id, GL_ACTIVE_UNIFORM_BLOCKS);
164                 for(unsigned i=0; i<count; ++i)
165                 {
166                         char name[128];
167                         int len;
168                         glGetActiveUniformBlockName(id, i, sizeof(name), &len, name);
169                         UniformBlockInfo &info = uniform_blocks[name];
170                         info.name = name;
171
172                         int value;
173                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_DATA_SIZE, &value);
174                         info.data_size = value;
175
176                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &value);
177                         vector<int> indices(value);
178                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &indices[0]);
179                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
180                         {
181                                 if(!uniforms_by_index[*j])
182                                         throw logic_error("Program::link");
183                                 info.uniforms.push_back(uniforms_by_index[*j]);
184                                 uniforms_by_index[*j]->block = &info;
185                         }
186
187                         vector<unsigned> indices2(indices.begin(), indices.end());
188                         vector<int> values(indices.size());
189                         glGetActiveUniformsiv(id, indices.size(), &indices2[0], GL_UNIFORM_OFFSET, &values[0]);
190                         for(unsigned j=0; j<indices.size(); ++j)
191                                 uniforms_by_index[indices[j]]->location = values[j];
192
193                         indices2.clear();
194                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
195                                 if(uniforms_by_index[*j]->size>1)
196                                         indices2.push_back(*j);
197                         if(!indices2.empty())
198                         {
199                                 glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_ARRAY_STRIDE, &values[0]);
200                                 for(unsigned j=0; j<indices2.size(); ++j)
201                                         uniforms_by_index[indices2[j]]->array_stride = values[j];
202                         }
203
204                         indices2.clear();
205                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
206                         {
207                                 GLenum t = uniforms_by_index[*j]->type;
208                                 if(t==GL_FLOAT_MAT4 || t==GL_FLOAT_MAT3 || t==GL_FLOAT_MAT2 ||
209                                         t==GL_FLOAT_MAT2x3 || t==GL_FLOAT_MAT2x4 || t==GL_FLOAT_MAT3x2 ||
210                                         t==GL_FLOAT_MAT3x4 || t==GL_FLOAT_MAT4x2 || t==GL_FLOAT_MAT4x3)
211                                         indices2.push_back(*j);
212                         }
213                         if(!indices2.empty())
214                         {
215                                 glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_MATRIX_STRIDE, &values[0]);
216                                 for(unsigned j=0; j<indices2.size(); ++j)
217                                         uniforms_by_index[indices2[j]]->matrix_stride = values[j];
218                         }
219
220                         sort(info.uniforms.begin(), info.uniforms.end(), uniform_location_compare);
221                         info.layout_hash = compute_layout_hash(info.uniforms);
222                         unsigned n_bindings = BufferRange::get_n_uniform_buffer_bindings();
223                         info.bind_point = info.layout_hash%n_bindings;
224                         while(used_bind_points.count(info.bind_point))
225                                 info.bind_point = (info.bind_point+1)%n_bindings;
226                         glUniformBlockBinding(id, i, info.bind_point);
227                         used_bind_points.insert(info.bind_point);
228                 }
229         }
230
231         UniformBlockInfo &default_block = uniform_blocks[string()];
232         default_block.data_size = 0;
233         default_block.bind_point = -1;
234
235         for(UniformMap::iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
236                 if(!i->second.block)
237                 {
238                         i->second.location = glGetUniformLocation(id, i->second.name.c_str());
239                         i->second.block = &default_block;
240                         default_block.uniforms.push_back(&i->second);
241                 }
242
243         default_block.layout_hash = compute_layout_hash(default_block.uniforms);
244
245         string layout_descriptor;
246         for(UniformBlockMap::const_iterator i=uniform_blocks.begin(); i!=uniform_blocks.end(); ++i)
247                 layout_descriptor += format("%d:%x\n", i->second.bind_point, i->second.layout_hash);
248         uniform_layout_hash = hash32(layout_descriptor);
249 }
250
251 Program::LayoutHash Program::compute_layout_hash(const vector<const UniformInfo *> &uniforms)
252 {
253         string layout_descriptor;
254         for(vector<const UniformInfo *>::const_iterator i = uniforms.begin(); i!=uniforms.end(); ++i)
255                 layout_descriptor += format("%d:%s:%x:%d\n", (*i)->location, (*i)->name, (*i)->type, (*i)->size);
256         return hash32(layout_descriptor);
257 }
258
259 bool Program::uniform_location_compare(const UniformInfo *uni1, const UniformInfo *uni2)
260 {
261         return uni1->location<uni2->location;
262 }
263
264 string Program::get_info_log() const
265 {
266         GLsizei len = get_program_i(id, GL_INFO_LOG_LENGTH);
267         char *buf = new char[len+1];
268         glGetProgramInfoLog(id, len+1, &len, buf);
269         string log(buf, len);
270         delete[] buf;
271         return log;
272 }
273
274 const Program::UniformBlockInfo &Program::get_uniform_block_info(const string &name) const
275 {
276         return get_item(uniform_blocks, name);
277 }
278
279 const Program::UniformInfo &Program::get_uniform_info(const string &name) const
280 {
281         return get_item(uniforms, name);
282 }
283
284 int Program::get_uniform_location(const string &n) const
285 {
286         UniformMap::const_iterator i = uniforms.find(n);
287         if(i==uniforms.end())
288         {
289                 if(n[n.size()-1]==']')
290                 {
291                         string::size_type open_bracket = n.rfind('[');
292                         if(open_bracket!=string::npos)
293                         {
294                                 /* The requested name looks like an array.  glGetActiveUniform only
295                                 gives us the first element of the array, so try to look that up and
296                                 add an offset. */
297                                 unsigned offset = lexical_cast<unsigned>(n.substr(open_bracket+1, n.size()-2-open_bracket));
298                                 i = uniforms.find(n.substr(0, open_bracket));
299                                 if(i!=uniforms.end() && i->second.block->bind_point<0 && offset<i->second.size)
300                                         return i->second.location+offset;
301                         }
302                 }
303                 return -1;
304         }
305
306         return i->second.block->bind_point<0 ? i->second.location : -1;
307 }
308
309 void Program::bind() const
310 {
311         if(!linked)
312                 throw invalid_operation("Program::bind");
313
314         if(!set_current(this))
315                 return;
316
317         glUseProgram(id);
318 }
319
320 void Program::unbind()
321 {
322         if(!set_current(0))
323                 return;
324
325         glUseProgram(0);
326 }
327
328
329 Program::Loader::Loader(Program &p):
330         DataFile::ObjectLoader<Program>(p)
331 {
332         add("attribute",       &Loader::attribute);
333         add("fragment_shader", &Loader::fragment_shader);
334         add("standard",        &Loader::standard);
335         add("vertex_shader",   &Loader::vertex_shader);
336 }
337
338 void Program::Loader::finish()
339 {
340         obj.link();
341 }
342
343 void Program::Loader::attribute(unsigned i, const string &n)
344 {
345         obj.bind_attribute(i, n);
346 }
347
348 void Program::Loader::fragment_shader(const string &src)
349 {
350         obj.attach_shader_owned(new FragmentShader(src));
351 }
352
353 void Program::Loader::standard()
354 {
355         ProgramBuilder::StandardFeatures feat;
356         load_sub(feat);
357         ProgramBuilder builder(feat);
358         builder.add_shaders(obj);
359 }
360
361 void Program::Loader::vertex_shader(const string &src)
362 {
363         obj.attach_shader_owned(new VertexShader(src));
364 }
365
366 } // namespace GL
367 } // namespace Msp