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