]> git.tdb.fi Git - libs/gl.git/blob - source/backends/opengl/program_backend.cpp
32c6d6e137c36e4789b47ccb2b381a7823396be2
[libs/gl.git] / source / backends / opengl / program_backend.cpp
1 #include <cstring>
2 #include <msp/core/algorithm.h>
3 #include <msp/gl/extensions/arb_es2_compatibility.h>
4 #include <msp/gl/extensions/arb_fragment_shader.h>
5 #include <msp/gl/extensions/arb_gl_spirv.h>
6 #include <msp/gl/extensions/arb_geometry_shader4.h>
7 #include <msp/gl/extensions/arb_separate_shader_objects.h>
8 #include <msp/gl/extensions/arb_shader_objects.h>
9 #include <msp/gl/extensions/arb_uniform_buffer_object.h>
10 #include <msp/gl/extensions/arb_vertex_shader.h>
11 #include <msp/gl/extensions/ext_gpu_shader4.h>
12 #include <msp/gl/extensions/khr_debug.h>
13 #include <msp/gl/extensions/nv_non_square_matrices.h>
14 #include <msp/io/print.h>
15 #include "deviceinfo.h"
16 #include "error.h"
17 #include "program.h"
18 #include "program_backend.h"
19 #include "glsl/compiler.h"
20
21 using namespace std;
22
23 namespace {
24
25 template<typename T, void (*&func)(GLint, GLsizei, const T *)>
26 void uniform_wrapper(unsigned index, unsigned count, const void *data)
27 {
28         func(index, count, static_cast<const T *>(data));
29 }
30
31 template<typename T, void (*&func)(GLint, GLsizei, GLboolean, const T *)>
32 void uniform_matrix_wrapper(unsigned index, unsigned count, const void *data)
33 {
34         func(index, count, false, static_cast<const T *>(data));
35 }
36
37 }
38
39 namespace Msp {
40 namespace GL {
41
42 OpenGLProgram::OpenGLProgram()
43 {
44         static Require _req(ARB_shader_objects);
45
46         id = glCreateProgram();
47 }
48
49 OpenGLProgram::~OpenGLProgram()
50 {
51         for(unsigned i=0; i<MAX_STAGES; ++i)
52                 if(stage_ids[i])
53                         glDeleteShader(stage_ids[i]);
54         glDeleteProgram(id);
55 }
56
57 bool OpenGLProgram::has_stages() const
58 {
59         for(unsigned i=0; i<MAX_STAGES; ++i)
60                 if(stage_ids[i])
61                         return true;
62         return false;
63 }
64
65 unsigned OpenGLProgram::add_stage(Stage type)
66 {
67         GLenum gl_type;
68         switch(type)
69         {
70         case VERTEX: { static Require _req(ARB_vertex_shader); gl_type = GL_VERTEX_SHADER; } break;
71         case GEOMETRY: { static Require _req(ARB_geometry_shader4); gl_type = GL_GEOMETRY_SHADER; } break;
72         case FRAGMENT: { static Require _req(ARB_fragment_shader); gl_type = GL_FRAGMENT_SHADER; } break;
73         default: throw invalid_argument("OpenGLProgram::add_stage");
74         }
75
76         if(stage_ids[type])
77                 throw invalid_operation("OpenGLProgram::add_stage");
78
79         unsigned stage_id = glCreateShader(gl_type);
80         stage_ids[type] = stage_id;
81         glAttachShader(id, stage_id);
82
83 #ifdef DEBUG
84         if(!debug_name.empty() && KHR_debug)
85                 set_stage_debug_name(stage_id, type);
86 #endif
87
88         return stage_id;
89 }
90
91 void OpenGLProgram::add_glsl_stages(const GlslModule &mod, const map<string, int> &spec_values, TransientData &transient)
92 {
93         SL::Compiler compiler(DeviceInfo::get_global().glsl_features);
94         compiler.set_source(mod.get_prepared_source(), "<module>");
95         compiler.specialize(spec_values);
96         compiler.compile(SL::Compiler::PROGRAM);
97 #ifdef DEBUG
98         string diagnostics = compiler.get_diagnostics();
99         if(!diagnostics.empty())
100                 IO::print("Program diagnostics:\n%s\n", diagnostics);
101 #endif
102
103         vector<SL::Stage::Type> stages = compiler.get_stages();
104         if(stages.empty())
105                 throw invalid_argument("OpenGLProgram::add_glsl_stages");
106
107         for(SL::Stage::Type st: stages)
108         {
109                 unsigned stage_id = 0;
110                 switch(st)
111                 {
112                 case SL::Stage::VERTEX: stage_id = add_stage(VERTEX); break;
113                 case SL::Stage::GEOMETRY: stage_id = add_stage(GEOMETRY); break;
114                 case SL::Stage::FRAGMENT: stage_id = add_stage(FRAGMENT); break;
115                 default: throw invalid_operation("OpenGLProgram::add_glsl_stages");
116                 }
117
118                 string stage_src = compiler.get_stage_glsl(st);
119                 const char *src_ptr = stage_src.data();
120                 int src_len = stage_src.size();
121                 glShaderSource(stage_id, 1, &src_ptr, &src_len);
122
123                 if(st==SL::Stage::VERTEX)
124                 {
125                         for(const auto &kvp: compiler.get_vertex_attributes())
126                                 glBindAttribLocation(id, kvp.second, kvp.first.c_str());
127                 }
128
129                 if(st==SL::Stage::FRAGMENT && EXT_gpu_shader4)
130                 {
131                         for(const auto &kvp: compiler.get_fragment_outputs())
132                                 glBindFragDataLocation(id, kvp.second, kvp.first.c_str());
133                 }
134
135                 compile_glsl_stage(mod, stage_id);
136         }
137
138         transient.textures = compiler.get_texture_bindings();
139         transient.blocks = compiler.get_uniform_block_bindings();
140
141         ReflectData &rd = static_cast<Program *>(this)->reflect_data;
142         rd.n_clip_distances = compiler.get_n_clip_distances();
143 }
144
145 void OpenGLProgram::compile_glsl_stage(const GlslModule &mod, unsigned stage_id)
146 {
147         glCompileShader(stage_id);
148         int status = 0;
149         glGetShaderiv(stage_id, GL_COMPILE_STATUS, &status);
150
151         int info_log_len = 0;
152         glGetShaderiv(stage_id, GL_INFO_LOG_LENGTH, &info_log_len);
153         string info_log(info_log_len+1, 0);
154         glGetShaderInfoLog(stage_id, info_log_len+1, &info_log_len, &info_log[0]);
155         info_log.erase(info_log_len);
156         info_log = mod.get_source_map().translate_errors(info_log);
157
158         if(!status)
159                 throw compile_error(info_log);
160 #ifdef DEBUG
161         if(!info_log.empty())
162                 IO::print("Shader compile info log:\n%s", info_log);
163 #endif
164 }
165
166 void OpenGLProgram::add_spirv_stages(const SpirVModule &mod, const map<string, int> &spec_values)
167 {
168         static Require _req(ARB_gl_spirv);
169         static Require _req2(ARB_ES2_compatibility);
170
171         unsigned n_stages = 0;
172         unsigned used_stage_ids[MAX_STAGES];
173         for(const SpirVModule::EntryPoint &e: mod.get_entry_points())
174         {
175                 unsigned stage_id = 0;
176                 switch(e.stage)
177                 {
178                 case SpirVModule::VERTEX: stage_id = add_stage(VERTEX); break;
179                 case SpirVModule::GEOMETRY: stage_id = add_stage(GEOMETRY); break;
180                 case SpirVModule::FRAGMENT: stage_id = add_stage(FRAGMENT); break;
181                 default: throw invalid_operation("OpenGLProgram::add_spirv_stages");
182                 }
183
184                 used_stage_ids[n_stages++] = stage_id;
185         }
186
187         if(!n_stages)
188                 throw invalid_argument("OpenGLProgram::add_spirv_stages");
189
190         const vector<uint32_t> &code = mod.get_code();
191         glShaderBinary(n_stages, used_stage_ids, GL_SHADER_BINARY_FORMAT_SPIR_V, &code[0], code.size()*4);
192
193         const vector<SpirVModule::Constant> &spec_consts = mod.get_spec_constants();
194         vector<unsigned> spec_id_array;
195         vector<unsigned> spec_value_array;
196         spec_id_array.reserve(spec_consts.size());
197         spec_value_array.reserve(spec_consts.size());
198         for(const SpirVModule::Constant &c: spec_consts)
199         {
200                 auto i = spec_values.find(c.name);
201                 if(i!=spec_values.end())
202                 {
203                         spec_id_array.push_back(c.constant_id);
204                         spec_value_array.push_back(i->second);
205                 }
206         }
207
208         auto j = mod.get_entry_points().begin();
209         for(unsigned i=0; i<MAX_STAGES; ++i)
210                 if(stage_ids[i])
211                         glSpecializeShader(stage_ids[i], j->name.c_str(), spec_id_array.size(), &spec_id_array[0], &spec_value_array[0]);
212 }
213
214 void OpenGLProgram::finalize(const Module &mod, TransientData &transient)
215 {
216         glLinkProgram(id);
217         int status = 0;
218         glGetProgramiv(id, GL_LINK_STATUS, &status);
219         linked = status;
220
221         int info_log_len = 0;
222         glGetProgramiv(id, GL_INFO_LOG_LENGTH, &info_log_len);
223         string info_log(info_log_len+1, 0);
224         glGetProgramInfoLog(id, info_log_len+1, &info_log_len, &info_log[0]);
225         info_log.erase(info_log_len);
226         if(mod.get_format()==Module::GLSL)
227                 info_log = static_cast<const GlslModule &>(mod).get_source_map().translate_errors(info_log);
228
229         if(!linked)
230                 throw compile_error(info_log);
231 #ifdef DEBUG
232         if(!info_log.empty())
233                 IO::print("Program link info log:\n%s", info_log);
234 #endif
235
236         if(mod.get_format()==Module::GLSL)
237         {
238                 query_uniforms();
239                 query_attributes();
240                 apply_bindings(transient);
241         }
242 }
243
244 void OpenGLProgram::query_uniforms()
245 {
246         ReflectData &rd = static_cast<Program *>(this)->reflect_data;
247
248         unsigned count = 0;
249         glGetProgramiv(id, GL_ACTIVE_UNIFORMS, reinterpret_cast<int *>(&count));
250         rd.uniforms.reserve(count);
251         vector<string> uniform_names(count);
252         for(unsigned i=0; i<count; ++i)
253         {
254                 char name[128];
255                 int len = 0;
256                 int size;
257                 GLenum type;
258                 glGetActiveUniform(id, i, sizeof(name), &len, &size, &type, name);
259                 if(len && strncmp(name, "gl_", 3))
260                 {
261                         /* Some implementations report the first element of a uniform array,
262                         others report just the name of the array itself. */
263                         if(len>3 && !strcmp(name+len-3, "[0]"))
264                                 name[len-3] = 0;
265
266                         rd.uniforms.push_back(ReflectData::UniformInfo());
267                         ReflectData::UniformInfo &info = rd.uniforms.back();
268                         info.name = name;
269                         info.tag = name;
270                         info.array_size = size;
271                         info.type = from_gl_type(type);
272                         uniform_names[i] = name;
273                 }
274         }
275
276         sort_member(rd.uniforms, &ReflectData::UniformInfo::tag);
277
278         if(ARB_uniform_buffer_object)
279         {
280                 vector<ReflectData::UniformInfo *> uniforms_by_index(count);
281                 for(unsigned i=0; i<count; ++i)
282                         if(!uniform_names[i].empty())
283                                 // The element is already known to be present
284                                 uniforms_by_index[i] = &*lower_bound_member(rd.uniforms, Tag(uniform_names[i]), &ReflectData::UniformInfo::tag);
285                 query_uniform_blocks(uniforms_by_index);
286         }
287
288         rd.uniform_blocks.push_back(ReflectData::UniformBlockInfo());
289         ReflectData::UniformBlockInfo &default_block = rd.uniform_blocks.back();
290
291         for(ReflectData::UniformInfo &u: rd.uniforms)
292                 if(!u.block)
293                 {
294                         u.location = glGetUniformLocation(id, u.name.c_str());
295                         u.block = &default_block;
296                         u.array_stride = get_type_size(u.type);
297                         if(is_matrix(u.type))
298                                 u.matrix_stride = get_type_size(get_matrix_column_type(u.type));
299                         default_block.uniforms.push_back(&u);
300
301                         if(is_image(u.type) && u.location>=0)
302                                 glGetUniformiv(id, u.location, &u.binding);
303                 }
304
305         default_block.sort_uniforms();
306         default_block.update_layout_hash();
307         rd.update_layout_hash();
308 }
309
310 void OpenGLProgram::query_uniform_blocks(const vector<ReflectData::UniformInfo *> &uniforms_by_index)
311 {
312         ReflectData &rd = static_cast<Program *>(this)->reflect_data;
313
314         unsigned count = 0;
315         glGetProgramiv(id, GL_ACTIVE_UNIFORM_BLOCKS, reinterpret_cast<int *>(&count));
316         // Reserve an extra index for the default block
317         rd.uniform_blocks.reserve(count+1);
318         for(unsigned i=0; i<count; ++i)
319         {
320                 char name[128];
321                 int len;
322                 glGetActiveUniformBlockName(id, i, sizeof(name), &len, name);
323                 rd.uniform_blocks.push_back(ReflectData::UniformBlockInfo());
324                 ReflectData::UniformBlockInfo &info = rd.uniform_blocks.back();
325                 info.name = name;
326
327                 int value;
328                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_DATA_SIZE, &value);
329                 info.data_size = value;
330
331                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_BINDING, &value);
332                 info.bind_point = value;
333
334                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &value);
335                 vector<int> indices(value);
336                 glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &indices[0]);
337                 for(int j: indices)
338                 {
339                         if(!uniforms_by_index[j])
340                                 throw logic_error("OpenGLProgram::query_uniform_blocks");
341                         info.uniforms.push_back(uniforms_by_index[j]);
342                         uniforms_by_index[j]->block = &info;
343                 }
344
345                 vector<unsigned> query_indices(indices.begin(), indices.end());
346                 vector<int> values(indices.size());
347                 glGetActiveUniformsiv(id, query_indices.size(), &query_indices[0], GL_UNIFORM_OFFSET, &values[0]);
348                 for(unsigned j=0; j<indices.size(); ++j)
349                         uniforms_by_index[indices[j]]->offset = values[j];
350
351                 query_indices.clear();
352                 for(int j: indices)
353                         if(uniforms_by_index[j]->array_size>1)
354                                 query_indices.push_back(j);
355                 if(!query_indices.empty())
356                 {
357                         glGetActiveUniformsiv(id, query_indices.size(), &query_indices[0], GL_UNIFORM_ARRAY_STRIDE, &values[0]);
358                         for(unsigned j=0; j<query_indices.size(); ++j)
359                                 uniforms_by_index[query_indices[j]]->array_stride = values[j];
360                 }
361
362                 query_indices.clear();
363                 for(int j: indices)
364                 {
365                         DataType t = uniforms_by_index[j]->type;
366                         if(is_matrix(t))
367                                 query_indices.push_back(j);
368                 }
369                 if(!query_indices.empty())
370                 {
371                         glGetActiveUniformsiv(id, query_indices.size(), &query_indices[0], GL_UNIFORM_MATRIX_STRIDE, &values[0]);
372                         for(unsigned j=0; j<query_indices.size(); ++j)
373                                 uniforms_by_index[query_indices[j]]->matrix_stride = values[j];
374                 }
375
376                 info.sort_uniforms();
377                 info.update_layout_hash();
378         }
379 }
380
381 void OpenGLProgram::query_attributes()
382 {
383         ReflectData &rd = static_cast<Program *>(this)->reflect_data;
384
385         unsigned count = 0;
386         glGetProgramiv(id, GL_ACTIVE_ATTRIBUTES, reinterpret_cast<int *>(&count));
387         rd.attributes.reserve(count);
388         for(unsigned i=0; i<count; ++i)
389         {
390                 char name[128];
391                 int len = 0;
392                 int size;
393                 GLenum type;
394                 glGetActiveAttrib(id, i, sizeof(name), &len, &size, &type, name);
395                 if(len && strncmp(name, "gl_", 3))
396                 {
397                         if(len>3 && !strcmp(name+len-3, "[0]"))
398                                 name[len-3] = 0;
399
400                         rd.attributes.push_back(ReflectData::AttributeInfo());
401                         ReflectData::AttributeInfo &info = rd.attributes.back();
402                         info.name = name;
403                         info.location = glGetAttribLocation(id, name);
404                         info.array_size = size;
405                         info.type = from_gl_type(type);
406                 }
407         }
408 }
409
410 void OpenGLProgram::apply_bindings(const TransientData &transient)
411 {
412         ReflectData &rd = static_cast<Program *>(this)->reflect_data;
413
414         for(unsigned i=0; i<rd.uniform_blocks.size(); ++i)
415         {
416                 auto j = transient.blocks.find(rd.uniform_blocks[i].name);
417                 if(j!=transient.blocks.end())
418                 {
419                         glUniformBlockBinding(id, i, j->second);
420                         rd.uniform_blocks[i].bind_point = j->second;
421                 }
422         }
423
424         if(!ARB_separate_shader_objects)
425                 glUseProgram(id);
426         for(const auto &kvp: transient.textures)
427         {
428                 int location = static_cast<const Program *>(this)->get_uniform_location(kvp.first);
429                 if(location>=0)
430                 {
431                         if(ARB_separate_shader_objects)
432                                 glProgramUniform1i(id, location, kvp.second);
433                         else
434                                 glUniform1i(location, kvp.second);
435                 }
436         }
437 }
438
439 void OpenGLProgram::finalize_uniforms()
440 {
441         ReflectData &rd = static_cast<Program *>(this)->reflect_data;
442
443         auto i = find_if(rd.uniform_blocks, [](const ReflectData::UniformBlockInfo &b){ return b.bind_point<0; });
444         if(i!=rd.uniform_blocks.end() && !i->uniforms.empty())
445         {
446                 for(const ReflectData::UniformInfo *u: i->uniforms)
447                         if(u->location>=0)
448                         {
449                                 UniformCall::FuncPtr func = 0;
450                                 if(u->type==FLOAT)
451                                         func = &uniform_wrapper<float, glUniform1fv>;
452                                 else if(u->type==FLOAT_VEC2)
453                                         func = &uniform_wrapper<float, glUniform2fv>;
454                                 else if(u->type==FLOAT_VEC3)
455                                         func = &uniform_wrapper<float, glUniform3fv>;
456                                 else if(u->type==FLOAT_VEC4)
457                                         func = &uniform_wrapper<float, glUniform4fv>;
458                                 else if(u->type==INT)
459                                         func = &uniform_wrapper<int, glUniform1iv>;
460                                 else if(u->type==INT_VEC2)
461                                         func = &uniform_wrapper<int, glUniform2iv>;
462                                 else if(u->type==INT_VEC3)
463                                         func = &uniform_wrapper<int, glUniform3iv>;
464                                 else if(u->type==INT_VEC4)
465                                         func = &uniform_wrapper<int, glUniform4iv>;
466                                 else if(u->type==UNSIGNED_INT)
467                                         func = &uniform_wrapper<unsigned, glUniform1uiv>;
468                                 else if(u->type==UINT_VEC2)
469                                         func = &uniform_wrapper<unsigned, glUniform2uiv>;
470                                 else if(u->type==UINT_VEC3)
471                                         func = &uniform_wrapper<unsigned, glUniform3uiv>;
472                                 else if(u->type==UINT_VEC4)
473                                         func = &uniform_wrapper<unsigned, glUniform4uiv>;
474                                 else if(u->type==FLOAT_MAT2)
475                                         func = &uniform_matrix_wrapper<float, glUniformMatrix2fv>;
476                                 else if(u->type==FLOAT_MAT3)
477                                         func = &uniform_matrix_wrapper<float, glUniformMatrix3fv>;
478                                 else if(u->type==FLOAT_MAT4)
479                                         func = &uniform_matrix_wrapper<float, glUniformMatrix4fv>;
480                                 else if(u->type==FLOAT_MAT2x3)
481                                         func = &uniform_matrix_wrapper<float, glUniformMatrix2x3fv>;
482                                 else if(u->type==FLOAT_MAT3x2)
483                                         func = &uniform_matrix_wrapper<float, glUniformMatrix3x2fv>;
484                                 else if(u->type==FLOAT_MAT2x4)
485                                         func = &uniform_matrix_wrapper<float, glUniformMatrix2x4fv>;
486                                 else if(u->type==FLOAT_MAT4x2)
487                                         func = &uniform_matrix_wrapper<float, glUniformMatrix4x2fv>;
488                                 else if(u->type==FLOAT_MAT3x4)
489                                         func = &uniform_matrix_wrapper<float, glUniformMatrix3x4fv>;
490                                 else if(u->type==FLOAT_MAT4x3)
491                                         func = &uniform_matrix_wrapper<float, glUniformMatrix4x3fv>;
492
493                                 if(func)
494                                         uniform_calls.push_back(UniformCall(u->location, u->array_size, func));
495                         }
496
497                 if(i->data_size<=0)
498                 {
499                         const ReflectData::UniformInfo &last = *i->uniforms.back();
500                         i->data_size = last.location*16+last.array_size*get_type_size(last.type);
501                 }
502         }
503 }
504
505 void OpenGLProgram::set_debug_name(const string &name)
506 {
507 #ifdef DEBUG
508         debug_name = name;
509         if(KHR_debug)
510         {
511                 glObjectLabel(GL_PROGRAM, id, name.size(), name.c_str());
512                 for(unsigned i=0; i<MAX_STAGES; ++i)
513                         if(stage_ids[i])
514                                 set_stage_debug_name(stage_ids[i], static_cast<Stage>(i));
515         }
516 #else
517         (void)name;
518 #endif
519 }
520
521 void OpenGLProgram::set_stage_debug_name(unsigned stage_id, Stage type)
522 {
523 #ifdef DEBUG
524         static const char *const suffixes[] = { " [VS]", " [GS]", " [FS]" };
525         string name = debug_name+suffixes[type];
526         glObjectLabel(GL_SHADER, stage_id, name.size(), name.c_str());
527 #else
528         (void)stage_id; (void)type;
529 #endif
530 }
531
532 } // namespace GL
533 } // namespace Msp