]> git.tdb.fi Git - libs/gl.git/blob - source/programbuilder.cpp
Move eye_obj matrices back out of the uniform block
[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", "g" },
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((get_gl_api()==OPENGL && !features.legacy) || (get_gl_api()==OPENGL_ES2 && get_glsl_version()>=Version(3, 0)))
240         {
241                 aliases["texture2D"] = "texture";
242                 aliases["shadow2D"] = "texture";
243         }
244         else
245                 aliases["shadow2D"] = "shadow2D(...).r";
246 }
247
248 void ProgramBuilder::set_optimize(bool o)
249 {
250         optimize = o;
251 }
252
253 Program *ProgramBuilder::create_program() const
254 {
255         Program *prog = new Program;
256         add_shaders(*prog);
257         return prog;
258 }
259
260 void ProgramBuilder::add_shaders(Program &prog) const
261 {
262         list<ShaderVariable> variables;
263         list<ShaderVariable *> resolved_vars;
264
265         variables.push_front(ShaderVariable("gl_Position"));
266         variables.push_front(ShaderVariable(features.legacy ? "gl_FragColor" : "frag_color"));
267
268         list<VariableDefinition>::const_iterator next_custom = custom_variables.begin();
269         for(const VariableDefinition *i=standard_variables; i->name; )
270         {
271                 const VariableDefinition *def = 0;
272                 if(next_custom!=custom_variables.end() && (!strcmp(next_custom->name, i->name) || !next_custom->flags))
273                 {
274                         def = &*next_custom;
275                         ++next_custom;
276                 }
277                 else
278                 {
279                         def = i;
280                         ++i;
281
282                         // Skip over anything that isn't used with the supplied flags
283                         if(def->flags && !evaluate_flags(def->flags))
284                                 continue;
285                 }
286
287                 if(def->scope==TYPE)
288                 {
289                         for(list<ShaderVariable *>::iterator j=resolved_vars.begin(); j!=resolved_vars.end(); ++j)
290                                 if(!(*j)->type && name_match(def->name, (*j)->variable->type))
291                                         (*j)->resolve_type(*def);
292
293                         continue;
294                 }
295
296                 const char *def_uq_name = unqualified_name(def->name);
297
298                 // See if this variable can satisfy any unresolved variables
299                 ShaderVariable *last_resolved = 0;
300                 for(list<ShaderVariable>::iterator j=variables.begin(); j!=variables.end(); ++j)
301                 {
302                         if(j->variable)
303                                 continue;
304
305                         if(!name_match(def_uq_name, j->resolved_name.c_str()))
306                                 continue;
307
308                         if(last_resolved)
309                         {
310                                 /* We've already resolved a non-fuzzy variable in this iteration.
311                                 If there are multiple variables that can be resolved, they refer
312                                 to the same variable. */
313                                 j->resolve(*last_resolved);
314                                 continue;
315                         }
316
317                         j->resolve(*def);
318                         resolved_vars.push_front(&*j);
319                         if(!j->fuzzy_space)
320                                 last_resolved = &*j;
321
322                         if(!def->expression)
323                                 continue;
324
325                         vector<string> identifiers = extract_identifiers(def->expression);
326                         for(vector<string>::const_iterator k=identifiers.begin(); k!=identifiers.end(); ++k)
327                         {
328                                 // Use an existing variable if possible, but only if it's not fuzzy
329                                 ShaderVariable *var = 0;
330                                 for(list<ShaderVariable>::iterator l=variables.begin(); (!var && l!=variables.end()); ++l)
331                                         if(!l->fuzzy_space && l->resolved_name==*k)
332                                                 var = &*l;
333
334                                 if(!var)
335                                 {
336                                         variables.push_back(ShaderVariable(*k));
337                                         var = &variables.back();
338                                 }
339                                 j->add_reference(*var);
340                         }
341                 }
342         }
343
344         // Array sizes need to be resolved for inline processing
345         for(list<ShaderVariable>::iterator i=variables.end(); i!=variables.begin(); )
346                 (--i)->resolve_array(features);
347
348         for(list<ShaderVariable *>::const_iterator i=resolved_vars.begin(); i!=resolved_vars.end(); ++i)
349                 (*i)->check_inline(features.legacy, !optimize);
350
351         prog.attach_shader_owned(new VertexShader(create_source(resolved_vars, VERTEX)));
352         prog.attach_shader_owned(new FragmentShader(create_source(resolved_vars, FRAGMENT)));
353
354         if(!features.legacy)
355         {
356                 // OpenGL ES does not support binding fragment shader outputs
357                 if(get_gl_api()!=OPENGL_ES2)
358                         prog.bind_fragment_data(0, "frag_color");
359
360                 prog.bind_attribute(VERTEX4, "vertex");
361                 if(features.lighting)
362                         prog.bind_attribute(NORMAL3, "normal");
363                 else if(features.material)
364                         prog.bind_attribute(COLOR4_FLOAT, "color");
365                 if(features.texture || features.normalmap)
366                         prog.bind_attribute(TEXCOORD4, "texcoord");
367         }
368         if(features.normalmap)
369         {
370                 prog.bind_attribute(get_component_type(TANGENT3), "tangent");
371                 prog.bind_attribute(get_component_type(BINORMAL3), "binormal");
372         }
373 }
374
375 string ProgramBuilder::create_source(const list<ShaderVariable *> &variables, VariableScope scope) const
376 {
377         string source;
378
379         bool legacy_qualifiers = features.legacy || (get_gl_api()==OPENGL_ES2 && !(get_glsl_version()>=Version(3, 0)));
380         bool use_blocks = !features.legacy && ARB_uniform_buffer_object;
381
382         if(!features.legacy)
383         {
384                 if(get_gl_api()==OPENGL_ES2)
385                 {
386                         if(use_blocks)
387                                 source += "#version 300 es\n";
388                         source += "precision mediump float;\n";
389                 }
390                 else
391                 {
392                         source += "#version 130\n";
393                         if(use_blocks)
394                                 source += "#extension GL_ARB_uniform_buffer_object: require\n";
395                 }
396         }
397
398         set<const VariableDefinition *> declared_types;
399         set<string> uniform_blocks;
400         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
401                 if((*i)->variable->scope==UNIFORM && (*i)->is_referenced_from(scope) && !(*i)->inlined)
402                 {
403                         if((*i)->type && !declared_types.count((*i)->type))
404                         {
405                                 source += format("%s;\n", (*i)->create_type_declaration());
406                                 declared_types.insert((*i)->type);
407                         }
408
409                         if(!(*i)->resolved_block.empty() && use_blocks)
410                                 uniform_blocks.insert((*i)->resolved_block);
411                         else
412                                 source += format("uniform %s;\n", (*i)->create_declaration());
413                 }
414
415         for(set<string>::const_iterator i=uniform_blocks.begin(); i!=uniform_blocks.end(); ++i)
416         {
417                 source += format("uniform %s\n{\n", *i);
418                 for(list<ShaderVariable *>::const_iterator j=variables.begin(); j!=variables.end(); ++j)
419                         if((*j)->resolved_block==*i)
420                                 source += format("\t%s;\n", (*j)->create_declaration());
421                 source += "};\n";
422         }
423
424         /* Interface variables need to have global declarations. */
425         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
426         {
427                 if(!(*i)->resolved_name.compare(0, 3, "gl_"))
428                         continue;
429
430                 InterfaceFlags interface = (*i)->get_interface_flags(scope);
431
432                 if(interface&INPUT)
433                 {
434                         const char *qualifier = (legacy_qualifiers ? scope==VERTEX ? "attribute" : "varying" : "in");
435                         source += format("%s %s;\n", qualifier, (*i)->create_declaration(interfaces[scope-1]));
436                 }
437
438                 if(interface&OUTPUT)
439                 {
440                         const char *qualifier = (legacy_qualifiers ? "varying" : "out");
441                         source += format("%s %s;\n", qualifier, (*i)->create_declaration(interfaces[scope]));
442                 }
443         }
444
445         source += "void main()\n{\n";
446
447         list<ShaderVariable *> loop_vars;
448         unsigned loop_size = 0;
449         for(list<ShaderVariable *>::const_iterator i=variables.begin(); i!=variables.end(); ++i)
450         {
451                 if(!loop_vars.empty() && !loop_vars.back()->in_loop && (*i)->array_size!=loop_size)
452                 {
453                         /* Declare all variables that need to be visible outside the loop.
454                         Output variables are already declared. */
455                         for(list<ShaderVariable *>::const_iterator j=loop_vars.begin(); j!=loop_vars.end(); ++j)
456                         {
457                                 InterfaceFlags interface = (*j)->get_interface_flags(scope);
458                                 if(!(*j)->in_loop && !(interface&OUTPUT))
459                                         source += format("\t%s;\n", (*j)->create_declaration());
460                         }
461
462                         source += format("\tfor(int i=0; i<%d; ++i)\n\t{\n", loop_size);
463                         for(list<ShaderVariable *>::const_iterator j=loop_vars.begin(); j!=loop_vars.end(); ++j)
464                         {
465                                 if((*j)->variable->scope==scope && !(*j)->inlined)
466                                 {
467                                         string decl;
468                                         if((*j)->in_loop)
469                                                 decl = (*j)->create_declaration(0, true);
470                                         else
471                                         {
472                                                 decl = (*j)->resolved_name;
473                                                 if(!(*j)->array_sum)
474                                                         decl += "[i]";
475                                         }
476                                         const char *oper = ((*j)->array_sum ? "+=" : "=");
477                                         source += format("\t\t%s %s %s;\n", decl, oper, create_expression(**j, "i"));
478                                 }
479
480                                 InterfaceFlags interface = (*j)->get_interface_flags(scope);
481                                 if(interface&OUTPUT)
482                                 {
483                                         string expr = ((*j)->inlined ? create_expression(**j, "i") : (*j)->resolved_name+"[i]");
484                                         source += format("\t\t%c_%s[i] = %s;\n", interfaces[scope], (*j)->resolved_name, expr);
485                                 }
486                         }
487                         source += "\t}\n";
488
489                         loop_vars.clear();
490                 }
491
492                 InterfaceFlags interface = (*i)->get_interface_flags(scope);
493
494                 if((*i)->array_size>1)
495                 {
496                         if((*i)->variable->scope==scope || (interface&OUTPUT))
497                         {
498                                 loop_size = (*i)->array_size;
499                                 loop_vars.push_back(*i);
500                         }
501                         continue;
502                 }
503
504                 if((*i)->variable->scope==scope && !(*i)->inlined)
505                 {
506                         string decl = ((interface&GOAL) ? (*i)->resolved_name : (*i)->create_declaration());
507                         source += format("\t%s = %s;\n", decl, create_expression(**i));
508                 }
509
510                 if((interface&(OUTPUT|GOAL))==OUTPUT)
511                 {
512                         string expr = ((*i)->inlined ? create_expression(**i) : (*i)->resolved_name);
513                         source += format("\t%c_%s = %s;\n", interfaces[scope], (*i)->resolved_name, expr);
514                 }
515         }
516
517         source += '}';
518
519         return source;
520 }
521
522 bool ProgramBuilder::evaluate_flags(const char *flags) const
523 {
524         if(!flags)
525                 return true;
526
527         bool cond = true;
528         char oper = '&';
529         for(const char *i=flags; *i; ++i)
530         {
531                 if(*i>='a' && *i<='z')
532                 {
533                         bool found = (feature_flags.find(*i)!=string::npos);
534                         if(oper=='|')
535                                 cond = (cond || found);
536                         else if(oper=='!')
537                                 cond = (cond && !found);
538                         else if(oper=='&')
539                                 cond = (cond && found);
540                         oper = '&';
541                 }
542                 else
543                         oper = *i;
544         }
545
546         return cond;
547 }
548
549 const char *ProgramBuilder::unqualified_name(const char *name)
550 {
551         for(const char *p=name; *p; ++p)
552                 if(*p==':' && *++p==':')
553                         name = p+1;
554         return name;
555 }
556
557 ProgramBuilder::MatchType ProgramBuilder::name_match(const char *n1, const char *n2, const char **space)
558 {
559         int i = 0;
560         int zzz = -1;
561         int zside = 0;
562         while(*n1 && *n2)
563         {
564                 if(*n1==*n2 || *n1=='z' || *n2=='z')
565                 {
566                         if(*n1!=*n2)
567                         {
568                                 int side = (*n1=='z' ? 1 : 2);
569                                 if(zzz<0)
570                                 {
571                                         zzz = i;
572                                         zside = side;
573                                         if(space)
574                                         {
575                                                 if(*n1=='z')
576                                                         *space = n2;
577                                                 else
578                                                         *space = n1;
579                                         }
580                                 }
581                                 else if(i>=zzz+3 || side!=zside)
582                                         return NO_MATCH;
583                         }
584                 }
585                 else
586                         return NO_MATCH;
587                 ++n1;
588                 ++n2;
589                 ++i;
590         }
591         return (!*n1 && !*n2) ? (zzz>=0 ? FUZZY : EXACT) : ((*n1=='[' || *n2=='[') ? ARRAY : NO_MATCH);
592 }
593
594 bool ProgramBuilder::parse_identifier(const char *ptr, unsigned &start, unsigned &length)
595 {
596         bool found = false;
597         bool member = false;
598         bool subscript = false;
599         for(const char *i=ptr;; ++i)
600         {
601                 if(!found)
602                 {
603                         if(!*i)
604                                 return false;
605                         if(isalpha(*i) || *i=='_')
606                         {
607                                 if(!member)
608                                 {
609                                         start = i-ptr;
610                                         found = true;
611                                 }
612                         }
613                         else if(*i=='.')
614                                 member = true;
615                         else
616                                 member = false;
617                 }
618                 else
619                 {
620                         if(subscript)
621                         {
622                                 if(*i==']')
623                                 {
624                                         length = i+1-(ptr+start);
625                                         return true;
626                                 }
627                                 else if(!isalpha(*i) || i>ptr+start+length+1)
628                                         return true;
629                         }
630                         else if(!isalnum(*i) && *i!='_')
631                         {
632                                 length = i-(ptr+start);
633                                 if(*i=='[')
634                                         subscript = true;
635                                 else
636                                         return true;
637                         }
638                 }
639         }
640 }
641
642 vector<string> ProgramBuilder::extract_identifiers(const char *expression)
643 {
644         vector<string> result;
645         const char *ptr = expression;
646         unsigned start = 0;
647         unsigned length = 0;
648         while(parse_identifier(ptr, start, length))
649         {
650                 result.push_back(string(ptr+start, length));
651                 ptr += start+length;
652         }
653         return result;
654 }
655
656 string ProgramBuilder::replace_identifiers(const char *expression, const map<string, string> &replace_map, bool with_functions)
657 {
658         string result;
659         const char *ptr = expression;
660         unsigned start = 0;
661         unsigned length = 0;
662         while(parse_identifier(ptr, start, length))
663         {
664                 result.append(ptr, start);
665                 string identifier(ptr+start, length);
666                 map<string, string>::const_iterator i = replace_map.find(identifier);
667                 if(i!=replace_map.end())
668                 {
669                         if(with_functions && ptr[start+length]=='(')
670                         {
671                                 string::size_type lparen = i->second.find('(');
672                                 string::size_type rparen = i->second.rfind(')');
673                                 if(lparen!=string::npos && rparen!=string::npos)
674                                 {
675                                         unsigned level = 1;
676                                         unsigned j;
677                                         for(j=start+length+1; (ptr[j] && level); ++j)
678                                         {
679                                                 level += (ptr[j]=='(');
680                                                 level -= (ptr[j]==')');
681                                         }
682
683                                         if(!level)
684                                         {
685                                                 string subexpr(ptr+start+length, ptr+j);
686                                                 result += i->second.substr(0, lparen);
687                                                 result += replace_identifiers(subexpr.c_str(), replace_map, with_functions);
688                                                 result += i->second.substr(rparen+1);
689                                                 ptr += j;
690                                                 continue;
691                                         }
692                                 }
693                         }
694
695                         result += i->second;
696                 }
697                 else
698                         result += identifier;
699                 ptr += start+length;
700         }
701         result += ptr;
702         return result;
703 }
704
705 string ProgramBuilder::create_expression(const ShaderVariable &var, const char *loop) const
706 {
707         string expr = var.create_expression(loop);
708         return replace_identifiers(expr.c_str(), aliases, true);
709 }
710
711
712 ProgramBuilder::StandardFeatures::StandardFeatures():
713         texture(false),
714         material(false),
715         lighting(false),
716         max_lights(1),
717         skylight(false),
718         specular(false),
719         normalmap(false),
720         shadow(false),
721         reflection(false),
722         legacy(get_gl_api()==OPENGL && !(get_glsl_version()>=Version(1, 30)))
723 { }
724
725 string ProgramBuilder::StandardFeatures::create_flags() const
726 {
727         string flags;
728         if(texture)
729                 flags += 't';
730         if(material)
731                 flags += 'm';
732         if(lighting)
733         {
734                 flags += 'l';
735                 if(skylight)
736                         flags += 'y';
737                 if(specular)
738                         flags += 'p';
739                 if(normalmap)
740                         flags += 'n';
741         }
742         if(shadow)
743                 flags += 's';
744         if(reflection)
745                 flags += 'e';
746         if(legacy)
747                 flags += 'g';
748
749         return flags;
750 }
751
752
753 ProgramBuilder::ShaderVariable::ShaderVariable(const std::string &n):
754         name(n),
755         variable(0),
756         type(0),
757         resolved_name(n),
758         fuzzy_space(name.find("zzz")!=string::npos),
759         array_sum(false),
760         array_size(0),
761         inlined(false),
762         inline_parens(false),
763         in_loop(false)
764 {
765         string::size_type bracket = name.find('[');
766         if(bracket!=string::npos)
767                 array_subscript = name.substr(bracket+1, name.size()-bracket-2);
768 }
769
770 void ProgramBuilder::ShaderVariable::resolve(const VariableDefinition &var)
771 {
772         variable = &var;
773         const char *space = 0;
774         const char *var_uq_name = unqualified_name(variable->name);
775         MatchType match = name_match(var_uq_name, resolved_name.c_str(), &space);
776
777         if(var_uq_name!=variable->name)
778                 resolved_block.assign(variable->name, var_uq_name-2);
779
780         if(match==FUZZY)
781                 resolve_space(string(space, 3));
782         else if(match==ARRAY)
783         {
784                 if(array_subscript.empty())
785                         array_sum = true;
786                 else if(var.scope==UNIFORM)
787                 {
788                         const char *bracket = strrchr(variable->type, '[');
789                         if(bracket)
790                                 array_subscript = string(bracket+1, strlen(bracket)-2);
791                 }
792         }
793 }
794
795 void ProgramBuilder::ShaderVariable::resolve(ShaderVariable &var)
796 {
797         for(list<ShaderVariable *>::iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
798                 (*i)->update_reference(*this, var);
799         var.referenced_by.insert(var.referenced_by.end(), referenced_by.begin(), referenced_by.end());
800 }
801
802 void ProgramBuilder::ShaderVariable::resolve_type(const VariableDefinition &var)
803 {
804         type = &var;
805 }
806
807 void ProgramBuilder::ShaderVariable::resolve_space(const string &space)
808 {
809         if(fuzzy_space)
810         {
811                 resolved_space = space;
812
813                 string::size_type zzz = resolved_name.find("zzz");
814                 resolved_name.replace(zzz, 3, resolved_space);
815                 fuzzy_space = false;
816
817                 // Resolving the space could have affected other variables that use this one
818                 for(list<ShaderVariable *>::iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
819                         (*i)->resolve_space(space);
820         }
821
822         for(list<ShaderVariable *>::iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
823                 if((*i)->fuzzy_space)
824                         (*i)->resolve_space(space);
825 }
826
827 void ProgramBuilder::ShaderVariable::resolve_array(const StandardFeatures &features, unsigned size_hint)
828 {
829         if(array_size)
830                 return;
831         if(!array_sum && array_subscript.empty())
832                 return;
833
834         if(!array_subscript.empty())
835         {
836                 string::size_type bracket = resolved_name.find('[');
837                 if(bracket!=string::npos)
838                         resolved_name = resolved_name.substr(0, bracket);
839         }
840
841         if(variable && variable->scope==UNIFORM)
842         {
843                 if(array_subscript=="MAX_LIGHTS")
844                         array_size = features.max_lights;
845                 else if(isnumrc(array_subscript))
846                         array_size = lexical_cast<unsigned>(array_subscript);
847                 else
848                         throw invalid_variable_definition("invalid array size");
849         }
850
851         if(!array_size)
852         {
853                 for(list<ShaderVariable *>::const_iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
854                         if((*i)->array_size)
855                         {
856                                 array_size = (*i)->array_size;
857                                 break;
858                         }
859         }
860
861         if(!array_size && size_hint)
862                 array_size = size_hint;
863
864         if(array_size)
865         {
866                 for(list<ShaderVariable *>::const_iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
867                         if(!(*i)->array_subscript.empty() && !(*i)->array_size)
868                                 (*i)->resolve_array(features, array_size);
869         }
870 }
871
872 void ProgramBuilder::ShaderVariable::add_reference(ShaderVariable &var)
873 {
874         referenced_vars.push_back(&var);
875         var.referenced_by.push_back(this);
876         if(var.fuzzy_space && !resolved_space.empty())
877                 var.resolve_space(resolved_space);
878 }
879
880 void ProgramBuilder::ShaderVariable::update_reference(ShaderVariable &from, ShaderVariable &to)
881 {
882         replace(referenced_vars.begin(), referenced_vars.end(), &from, &to);
883         replace(referenced_by.begin(), referenced_by.end(), &from, &to);
884         if(from.fuzzy_space && !to.fuzzy_space && !to.resolved_space.empty())
885                 resolve_space(to.resolved_space);
886 }
887
888 void ProgramBuilder::ShaderVariable::check_inline(bool allow_legacy, bool trivial_only)
889 {
890         if(variable->expression)
891         {
892                 if(array_sum && array_size>1)
893                         return;
894                 if(!allow_legacy && !strncmp(variable->expression, "gl_", 3))
895                         return;
896
897                 // Never inline goal variables
898                 if(referenced_by.empty())
899                         return;
900
901                 // Inline an expression consisting of a single identifier
902                 unsigned start, length;
903                 if(parse_identifier(variable->expression, start, length))
904                         if(start==0 && variable->expression[length]==0)
905                         {
906                                 inlined = true;
907                                 return;
908                         }
909
910                 if(trivial_only)
911                         return;
912
913                 /* If all references to the variable come from arrays in the same scope
914                 and of the same size, the variable can be embedded in the loop. */
915                 in_loop = (array_size>1 && !array_sum);
916                 for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
917                         if((*i)->variable->scope!=variable->scope || (*i)->array_size!=array_size)
918                                 in_loop = false;
919                 
920                 /* Count all refs to this variable.  Refs from array variables count once
921                 per loop iteration. */
922                 unsigned total_refs = 0;
923                 unsigned in_scope_refs = 0;
924                 for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
925                 {
926                         unsigned count = max((*i)->array_size*!in_loop, 1U);
927                         total_refs += count;
928                         if((*i)->variable->scope==variable->scope)
929                                 in_scope_refs += count;
930                 }
931
932                 /* Inline if there's only one ref, or if all refs are in other scopes.
933                 In the latter case, the actual inlining will happen in the interface
934                 variable assignment. */
935                 if(total_refs==1 || in_scope_refs==0)
936                 {
937                         inlined = true;
938                         unsigned level = 0;
939                         for(const char *c=variable->expression; (!inline_parens && *c); ++c)
940                         {
941                                 if(*c=='(')
942                                         ++level;
943                                 else if(*c==')')
944                                         --level;
945                                 else if(level==0 && !isalnum(*c) && *c!='_' && *c!='.')
946                                         inline_parens = true;
947                         }
948                 }
949         }
950 }
951
952 bool ProgramBuilder::ShaderVariable::is_referenced_from(VariableScope scope) const
953 {
954         for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
955                 if((*i)->variable->scope==scope)
956                         return true;
957         return false;
958 }
959
960 ProgramBuilder::InterfaceFlags ProgramBuilder::ShaderVariable::get_interface_flags(VariableScope scope) const
961 {
962         /* Uniforms are available to all stages and are not passed through
963         interfaces */
964         if(variable->scope==UNIFORM)
965                 return NO_INTERFACE;
966
967         int flags = NO_INTERFACE;
968
969         for(list<ShaderVariable *>::const_iterator i=referenced_by.begin(); i!=referenced_by.end(); ++i)
970         {
971                 /* Variables used in a later scope than they are declared in need to go
972                 through the interface */
973                 if((*i)->variable->scope>scope && variable->scope<=scope)
974                         flags |= OUTPUT;
975                 if((*i)->variable->scope>=scope && variable->scope<scope)
976                         if(!inlined || variable->scope!=ATTRIBUTE || scope!=VERTEX)
977                                 flags |= INPUT;
978         }
979
980         // Variables without any references are goals and also outputs.
981         if(referenced_by.empty() && variable->scope==scope)
982                 flags |= OUTPUT|GOAL;
983
984         return static_cast<InterfaceFlags>(flags);
985 }
986
987 string ProgramBuilder::ShaderVariable::create_type_declaration() const
988 {
989         if(!type)
990                 throw logic_error("no type");
991
992         if(!strncmp(type->type, "struct", 6))
993         {
994                 const char *brace = strchr(type->type, '{');
995                 if(brace)
996                         return format("struct %s %s", type->name, brace);
997         }
998
999         throw invalid_variable_definition("invalid typedef");
1000 }
1001
1002 string ProgramBuilder::ShaderVariable::create_declaration(char interface, bool loop) const
1003 {
1004         if(variable->scope==UNIFORM && !array_subscript.empty())
1005         {
1006                 const char *bracket = strrchr(variable->type, '[');
1007                 if(bracket)
1008                         return format("%s %s[%d]", string(variable->type, bracket), resolved_name, array_size);
1009         }
1010
1011         string array;
1012         if(!array_sum && array_size>1 && !loop)
1013                 array = format("[%d]", array_size);
1014
1015         if(interface)
1016                 return format("%s %c_%s%s", variable->type, interface, resolved_name, array);
1017         else
1018                 return format("%s %s%s", variable->type, resolved_name, array);
1019 }
1020
1021 string ProgramBuilder::ShaderVariable::create_replacement(VariableScope from_scope, const char *loop) const
1022 {
1023         string replacement = resolved_name;
1024         InterfaceFlags interface = NO_INTERFACE;
1025         if(variable)
1026         {
1027                 interface = get_interface_flags(from_scope);
1028                 if((interface&INPUT) && interfaces[from_scope-1])
1029                         replacement = format("%c_%s", interfaces[from_scope-1], replacement);
1030                 else if(inlined)
1031                 {
1032                         replacement = create_expression(loop);
1033                         if(inline_parens)
1034                                 replacement = "("+replacement+")";
1035                         return replacement;
1036                 }
1037         }
1038
1039         // Add an array subscript, unless the variable is embedded in a loop
1040         if(!array_subscript.empty() && !in_loop)
1041         {
1042                 if(loop)
1043                         return format("%s[%s]", replacement, loop);
1044                 else if(!variable || variable->scope==UNIFORM)
1045                         return replacement+"[0]";
1046         }
1047
1048         return replacement;
1049 }
1050
1051 string ProgramBuilder::ShaderVariable::create_expression(const char *loop) const
1052 {
1053         map<string, string> replace_map;
1054         for(list<ShaderVariable *>::const_iterator i=referenced_vars.begin(); i!=referenced_vars.end(); ++i)
1055         {
1056                 string replacement = (*i)->create_replacement(variable->scope, loop);
1057                 if(replacement!=(*i)->name)
1058                         replace_map[(*i)->name] = replacement;
1059         }
1060
1061         if(replace_map.empty())
1062                 return variable->expression;
1063         else
1064                 return replace_identifiers(variable->expression, replace_map);
1065 }
1066
1067
1068 ProgramBuilder::StandardFeatures::Loader::Loader(StandardFeatures &f):
1069         DataFile::ObjectLoader<StandardFeatures>(f)
1070 {
1071         add("custom",    &StandardFeatures::custom);
1072         add("lighting",  &StandardFeatures::lighting);
1073         add("material",  &StandardFeatures::material);
1074         add("max_lights", &StandardFeatures::max_lights);
1075         add("normalmap", &StandardFeatures::normalmap);
1076         add("reflection", &StandardFeatures::reflection);
1077         add("shadow",    &StandardFeatures::shadow);
1078         add("skylight",  &StandardFeatures::skylight);
1079         add("specular",  &StandardFeatures::specular);
1080         add("texture",   &StandardFeatures::texture);
1081 }
1082
1083 } // namespace GL
1084 } // namespace Msp