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