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