]> git.tdb.fi Git - libs/gl.git/blob - source/core/program.cpp
038c031393ae33a5fcaeee27a1c00910f5da0c3c
[libs/gl.git] / source / core / program.cpp
1 #include <cstring>
2 #include <set>
3 #include <msp/core/algorithm.h>
4 #include <msp/core/hash.h>
5 #include <msp/core/maputils.h>
6 #include <msp/core/raii.h>
7 #include <msp/gl/extensions/arb_es2_compatibility.h>
8 #include <msp/gl/extensions/arb_fragment_shader.h>
9 #include <msp/gl/extensions/arb_gl_spirv.h>
10 #include <msp/gl/extensions/arb_geometry_shader4.h>
11 #include <msp/gl/extensions/arb_separate_shader_objects.h>
12 #include <msp/gl/extensions/arb_shader_objects.h>
13 #include <msp/gl/extensions/arb_uniform_buffer_object.h>
14 #include <msp/gl/extensions/arb_vertex_shader.h>
15 #include <msp/gl/extensions/ext_gpu_shader4.h>
16 #include <msp/gl/extensions/nv_non_square_matrices.h>
17 #include <msp/io/print.h>
18 #include <msp/strings/format.h>
19 #include "buffer.h"
20 #include "error.h"
21 #include "misc.h"
22 #include "program.h"
23 #include "resources.h"
24 #include "shader.h"
25 #include "glsl/compiler.h"
26
27 using namespace std;
28
29 namespace Msp {
30 namespace GL {
31
32 Program::Program()
33 {
34         init();
35 }
36
37 Program::Program(const string &source)
38 {
39         init();
40
41         GlslModule mod;
42         mod.set_source(source);
43         add_stages(mod);
44
45         link();
46         module = 0;
47 }
48
49 Program::Program(const string &vert, const string &frag)
50 {
51         init();
52
53 #pragma GCC diagnostic push
54 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
55         attach_shader_owned(new VertexShader(vert));
56         attach_shader_owned(new FragmentShader(frag));
57 #pragma GCC diagnostic pop
58         link();
59 }
60
61 Program::Program(const Module &mod, const map<string, int> &spec_values)
62 {
63         init();
64         add_stages(mod, spec_values);
65         link();
66 }
67
68 void Program::init()
69 {
70         static Require _req(ARB_shader_objects);
71
72         id = glCreateProgram();
73         module = 0;
74         transient = 0;
75         linked = false;
76 }
77
78 Program::~Program()
79 {
80         for(vector<unsigned>::iterator i=stage_ids.begin(); i!=stage_ids.end(); ++i)
81                 glDeleteShader(*i);
82         glDeleteProgram(id);
83 }
84
85 void Program::add_stages(const Module &mod, const map<string, int> &spec_values)
86 {
87         if(!stage_ids.empty())
88                 throw invalid_operation("Program::add_stages");
89
90         switch(mod.get_format())
91         {
92         case Module::GLSL: return add_glsl_stages(static_cast<const GlslModule &>(mod), spec_values);
93         case Module::SPIR_V: return add_spirv_stages(static_cast<const SpirVModule &>(mod), spec_values);
94         default: throw invalid_argument("Program::add_stages");
95         }
96 }
97
98 unsigned Program::add_stage(GLenum type)
99 {
100         switch(type)
101         {
102         case GL_VERTEX_SHADER: { static Require _req(ARB_vertex_shader); } break;
103         case GL_GEOMETRY_SHADER: { static Require _req(ARB_geometry_shader4); } break;
104         case GL_FRAGMENT_SHADER: { static Require _req(ARB_fragment_shader); } break;
105         default: throw invalid_argument("Program::add_stage");
106         }
107
108         unsigned stage_id = glCreateShader(type);
109         stage_ids.push_back(stage_id);
110         glAttachShader(id, stage_id);
111
112         return stage_id;
113 }
114
115 void Program::add_glsl_stages(const GlslModule &mod, const map<string, int> &spec_values)
116 {
117         module = &mod;
118
119         SL::Compiler compiler;
120         compiler.set_source(mod.get_prepared_source(), "<module>");
121         compiler.specialize(spec_values);
122         compiler.compile(SL::Compiler::PROGRAM);
123 #ifdef DEBUG
124         string diagnostics = compiler.get_diagnostics();
125         if(!diagnostics.empty())
126                 IO::print("Program diagnostics:\n%s\n", diagnostics);
127 #endif
128
129         vector<SL::Stage::Type> stages = compiler.get_stages();
130         for(vector<SL::Stage::Type>::const_iterator i=stages.begin(); i!=stages.end(); ++i)
131         {
132                 unsigned stage_id = 0;
133                 switch(*i)
134                 {
135                 case SL::Stage::VERTEX: stage_id = add_stage(GL_VERTEX_SHADER); break;
136                 case SL::Stage::GEOMETRY: stage_id = add_stage(GL_GEOMETRY_SHADER); break;
137                 case SL::Stage::FRAGMENT: stage_id = add_stage(GL_FRAGMENT_SHADER); break;
138                 default: throw invalid_operation("Program::add_glsl_stages");
139                 }
140
141                 string stage_src = compiler.get_stage_glsl(*i);
142                 const char *src_ptr = stage_src.data();
143                 int src_len = stage_src.size();
144                 glShaderSource(stage_id, 1, &src_ptr, &src_len);
145
146                 if(*i==SL::Stage::VERTEX)
147                 {
148                         const map<string, unsigned> &attribs = compiler.get_vertex_attributes();
149                         for(map<string, unsigned>::const_iterator j=attribs.begin(); j!=attribs.end(); ++j)
150                                 glBindAttribLocation(id, j->second, j->first.c_str());
151                 }
152
153                 if(*i==SL::Stage::FRAGMENT && EXT_gpu_shader4)
154                 {
155                         const map<string, unsigned> &frag_outs = compiler.get_fragment_outputs();
156                         for(map<string, unsigned>::const_iterator j=frag_outs.begin(); j!=frag_outs.end(); ++j)
157                                 glBindFragDataLocation(id, j->second, j->first.c_str());
158                 }
159
160                 compile_glsl_stage(stage_id);
161         }
162
163         if(!transient)
164                 transient = new TransientData;
165         transient->textures = compiler.get_texture_bindings();
166         transient->blocks = compiler.get_uniform_block_bindings();
167 }
168
169 void Program::compile_glsl_stage(unsigned stage_id)
170 {
171         glCompileShader(stage_id);
172         bool compiled = get_shader_i(stage_id, GL_COMPILE_STATUS);
173
174         GLsizei info_log_len = get_shader_i(stage_id, GL_INFO_LOG_LENGTH);
175         string info_log(info_log_len+1, 0);
176         glGetShaderInfoLog(stage_id, info_log_len+1, &info_log_len, &info_log[0]);
177         info_log.erase(info_log_len);
178         if(module && module->get_format()==Module::GLSL)
179                 info_log = static_cast<const GlslModule *>(module)->get_source_map().translate_errors(info_log);
180
181         if(!compiled)
182                 throw compile_error(info_log);
183 #ifdef DEBUG
184         if(!info_log.empty())
185                 IO::print("Shader compile info log:\n%s", info_log);
186 #endif
187 }
188
189 void Program::add_spirv_stages(const SpirVModule &mod, const map<string, int> &spec_values)
190 {
191         static Require _req(ARB_gl_spirv);
192         static Require _req2(ARB_ES2_compatibility);
193
194         module = &mod;
195
196         const vector<SpirVModule::EntryPoint> &entry_points = mod.get_entry_points();
197         std::set<SpirVModule::Stage> stages;
198         for(vector<SpirVModule::EntryPoint>::const_iterator i=entry_points.begin(); i!=entry_points.end(); ++i)
199         {
200                 if(stages.count(i->stage))
201                         throw invalid_argument("Program::add_spirv_stages");
202
203                 switch(i->stage)
204                 {
205                 case SpirVModule::VERTEX: add_stage(GL_VERTEX_SHADER); break;
206                 case SpirVModule::GEOMETRY: add_stage(GL_GEOMETRY_SHADER); break;
207                 case SpirVModule::FRAGMENT: add_stage(GL_FRAGMENT_SHADER); break;
208                 default: throw invalid_operation("Program::add_spirv_stages");
209                 }
210
211                 stages.insert(i->stage);
212         }
213
214         const vector<UInt32> &code = mod.get_code();
215         glShaderBinary(stage_ids.size(), &stage_ids[0], GL_SHADER_BINARY_FORMAT_SPIR_V, &code[0], code.size()*4);
216
217         if(!spec_values.empty() && !transient)
218                 transient = new TransientData;
219
220         const vector<SpirVModule::Constant> &spec_consts = mod.get_spec_constants();
221         vector<unsigned> spec_id_array;
222         vector<unsigned> spec_value_array;
223         spec_id_array.reserve(spec_consts.size());
224         spec_value_array.reserve(spec_consts.size());
225         for(vector<SpirVModule::Constant>::const_iterator i=spec_consts.begin(); i!=spec_consts.end(); ++i)
226         {
227                 map<string, int>::const_iterator j = spec_values.find(i->name);
228                 if(j!=spec_values.end())
229                 {
230                         spec_id_array.push_back(i->constant_id);
231                         spec_value_array.push_back(j->second);
232                         transient->spec_values[i->constant_id] = j->second;
233                 }
234         }
235
236         vector<SpirVModule::EntryPoint>::const_iterator j=entry_points.begin();
237         for(vector<unsigned>::const_iterator i=stage_ids.begin(); i!=stage_ids.end(); ++i, ++j)
238                 glSpecializeShader(*i, j->name.c_str(), spec_id_array.size(), &spec_id_array[0], &spec_value_array[0]);
239 }
240
241 #pragma GCC diagnostic push
242 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
243 void Program::attach_shader(Shader &shader)
244 {
245         unsigned shader_id = shader.steal_id();
246         if(!shader_id)
247                 throw invalid_argument("Program::attach_shader");
248         stage_ids.push_back(shader_id);
249         compile_glsl_stage(shader_id);
250 }
251
252 void Program::attach_shader_owned(Shader *shader)
253 {
254         attach_shader(*shader);
255         delete shader;
256 }
257
258 void Program::detach_shader(Shader &)
259 {
260 }
261
262 const vector<Shader *> &Program::get_attached_shaders() const
263 {
264         static vector<Shader *> dummy;
265         return dummy;
266 }
267
268 void Program::bind_attribute(unsigned index, const string &name)
269 {
270         static Require _req(ARB_vertex_shader);
271         glBindAttribLocation(id, index, name.c_str());
272 }
273
274 void Program::bind_attribute(VertexAttribute attr, const string &name)
275 {
276         bind_attribute(get_attribute_semantic(attr), name);
277 }
278
279 void Program::bind_fragment_data(unsigned index, const string &name)
280 {
281         static Require _req(EXT_gpu_shader4);
282         glBindFragDataLocation(id, index, name.c_str());
283 }
284 #pragma GCC diagnostic pop
285
286 void Program::link()
287 {
288         if(stage_ids.empty())
289                 throw invalid_operation("Program::link");
290
291         uniforms.clear();
292         uniform_blocks.clear();
293         attributes.clear();
294
295         glLinkProgram(id);
296         linked = get_program_i(id, GL_LINK_STATUS);
297
298         GLsizei info_log_len = get_program_i(id, GL_INFO_LOG_LENGTH);
299         string info_log(info_log_len+1, 0);
300         glGetProgramInfoLog(id, info_log_len+1, &info_log_len, &info_log[0]);
301         info_log.erase(info_log_len);
302         if(module && module->get_format()==Module::GLSL)
303                 info_log = static_cast<const GlslModule *>(module)->get_source_map().translate_errors(info_log);
304
305         if(!linked)
306                 throw compile_error(info_log);
307 #ifdef DEBUG
308         if(!info_log.empty())
309                 IO::print("Program link info log:\n%s", info_log);
310 #endif
311
312         if(module->get_format()==Module::GLSL)
313         {
314                 query_uniforms();
315                 query_attributes();
316                 if(transient)
317                 {
318                         for(unsigned i=0; i<uniform_blocks.size(); ++i)
319                         {
320                                 map<string, unsigned>::const_iterator j = transient->blocks.find(uniform_blocks[i].name);
321                                 if(j!=transient->blocks.end())
322                                 {
323                                         glUniformBlockBinding(id, i, j->second);
324                                         uniform_blocks[i].bind_point = j->second;
325                                 }
326                         }
327
328                         Conditional<BindRestore> _bind(!ARB_separate_shader_objects, this);
329                         for(map<string, unsigned>::const_iterator i=transient->textures.begin(); i!=transient->textures.end(); ++i)
330                         {
331                                 int location = get_uniform_location(i->first);
332                                 if(location>=0)
333                                 {
334                                         if(ARB_separate_shader_objects)
335                                                 glProgramUniform1i(id, location, i->second);
336                                         else
337                                                 glUniform1i(location, i->second);
338                                 }
339                         }
340                 }
341         }
342         else if(module->get_format()==Module::SPIR_V)
343         {
344                 collect_uniforms();
345                 collect_attributes();
346         }
347
348         delete transient;
349         transient = 0;
350
351         for(vector<UniformInfo>::const_iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
352                 require_type(i->type);
353         for(vector<AttributeInfo>::const_iterator i=attributes.begin(); i!=attributes.end(); ++i)
354                 require_type(i->type);
355 }
356
357 void Program::query_uniforms()
358 {
359         unsigned count = get_program_i(id, GL_ACTIVE_UNIFORMS);
360         uniforms.reserve(count);
361         vector<string> uniform_names(count);
362         for(unsigned i=0; i<count; ++i)
363         {
364                 char name[128];
365                 int len = 0;
366                 int size;
367                 GLenum type;
368                 glGetActiveUniform(id, i, sizeof(name), &len, &size, &type, name);
369                 if(len && strncmp(name, "gl_", 3))
370                 {
371                         /* Some implementations report the first element of a uniform array,
372                         others report just the name of the array itself. */
373                         if(len>3 && !strcmp(name+len-3, "[0]"))
374                                 name[len-3] = 0;
375
376                         uniforms.push_back(UniformInfo());
377                         UniformInfo &info = uniforms.back();
378                         info.name = name;
379                         info.tag = name;
380                         info.array_size = size;
381                         info.type = from_gl_type(type);
382                         uniform_names[i] = name;
383                 }
384         }
385
386         sort_member(uniforms, &UniformInfo::tag);
387
388         if(ARB_uniform_buffer_object)
389         {
390                 vector<UniformInfo *> uniforms_by_index(count);
391                 for(unsigned i=0; i<count; ++i)
392                         if(!uniform_names[i].empty())
393                                 // The element is already known to be present
394                                 uniforms_by_index[i] = &*lower_bound_member(uniforms, Tag(uniform_names[i]), &UniformInfo::tag);
395                 query_uniform_blocks(uniforms_by_index);
396         }
397
398         uniform_blocks.push_back(UniformBlockInfo());
399         UniformBlockInfo &default_block = uniform_blocks.back();
400
401         for(vector<UniformInfo>::iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
402                 if(!i->block)
403                 {
404                         i->location = glGetUniformLocation(id, i->name.c_str());
405                         i->block = &default_block;
406                         default_block.uniforms.push_back(&*i);
407
408                         if(is_image(i->type) && i->location>=0)
409                                 glGetUniformiv(id, i->location, &i->binding);
410                 }
411
412         default_block.layout_hash = compute_layout_hash(default_block.uniforms);
413
414         update_layout_hash();
415 }
416
417 void Program::query_uniform_blocks(const vector<UniformInfo *> &uniforms_by_index)
418 {
419         unsigned count = get_program_i(id, GL_ACTIVE_UNIFORM_BLOCKS);
420         // Reserve an extra index for the default block
421         uniform_blocks.reserve(count+1);
422         for(unsigned i=0; i<count; ++i)
423         {
424                 char name[128];
425                 int len;
426                 glGetActiveUniformBlockName(id, i, sizeof(name), &len, name);
427                 uniform_blocks.push_back(UniformBlockInfo());
428                 UniformBlockInfo &info = uniform_blocks.back();
429                 info.name = name;
430
431                 int value;
432                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_DATA_SIZE, &value);
433                 info.data_size = value;
434
435                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_BINDING, &value);
436                 info.bind_point = value;
437
438                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &value);
439                 vector<int> indices(value);
440                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &indices[0]);
441                 for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
442                 {
443                         if(!uniforms_by_index[*j])
444                                 throw logic_error("Program::link");
445                         info.uniforms.push_back(uniforms_by_index[*j]);
446                         uniforms_by_index[*j]->block = &info;
447                 }
448
449                 vector<unsigned> query_indices(indices.begin(), indices.end());
450                 vector<int> values(indices.size());
451                 glGetActiveUniformsiv(id, query_indices.size(), &query_indices[0], GL_UNIFORM_OFFSET, &values[0]);
452                 for(unsigned j=0; j<indices.size(); ++j)
453                         uniforms_by_index[indices[j]]->offset = values[j];
454
455                 query_indices.clear();
456                 for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
457                         if(uniforms_by_index[*j]->array_size>1)
458                                 query_indices.push_back(*j);
459                 if(!query_indices.empty())
460                 {
461                         glGetActiveUniformsiv(id, query_indices.size(), &query_indices[0], GL_UNIFORM_ARRAY_STRIDE, &values[0]);
462                         for(unsigned j=0; j<query_indices.size(); ++j)
463                                 uniforms_by_index[query_indices[j]]->array_stride = values[j];
464                 }
465
466                 query_indices.clear();
467                 for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
468                 {
469                         DataType t = uniforms_by_index[*j]->type;
470                         if(is_matrix(t))
471                                 query_indices.push_back(*j);
472                 }
473                 if(!query_indices.empty())
474                 {
475                         glGetActiveUniformsiv(id, query_indices.size(), &query_indices[0], GL_UNIFORM_MATRIX_STRIDE, &values[0]);
476                         for(unsigned j=0; j<query_indices.size(); ++j)
477                                 uniforms_by_index[query_indices[j]]->matrix_stride = values[j];
478                 }
479
480                 sort(info.uniforms, uniform_location_compare);
481                 info.layout_hash = compute_layout_hash(info.uniforms);
482         }
483 }
484
485 void Program::query_attributes()
486 {
487         unsigned count = get_program_i(id, GL_ACTIVE_ATTRIBUTES);
488         attributes.reserve(count);
489         for(unsigned i=0; i<count; ++i)
490         {
491                 char name[128];
492                 int len = 0;
493                 int size;
494                 GLenum type;
495                 glGetActiveAttrib(id, i, sizeof(name), &len, &size, &type, name);
496                 if(len && strncmp(name, "gl_", 3))
497                 {
498                         if(len>3 && !strcmp(name+len-3, "[0]"))
499                                 name[len-3] = 0;
500
501                         attributes.push_back(AttributeInfo());
502                         AttributeInfo &info = attributes.back();
503                         info.name = name;
504                         info.location = glGetAttribLocation(id, name);
505                         info.array_size = size;
506                         info.type = from_gl_type(type);
507                 }
508         }
509 }
510
511 void Program::collect_uniforms()
512 {
513         const SpirVModule &mod = static_cast<const SpirVModule &>(*module);
514
515         // Prepare the default block
516         uniform_blocks.push_back(UniformBlockInfo());
517         vector<vector<string> > block_uniform_names(1);
518
519         const vector<SpirVModule::Variable> &variables = mod.get_variables();
520         for(vector<SpirVModule::Variable>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
521         {
522                 if(i->storage==SpirVModule::UNIFORM && i->struct_type)
523                 {
524                         uniform_blocks.push_back(UniformBlockInfo());
525                         UniformBlockInfo &info = uniform_blocks.back();
526                         info.name = i->struct_type->name;
527                         info.bind_point = i->binding;
528                         info.data_size = i->struct_type->size;
529
530                         string prefix;
531                         if(!i->name.empty())
532                                 prefix = i->struct_type->name+".";
533                         block_uniform_names.push_back(vector<string>());
534                         collect_block_uniforms(*i->struct_type, prefix, 0, block_uniform_names.back());
535                 }
536                 else if(i->storage==SpirVModule::UNIFORM_CONSTANT && i->location>=0)
537                 {
538                         block_uniform_names[0].push_back(i->name);
539                         uniforms.push_back(UniformInfo());
540                         UniformInfo &info = uniforms.back();
541                         info.name = i->name;
542                         info.tag = i->name;
543                         info.location = i->location;
544                         info.binding = i->binding;
545                         info.array_size = i->array_size;
546                         info.type = i->type;
547                 }
548         }
549
550         sort_member(uniforms, &UniformInfo::tag);
551
552         for(unsigned i=0; i<uniform_blocks.size(); ++i)
553         {
554                 UniformBlockInfo &block = uniform_blocks[i];
555                 const vector<string> &names = block_uniform_names[i];
556                 for(vector<string>::const_iterator j=names.begin(); j!=names.end(); ++j)
557                 {
558                         // The element is already known to be present
559                         UniformInfo &uni = *lower_bound_member(uniforms, Tag(*j), &UniformInfo::tag);
560                         block.uniforms.push_back(&uni);
561                         uni.block = &block;
562                 }
563                 sort(block.uniforms, uniform_location_compare);
564                 block.layout_hash = compute_layout_hash(block.uniforms);
565         }
566
567         update_layout_hash();
568 }
569
570 void Program::collect_block_uniforms(const SpirVModule::Structure &strct, const string &prefix, unsigned base_offset, vector<string> &uniform_names)
571 {
572         for(vector<SpirVModule::StructMember>::const_iterator i=strct.members.begin(); i!=strct.members.end(); ++i)
573         {
574                 unsigned offset = base_offset+i->offset;
575                 if(i->struct_type)
576                 {
577                         unsigned array_size = i->array_size;
578                         if(i->array_size_spec)
579                         {
580                                 array_size = i->array_size_spec->i_value;
581                                 if(transient)
582                                 {
583                                         map<unsigned, int>::const_iterator j = transient->spec_values.find(i->array_size_spec->constant_id);
584                                         if(j!=transient->spec_values.end())
585                                                 array_size = j->second;
586                                 }
587                         }
588
589                         if(array_size)
590                         {
591                                 for(unsigned j=0; j<array_size; ++j, offset+=i->array_stride)
592                                         collect_block_uniforms(*i->struct_type, format("%s%s[%d].", prefix, i->name, j), offset, uniform_names);
593                         }
594                         else
595                                 collect_block_uniforms(*i->struct_type, prefix+i->name+".", offset, uniform_names);
596                 }
597                 else
598                 {
599                         string name = prefix+i->name;
600                         uniform_names.push_back(name);
601                         uniforms.push_back(UniformInfo());
602                         UniformInfo &info = uniforms.back();
603                         info.name = name;
604                         info.tag = name;
605                         info.offset = offset;
606                         info.array_size = i->array_size;
607                         info.array_stride = i->array_stride;
608                         info.matrix_stride = i->matrix_stride;
609                         info.type = i->type;
610                 }
611         }
612 }
613
614 void Program::collect_attributes()
615 {
616         const SpirVModule &mod = static_cast<const SpirVModule &>(*module);
617
618         const vector<SpirVModule::EntryPoint> &entry_points = mod.get_entry_points();
619         for(vector<SpirVModule::EntryPoint>::const_iterator i=entry_points.begin(); i!=entry_points.end(); ++i)
620                 if(i->stage==SpirVModule::VERTEX && i->name=="main")
621                 {
622                         for(vector<const SpirVModule::Variable *>::const_iterator j=i->globals.begin(); j!=i->globals.end(); ++j)
623                                 if((*j)->storage==SpirVModule::INPUT)
624                                 {
625                                         attributes.push_back(AttributeInfo());
626                                         AttributeInfo &info = attributes.back();
627                                         info.name = (*j)->name;
628                                         info.location = (*j)->location;
629                                         info.array_size = (*j)->array_size;
630                                         info.type = (*j)->type;
631                                 }
632                 }
633 }
634
635 void Program::update_layout_hash()
636 {
637         string layout_descriptor;
638         for(vector<UniformBlockInfo>::const_iterator i=uniform_blocks.begin(); i!=uniform_blocks.end(); ++i)
639                 layout_descriptor += format("%d:%x\n", i->bind_point, i->layout_hash);
640         uniform_layout_hash = hash32(layout_descriptor);
641 }
642
643 Program::LayoutHash Program::compute_layout_hash(const vector<const UniformInfo *> &uniforms)
644 {
645         string layout_descriptor;
646         for(vector<const UniformInfo *>::const_iterator i = uniforms.begin(); i!=uniforms.end(); ++i)
647                 layout_descriptor += format("%d:%s:%x:%d\n", (*i)->location, (*i)->name, (*i)->type, (*i)->array_size);
648         return hash32(layout_descriptor);
649 }
650
651 bool Program::uniform_location_compare(const UniformInfo *uni1, const UniformInfo *uni2)
652 {
653         return uni1->location<uni2->location;
654 }
655
656 string Program::get_info_log() const
657 {
658         GLsizei len = get_program_i(id, GL_INFO_LOG_LENGTH);
659         string log(len+1, 0);
660         glGetProgramInfoLog(id, len+1, &len, &log[0]);
661         log.erase(len);
662         return log;
663 }
664
665 const Program::UniformBlockInfo &Program::get_uniform_block_info(const string &name) const
666 {
667         for(vector<UniformBlockInfo>::const_iterator i=uniform_blocks.begin(); i!=uniform_blocks.end(); ++i)
668                 if(i->name==name)
669                         return *i;
670         throw key_error(name);
671 }
672
673 const Program::UniformInfo &Program::get_uniform_info(const string &name) const
674 {
675         vector<UniformInfo>::const_iterator i = lower_bound_member(uniforms, Tag(name), &UniformInfo::tag);
676         if(i==uniforms.end() || i->name!=name)
677                 throw key_error(name);
678         return *i;
679 }
680
681 const Program::UniformInfo &Program::get_uniform_info(Tag tag) const
682 {
683         vector<UniformInfo>::const_iterator i = lower_bound_member(uniforms, tag, &UniformInfo::tag);
684         if(i==uniforms.end() || i->tag!=tag)
685                 throw key_error(tag);
686         return *i;
687 }
688
689 int Program::get_uniform_location(const string &name) const
690 {
691         if(name[name.size()-1]==']')
692                 throw invalid_argument("Program::get_uniform_location");
693
694         vector<UniformInfo>::const_iterator i = lower_bound_member(uniforms, Tag(name), &UniformInfo::tag);
695         return i!=uniforms.end() && i->name==name && i->block->bind_point<0 ? i->location : -1;
696 }
697
698 int Program::get_uniform_location(Tag tag) const
699 {
700         vector<UniformInfo>::const_iterator i = lower_bound_member(uniforms, tag, &UniformInfo::tag);
701         return i!=uniforms.end() && i->tag==tag && i->block->bind_point<0 ? i->location : -1;
702 }
703
704 int Program::get_uniform_binding(Tag tag) const
705 {
706         vector<UniformInfo>::const_iterator i = lower_bound_member(uniforms, tag, &UniformInfo::tag);
707         return i!=uniforms.end() && i->tag==tag ? i->binding : -1;
708 }
709
710 const Program::AttributeInfo &Program::get_attribute_info(const string &name) const
711 {
712         vector<AttributeInfo>::const_iterator i = lower_bound_member(attributes, name, &AttributeInfo::name);
713         if(i==attributes.end() || i->name!=name)
714                 throw key_error(name);
715         return *i;
716 }
717
718 int Program::get_attribute_location(const string &name) const
719 {
720         if(name[name.size()-1]==']')
721                 throw invalid_argument("Program::get_attribute_location");
722
723         vector<AttributeInfo>::const_iterator i = lower_bound_member(attributes, name, &AttributeInfo::name);
724         return i!=attributes.end() && i->name==name ? i->location : -1;
725 }
726
727 void Program::bind() const
728 {
729         if(!linked)
730                 throw invalid_operation("Program::bind");
731
732         if(!set_current(this))
733                 return;
734
735         glUseProgram(id);
736 }
737
738 void Program::unbind()
739 {
740         if(!set_current(0))
741                 return;
742
743         glUseProgram(0);
744 }
745
746
747 Program::UniformInfo::UniformInfo():
748         block(0),
749         location(-1),
750         array_size(0),
751         array_stride(0),
752         matrix_stride(0),
753         type(VOID),
754         binding(-1)
755 { }
756
757
758 Program::UniformBlockInfo::UniformBlockInfo():
759         data_size(0),
760         bind_point(-1),
761         layout_hash(0)
762 { }
763
764
765 Program::AttributeInfo::AttributeInfo():
766         location(-1),
767         array_size(0),
768         type(VOID)
769 { }
770
771
772 Program::Loader::Loader(Program &p, Collection &c):
773         DataFile::CollectionObjectLoader<Program>(p, &c)
774 {
775         add("module",          &Loader::module);
776
777         // Deprecated
778         add("attribute",       &Loader::attribute);
779         add("fragment_shader", &Loader::fragment_shader);
780         add("geometry_shader", &Loader::geometry_shader);
781         add("vertex_shader",   &Loader::vertex_shader);
782 }
783
784 void Program::Loader::finish()
785 {
786         obj.link();
787 }
788
789 void Program::Loader::module(const string &n)
790 {
791         map<string, int> spec_values;
792         SpecializationLoader ldr(spec_values);
793         load_sub_with(ldr);
794         obj.add_stages(get_collection().get<Module>(n), spec_values);
795 }
796
797 #pragma GCC diagnostic push
798 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
799 void Program::Loader::attribute(unsigned i, const string &n)
800 {
801         obj.bind_attribute(i, n);
802 }
803
804 void Program::Loader::fragment_shader(const string &src)
805 {
806         obj.attach_shader_owned(new FragmentShader(src));
807 }
808
809 void Program::Loader::geometry_shader(const string &src)
810 {
811         obj.attach_shader_owned(new GeometryShader(src));
812 }
813
814 void Program::Loader::vertex_shader(const string &src)
815 {
816         obj.attach_shader_owned(new VertexShader(src));
817 }
818 #pragma GCC diagnostic pop
819
820
821 DataFile::Loader::ActionMap Program::SpecializationLoader::shared_actions;
822
823 Program::SpecializationLoader::SpecializationLoader(map<string, int> &sv):
824         spec_values(sv)
825 {
826         set_actions(shared_actions);
827 }
828
829 void Program::SpecializationLoader::init_actions()
830 {
831         add("specialize", &SpecializationLoader::specialize_bool);
832         add("specialize", &SpecializationLoader::specialize_int);
833 }
834
835 void Program::SpecializationLoader::specialize_bool(const string &name, bool value)
836 {
837         spec_values[name] = value;
838 }
839
840 void Program::SpecializationLoader::specialize_int(const string &name, int value)
841 {
842         spec_values[name] = value;
843 }
844
845 } // namespace GL
846 } // namespace Msp