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