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