]> git.tdb.fi Git - libs/gl.git/blob - source/program.cpp
Add support for non-square matrix uniforms
[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/gl/extensions/nv_non_square_matrices.h>
11 #include <msp/io/print.h>
12 #include <msp/strings/format.h>
13 #include "buffer.h"
14 #include "error.h"
15 #include "misc.h"
16 #include "program.h"
17 #include "programcompiler.h"
18 #include "resources.h"
19 #include "shader.h"
20
21 using namespace std;
22
23 namespace Msp {
24 namespace GL {
25
26 Program::Program()
27 {
28         init();
29 }
30
31 Program::Program(const ProgramBuilder::StandardFeatures &features)
32 {
33         init();
34
35         ProgramBuilder builder(features);
36         builder.add_shaders(*this);
37         link();
38 }
39
40 Program::Program(const std::string &source)
41 {
42         init();
43
44         ProgramCompiler compiler;
45         if(source.find(';')==string::npos && source.size()>5 && !source.compare(source.size()-5, 5, ".glsl"))
46         {
47                 if(RefPtr<IO::Seekable> io = Resources::get_builtins().open(source))
48                         compiler.compile(*io, source);
49                 else
50                         throw IO::file_not_found(source);
51         }
52         else
53                 compiler.compile(source);
54         compiler.add_shaders(*this);
55         link();
56 }
57
58 Program::Program(const string &vert, const string &frag)
59 {
60         init();
61
62         attach_shader_owned(new VertexShader(vert));
63         attach_shader_owned(new FragmentShader(frag));
64         link();
65 }
66
67 void Program::init()
68 {
69         static Require _req(ARB_shader_objects);
70
71         linked = false;
72         id = glCreateProgram();
73 }
74
75 Program::~Program()
76 {
77         for(ShaderList::iterator i=owned_data.begin(); i!=owned_data.end(); ++i)
78                 delete *i;
79         glDeleteProgram(id);
80 }
81
82 void Program::attach_shader(Shader &shader)
83 {
84         if(find(shaders.begin(), shaders.end(), &shader)==shaders.end())
85         {
86                 glAttachShader(id, shader.get_id());
87                 shaders.push_back(&shader);
88         }
89 }
90
91 void Program::attach_shader_owned(Shader *shader)
92 {
93         attach_shader(*shader);
94         if(find(owned_data.begin(), owned_data.end(), shader)==owned_data.end())
95                 owned_data.push_back(shader);
96 }
97
98 void Program::detach_shader(Shader &shader)
99 {
100         ShaderList::iterator i = remove(shaders.begin(), shaders.end(), &shader);
101         if(i!=shaders.end())
102         {
103                 shaders.erase(i, shaders.end());
104                 glDetachShader(id, shader.get_id());
105         }
106 }
107
108 void Program::bind_attribute(unsigned index, const string &name)
109 {
110         static Require _req(ARB_vertex_shader);
111         glBindAttribLocation(id, index, name.c_str());
112 }
113
114 void Program::bind_attribute(VertexComponent comp, const string &name)
115 {
116         bind_attribute(get_component_type(comp), name);
117 }
118
119 void Program::bind_fragment_data(unsigned index, const string &name)
120 {
121         static Require _req(EXT_gpu_shader4);
122         glBindFragDataLocation(id, index, name.c_str());
123 }
124
125 void Program::link()
126 {
127         for(ShaderList::iterator i=shaders.begin(); i!=shaders.end(); ++i)
128                 if(!(*i)->is_compiled())
129                         (*i)->compile();
130
131         uniforms.clear();
132
133         glLinkProgram(id);
134         linked = get_program_i(id, GL_LINK_STATUS);
135         if(!linked)
136                 throw compile_error(get_info_log());
137
138 #ifdef DEBUG
139         std::string info_log = get_info_log();
140         if(!info_log.empty())
141                 IO::print("Program link info log:\n%s", info_log);
142 #endif
143
144         query_uniforms();
145         query_attributes();
146
147         for(UniformMap::const_iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
148                 require_type(i->second.type);
149         for(AttributeMap::const_iterator i=attributes.begin(); i!=attributes.end(); ++i)
150                 require_type(i->second.type);
151 }
152
153 void Program::require_type(GLenum t)
154 {
155         switch(t)
156         {
157         case GL_FLOAT_MAT2x3:
158         case GL_FLOAT_MAT2x4:
159         case GL_FLOAT_MAT3x2:
160         case GL_FLOAT_MAT3x4:
161         case GL_FLOAT_MAT4x2:
162         case GL_FLOAT_MAT4x3:
163                 { static Require _req(NV_non_square_matrices); }
164                 break;
165         }
166 }
167
168 void Program::query_uniforms()
169 {
170         unsigned count = get_program_i(id, GL_ACTIVE_UNIFORMS);
171         vector<UniformInfo *> uniforms_by_index(count);
172         for(unsigned i=0; i<count; ++i)
173         {
174                 char name[128];
175                 int len = 0;
176                 int size;
177                 GLenum type;
178                 glGetActiveUniform(id, i, sizeof(name), &len, &size, &type, name);
179                 if(len && strncmp(name, "gl_", 3))
180                 {
181                         /* Some implementations report the first element of a uniform array,
182                         others report just the name of the array itself. */
183                         if(len>3 && !strcmp(name+len-3, "[0]"))
184                                 name[len-3] = 0;
185
186                         UniformInfo &info = uniforms[name];
187                         info.block = 0;
188                         info.name = name;
189                         info.size = size;
190                         info.array_stride = 0;
191                         info.matrix_stride = 0;
192                         info.type = type;
193                         uniforms_by_index[i] = &info;
194                 }
195         }
196
197         if(ARB_uniform_buffer_object)
198                 query_uniform_blocks(uniforms_by_index);
199
200         UniformBlockInfo &default_block = uniform_blocks[string()];
201         default_block.data_size = 0;
202         default_block.bind_point = -1;
203
204         for(UniformMap::iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
205                 if(!i->second.block)
206                 {
207                         i->second.location = glGetUniformLocation(id, i->second.name.c_str());
208                         i->second.block = &default_block;
209                         default_block.uniforms.push_back(&i->second);
210                 }
211
212         default_block.layout_hash = compute_layout_hash(default_block.uniforms);
213
214         string layout_descriptor;
215         for(UniformBlockMap::const_iterator i=uniform_blocks.begin(); i!=uniform_blocks.end(); ++i)
216                 layout_descriptor += format("%d:%x\n", i->second.bind_point, i->second.layout_hash);
217         uniform_layout_hash = hash32(layout_descriptor);
218 }
219
220 void Program::query_uniform_blocks(const vector<UniformInfo *> &uniforms_by_index)
221 {
222         uniform_blocks.clear();
223
224         std::set<unsigned> used_bind_points;
225         unsigned count = get_program_i(id, GL_ACTIVE_UNIFORM_BLOCKS);
226         for(unsigned i=0; i<count; ++i)
227         {
228                 char name[128];
229                 int len;
230                 glGetActiveUniformBlockName(id, i, sizeof(name), &len, name);
231                 UniformBlockInfo &info = uniform_blocks[name];
232                 info.name = name;
233
234                 int value;
235                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_DATA_SIZE, &value);
236                 info.data_size = value;
237
238                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &value);
239                 vector<int> indices(value);
240                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &indices[0]);
241                 for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
242                 {
243                         if(!uniforms_by_index[*j])
244                                 throw logic_error("Program::link");
245                         info.uniforms.push_back(uniforms_by_index[*j]);
246                         uniforms_by_index[*j]->block = &info;
247                 }
248
249                 vector<unsigned> indices2(indices.begin(), indices.end());
250                 vector<int> values(indices.size());
251                 glGetActiveUniformsiv(id, indices.size(), &indices2[0], GL_UNIFORM_OFFSET, &values[0]);
252                 for(unsigned j=0; j<indices.size(); ++j)
253                         uniforms_by_index[indices[j]]->location = values[j];
254
255                 indices2.clear();
256                 for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
257                         if(uniforms_by_index[*j]->size>1)
258                                 indices2.push_back(*j);
259                 if(!indices2.empty())
260                 {
261                         glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_ARRAY_STRIDE, &values[0]);
262                         for(unsigned j=0; j<indices2.size(); ++j)
263                                 uniforms_by_index[indices2[j]]->array_stride = values[j];
264                 }
265
266                 indices2.clear();
267                 for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
268                 {
269                         GLenum t = uniforms_by_index[*j]->type;
270                         if(t==GL_FLOAT_MAT4 || t==GL_FLOAT_MAT3 || t==GL_FLOAT_MAT2 ||
271                                 t==GL_FLOAT_MAT2x3 || t==GL_FLOAT_MAT2x4 || t==GL_FLOAT_MAT3x2 ||
272                                 t==GL_FLOAT_MAT3x4 || t==GL_FLOAT_MAT4x2 || t==GL_FLOAT_MAT4x3)
273                                 indices2.push_back(*j);
274                 }
275                 if(!indices2.empty())
276                 {
277                         glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_MATRIX_STRIDE, &values[0]);
278                         for(unsigned j=0; j<indices2.size(); ++j)
279                                 uniforms_by_index[indices2[j]]->matrix_stride = values[j];
280                 }
281
282                 sort(info.uniforms.begin(), info.uniforms.end(), uniform_location_compare);
283                 info.layout_hash = compute_layout_hash(info.uniforms);
284                 unsigned n_bindings = BufferRange::get_n_uniform_buffer_bindings();
285                 info.bind_point = info.layout_hash%n_bindings;
286                 while(used_bind_points.count(info.bind_point))
287                         info.bind_point = (info.bind_point+1)%n_bindings;
288                 glUniformBlockBinding(id, i, info.bind_point);
289                 used_bind_points.insert(info.bind_point);
290         }
291 }
292
293 void Program::query_attributes()
294 {
295         unsigned count = get_program_i(id, GL_ACTIVE_ATTRIBUTES);
296         for(unsigned i=0; i<count; ++i)
297         {
298                 char name[128];
299                 int len = 0;
300                 int size;
301                 GLenum type;
302                 glGetActiveAttrib(id, i, sizeof(name), &len, &size, &type, name);
303                 if(len && strncmp(name, "gl_", 3))
304                 {
305                         if(len>3 && !strcmp(name+len-3, "[0]"))
306                                 name[len-3] = 0;
307
308                         AttributeInfo &info = attributes[name];
309                         info.name = name;
310                         info.location = glGetAttribLocation(id, name);
311                         info.size = size;
312                         info.type = type;
313                 }
314         }
315 }
316
317 Program::LayoutHash Program::compute_layout_hash(const vector<const UniformInfo *> &uniforms)
318 {
319         string layout_descriptor;
320         for(vector<const UniformInfo *>::const_iterator i = uniforms.begin(); i!=uniforms.end(); ++i)
321                 layout_descriptor += format("%d:%s:%x:%d\n", (*i)->location, (*i)->name, (*i)->type, (*i)->size);
322         return hash32(layout_descriptor);
323 }
324
325 bool Program::uniform_location_compare(const UniformInfo *uni1, const UniformInfo *uni2)
326 {
327         return uni1->location<uni2->location;
328 }
329
330 string Program::get_info_log() const
331 {
332         GLsizei len = get_program_i(id, GL_INFO_LOG_LENGTH);
333         char *buf = new char[len+1];
334         glGetProgramInfoLog(id, len+1, &len, buf);
335         string log(buf, len);
336         delete[] buf;
337         return log;
338 }
339
340 const Program::UniformBlockInfo &Program::get_uniform_block_info(const string &name) const
341 {
342         return get_item(uniform_blocks, name);
343 }
344
345 const Program::UniformInfo &Program::get_uniform_info(const string &name) const
346 {
347         return get_item(uniforms, name);
348 }
349
350 int Program::get_uniform_location(const string &n) const
351 {
352         if(n[n.size()-1]==']')
353                 throw invalid_argument("Program::get_uniform_location");
354
355         UniformMap::const_iterator i = uniforms.find(n);
356         if(i==uniforms.end())
357                 return -1;
358
359         return i->second.block->bind_point<0 ? i->second.location : -1;
360 }
361
362 const Program::AttributeInfo &Program::get_attribute_info(const string &name) const
363 {
364         return get_item(attributes, name);
365 }
366
367 int Program::get_attribute_location(const string &n) const
368 {
369         if(n[n.size()-1]==']')
370                 throw invalid_argument("Program::get_attribute_location");
371
372         AttributeMap::const_iterator i = attributes.find(n);
373         return i!=attributes.end() ? i->second.location : -1;
374 }
375
376 void Program::bind() const
377 {
378         if(!linked)
379                 throw invalid_operation("Program::bind");
380
381         if(!set_current(this))
382                 return;
383
384         glUseProgram(id);
385 }
386
387 void Program::unbind()
388 {
389         if(!set_current(0))
390                 return;
391
392         glUseProgram(0);
393 }
394
395
396 Program::Loader::Loader(Program &p):
397         DataFile::ObjectLoader<Program>(p)
398 {
399         add("attribute",       &Loader::attribute);
400         add("fragment_shader", &Loader::fragment_shader);
401         add("geometry_shader", &Loader::geometry_shader);
402         add("standard",        &Loader::standard);
403         add("vertex_shader",   &Loader::vertex_shader);
404 }
405
406 void Program::Loader::finish()
407 {
408         obj.link();
409 }
410
411 void Program::Loader::attribute(unsigned i, const string &n)
412 {
413         obj.bind_attribute(i, n);
414 }
415
416 void Program::Loader::fragment_shader(const string &src)
417 {
418         obj.attach_shader_owned(new FragmentShader(src));
419 }
420
421 void Program::Loader::geometry_shader(const string &src)
422 {
423         obj.attach_shader_owned(new GeometryShader(src));
424 }
425
426 void Program::Loader::standard()
427 {
428         ProgramBuilder::StandardFeatures feat;
429         load_sub(feat);
430         ProgramBuilder builder(feat);
431         builder.add_shaders(obj);
432 }
433
434 void Program::Loader::vertex_shader(const string &src)
435 {
436         obj.attach_shader_owned(new VertexShader(src));
437 }
438
439 } // namespace GL
440 } // namespace Msp