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