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