]> git.tdb.fi Git - libs/gl.git/blob - source/programbuilder.cpp
Alias texture lookup functions of all dimensionalities
[libs/gl.git] / source / programbuilder.cpp
1 #include <algorithm>
2 #include <cstring>
3 #include <set>
4 #include <msp/gl/extensions/arb_uniform_buffer_object.h>
5 #include <msp/strings/format.h>
6 #include <msp/strings/utils.h>
7 #include "extension.h"
8 #include "program.h"
9 #include "programbuilder.h"
10 #include "shader.h"
11 #include "vertexformat.h"
12
13 using namespace std;
14
15 namespace Msp {
16 namespace GL {
17
18 /*
19 Naming conventions:
20   n_*        Normalized vector
21   l_*        Lighting component
22
23   obj_*      Object space
24   eye_*      Eye space
25   tbn_*      Tangent-Binormal-Normal space
26   shd_*      Shadow space
27   env_*      Environment space
28   *_dir      Direction vector
29
30   zzz_*      Wildcard space, resolved by the builder
31              All wildcard spaces within an expression must match
32
33   xxx_yyy_*  Matrix that transforms between yyy to xxx
34              The vector is on the side of its designated space, result will be
35              in the other space
36   *_matrix   A matrix (duh)
37   *_rmatrix  A mat4 that works with a row vector
38
39   rgb_*      Color with rgb components only
40   color_*    Color with rgba components
41 */
42
43 /* The array is stored in reverse order, so that variables always come after
44 anything that might need them. */
45 const ProgramBuilder::VariableDefinition ProgramBuilder::standard_variables[] =
46 {
47         { FRAGMENT, "gl_FragColor", "vec4", "frag_color", 0 },
48         { FRAGMENT, "frag_color", "vec4", "basic_color", "!e!l" },
49         { FRAGMENT, "frag_color", "vec4", "vec4(rgb_surface, surface_alpha)", "!el" },
50         { FRAGMENT, "frag_color", "vec4", "vec4(rgb_surface+rgb_reflection, surface_alpha)", "e" },
51
52         { FRAGMENT, "rgb_reflection", "vec3", "reflect_sample.rgb*reflectivity", 0 },
53         { FRAGMENT, "reflect_sample", "vec4", "textureCube(environment, env_reflect_dir)", 0 },
54         { FRAGMENT, "env_reflect_dir", "vec3", "env_eye_matrix*eye_reflect_dir", 0 },
55         { FRAGMENT, "eye_reflect_dir", "vec3", "eye_tbn_matrix*tbn_reflect_dir", "n" },
56
57         { FRAGMENT, "rgb_surface", "vec3", "rgb_unlit_surface", "!l" },
58         { FRAGMENT, "rgb_surface", "vec3", "rgb_lit_surface", "l" },
59         { FRAGMENT, "rgb_unlit_surface", "vec3", "basic_color.rgb", "!s" },
60         { FRAGMENT, "rgb_unlit_surface", "vec3", "basic_color.rgb*l_shadow", "s" },
61         { FRAGMENT, "rgb_lit_surface", "vec3", "rgb_illumination_diffuse", "!m!t" },
62         { FRAGMENT, "rgb_lit_surface", "vec3", "rgb_illumination_diffuse*diffuse_sample.rgb", "!mt" },
63         { FRAGMENT, "rgb_lit_surface", "vec3", "rgb_surface_ambient+rgb_surface_diffuse", "m!p" },
64         { FRAGMENT, "rgb_lit_surface", "vec3", "rgb_surface_ambient+rgb_surface_diffuse+rgb_surface_specular", "mp" },
65
66         { FRAGMENT, "surface_alpha", "float", "basic_color.a", "!m" },
67         { FRAGMENT, "surface_alpha", "float", "basic_color.a", "m!l" },
68         { FRAGMENT, "surface_alpha", "float", "material.diffuse.a", "ml!t" },
69         { FRAGMENT, "surface_alpha", "float", "material.diffuse.a*diffuse_sample.a", "mlt" },
70         { FRAGMENT, "basic_color", "vec4", "vec4(1.0)", "!m!t" },
71         { FRAGMENT, "basic_color", "vec4", "diffuse_sample", "!mt" },
72         { FRAGMENT, "basic_color", "vec4", "color", "m!t" },
73         { FRAGMENT, "basic_color", "vec4", "color*diffuse_sample", "mt" },
74
75         { FRAGMENT, "rgb_surface_ambient", "vec3", "rgb_illumination_ambient*material.ambient.rgb", "!t" },
76         { FRAGMENT, "rgb_surface_ambient", "vec3", "rgb_illumination_ambient*material.ambient.rgb*diffuse_sample.rgb", "t" },
77         { FRAGMENT, "rgb_illumination_ambient", "vec3", "ambient_color.rgb", "!y" },
78         { FRAGMENT, "rgb_illumination_ambient", "vec3", "ambient_color.rgb+l_skylight*sky_color.rgb", "y" },
79         { FRAGMENT, "l_skylight", "float", "dot(n_zzz_normal, zzz_sky_dir)*0.5+0.5", 0 },
80
81         { FRAGMENT, "rgb_surface_specular", "vec3", "rgb_illumination_specular*material.specular.rgb", 0 },
82         { FRAGMENT, "rgb_illumination_specular", "vec3", "rgb_illumination_specular_direct", "!y|e" },
83         { FRAGMENT, "rgb_illumination_specular", "vec3", "rgb_illumination_specular_direct+l_sky_specular*sky_color.rgb", "y!e" },
84         { FRAGMENT, "rgb_illumination_specular_direct", "vec3", "rgb_light_specular", "!s" },
85         { FRAGMENT, "rgb_illumination_specular_direct", "vec3", "rgb_light_specular*l_shadow", "s" },
86         { FRAGMENT, "rgb_light_specular[i]", "vec3", "l_specular[i]*light_sources[i].specular.rgb", 0 },
87         { FRAGMENT, "l_sky_specular", "float", "pow((1.0-pow(clamp(dot(zzz_reflect_dir, zzz_sky_dir)-horizon_limit, -1.0, 0.0), 2.0)), material.shininess/2.0)", 0 },
88         { FRAGMENT, "l_specular[i]", "float", "pow(max(dot(n_zzz_half_vec[i], n_zzz_normal), 0.0), material.shininess)", 0 },
89
90         { FRAGMENT, "rgb_surface_diffuse", "vec3", "rgb_illumination_diffuse*material.diffuse.rgb", "!t" },
91         { FRAGMENT, "rgb_surface_diffuse", "vec3", "rgb_illumination_diffuse*material.diffuse.rgb*diffuse_sample.rgb", "t" },
92         { FRAGMENT, "rgb_illumination_diffuse", "vec3", "rgb_light_diffuse", "!s" },
93         { FRAGMENT, "rgb_illumination_diffuse", "vec3", "rgb_light_diffuse*l_shadow", "s" },
94         { FRAGMENT, "rgb_light_diffuse[i]", "vec3", "l_diffuse[i]*light_sources[i].diffuse.rgb", 0 },
95         { FRAGMENT, "l_diffuse[i]", "float", "max(dot(n_zzz_normal, n_zzz_light_dir[i]), 0.0)", 0 },
96
97         { FRAGMENT, "l_shadow", "float", "mix(1.0, shadow_sample, shadow_darkness)", 0 },
98         { FRAGMENT, "shadow_sample", "float", "shadow2D(shadow, shd_vertex)", 0 },
99
100         { FRAGMENT, "zzz_reflect_dir", "vec3", "reflect(zzz_incident_dir, n_zzz_normal)", 0 },
101         { FRAGMENT, "n_zzz_half_vec[i]", "vec3", "normalize(zzz_light_dir[i]-zzz_incident_dir)", 0 },
102         { FRAGMENT, "n_zzz_light_dir[i]", "vec3", "normalize(zzz_light_dir[i])", 0 },
103         { FRAGMENT, "n_tbn_normal", "vec3", "normal_sample*2.0-1.0", "n" },
104         { FRAGMENT, "n_eye_normal", "vec3", "normalize(eye_normal)", "!n" },
105         { FRAGMENT, "normal_sample", "vec3", "texture2D(normalmap, texture_coord).xyz", 0 },
106         { FRAGMENT, "diffuse_sample", "vec4", "texture2D(diffusemap, texture_coord)", 0 },
107
108         { VERTEX, "gl_Position", "vec4", "projection_matrix*eye_vertex", 0 },
109         { VERTEX, "shd_vertex", "vec3", "(shd_eye_matrix*eye_vertex).xyz", 0 },
110         { VERTEX, "tbn_sky_dir", "vec3", "eye_sky_dir*eye_tbn_matrix", "n" },
111         { VERTEX, "tbn_light_dir[i]", "vec3", "eye_light_dir[i]*eye_tbn_matrix", 0 },
112         { VERTEX, "eye_light_dir[i]", "vec3", "normalize(eye_light_position[i].xyz-eye_vertex.xyz*eye_light_position[i].w)", 0 },
113         { VERTEX, "eye_light_position[i]", "vec4", "light_sources[i].position", 0 },
114         { VERTEX, "tbn_incident_dir", "vec3", "eye_incident_dir*eye_tbn_matrix", 0 },
115         { VERTEX, "eye_incident_dir", "vec3", "normalize(eye_vertex.xyz)", 0 },
116         { VERTEX, "eye_tbn_matrix", "mat3", "mat3(eye_tangent, eye_binormal, eye_normal)", 0 },
117         { VERTEX, "eye_vertex", "vec4", "eye_obj_matrix*vertex", 0 },
118         { VERTEX, "eye_normal", "vec3", "eye_obj_normal_matrix*normal", 0 },
119         { VERTEX, "eye_tangent", "vec3", "eye_obj_normal_matrix*tangent", 0 },
120         { VERTEX, "eye_binormal", "vec3", "eye_obj_normal_matrix*binormal", 0 },
121         { VERTEX, "texture_coord", "vec2", "texcoord.xy", 0 },
122
123         { ATTRIBUTE, "vertex", "vec4", "gl_Vertex", 0 },
124         { ATTRIBUTE, "texcoord", "vec4", "gl_MultiTexCoord0", 0 },
125         { ATTRIBUTE, "color", "vec4", "gl_Color", 0 },
126         { ATTRIBUTE, "normal", "vec3", "gl_Normal", 0 },
127         { ATTRIBUTE, "tangent", "vec3", 0, 0 },
128         { ATTRIBUTE, "binormal", "vec3", 0, 0 },
129
130         { UNIFORM, "diffusemap", "sampler2D", 0, 0 },
131         { UNIFORM, "shadow", "sampler2DShadow", 0, 0 },
132         { UNIFORM, "ShadowMap::shadow_darkness", "float", 0, 0 },
133         { UNIFORM, "normalmap", "sampler2D", 0, 0 },
134         { UNIFORM, "environment", "samplerCube", 0, 0 },
135         { UNIFORM, "EnvMap::env_eye_matrix", "mat3", 0, 0 },
136         { UNIFORM, "Material::reflectivity", "float", 0, 0 },
137         { UNIFORM, "eye_obj_matrix", "mat4", "gl_ModelViewMatrix", 0 },
138         { UNIFORM, "eye_obj_normal_matrix", "mat3", "gl_NormalMatrix", 0 },
139         { UNIFORM, "Transform::projection_matrix", "mat4", "gl_ProjectionMatrix", 0 },
140         { UNIFORM, "ShadowMap::shd_eye_matrix", "mat4", 0, 0 },
141         { UNIFORM, "Lighting::light_sources", "LightSourceParameters[MAX_LIGHTS]", "gl_LightSource[i]", 0 },
142         { UNIFORM, "Lighting::ambient_color", "vec4", "gl_LightModel.ambient", 0 },
143         { UNIFORM, "Lighting::sky_color", "vec4", 0, 0 },
144         { UNIFORM, "Lighting::eye_sky_dir", "vec3", 0, 0 },
145         { UNIFORM, "Lighting::horizon_limit", "float", 0, 0 },
146         { UNIFORM, "Material::material", "MaterialParameters", "gl_FrontMaterial", 0 },
147
148         { TYPE, "LightSourceParameters", "struct { vec4 position; vec4 diffuse; vec4 specular; }", "gl_LightSourceParameters", 0 },
149         { TYPE, "MaterialParameters", "struct { vec4 ambient; vec4 diffuse; vec4 specular; float shininess; }", "gl_MaterialParameters", 0 },
150
151         // Terminator entry
152         { NO_SCOPE, 0, 0, 0, 0 }
153 };
154
155 const char ProgramBuilder::interfaces[] = { 0, 0, 0, 0, 'v', 0 };
156
157 ProgramBuilder::ProgramBuilder(const StandardFeatures &f):
158         features(f),
159         feature_flags(features.create_flags()),
160         optimize(true)
161 {
162         if(!features.custom.empty())
163         {
164                 const char *whitespace = " \t\n";
165                 string::size_type start = 0;
166                 while(1)
167                 {
168                         start = features.custom.find_first_not_of(whitespace, start);
169                         if(start==string::npos)
170                                 break;
171
172                         string::size_type semicolon = features.custom.find(';', start);
173                         if(semicolon==start)
174                         {
175                                 ++start;
176                                 continue;
177                         }
178                         else if(semicolon==string::npos)
179                                 throw invalid_variable_definition(features.custom.substr(start));
180
181                         string::size_type equals = features.custom.find('=', start);
182                         if(equals>semicolon)
183                                 equals = string::npos;
184
185                         VariableDefinition var;
186                         string::size_type decl_end = min(equals, semicolon);
187                         for(unsigned i=0;; ++i)
188                         {
189                                 string::size_type word_end = features.custom.find_first_of(whitespace, start);
190                                 word_end = min(word_end, decl_end);
191                                 features.custom[word_end] = 0;
192
193                                 const char *word = &features.custom[start];
194                                 if(i==0)
195                                 {
196                                         if(!strcmp(word, "uniform"))
197                                                 var.scope = UNIFORM;
198                                         else if(!strcmp(word, "attribute"))
199                                                 var.scope = ATTRIBUTE;
200                                         else if(!strcmp(word, "vertex"))
201                                                 var.scope = VERTEX;
202                                         else if(!strcmp(word, "fragment"))
203                                                 var.scope = FRAGMENT;
204                                         else
205                                                 throw invalid_variable_definition(word);
206                                 }
207                                 else if(i==1)
208                                         var.type = word;
209                                 else if(i==2)
210                                         var.name = word;
211
212                                 start = features.custom.find_first_not_of(whitespace, word_end+1);
213                                 if(start>=decl_end)
214                                         break;
215                         }
216
217                         if(equals!=string::npos)
218                         {
219                                 start = features.custom.find_first_not_of(whitespace, equals+1);
220                                 if(start>=semicolon)
221                                         throw invalid_variable_definition("no expression");
222                                 features.custom[semicolon] = 0;
223                                 var.expression = &features.custom[start];
224                         }
225                         else
226                                 var.expression = 0;
227
228                         var.flags = 0;
229                         for(const VariableDefinition *j=standard_variables; j->name; ++j)
230                                 if(!strcmp(var.name, j->name))
231                                         var.flags = "o";
232
233                         custom_variables.push_front(var);
234
235                         start = semicolon+1;
236                 }
237         }
238
239         if(!features.legacy)
240         {
241                 aliases["texture1D"] = "texture";
242                 aliases["texture2D"] = "texture";
243                 aliases["texture3D"] = "texture";
244                 aliases["textureCube"] = "texture";
245                 aliases["shadow2D"] = "texture";
246         }
247         else
248                 aliases["shadow2D"] = "shadow2D(...).r";
249 }
250
251 void ProgramBuilder::set_optimize(bool o)
252 {
253         optimize = o;
254 }
255
256 Program *ProgramBuilder::create_program() const
257 {
258         Program *prog = new Program;
259         add_shaders(*prog);
260         return prog;
261 }
262
263 void ProgramBuilder::add_shaders(Program &prog) const
264 {
265         list<ShaderVariable> variables;
266         list<ShaderVariable *> resolved_vars;
267
268         variables.push_front(ShaderVariable("gl_Position"));
269         variables.push_front(ShaderVariable(features.legacy ? "gl_FragColor" : "frag_color"));
270
271         list<VariableDefinition>::const_iterator next_custom = custom_variables.begin();
272         for(const VariableDefinition *i=standard_variables; i->name; )
273         {
274                 const VariableDefinition *def = 0;
275                 if(next_custom!=custom_variables.end() && (!strcmp(next_custom->name, i->name) || !next_custom->flags))
276                 {
277                         def = &*next_custom;
278                         ++next_custom;
279                 }
280                 else
281                 {
282                         def = i;
283                         ++i;
284
285                         // Skip over anything that isn't used with the supplied flags
286                         if(def->flags && !evaluate_flags(def->flags))
287                                 continue;
288                 }
289
290                 if(def->scope==TYPE)
291                 {
292                         for(list<ShaderVariable *>::iterator j=resolved_vars.begin(); j!=resolved_vars.end(); ++j)
293                                 if(!(*j)->type && name_match(def->name, (*j)->variable->type))
294                                         (*j)->resolve_type(*def);
295
296                         continue;
297                 }
298
299                 const char *def_uq_name = unqualified_name(def->name);
300
301                 // See if this variable can satisfy any unresolved variables
302                 ShaderVariable *last_resolved = 0;
303                 for(list<ShaderVariable>::iterator j=variables.begin(); j!=variables.end(); ++j)
304                 {
305                         if(j->variable)
306                                 continue;
307
308                         if(!name_match(def_uq_name, j->resolved_name.c_str()))
309                                 continue;
310
311                         if(last_resolved)
312                         {
313                                 /* We've already resolved a non-fuzzy variable in this iteration.
314                                 If there are multiple variables that can be resolved, they refer
315                                 to the same variable. */
316                                 j->resolve(*last_resolved);
317                                 continue;
318                         }
319
320                         j->resolve(*def);
321                         resolved_vars.push_front(&*j);
322                         if(!j->fuzzy_space)
323                                 last_resolved = &*j;
324
325                         if(!def->expression)
326                                 continue;
327
328                         vector<string> identifiers = extract_identifiers(def->expression);
329                         for(vector<string>::const_iterator k=identifiers.begin(); k!=identifiers.end(); ++k)
330                         {
331                                 // Use an existing variable if possible, but only if it's not fuzzy
332                                 ShaderVariable *var = 0;
333                                 for(list<ShaderVariable>::iterator l=variables.begin(); (!var && l!=variables.end()); ++l)
334                                         if(!l->fuzzy_space && l->resolved_name==*k)
335                                                 var = &*l;
336
337                                 if(!var)
338                                 {
339                                         variables.push_back(ShaderVariable(*k));
340                                         var = &variables.back();
341                                 }
342                                 j->add_reference(*var);
343                         }
344                 }
345         }
346
347         // Array sizes need to be resolved for inline processing
348         for(list<ShaderVariable>::iterator i=variables.end(); i!=variables.begin(); )
349                 (--i)->resolve_array(features);
350
351         bool legacy_variables = evaluate_flags("g");
352         for(list<ShaderVariable *>::const_iterator i=resolved_vars.begin(); i!=resolved_vars.end(); ++i)
353                 (*i)->check_inline(legacy_variables, !optimize);
354
355         prog.attach_shader_owned(new VertexShader(create_source(resolved_vars, VERTEX)));
356         prog.attach_shader_owned(new FragmentShader(create_source(resolved_vars, FRAGMENT)));
357
358         if(!features.legacy)
359         {
360                 // OpenGL ES does not support binding fragment shader outputs
361                 if(get_gl_api()!=OPENGL_ES2)
362                         prog.bind_fragment_data(0, "frag_color");
363
364                 prog.bind_attribute(VERTEX4, "vertex");
365                 if(features.lighting)
366                         prog.bind_attribute(NORMAL3, "normal");
367                 else if(features.material)
368                         prog.bind_attribute(COLOR4_FLOAT, "color");
369                 if(features.texture || features.normalmap)
370                         prog.bind_attribute(TEXCOORD4, "texcoord");
371         }
372         if(features.normalmap)
373         {
374                 prog.bind_attribute(get_component_type(TANGENT3), "tangent");
375                 prog.bind_attribute(get_component_type(BINORMAL3), "binormal");
376         }
377 }
378
379 string ProgramBuilder::create_source(const list<ShaderVariable *> &variables, VariableScope scope) const
380 {
381         string source;
382
383         bool use_blocks = !features.legacy && ARB_uniform_buffer_object;
384
385         if(!features.legacy)
386         {
387                 if(get_gl_api()==OPENGL_ES2)
388                 {
389                         if(use_blocks)
390                                 source += "#version 300 es\n";
391                 }
392                 else
393                 {
394                         source += "#version 130\n";
395                         if(use_blocks)
396                                 source += "#extension GL_ARB_uniform_buffer_object: require\n";
397                 }
398         }
399
400         if(get_gl_api()==OPENGL_ES2)
401                 source += "precision mediump float;\n";
402
403         set<const VariableDefinition *> declared_types;
404         set<string> uniform_blocks;
405         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
406                 if((*i)->variable->scope==UNIFORM && (*i)->is_referenced_from(scope) && !(*i)->inlined)
407                 {
408                         if((*i)->type && !declared_types.count((*i)->type))
409                         {
410                                 source += format("%s;\n", (*i)->create_type_declaration());
411                                 declared_types.insert((*i)->type);
412                         }
413
414                         if(!(*i)->resolved_block.empty() && use_blocks)
415                                 uniform_blocks.insert((*i)->resolved_block);
416                         else
417                                 source += format("uniform %s;\n", (*i)->create_declaration());
418                 }
419
420         for(set<string>::const_iterator i=uniform_blocks.begin(); i!=uniform_blocks.end(); ++i)
421         {
422                 source += format("uniform %s\n{\n", *i);
423                 for(list<ShaderVariable *>::const_iterator j=variables.begin(); j!=variables.end(); ++j)
424                         if((*j)->resolved_block==*i)
425                                 source += format("\t%s;\n", (*j)->create_declaration());
426                 source += "};\n";
427         }
428
429         /* Interface variables need to have global declarations. */
430         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
431         {
432                 if(!(*i)->resolved_name.compare(0, 3, "gl_"))
433                         continue;
434
435                 InterfaceFlags iface = (*i)->get_interface_flags(scope);
436
437                 if(iface&INPUT)
438                 {
439                         const char *qualifier = (features.legacy ? scope==VERTEX ? "attribute" : "varying" : "in");
440                         source += format("%s %s;\n", qualifier, (*i)->create_declaration(interfaces[scope-1]));
441                 }
442
443                 if(iface&OUTPUT)
444                 {
445                         const char *qualifier = (features.legacy ? "varying" : "out");
446                         source += format("%s %s;\n", qualifier, (*i)->create_declaration(interfaces[scope]));
447                 }
448         }
449
450         source += "void main()\n{\n";
451
452         list<ShaderVariable *> loop_vars;
453         unsigned loop_size = 0;
454         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
455         {
456                 if(!loop_vars.empty() && !loop_vars.back()->in_loop && (*i)->array_size!=loop_size)
457                 {
458                         /* Declare all variables that need to be visible outside the loop.
459                         Output variables are already declared. */
460                         for(list<ShaderVariable *>::const_iterator j=loop_vars.begin(); j!=loop_vars.end(); ++j)
461                         {
462                                 InterfaceFlags iface = (*j)->get_interface_flags(scope);
463                                 if(!(*j)->in_loop && !(iface&OUTPUT))
464                                         source += format("\t%s;\n", (*j)->create_declaration());
465                         }
466
467                         source += format("\tfor(int i=0; i<%d; ++i)\n\t{\n", loop_size);
468                         for(list<ShaderVariable *>::const_iterator j=loop_vars.begin(); j!=loop_vars.end(); ++j)
469                         {
470                                 if((*j)->variable->scope==scope && !(*j)->inlined)
471                                 {
472                                         string decl;
473                                         if((*j)->in_loop)
474                                                 decl = (*j)->create_declaration(0, true);
475                                         else
476                                         {
477                                                 decl = (*j)->resolved_name;
478                                                 if(!(*j)->array_sum)
479                                                         decl += "[i]";
480                                         }
481                                         const char *oper = ((*j)->array_sum ? "+=" : "=");
482                                         source += format("\t\t%s %s %s;\n", decl, oper, create_expression(**j, "i"));
483                                 }
484
485                                 InterfaceFlags iface = (*j)->get_interface_flags(scope);
486                                 if(iface&OUTPUT)
487                                 {
488                                         string expr = ((*j)->inlined ? create_expression(**j, "i") : (*j)->resolved_name+"[i]");
489                                         source += format("\t\t%c_%s[i] = %s;\n", interfaces[scope], (*j)->resolved_name, expr);
490                                 }
491                         }
492                         source += "\t}\n";
493
494                         loop_vars.clear();
495                 }
496
497                 InterfaceFlags iface = (*i)->get_interface_flags(scope);
498
499                 if((*i)->array_size>1)
500                 {
501                         if((*i)->variable->scope==scope || (iface&OUTPUT))
502                         {
503                                 loop_size = (*i)->array_size;
504                                 loop_vars.push_back(*i);
505                         }
506                         continue;
507                 }
508
509                 if((*i)->variable->scope==scope && !(*i)->inlined)
510                 {
511                         string decl = ((iface&GOAL) ? (*i)->resolved_name : (*i)->create_declaration());
512                         source += format("\t%s = %s;\n", decl, create_expression(**i));
513                 }
514
515                 if((iface&(OUTPUT|GOAL))==OUTPUT)
516                 {
517                         string expr = ((*i)->inlined ? create_expression(**i) : (*i)->resolved_name);
518                         source += format("\t%c_%s = %s;\n", interfaces[scope], (*i)->resolved_name, expr);
519                 }
520         }
521
522         source += '}';
523
524         return source;
525 }
526
527 bool ProgramBuilder::evaluate_flags(const char *flags) const
528 {
529         if(!flags)
530                 return true;
531
532         bool cond = true;
533         char oper = '&';
534         for(const char *i=flags; *i; ++i)
535         {
536                 if(*i>='a' && *i<='z')
537                 {
538                         bool found = (feature_flags.find(*i)!=string::npos);
539                         if(oper=='|')
540                                 cond = (cond || found);
541                         else if(oper=='!')
542                                 cond = (cond && !found);
543                         else if(oper=='&')
544                                 cond = (cond && found);
545                         oper = '&';
546                 }
547                 else
548                         oper = *i;
549         }
550
551         return cond;
552 }
553
554 const char *ProgramBuilder::unqualified_name(const char *name)
555 {
556         for(const char *p=name; *p; ++p)
557                 if(*p==':' && *++p==':')
558                         name = p+1;
559         return name;
560 }
561
562 ProgramBuilder::MatchType ProgramBuilder::name_match(const char *n1, const char *n2, const char **space)
563 {
564         int i = 0;
565         int zzz = -1;
566         int zside = 0;
567         while(*n1 && *n2)
568         {
569                 if(*n1==*n2 || *n1=='z' || *n2=='z')
570                 {
571                         if(*n1!=*n2)
572                         {
573                                 int side = (*n1=='z' ? 1 : 2);
574                                 if(zzz<0)
575                                 {
576                                         zzz = i;
577                                         zside = side;
578                                         if(space)
579                                         {
580                                                 if(*n1=='z')
581                                                         *space = n2;
582                                                 else
583                                                         *space = n1;
584                                         }
585                                 }
586                                 else if(i>=zzz+3 || side!=zside)
587                                         return NO_MATCH;
588                         }
589                 }
590                 else
591                         return NO_MATCH;
592                 ++n1;
593                 ++n2;
594                 ++i;
595         }
596         return (!*n1 && !*n2) ? (zzz>=0 ? FUZZY : EXACT) : ((*n1=='[' || *n2=='[') ? ARRAY : NO_MATCH);
597 }
598
599 bool ProgramBuilder::parse_identifier(const char *ptr, unsigned &start, unsigned &length)
600 {
601         bool found = false;
602         bool member = false;
603         bool subscript = false;
604         for(const char *i=ptr;; ++i)
605         {
606                 if(!found)
607                 {
608                         if(!*i)
609                                 return false;
610                         if(isalpha(*i) || *i=='_')
611                         {
612                                 if(!member)
613                                 {
614                                         start = i-ptr;
615                                         found = true;
616                                 }
617                         }
618                         else if(*i=='.')
619                                 member = true;
620                         else
621                                 member = false;
622                 }
623                 else
624                 {
625                         if(subscript)
626                         {
627                                 if(*i==']')
628                                 {
629                                         length = i+1-(ptr+start);
630                                         return true;
631                                 }
632                                 else if(!isalpha(*i) || i>ptr+start+length+1)
633                                         return true;
634                         }
635                         else if(!isalnum(*i) && *i!='_')
636                         {
637                                 length = i-(ptr+start);
638                                 if(*i=='[')
639                                         subscript = true;
640                                 else
641                                         return true;
642                         }
643                 }
644         }
645 }
646
647 vector<string> ProgramBuilder::extract_identifiers(const char *expression)
648 {
649         vector<string> result;
650         const char *ptr = expression;
651         unsigned start = 0;
652         unsigned length = 0;
653         while(parse_identifier(ptr, start, length))
654         {
655                 result.push_back(string(ptr+start, length));
656                 ptr += start+length;
657         }
658         return result;
659 }
660
661 string ProgramBuilder::replace_identifiers(const char *expression, const map<string, string> &replace_map, bool with_functions)
662 {
663         string result;
664         const char *ptr = expression;
665         unsigned start = 0;
666         unsigned length = 0;
667         while(parse_identifier(ptr, start, length))
668         {
669                 result.append(ptr, start);
670                 string identifier(ptr+start, length);
671                 map<string, string>::const_iterator i = replace_map.find(identifier);
672                 if(i!=replace_map.end())
673                 {
674                         if(with_functions && ptr[start+length]=='(')
675                         {
676                                 string::size_type lparen = i->second.find('(');
677                                 string::size_type rparen = i->second.rfind(')');
678                                 if(lparen!=string::npos && rparen!=string::npos)
679                                 {
680                                         unsigned level = 1;
681                                         unsigned j;
682                                         for(j=start+length+1; (ptr[j] && level); ++j)
683                                         {
684                                                 level += (ptr[j]=='(');
685                                                 level -= (ptr[j]==')');
686                                         }
687
688                                         if(!level)
689                                         {
690                                                 string subexpr(ptr+start+length, ptr+j);
691                                                 result += i->second.substr(0, lparen);
692                                                 result += replace_identifiers(subexpr.c_str(), replace_map, with_functions);
693                                                 result += i->second.substr(rparen+1);
694                                                 ptr += j;
695                                                 continue;
696                                         }
697                                 }
698                         }
699
700                         result += i->second;
701                 }
702                 else
703                         result += identifier;
704                 ptr += start+length;
705         }
706         result += ptr;
707         return result;
708 }
709
710 string ProgramBuilder::create_expression(const ShaderVariable &var, const char *loop) const
711 {
712         string expr = var.create_expression(loop);
713         return replace_identifiers(expr.c_str(), aliases, true);
714 }
715
716
717 ProgramBuilder::StandardFeatures::StandardFeatures():
718         texture(false),
719         material(false),
720         lighting(false),
721         max_lights(1),
722         skylight(false),
723         specular(false),
724         normalmap(false),
725         shadow(false),
726         reflection(false)
727 {
728         if(get_gl_api()==OPENGL_ES2)
729                 legacy = !(get_glsl_version()>=Version(3, 0));
730         else
731                 legacy = !(get_glsl_version()>=Version(1, 30));
732 }
733
734 string ProgramBuilder::StandardFeatures::create_flags() const
735 {
736         string flags;
737         if(texture)
738                 flags += 't';
739         if(material)
740                 flags += 'm';
741         if(lighting)
742         {
743                 flags += 'l';
744                 if(skylight)
745                         flags += 'y';
746                 if(specular)
747                         flags += 'p';
748                 if(normalmap)
749                         flags += 'n';
750         }
751         if(shadow)
752                 flags += 's';
753         if(reflection)
754                 flags += 'e';
755         if(legacy && get_gl_api()==OPENGL)
756                 flags += 'g';
757
758         return flags;
759 }
760
761
762 ProgramBuilder::ShaderVariable::ShaderVariable(const std::string &n):
763         name(n),
764         variable(0),
765         type(0),
766         resolved_name(n),
767         fuzzy_space(name.find("zzz")!=string::npos),
768         array_sum(false),
769         array_size(0),
770         inlined(false),
771         inline_parens(false),
772         in_loop(false)
773 {
774         string::size_type bracket = name.find('[');
775         if(bracket!=string::npos)
776                 array_subscript = name.substr(bracket+1, name.size()-bracket-2);
777 }
778
779 void ProgramBuilder::ShaderVariable::resolve(const VariableDefinition &var)
780 {
781         variable = &var;
782         const char *space = 0;
783         const char *var_uq_name = unqualified_name(variable->name);
784         MatchType match = name_match(var_uq_name, resolved_name.c_str(), &space);
785
786         if(var_uq_name!=variable->name)
787                 resolved_block.assign(variable->name, var_uq_name-2);
788
789         if(match==FUZZY)
790                 resolve_space(string(space, 3));
791         else if(match==ARRAY)
792         {
793                 if(array_subscript.empty())
794                         array_sum = true;
795                 else if(var.scope==UNIFORM)
796                 {
797                         const char *bracket = strrchr(variable->type, '[');
798                         if(bracket)
799                                 array_subscript = string(bracket+1, strlen(bracket)-2);
800                 }
801         }
802 }
803
804 void ProgramBuilder::ShaderVariable::resolve(ShaderVariable &var)
805 {
806         for(list<ShaderVariable *>::iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
807                 (*i)->update_reference(*this, var);
808         var.referenced_by.insert(var.referenced_by.end(), referenced_by.begin(), referenced_by.end());
809 }
810
811 void ProgramBuilder::ShaderVariable::resolve_type(const VariableDefinition &var)
812 {
813         type = &var;
814 }
815
816 void ProgramBuilder::ShaderVariable::resolve_space(const string &space)
817 {
818         if(fuzzy_space)
819         {
820                 resolved_space = space;
821
822                 string::size_type zzz = resolved_name.find("zzz");
823                 resolved_name.replace(zzz, 3, resolved_space);
824                 fuzzy_space = false;
825
826                 // Resolving the space could have affected other variables that use this one
827                 for(list<ShaderVariable *>::iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
828                         (*i)->resolve_space(space);
829         }
830
831         for(list<ShaderVariable *>::iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
832                 if((*i)->fuzzy_space)
833                         (*i)->resolve_space(space);
834 }
835
836 void ProgramBuilder::ShaderVariable::resolve_array(const StandardFeatures &features, unsigned size_hint)
837 {
838         if(array_size)
839                 return;
840         if(!array_sum && array_subscript.empty())
841                 return;
842
843         if(!array_subscript.empty())
844         {
845                 string::size_type bracket = resolved_name.find('[');
846                 if(bracket!=string::npos)
847                         resolved_name = resolved_name.substr(0, bracket);
848         }
849
850         if(variable && variable->scope==UNIFORM)
851         {
852                 if(array_subscript=="MAX_LIGHTS")
853                         array_size = features.max_lights;
854                 else if(isnumrc(array_subscript))
855                         array_size = lexical_cast<unsigned>(array_subscript);
856                 else
857                         throw invalid_variable_definition("invalid array size");
858         }
859
860         if(!array_size)
861         {
862                 for(list<ShaderVariable *>::const_iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
863                         if((*i)->array_size)
864                         {
865                                 array_size = (*i)->array_size;
866                                 break;
867                         }
868         }
869
870         if(!array_size && size_hint)
871                 array_size = size_hint;
872
873         if(array_size)
874         {
875                 for(list<ShaderVariable *>::const_iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
876                         if(!(*i)->array_subscript.empty() && !(*i)->array_size)
877                                 (*i)->resolve_array(features, array_size);
878         }
879 }
880
881 void ProgramBuilder::ShaderVariable::add_reference(ShaderVariable &var)
882 {
883         referenced_vars.push_back(&var);
884         var.referenced_by.push_back(this);
885         if(var.fuzzy_space && !resolved_space.empty())
886                 var.resolve_space(resolved_space);
887 }
888
889 void ProgramBuilder::ShaderVariable::update_reference(ShaderVariable &from, ShaderVariable &to)
890 {
891         replace(referenced_vars.begin(), referenced_vars.end(), &from, &to);
892         replace(referenced_by.begin(), referenced_by.end(), &from, &to);
893         if(from.fuzzy_space && !to.fuzzy_space && !to.resolved_space.empty())
894                 resolve_space(to.resolved_space);
895 }
896
897 void ProgramBuilder::ShaderVariable::check_inline(bool allow_legacy, bool trivial_only)
898 {
899         if(variable->expression)
900         {
901                 if(array_sum && array_size>1)
902                         return;
903                 if(!allow_legacy && !strncmp(variable->expression, "gl_", 3))
904                         return;
905
906                 // Never inline goal variables
907                 if(referenced_by.empty())
908                         return;
909
910                 // Inline an expression consisting of a single identifier
911                 unsigned start, length;
912                 if(parse_identifier(variable->expression, start, length))
913                         if(start==0 && variable->expression[length]==0)
914                         {
915                                 inlined = true;
916                                 return;
917                         }
918
919                 if(trivial_only)
920                         return;
921
922                 /* If all references to the variable come from arrays in the same scope
923                 and of the same size, the variable can be embedded in the loop. */
924                 in_loop = (array_size>1 && !array_sum);
925                 for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
926                         if((*i)->variable->scope!=variable->scope || (*i)->array_size!=array_size)
927                                 in_loop = false;
928                 
929                 /* Count all refs to this variable.  Refs from array variables count once
930                 per loop iteration. */
931                 unsigned total_refs = 0;
932                 unsigned in_scope_refs = 0;
933                 for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
934                 {
935                         unsigned count = max((*i)->array_size*!in_loop, 1U);
936                         total_refs += count;
937                         if((*i)->variable->scope==variable->scope)
938                                 in_scope_refs += count;
939                 }
940
941                 /* Inline if there's only one ref, or if all refs are in other scopes.
942                 In the latter case, the actual inlining will happen in the interface
943                 variable assignment. */
944                 if(total_refs==1 || in_scope_refs==0)
945                 {
946                         inlined = true;
947                         unsigned level = 0;
948                         for(const char *c=variable->expression; (!inline_parens && *c); ++c)
949                         {
950                                 if(*c=='(')
951                                         ++level;
952                                 else if(*c==')')
953                                         --level;
954                                 else if(level==0 && !isalnum(*c) && *c!='_' && *c!='.')
955                                         inline_parens = true;
956                         }
957                 }
958         }
959 }
960
961 bool ProgramBuilder::ShaderVariable::is_referenced_from(VariableScope scope) const
962 {
963         for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
964                 if((*i)->variable->scope==scope)
965                         return true;
966         return false;
967 }
968
969 ProgramBuilder::InterfaceFlags ProgramBuilder::ShaderVariable::get_interface_flags(VariableScope scope) const
970 {
971         /* Uniforms are available to all stages and are not passed through
972         interfaces */
973         if(variable->scope==UNIFORM)
974                 return NO_INTERFACE;
975
976         int flags = NO_INTERFACE;
977
978         for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
979         {
980                 /* Variables used in a later scope than they are declared in need to go
981                 through the interface */
982                 if((*i)->variable->scope>scope && variable->scope<=scope)
983                         flags |= OUTPUT;
984                 if((*i)->variable->scope>=scope && variable->scope<scope)
985                         if(!inlined || variable->scope!=ATTRIBUTE || scope!=VERTEX)
986                                 flags |= INPUT;
987         }
988
989         // Variables without any references are goals and also outputs.
990         if(referenced_by.empty() && variable->scope==scope)
991                 flags |= OUTPUT|GOAL;
992
993         return static_cast<InterfaceFlags>(flags);
994 }
995
996 string ProgramBuilder::ShaderVariable::create_type_declaration() const
997 {
998         if(!type)
999                 throw logic_error("no type");
1000
1001         if(!strncmp(type->type, "struct", 6))
1002         {
1003                 const char *brace = strchr(type->type, '{');
1004                 if(brace)
1005                         return format("struct %s %s", type->name, brace);
1006         }
1007
1008         throw invalid_variable_definition("invalid typedef");
1009 }
1010
1011 string ProgramBuilder::ShaderVariable::create_declaration(char iface, bool loop) const
1012 {
1013         if(variable->scope==UNIFORM && !array_subscript.empty())
1014         {
1015                 const char *bracket = strrchr(variable->type, '[');
1016                 if(bracket)
1017                         return format("%s %s[%d]", string(variable->type, bracket), resolved_name, array_size);
1018         }
1019
1020         string array;
1021         if(!array_sum && array_size>1 && !loop)
1022                 array = format("[%d]", array_size);
1023
1024         if(iface)
1025                 return format("%s %c_%s%s", variable->type, iface, resolved_name, array);
1026         else
1027                 return format("%s %s%s", variable->type, resolved_name, array);
1028 }
1029
1030 string ProgramBuilder::ShaderVariable::create_replacement(VariableScope from_scope, const char *loop) const
1031 {
1032         string replacement = resolved_name;
1033         InterfaceFlags iface = NO_INTERFACE;
1034         if(variable)
1035         {
1036                 iface = get_interface_flags(from_scope);
1037                 if((iface&INPUT) && interfaces[from_scope-1])
1038                         replacement = format("%c_%s", interfaces[from_scope-1], replacement);
1039                 else if(inlined)
1040                 {
1041                         replacement = create_expression(loop);
1042                         if(inline_parens)
1043                                 replacement = "("+replacement+")";
1044                         return replacement;
1045                 }
1046         }
1047
1048         // Add an array subscript, unless the variable is embedded in a loop
1049         if(!array_subscript.empty() && !in_loop)
1050         {
1051                 if(loop)
1052                         return format("%s[%s]", replacement, loop);
1053                 else if(!variable || variable->scope==UNIFORM)
1054                         return replacement+"[0]";
1055         }
1056
1057         return replacement;
1058 }
1059
1060 string ProgramBuilder::ShaderVariable::create_expression(const char *loop) const
1061 {
1062         map<string, string> replace_map;
1063         for(list<ShaderVariable *>::const_iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
1064         {
1065                 string replacement = (*i)->create_replacement(variable->scope, loop);
1066                 if(replacement!=(*i)->name)
1067                         replace_map[(*i)->name] = replacement;
1068         }
1069
1070         if(replace_map.empty())
1071                 return variable->expression;
1072         else
1073                 return replace_identifiers(variable->expression, replace_map);
1074 }
1075
1076
1077 ProgramBuilder::StandardFeatures::Loader::Loader(StandardFeatures &f):
1078         DataFile::ObjectLoader<StandardFeatures>(f)
1079 {
1080         add("custom",    &StandardFeatures::custom);
1081         add("lighting",  &StandardFeatures::lighting);
1082         add("material",  &StandardFeatures::material);
1083         add("max_lights", &StandardFeatures::max_lights);
1084         add("normalmap", &StandardFeatures::normalmap);
1085         add("reflection", &StandardFeatures::reflection);
1086         add("shadow",    &StandardFeatures::shadow);
1087         add("skylight",  &StandardFeatures::skylight);
1088         add("specular",  &StandardFeatures::specular);
1089         add("texture",   &StandardFeatures::texture);
1090 }
1091
1092 } // namespace GL
1093 } // namespace Msp