]> git.tdb.fi Git - libs/gl.git/blob - source/program.cpp
Require the first keyframe of an animation to be at zero offset
[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         legacy_vars = false;
133
134         glLinkProgram(id);
135         linked = get_program_i(id, GL_LINK_STATUS);
136         if(!linked)
137                 throw compile_error(get_info_log());
138
139 #ifdef DEBUG
140         std::string info_log = get_info_log();
141         if(!info_log.empty())
142                 IO::print("Program link info log:\n%s", info_log);
143 #endif
144
145         unsigned count = get_program_i(id, GL_ACTIVE_UNIFORMS);
146         vector<UniformInfo *> uniforms_by_index(count);
147         for(unsigned i=0; i<count; ++i)
148         {
149                 char name[128];
150                 int len = 0;
151                 int size;
152                 GLenum type;
153                 glGetActiveUniform(id, i, sizeof(name), &len, &size, &type, name);
154                 if(len && strncmp(name, "gl_", 3))
155                 {
156                         /* Some implementations report the first element of a uniform array,
157                         others report just the name of the array itself. */
158                         if(len>3 && !strcmp(name+len-3, "[0]"))
159                                 name[len-3] = 0;
160
161                         UniformInfo &info = uniforms[name];
162                         info.block = 0;
163                         info.name = name;
164                         info.size = size;
165                         info.array_stride = 0;
166                         info.matrix_stride = 0;
167                         info.type = type;
168                         uniforms_by_index[i] = &info;
169                 }
170                 else
171                         legacy_vars = true;
172         }
173
174         count = get_program_i(id, GL_ACTIVE_ATTRIBUTES);
175         for(unsigned i=0; i<count; ++i)
176         {
177                 char name[128];
178                 int len = 0;
179                 int size;
180                 GLenum type;
181                 glGetActiveAttrib(id, i, sizeof(name), &len, &size, &type, name);
182                 if(len && !strncmp(name, "gl_", 3))
183                         legacy_vars = true;
184         }
185
186         if(ARB_uniform_buffer_object)
187         {
188                 uniform_blocks.clear();
189
190                 std::set<unsigned> used_bind_points;
191                 count = get_program_i(id, GL_ACTIVE_UNIFORM_BLOCKS);
192                 for(unsigned i=0; i<count; ++i)
193                 {
194                         char name[128];
195                         int len;
196                         glGetActiveUniformBlockName(id, i, sizeof(name), &len, name);
197                         UniformBlockInfo &info = uniform_blocks[name];
198                         info.name = name;
199
200                         int value;
201                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_DATA_SIZE, &value);
202                         info.data_size = value;
203
204                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &value);
205                         vector<int> indices(value);
206                         glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &indices[0]);
207                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
208                         {
209                                 if(!uniforms_by_index[*j])
210                                         throw logic_error("Program::link");
211                                 info.uniforms.push_back(uniforms_by_index[*j]);
212                                 uniforms_by_index[*j]->block = &info;
213                         }
214
215                         vector<unsigned> indices2(indices.begin(), indices.end());
216                         vector<int> values(indices.size());
217                         glGetActiveUniformsiv(id, indices.size(), &indices2[0], GL_UNIFORM_OFFSET, &values[0]);
218                         for(unsigned j=0; j<indices.size(); ++j)
219                                 uniforms_by_index[indices[j]]->location = values[j];
220
221                         indices2.clear();
222                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
223                                 if(uniforms_by_index[*j]->size>1)
224                                         indices2.push_back(*j);
225                         if(!indices2.empty())
226                         {
227                                 glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_ARRAY_STRIDE, &values[0]);
228                                 for(unsigned j=0; j<indices2.size(); ++j)
229                                         uniforms_by_index[indices2[j]]->array_stride = values[j];
230                         }
231
232                         indices2.clear();
233                         for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
234                         {
235                                 GLenum t = uniforms_by_index[*j]->type;
236                                 if(t==GL_FLOAT_MAT4 || t==GL_FLOAT_MAT3 || t==GL_FLOAT_MAT2 ||
237                                         t==GL_FLOAT_MAT2x3 || t==GL_FLOAT_MAT2x4 || t==GL_FLOAT_MAT3x2 ||
238                                         t==GL_FLOAT_MAT3x4 || t==GL_FLOAT_MAT4x2 || t==GL_FLOAT_MAT4x3)
239                                         indices2.push_back(*j);
240                         }
241                         if(!indices2.empty())
242                         {
243                                 glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_MATRIX_STRIDE, &values[0]);
244                                 for(unsigned j=0; j<indices2.size(); ++j)
245                                         uniforms_by_index[indices2[j]]->matrix_stride = values[j];
246                         }
247
248                         sort(info.uniforms.begin(), info.uniforms.end(), uniform_location_compare);
249                         info.layout_hash = compute_layout_hash(info.uniforms);
250                         unsigned n_bindings = BufferRange::get_n_uniform_buffer_bindings();
251                         info.bind_point = info.layout_hash%n_bindings;
252                         while(used_bind_points.count(info.bind_point))
253                                 info.bind_point = (info.bind_point+1)%n_bindings;
254                         glUniformBlockBinding(id, i, info.bind_point);
255                         used_bind_points.insert(info.bind_point);
256                 }
257         }
258
259         UniformBlockInfo &default_block = uniform_blocks[string()];
260         default_block.data_size = 0;
261         default_block.bind_point = -1;
262
263         for(UniformMap::iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
264                 if(!i->second.block)
265                 {
266                         i->second.location = glGetUniformLocation(id, i->second.name.c_str());
267                         i->second.block = &default_block;
268                         default_block.uniforms.push_back(&i->second);
269                 }
270
271         default_block.layout_hash = compute_layout_hash(default_block.uniforms);
272
273         string layout_descriptor;
274         for(UniformBlockMap::const_iterator i=uniform_blocks.begin(); i!=uniform_blocks.end(); ++i)
275                 layout_descriptor += format("%d:%x\n", i->second.bind_point, i->second.layout_hash);
276         uniform_layout_hash = hash32(layout_descriptor);
277 }
278
279 Program::LayoutHash Program::compute_layout_hash(const vector<const UniformInfo *> &uniforms)
280 {
281         string layout_descriptor;
282         for(vector<const UniformInfo *>::const_iterator i = uniforms.begin(); i!=uniforms.end(); ++i)
283                 layout_descriptor += format("%d:%s:%x:%d\n", (*i)->location, (*i)->name, (*i)->type, (*i)->size);
284         return hash32(layout_descriptor);
285 }
286
287 bool Program::uniform_location_compare(const UniformInfo *uni1, const UniformInfo *uni2)
288 {
289         return uni1->location<uni2->location;
290 }
291
292 string Program::get_info_log() const
293 {
294         GLsizei len = get_program_i(id, GL_INFO_LOG_LENGTH);
295         char *buf = new char[len+1];
296         glGetProgramInfoLog(id, len+1, &len, buf);
297         string log(buf, len);
298         delete[] buf;
299         return log;
300 }
301
302 const Program::UniformBlockInfo &Program::get_uniform_block_info(const string &name) const
303 {
304         return get_item(uniform_blocks, name);
305 }
306
307 const Program::UniformInfo &Program::get_uniform_info(const string &name) const
308 {
309         return get_item(uniforms, name);
310 }
311
312 int Program::get_uniform_location(const string &n) const
313 {
314         if(n[n.size()-1]==']')
315                 throw invalid_argument("Program::get_uniform_location");
316
317         UniformMap::const_iterator i = uniforms.find(n);
318         if(i==uniforms.end())
319                 return -1;
320
321         return i->second.block->bind_point<0 ? i->second.location : -1;
322 }
323
324 void Program::bind() const
325 {
326         if(!linked)
327                 throw invalid_operation("Program::bind");
328
329         if(!set_current(this))
330                 return;
331
332         glUseProgram(id);
333 }
334
335 void Program::unbind()
336 {
337         if(!set_current(0))
338                 return;
339
340         glUseProgram(0);
341 }
342
343
344 Program::Loader::Loader(Program &p):
345         DataFile::ObjectLoader<Program>(p)
346 {
347         add("attribute",       &Loader::attribute);
348         add("fragment_shader", &Loader::fragment_shader);
349         add("geometry_shader", &Loader::geometry_shader);
350         add("standard",        &Loader::standard);
351         add("vertex_shader",   &Loader::vertex_shader);
352 }
353
354 void Program::Loader::finish()
355 {
356         obj.link();
357 }
358
359 void Program::Loader::attribute(unsigned i, const string &n)
360 {
361         obj.bind_attribute(i, n);
362 }
363
364 void Program::Loader::fragment_shader(const string &src)
365 {
366         obj.attach_shader_owned(new FragmentShader(src));
367 }
368
369 void Program::Loader::geometry_shader(const string &src)
370 {
371         obj.attach_shader_owned(new GeometryShader(src));
372 }
373
374 void Program::Loader::standard()
375 {
376         ProgramBuilder::StandardFeatures feat;
377         load_sub(feat);
378         ProgramBuilder builder(feat);
379         builder.add_shaders(obj);
380 }
381
382 void Program::Loader::vertex_shader(const string &src)
383 {
384         obj.attach_shader_owned(new VertexShader(src));
385 }
386
387 } // namespace GL
388 } // namespace Msp