]> git.tdb.fi Git - libs/gl.git/blob - source/programbuilder.cpp
Shader optimization
[libs/gl.git] / source / programbuilder.cpp
1 #include <algorithm>
2 #include <msp/strings/format.h>
3 #include "program.h"
4 #include "programbuilder.h"
5 #include "shader.h"
6
7 using namespace std;
8
9 namespace Msp {
10 namespace GL {
11
12 /*
13 Naming conventions:
14   n_*        Normalized vector
15   l_*        Lighting component
16
17   obj_*      Object space
18   eye_*      Eye space
19   tbn_*      Tangent-Binormal-Normal space
20   shd_*      Shadow space
21   *_dir      Direction vector
22
23   zzz_*      Wildcard space, resolved by the builder
24              All wildcard spaces within an expression must match
25
26   xxx_yyy_*  Matrix that transforms between yyy to xxx
27              The vector is on the side of its designated space, result will be
28              in the other space
29   *_matrix   A matrix (duh)
30   *_rmatrix  A mat4 that works with a row vector
31
32   rgb_*      Color with rgb components only
33   color_*    Color with rgba components
34 */
35
36 /* The array are stored in reverse order, so that variables always come after
37 anything that might need them. */
38 const ProgramBuilder::StandardVariable ProgramBuilder::standard_variables[] =
39 {
40         { FRAGMENT, "gl_FragColor", 0, "color_base", "!t" },
41         { FRAGMENT, "gl_FragColor", 0, "tex_sample", "!l!s!mt" },
42         { FRAGMENT, "gl_FragColor", 0, "tex_sample*color_base", "l|s|mt" },
43         { FRAGMENT, "color_base", "vec4", "vec4(1.0)", "!l!s!m" },
44         { FRAGMENT, "color_base", "vec4", "color", "!l!sm" },
45         { FRAGMENT, "color_base", "vec4", "vec4(vec3(l_shadow), 1.0)", "!ls!m" },
46         { FRAGMENT, "color_base", "vec4", "color*vec4(vec3(l_shadow), 1.0)", "!lsm" },
47         { FRAGMENT, "color_base", "vec4", "vec4(rgb_light_full, 1.0)", "l!m" },
48         { FRAGMENT, "color_base", "vec4", "vec4(rgb_light_full, gl_FrontMaterial.diffuse.a)", "lm" },
49         { FRAGMENT, "rgb_light_full", "vec3", "rgb_light_shadow+gl_FrontLightModelProduct.sceneColor.rgb", "m" },
50         { FRAGMENT, "rgb_light_full", "vec3", "rgb_light_shadow", "!m" },
51         { FRAGMENT, "rgb_light_shadow", "vec3", "rgb_light*l_shadow", "s" },
52         { FRAGMENT, "rgb_light_shadow", "vec3", "rgb_light", "!s" },
53         { FRAGMENT, "rgb_light", "vec3", "vec3(l_diffuse)", "!m!p" },
54         { FRAGMENT, "rgb_light", "vec3", "vec3(l_diffuse+l_specular)", "!mp" },
55         { FRAGMENT, "rgb_light", "vec3", "l_diffuse*gl_FrontLightProduct[0].diffuse.rgb", "m!p" },
56         { FRAGMENT, "rgb_light", "vec3", "l_diffuse*gl_FrontLightProduct[0].diffuse.rgb+l_specular*gl_FrontLightProduct[0].specular.rgb", "mp" },
57         { FRAGMENT, "l_shadow", "float", "mix(1.0, shadow_sample, shadow_darkness)", 0 },
58         { FRAGMENT, "shadow_sample", "float", "shadow2D(shadow, shd_vertex).r", 0 },
59         { FRAGMENT, "l_diffuse", "float", "max(dot(n_zzz_normal, n_zzz_light_dir), 0.0)", 0 },
60         { FRAGMENT, "l_specular", "float", "pow(max(dot(n_zzz_half_vec, n_zzz_normal), 0.0), gl_FrontMaterial.shininess)", 0 },
61         { FRAGMENT, "n_zzz_half_vec", "vec3", "normalize(zzz_light_dir-zzz_incident_dir)", 0 },
62         { FRAGMENT, "n_zzz_light_dir", "vec3", "normalize(zzz_light_dir)", 0 },
63         { FRAGMENT, "n_tbn_normal", "vec3", "texture2D(normalmap, texture_coord).xyz*2.0-1.0", "n" },
64         { FRAGMENT, "n_eye_normal", "vec3", "normalize(eye_normal)", "!n" },
65         { FRAGMENT, "tex_sample", "vec4", "texture2D(texture, texture_coord)", 0 },
66
67         { VERTEX, "gl_Position", 0, "gl_ProjectionMatrix*eye_vertex", 0 },
68         { VERTEX, "shd_vertex", "vec3", "eye_vertex*eye_shd_rmatrix", 0 },
69         { VERTEX, "eye_shd_rmatrix", "mat4", "mat4(gl_EyePlaneS[shadow_unit], gl_EyePlaneT[shadow_unit], gl_EyePlaneR[shadow_unit], vec4(0.0, 0.0, 0.0, 1.0))", 0 },
70         { VERTEX, "tbn_light_dir", "vec3", "eye_light_dir*eye_tbn_matrix", 0 },
71         { VERTEX, "eye_light_dir", "vec3", "normalize(gl_LightSource[0].position.xyz-eye_vertex.xyz*gl_LightSource[0].position.w)", 0 },
72         { VERTEX, "tbn_incident_dir", "vec3", "eye_incident_dir*eye_tbn_matrix", 0 },
73         { VERTEX, "eye_incident_dir", "vec3", "normalize(eye_vertex.xyz)", 0 },
74         { VERTEX, "eye_tbn_matrix", "mat3", "mat3(eye_tangent, eye_binormal, eye_normal)", 0 },
75         { VERTEX, "eye_vertex", "vec4", "gl_ModelViewMatrix*gl_Vertex", "!r" },
76         { VERTEX, "eye_vertex", "vec4", "transform_vertex(gl_Vertex)", "r" },
77         { VERTEX, "eye_normal", "vec3", "gl_NormalMatrix*gl_Normal", "!r" },
78         { VERTEX, "eye_normal", "vec3", "transform_normal(gl_Normal)", "r" },
79         { VERTEX, "eye_tangent", "vec3", "gl_NormalMatrix*tangent", "!r" },
80         { VERTEX, "eye_tangent", "vec3", "transform_normal(tangent)", "r" },
81         { VERTEX, "eye_binormal", "vec3", "gl_NormalMatrix*binormal", "!r" },
82         { VERTEX, "eye_binormal", "vec3", "transform_normal(binormal)", "r" },
83         { VERTEX, "color", "vec4", "gl_Color", 0 },
84         { VERTEX, "texture_coord", "vec2", "gl_MultiTexCoord0", 0 },
85
86         { ATTRIBUTE, "tangent", "vec3", 0, 0 },
87         { ATTRIBUTE, "binormal", "vec3", 0, 0 },
88
89         { UNIFORM, "shadow_unit", "int", 0, 0 },
90         { UNIFORM, "texture", "sampler2D", 0, 0 },
91         { UNIFORM, "shadow", "sampler2DShadow", 0, 0 },
92         { UNIFORM, "shadow_darkness", "float", 0, 0 },
93         { UNIFORM, "normalmap", "sampler2D", 0, 0 },
94
95         // Terminator entry
96         { NO_SCOPE,  0, 0, 0, 0 }
97 };
98
99 ProgramBuilder::ProgramBuilder(const StandardFeatures &f):
100         features(f),
101         feature_flags(features.create_flags()),
102         optimize(true)
103 { }
104
105 void ProgramBuilder::set_optimize(bool o)
106 {
107         optimize = o;
108 }
109
110 Program *ProgramBuilder::create_program() const
111 {
112         Program *prog = new Program;
113         add_shaders(*prog);
114         return prog;
115 }
116
117 void ProgramBuilder::add_shaders(Program &prog) const
118 {
119         list<ShaderVariable> variables;
120         list<ShaderVariable *> resolved_vars;
121
122         variables.push_front(ShaderVariable("gl_Position"));
123         variables.push_front(ShaderVariable("gl_FragColor"));
124
125         for(const StandardVariable *i=standard_variables; i->name; ++i)
126         {
127                 // Skip over anything that isn't used with the supplied flags
128                 if(i->flags && !evaluate_flags(i->flags))
129                         continue;
130
131                 // See if this variable can satisfy any unresolved variables
132                 ShaderVariable *last_resolved = 0;
133                 for(list<ShaderVariable>::iterator j=variables.begin(); j!=variables.end(); ++j)
134                 {
135                         if(j->variable)
136                                 continue;
137
138                         if(!name_match(i->name, j->resolved_name.c_str()))
139                                 continue;
140
141                         if(last_resolved)
142                         {
143                                 /* We've already resolved a non-fuzzy variable in this iteration.
144                                 If there are multiple variables that can be resolved, they refer
145                                 to the same variable. */
146                                 j->resolve(*last_resolved);
147                                 continue;
148                         }
149
150                         j->resolve(*i);
151                         resolved_vars.push_front(&*j);
152                         if(!j->fuzzy_space)
153                                 last_resolved = &*j;
154
155                         if(!i->expression)
156                                 continue;
157
158                         vector<string> identifiers = extract_identifiers(i->expression);
159                         for(vector<string>::const_iterator k=identifiers.begin(); k!=identifiers.end(); ++k)
160                         {
161                                 // Use an existing variable if possible, but only if it's not fuzzy
162                                 ShaderVariable *var = 0;
163                                 for(list<ShaderVariable>::iterator l=variables.begin(); (!var && l!=variables.end()); ++l)
164                                         if(!l->fuzzy_space && l->resolved_name==*k)
165                                                 var = &*l;
166
167                                 if(!var)
168                                 {
169                                         variables.push_back(ShaderVariable(*k));
170                                         var = &variables.back();
171                                 }
172                                 j->add_reference(*var);
173                         }
174                 }
175         }
176
177         if(optimize)
178         {
179                 for(list<ShaderVariable *>::const_iterator i=resolved_vars.begin(); i!=resolved_vars.end(); ++i)
180                         (*i)->check_inline();
181         }
182
183         prog.attach_shader_owned(new VertexShader(create_source(resolved_vars, VERTEX)));
184         prog.attach_shader_owned(new FragmentShader(create_source(resolved_vars, FRAGMENT)));
185 }
186
187 string ProgramBuilder::create_source(const list<ShaderVariable *> &variables, VariableScope scope) const
188 {
189         string source;
190
191         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
192                 if((*i)->variable->scope==UNIFORM && (*i)->is_referenced_from(scope))
193                         source += format("uniform %s %s;\n", (*i)->variable->type, (*i)->resolved_name);
194
195         if(scope==VERTEX)
196         {
197                 for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
198                         if((*i)->variable->scope==ATTRIBUTE)
199                                 source += format("attribute %s %s;\n", (*i)->variable->type, (*i)->resolved_name);
200         }
201
202         /* Any variables defined in vertex scope but referenced from fragment scope
203         should be exported as varyings over the interface. */
204         list<ShaderVariable *> varyings;
205         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
206                 if((*i)->variable->scope==VERTEX && (*i)->is_referenced_from(FRAGMENT))
207                 {
208                         varyings.push_back(*i);
209                         source += format("varying %s v_%s;\n", (*i)->variable->type, (*i)->resolved_name);
210                 }
211
212         if(scope==VERTEX && features.transform)
213         {
214                 // Add the prototypes here, until I come up with something better
215                 source += "vec4 transform_vertex(vec4);\n";
216                 source += "vec3 transform_normal(vec3);\n";
217         }
218
219         source += "void main()\n{\n";
220
221         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
222                 if((*i)->variable->scope==scope && !(*i)->inlined)
223                 {
224                         source += '\t';
225                         if((*i)->variable->type)
226                         {
227                                 source += (*i)->variable->type;
228                                 source += ' ';
229                         }
230                         source += format("%s = %s;\n", (*i)->resolved_name, (*i)->get_expression());
231                 }
232
233         if(scope==VERTEX)
234         {
235                 for(list<ShaderVariable *>::const_iterator i=varyings.begin(); i!=varyings.end(); ++i)
236                 {
237                         if((*i)->inlined)
238                                 source += format("\tv_%s = %s;\n", (*i)->resolved_name, (*i)->get_expression());
239                         else
240                                 source += format("\tv_%s = %s;\n", (*i)->resolved_name, (*i)->resolved_name);
241                 }
242         }
243
244         source += '}';
245
246         return source;
247 }
248
249 bool ProgramBuilder::evaluate_flags(const char *flags) const
250 {
251         if(!flags)
252                 return true;
253
254         bool cond = true;
255         char oper = '&';
256         for(const char *i=flags; *i; ++i)
257         {
258                 if(*i>='a' && *i<='z')
259                 {
260                         bool found = (feature_flags.find(*i)!=string::npos);
261                         if(oper=='|')
262                                 cond = (cond || found);
263                         else if(oper=='!')
264                                 cond = (cond && !found);
265                         else if(oper=='&')
266                                 cond = (cond && found);
267                         oper = '&';
268                 }
269                 else
270                         oper = *i;
271         }
272
273         return cond;
274 }
275
276 ProgramBuilder::MatchLevel ProgramBuilder::name_match(const char *n1, const char *n2, const char **space)
277 {
278         int i = 0;
279         int zzz = -1;
280         int zside = 0;
281         while(*n1 && *n2)
282         {
283                 if(*n1==*n2 || *n1=='z' || *n2=='z')
284                 {
285                         if(*n1!=*n2)
286                         {
287                                 int side = (*n1=='z' ? 1 : 2);
288                                 if(zzz<0)
289                                 {
290                                         zzz = i;
291                                         zside = side;
292                                         if(space)
293                                         {
294                                                 if(*n1=='z')
295                                                         *space = n2;
296                                                 else
297                                                         *space = n1;
298                                         }
299                                 }
300                                 else if(i>=zzz+3 || side!=zside)
301                                         return NO_MATCH;
302                         }
303                 }
304                 else
305                         return NO_MATCH;
306                 ++n1;
307                 ++n2;
308                 ++i;
309         }
310         return (!*n1 && !*n2) ? zzz>=0 ? FUZZY : EXACT : NO_MATCH;
311 }
312
313 bool ProgramBuilder::parse_identifier(const char *ptr, unsigned &start, unsigned &length)
314 {
315         bool found = false;
316         bool member = false;
317         for(const char *i=ptr;; ++i)
318         {
319                 if(!found)
320                 {
321                         if(!*i)
322                                 return false;
323                         if(isalpha(*i) || *i=='_')
324                         {
325                                 if(!member)
326                                 {
327                                         start = i-ptr;
328                                         found = true;
329                                 }
330                         }
331                         else if(*i=='.')
332                                 member = true;
333                         else
334                                 member = false;
335                 }
336                 else
337                 {
338                         if(!isalnum(*i) && *i!='_')
339                         {
340                                 length = i-(ptr+start);
341                                 return true;
342                         }
343                 }
344         }
345 }
346
347 vector<string> ProgramBuilder::extract_identifiers(const char *expression)
348 {
349         vector<string> result;
350         const char *ptr = expression;
351         unsigned start, length;
352         while(parse_identifier(ptr, start, length))
353         {
354                 result.push_back(string(ptr+start, length));
355                 ptr += start+length;
356         }
357         return result;
358 }
359
360 string ProgramBuilder::replace_identifiers(const char *expression, const map<string, string> &replace_map)
361 {
362         string result;
363         const char *ptr = expression;
364         unsigned start, length;
365         while(parse_identifier(ptr, start, length))
366         {
367                 result.append(ptr, start);
368                 string identifier(ptr+start, length);
369                 map<string, string>::const_iterator i = replace_map.find(identifier);
370                 if(i!=replace_map.end())
371                         result += i->second;
372                 else
373                         result += identifier;
374                 ptr += start+length;
375         }
376         result += ptr;
377         return result;
378 }
379
380
381 ProgramBuilder::StandardFeatures::StandardFeatures():
382         texture(false),
383         material(false),
384         lighting(false),
385         specular(false),
386         normalmap(false),
387         shadow(false),
388         reflection(false),
389         transform(false)
390 { }
391
392 string ProgramBuilder::StandardFeatures::create_flags() const
393 {
394         string flags;
395         if(texture)
396                 flags += 't';
397         if(material)
398                 flags += 'm';
399         if(lighting)
400         {
401                 flags += 'l';
402                 if(specular)
403                         flags += 'p';
404                 if(normalmap)
405                         flags += 'n';
406         }
407         if(shadow)
408                 flags += 's';
409         if(reflection)
410                 flags += 'e';
411         if(transform)
412                 flags += 'r';
413
414         return flags;
415 }
416
417
418 ProgramBuilder::ShaderVariable::ShaderVariable(const std::string &n):
419         name(n),
420         variable(0),
421         resolved_name(n),
422         fuzzy_space(name.find("zzz")!=string::npos),
423         inlined(false),
424         inline_parens(false)
425 { }
426
427 void ProgramBuilder::ShaderVariable::resolve(const StandardVariable &var)
428 {
429         variable = &var;
430         const char *space = 0;
431         if(name_match(var.name, resolved_name.c_str(), &space)==FUZZY)
432                 resolve_space(string(space, 3));
433 }
434
435 void ProgramBuilder::ShaderVariable::resolve(ShaderVariable &var)
436 {
437         for(list<ShaderVariable *>::iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
438                 (*i)->update_reference(*this, var);
439         var.referenced_by.insert(var.referenced_by.end(), referenced_by.begin(), referenced_by.end());
440 }
441
442 void ProgramBuilder::ShaderVariable::resolve_space(const string &space)
443 {
444         if(fuzzy_space)
445         {
446                 resolved_space = space;
447
448                 string::size_type zzz = resolved_name.find("zzz");
449                 resolved_name.replace(zzz, 3, resolved_space);
450                 fuzzy_space = false;
451
452                 // Resolving the space could have affected other variables that use this one
453                 for(list<ShaderVariable *>::iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
454                         (*i)->resolve_space(space);
455         }
456
457         for(list<ShaderVariable *>::iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
458                 if((*i)->fuzzy_space)
459                         (*i)->resolve_space(space);
460 }
461
462 void ProgramBuilder::ShaderVariable::add_reference(ShaderVariable &var)
463 {
464         referenced_vars.push_back(&var);
465         var.referenced_by.push_back(this);
466         if(var.fuzzy_space && !resolved_space.empty())
467                 var.resolve_space(resolved_space);
468 }
469
470 void ProgramBuilder::ShaderVariable::update_reference(ShaderVariable &from, ShaderVariable &to)
471 {
472         replace(referenced_vars.begin(), referenced_vars.end(), &from, &to);
473         replace(referenced_by.begin(), referenced_by.end(), &from, &to);
474         if(from.fuzzy_space && !to.fuzzy_space && !to.resolved_space.empty())
475                 resolve_space(to.resolved_space);
476 }
477
478 void ProgramBuilder::ShaderVariable::check_inline()
479 {
480         if(variable->expression)
481         {
482                 unsigned total_refs = referenced_by.size();
483                 unsigned in_scope_refs = 0;
484                 for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
485                         if((*i)->variable->scope==variable->scope)
486                                 ++in_scope_refs;
487                 if(total_refs==1 || (total_refs>0 && in_scope_refs==0))
488                 {
489                         inlined = true;
490                         unsigned level = 0;
491                         for(const char *c=variable->expression; (!inline_parens && *c); ++c)
492                         {
493                                 if(*c=='(')
494                                         ++level;
495                                 else if(*c==')')
496                                         --level;
497                                 else if(level==0 && !isalnum(*c) && *c!='_' && *c!='.')
498                                         inline_parens = true;
499                         }
500                 }
501         }
502 }
503
504 bool ProgramBuilder::ShaderVariable::is_referenced_from(VariableScope scope) const
505 {
506         for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
507                 if((*i)->variable->scope==scope)
508                         return true;
509         return false;
510 }
511
512 string ProgramBuilder::ShaderVariable::get_expression() const
513 {
514         map<string, string> replace_map;
515         for(list<ShaderVariable *>::const_iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
516                 if((*i)->variable)
517                 {
518                         string replacement = (*i)->resolved_name;
519                         if(variable->scope==FRAGMENT && (*i)->variable->scope==VERTEX)
520                                 replacement = "v_"+replacement;
521                         else if((*i)->inlined)
522                         {
523                                 replacement = (*i)->get_expression();
524                                 if((*i)->inline_parens)
525                                         replacement = "("+replacement+")";
526                         }
527                         if(replacement!=(*i)->name)
528                                 replace_map[(*i)->name] = replacement;
529                 }
530
531         if(replace_map.empty())
532                 return variable->expression;
533         else
534                 return replace_identifiers(variable->expression, replace_map);
535 }
536
537
538 ProgramBuilder::StandardFeatures::Loader::Loader(StandardFeatures &f):
539         DataFile::ObjectLoader<StandardFeatures>(f)
540 {
541         add("lighting",  &StandardFeatures::lighting);
542         add("material",  &StandardFeatures::material);
543         add("normalmap", &StandardFeatures::normalmap);
544         add("reflection", &StandardFeatures::reflection);
545         add("shadow",    &StandardFeatures::shadow);
546         add("specular",  &StandardFeatures::specular);
547         add("texture",   &StandardFeatures::texture);
548         add("transform", &StandardFeatures::transform);
549 }
550
551 } // namespace GL
552 } // namespace Msp