]> git.tdb.fi Git - libs/gl.git/blob - source/program.cpp
Generate a hash describing the layout of uniforms in a Program
[libs/gl.git] / source / program.cpp
1 #include <algorithm>
2 #include <msp/core/hash.h>
3 #include <msp/strings/format.h>
4 #include "arb_shader_objects.h"
5 #include "arb_vertex_shader.h"
6 #include "error.h"
7 #include "extension.h"
8 #include "program.h"
9 #include "shader.h"
10
11 using namespace std;
12
13 namespace {
14
15 const char *standard_vertex_src[] =
16 {
17         "n",   "attribute vec3 tangent;\n",
18         "n",   "attribute vec3 binormal;\n",
19         "t|n", "varying vec2 v_texcoord;\n",
20         "s",   "varying vec3 v_shadowcoord;\n",
21         "!lm", "varying vec4 v_color;\n",
22         "l!n", "varying vec3 v_normal;\n",
23         "l",   "varying vec3 v_light_dir;\n",
24         "p|e", "varying vec3 v_eye_dir;\n",
25         "r",   "vec4 transform_vertex(vec4);\n",
26         "lr",  "vec3 transform_normal(vec3);\n",
27          0,    "void main()\n",
28          0,    "{\n",
29         "r",   "\tvec4 eye_pos = transform_vertex(gl_Vertex);\n",
30         "!r",  "\tvec4 eye_pos = gl_ModelViewMatrix*gl_Vertex;\n",
31          0,    "\tgl_Position = gl_ProjectionMatrix*eye_pos;\n",
32         "lr",  "\tvec3 eye_normal = transform_normal(gl_Normal);\n",
33         "l!r", "\tvec3 eye_normal = gl_NormalMatrix*gl_Normal;\n",
34         "l!n", "\tv_normal = eye_normal;\n",
35         "nr",  "\tvec3 eye_tangent = transform_normal(tangent);\n",
36         "n!r", "\tvec3 eye_tangent = gl_NormalMatrix*tangent;\n",
37         "nr",  "\tvec3 eye_binormal = transform_normal(binormal);\n",
38         "n!r", "\tvec3 eye_binormal = gl_NormalMatrix*binormal;\n",
39         "l",   "\tvec3 eye_light_dir = normalize(gl_LightSource[0].position.xyz-eye_pos.xyz*gl_LightSource[0].position.w);\n",
40         "n",   "\tv_light_dir = vec3(dot(eye_tangent, eye_light_dir), dot(eye_binormal, eye_light_dir), dot(eye_normal, eye_light_dir));\n",
41         "l!n", "\tv_light_dir = eye_light_dir;\n",
42         "p|e", "\tvec3 eye_dir = -normalize(eye_pos.xyz);\n",
43         "p|en",  "\tv_eye_dir = vec3(dot(eye_tangent, eye_dir), dot(eye_binormal, eye_dir), dot(eye_normal, eye_dir));\n",
44         "p|e!n", "\tv_eye_dir = eye_dir;\n",
45         "t|n", "\tv_texcoord = gl_MultiTexCoord0.xy;\n",
46         "s",   "\tv_shadowcoord = vec3(dot(gl_EyePlaneS[3], eye_pos), dot(gl_EyePlaneT[3], eye_pos), dot(gl_EyePlaneR[3], eye_pos));\n",
47         "!lm", "\tv_color = gl_Color;\n",
48          0,    "}",
49         0, 0
50 };
51
52 const char *standard_fragment_src[] =
53 {
54         "t",   "uniform sampler2D texture;\n",
55         "n",   "uniform sampler2D normalmap;\n",
56         "s",   "uniform sampler2DShadow shadow;\n",
57         "e",   "uniform samplerCube environment;\n",
58         "e",   "uniform float reflectivity;\n",
59         "t|n", "varying vec2 v_texcoord;\n",
60         "s",   "varying vec3 v_shadowcoord;\n",
61         "!lm", "varying vec4 v_color;\n",
62         "l!n", "varying vec3 v_normal;\n",
63         "l",   "varying vec3 v_light_dir;\n",
64         "p|e", "varying vec3 v_eye_dir;\n",
65          0,    "void main()\n",
66          0,    "{\n",
67         "n",   "\tvec3 n_normal = texture2D(normalmap, v_texcoord).xyz*2.0-1.0;\n",
68         "l!n", "\tvec3 n_normal = normalize(v_normal);\n",
69         "l",   "\tfloat l_diffuse = max(dot(n_normal, normalize(v_light_dir)), 0.0);\n",
70         "p",   "\tvec3 half_dir = normalize(v_eye_dir+v_light_dir);\n",
71         "p",   "\tfloat l_specular = pow(max(dot(half_dir, n_normal), 0.0), gl_FrontMaterial.shininess);\n",
72         "s",   "\tfloat l_shadow = shadow2D(shadow, v_shadowcoord).r;\n",
73         /* XXX This is incorrect with normal mapping, since the vectors are in TBN
74         space but environment map is expected to be in eye space */
75         "e",   "\tvec4 reflection = textureCube(environment, n_normal*(dot(n_normal, v_eye_dir)*2.0)-v_eye_dir);\n",
76          0,    "\tgl_FragColor = ",
77         "!t!l!m", "vec4(1.0, 1.0, 1.0, 1.0)",
78         "t",     "texture2D(texture, v_texcoord)",
79         "l|mt",  "*",
80         "!lm",   "v_color",
81         "l",     "((l_diffuse",
82         "lm",    "*gl_FrontLightProduct[0].diffuse",
83         "p",     "+l_specular",
84         "pm",    "*gl_FrontLightProduct[0].specular",
85         "l",     ")",
86         "s",     "*l_shadow",
87         "lm",    "+gl_FrontLightModelProduct.sceneColor",
88         "l",     ")",
89         "e",     "+reflection*reflectivity",
90          0,      ";\n",
91          0,    "}\n",
92         0, 0
93 };
94
95 }
96
97 namespace Msp {
98 namespace GL {
99
100 Program::Program()
101 {
102         init();
103 }
104
105 Program::Program(const StandardFeatures &features)
106 {
107         init();
108
109         add_standard_shaders(features);
110         if(!features.transform)
111                 link();
112 }
113
114 Program::Program(const string &vert, const string &frag)
115 {
116         init();
117
118         attach_shader_owned(new Shader(VERTEX_SHADER, vert));
119         attach_shader_owned(new Shader(FRAGMENT_SHADER, frag));
120         link();
121 }
122
123 void Program::init()
124 {
125         static RequireExtension _ext("GL_ARB_shader_objects");
126
127         linked = false;
128         id = glCreateProgramObjectARB();
129 }
130
131 Program::~Program()
132 {
133         for(list<Shader *>::iterator i=owned_data.begin(); i!=owned_data.end(); ++i)
134                 delete *i;
135         glDeleteObjectARB(id);
136 }
137
138 void Program::attach_shader(Shader &shader)
139 {
140         if(find(shaders.begin(), shaders.end(), &shader)==shaders.end())
141         {
142                 glAttachObjectARB(id, shader.get_id());
143                 shaders.push_back(&shader);
144         }
145 }
146
147 void Program::attach_shader_owned(Shader *shader)
148 {
149         attach_shader(*shader);
150         if(find(owned_data.begin(), owned_data.end(), shader)==owned_data.end())
151                 owned_data.push_back(shader);
152 }
153
154 void Program::detach_shader(Shader &shader)
155 {
156         list<Shader *>::iterator i = remove(shaders.begin(), shaders.end(), &shader);
157         if(i!=shaders.end())
158         {
159                 shaders.erase(i, shaders.end());
160                 glDetachObjectARB(id, shader.get_id());
161         }
162 }
163
164 void Program::add_standard_shaders(const StandardFeatures &features)
165 {
166         string flags = features.create_flags();
167         string vertex_src = process_standard_source(standard_vertex_src, flags);
168         string fragment_src = process_standard_source(standard_fragment_src, flags);
169         attach_shader_owned(new Shader(VERTEX_SHADER, vertex_src));
170         attach_shader_owned(new Shader(FRAGMENT_SHADER, fragment_src));
171 }
172
173 string Program::process_standard_source(const char **source, const string &flags)
174 {
175         string result;
176
177         for(unsigned i=0; source[i+1]; i+=2)
178         {
179                 if(source[i])
180                 {
181                         bool cond = true;
182                         char oper = '&';
183                         for(const char *c=source[i]; *c; ++c)
184                         {
185                                 if(*c>='a' && *c<='z')
186                                 {
187                                         bool found = (flags.find(*c)!=string::npos);
188                                         if(oper=='|')
189                                                 cond = (cond || found);
190                                         else if(oper=='!')
191                                                 cond = (cond && !found);
192                                         else if(oper=='&')
193                                                 cond = (cond && found);
194                                         oper = '&';
195                                 }
196                                 else
197                                         oper = *c;
198                         }
199
200                         if(!cond)
201                                 continue;
202                 }
203
204                 result += source[i+1];
205         }
206
207         return result;
208 }
209
210 void Program::bind_attribute(unsigned index, const string &name)
211 {
212         static RequireExtension _ext("GL_ARB_vertex_shader");
213         glBindAttribLocationARB(id, index, name.c_str());
214 }
215
216 void Program::link()
217 {
218         for(list<Shader *>::iterator i=shaders.begin(); i!=shaders.end(); ++i)
219                 if(!(*i)->is_compiled())
220                         (*i)->compile();
221
222         uniforms.clear();
223
224         glLinkProgramARB(id);
225         int value;
226         glGetObjectParameterivARB(id, GL_OBJECT_LINK_STATUS_ARB, &value);
227         if(!(linked = value))
228                 throw compile_error(get_info_log());
229
230         glGetObjectParameterivARB(id, GL_OBJECT_ACTIVE_UNIFORMS_ARB, &value);
231         for(int i=0; i<value; ++i)
232         {
233                 UniformInfo info;
234                 char name[128];
235                 int len = 0;
236                 glGetActiveUniformARB(id, i, 128, &len, &info.size, &info.type, name);
237                 if(len)
238                 {
239                         info.name = name;
240                         info.location = glGetUniformLocationARB(id, name);
241                         uniforms[name] = info;
242                 }
243         }
244
245         string layout_descriptor;
246         for(map<string, UniformInfo>::const_iterator i = uniforms.begin(); i!=uniforms.end(); ++i)
247                 if(i->second.location>=0)
248                 {
249                         if(!layout_descriptor.empty())
250                                 layout_descriptor += '\n';
251                         layout_descriptor += format("%d:%s:%x", i->second.location, i->second.name, i->second.type);
252                 }
253         uniform_layout_hash = hash32(layout_descriptor);
254 }
255
256 string Program::get_info_log() const
257 {
258         GLsizei len = 0;
259         glGetObjectParameterivARB(id, GL_OBJECT_INFO_LOG_LENGTH_ARB, &len);
260         char *buf = new char[len+1];
261         glGetInfoLogARB(id, len+1, &len, buf);
262         string log(buf, len);
263         delete[] buf;
264         return log;
265 }
266
267 void Program::bind() const
268 {
269         if(!linked)
270                 throw invalid_operation("Program::bind");
271
272         if(!set_current(this))
273                 return;
274
275         glUseProgramObjectARB(id);
276 }
277
278 int Program::get_uniform_location(const string &n) const
279 {
280         map<string, UniformInfo>::const_iterator i = uniforms.find(n);
281         if(i==uniforms.end())
282         {
283                 if(n[n.size()-1]==']')
284                 {
285                         string::size_type open_bracket = n.rfind('[');
286                         if(open_bracket!=string::npos)
287                         {
288                                 /* The requested name looks like an array.  glGetActiveUniform only
289                                 gives us the first element of the array, so try to look that up and
290                                 add an offset. */
291                                 int offset = lexical_cast<unsigned>(n.substr(open_bracket+1, n.size()-2-open_bracket));
292                                 i = uniforms.find(n.substr(0, open_bracket)+"[0]");
293                                 if(i!=uniforms.end() && offset<i->second.size)
294                                         return i->second.location+offset;
295                         }
296                 }
297                 return -1;
298         }
299
300         return i->second.location;
301 }
302
303 void Program::unbind()
304 {
305         if(!set_current(0))
306                 return;
307
308         glUseProgramObjectARB(0);
309 }
310
311
312 Program::StandardFeatures::StandardFeatures():
313         texture(false),
314         material(false),
315         lighting(false),
316         specular(false),
317         normalmap(false),
318         shadow(false),
319         reflection(false),
320         transform(false)
321 { }
322
323 string Program::StandardFeatures::create_flags() const
324 {
325         string flags;
326         if(texture)
327                 flags += 't';
328         if(material)
329                 flags += 'm';
330         if(lighting)
331         {
332                 flags += 'l';
333                 if(specular)
334                         flags += 'p';
335                 if(normalmap)
336                         flags += 'n';
337         }
338         if(shadow)
339                 flags += 's';
340         if(reflection)
341                 flags += 'e';
342         if(transform)
343                 flags += 'r';
344
345         return flags;
346 }
347
348
349 Program::Loader::Loader(Program &p):
350         DataFile::ObjectLoader<Program>(p)
351 {
352         add("attribute",       &Loader::attribute);
353         add("fragment_shader", &Loader::fragment_shader);
354         add("standard",        &Loader::standard);
355         add("vertex_shader",   &Loader::vertex_shader);
356 }
357
358 void Program::Loader::finish()
359 {
360         obj.link();
361 }
362
363 void Program::Loader::attribute(unsigned i, const string &n)
364 {
365         obj.bind_attribute(i, n);
366 }
367
368 void Program::Loader::fragment_shader(const string &src)
369 {
370         obj.attach_shader_owned(new Shader(FRAGMENT_SHADER, src));
371 }
372
373 void Program::Loader::standard()
374 {
375         StandardFeatures feat;
376         load_sub(feat);
377         obj.add_standard_shaders(feat);
378 }
379
380 void Program::Loader::vertex_shader(const string &src)
381 {
382         obj.attach_shader_owned(new Shader(VERTEX_SHADER, src));
383 }
384
385
386 Program::StandardFeatures::Loader::Loader(StandardFeatures &f):
387         DataFile::ObjectLoader<StandardFeatures>(f)
388 {
389         add("lighting",  &StandardFeatures::lighting);
390         add("material",  &StandardFeatures::material);
391         add("normalmap", &StandardFeatures::normalmap);
392         add("shadow",    &StandardFeatures::shadow);
393         add("specular",  &StandardFeatures::specular);
394         add("texture",   &StandardFeatures::texture);
395         add("transform", &StandardFeatures::transform);
396 }
397
398 } // namespace GL
399 } // namespace Msp