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