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