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