]> git.tdb.fi Git - libs/gl.git/blob - source/program.cpp
1343c00f48cf0556984d65ff7db245a7628d3b7e
[libs/gl.git] / source / program.cpp
1 /* $Id$
2
3 This file is part of libmspgl
4 Copyright © 2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <algorithm>
9 #include "arb_shader_objects.h"
10 #include "arb_vertex_shader.h"
11 #include "except.h"
12 #include "extension.h"
13 #include "program.h"
14 #include "shader.h"
15
16 using namespace std;
17
18 namespace {
19
20 const char *standard_vertex_src[] =
21 {
22         "n",   "attribute vec3 tangent;\n",
23         "n",   "attribute vec3 binormal;\n",
24         "t|n", "varying vec2 v_texcoord;\n",
25         "s",   "varying vec3 v_shadowcoord;\n",
26         "!lm", "varying vec4 v_color;\n",
27         "l!n", "varying vec3 v_normal;\n",
28         "l",   "varying vec3 v_light_dir;\n",
29         "p",   "varying vec3 v_eye_dir;\n",
30          0,    "void main()\n",
31          0,    "{\n",
32          0,    "\tvec4 eye_pos = gl_ModelViewMatrix*gl_Vertex;\n",
33          0,    "\tgl_Position = gl_ProjectionMatrix*eye_pos;\n",
34         "l",   "\tvec3 eye_normal = gl_NormalMatrix*gl_Normal;\n",
35         "l!n", "\tv_normal = eye_normal;\n",
36         "n",   "\tvec3 eye_tangent = gl_NormalMatrix*tangent;\n",
37         "n",   "\tvec3 eye_binormal = gl_NormalMatrix*binormal;\n",
38         "l",   "\tvec3 eye_light_dir = normalize(gl_LightSource[0].position.xyz-eye_pos.xyz*gl_LightSource[0].position.w);\n",
39         "n",   "\tv_light_dir = vec3(dot(eye_tangent, eye_light_dir), dot(eye_binormal, eye_light_dir), dot(eye_normal, eye_light_dir));\n",
40         "l!n", "\tv_light_dir = eye_light_dir;\n",
41         "p",   "\tvec3 eye_dir = -normalize(eye_pos.xyz);\n",
42         "pn",  "\tv_eye_dir = vec3(dot(eye_tangent, eye_dir), dot(eye_binormal, eye_dir), dot(eye_normal, eye_dir));\n",
43         "p!n", "\tv_eye_dir = eye_dir;\n",
44         "t|n", "\tv_texcoord = gl_MultiTexCoord0.xy;\n",
45         "s",   "\tv_shadowcoord = vec3(dot(gl_EyePlaneS[3], eye_pos), dot(gl_EyePlaneT[3], eye_pos), dot(gl_EyePlaneR[3], eye_pos));\n",
46         "!lm", "\tv_color = gl_Color;\n",
47          0,    "}",
48         0, 0
49 };
50
51 const char *standard_fragment_src[] =
52 {
53         "t",   "uniform sampler2D texture;\n",
54         "n",   "uniform sampler2D normalmap;\n",
55         "s",   "uniform sampler2DShadow shadow;\n",
56         "t|n", "varying vec2 v_texcoord;\n",
57         "s",   "varying vec3 v_shadowcoord;\n",
58         "!lm", "varying vec4 v_color;\n",
59         "l!n", "varying vec3 v_normal;\n",
60         "l",   "varying vec3 v_light_dir;\n",
61         "p",   "varying vec3 v_eye_dir;\n",
62          0,    "void main()\n",
63          0,    "{\n",
64         "n",   "\tvec3 n_normal = texture2D(normalmap, v_texcoord).xyz*2.0-1.0;\n",
65         "l!n", "\tvec3 n_normal = normalize(v_normal);\n",
66         "l",   "\tfloat l_diffuse = max(dot(n_normal, normalize(v_light_dir)), 0.0);\n",
67         "p",   "\tvec3 half = normalize(v_eye_dir+v_light_dir);\n",
68         "p",   "\tfloat l_specular = pow(max(dot(half, n_normal), 0.0), gl_FrontMaterial.shininess);\n",
69         "s",   "\tfloat l_shadow = shadow2D(shadow, v_shadowcoord).r;\n",
70          0,    "\tgl_FragColor = ",
71         "!t!l!m", "vec4(1.0, 1.0, 1.0, 1.0)",
72         "t",     "texture2D(texture, v_texcoord)",
73         "l|mt",  "*",
74         "!lm",   "v_color",
75         "l",     "((l_diffuse",
76         "lm",    "*gl_FrontLightProduct[0].diffuse",
77         "p",     "+l_specular",
78         "pm",    "*gl_FrontLightProduct[0].specular",
79         "l",     ")",
80         "s",     "*l_shadow",
81         "lm",    "+gl_FrontLightModelProduct.sceneColor",
82         "l",     ")",
83          0,      ";\n",
84          0,    "}\n",
85         0, 0
86 };
87
88 }
89
90 namespace Msp {
91 namespace GL {
92
93 Program::Program():
94         del_shaders(false)
95 {
96         init();
97 }
98
99 Program::Program(const StandardFeatures &features):
100         del_shaders(true)
101 {
102         init();
103
104         add_standard_shaders(features);
105         link();
106 }
107
108 Program::Program(const string &vert, const string &frag):
109         del_shaders(true)
110 {
111         init();
112
113         attach_shader(*new Shader(VERTEX_SHADER, vert));
114         attach_shader(*new Shader(FRAGMENT_SHADER, frag));
115         link();
116 }
117
118 void Program::init()
119 {
120         static RequireExtension _ext("GL_ARB_shader_objects");
121
122         linked = false;
123         id = glCreateProgramObjectARB();
124 }
125
126 Program::~Program()
127 {
128         if(del_shaders)
129         {
130                 for(list<Shader *>::iterator i=shaders.begin(); i!=shaders.end(); ++i)
131                         delete *i;
132         }
133         glDeleteObjectARB(id);
134 }
135
136 void Program::attach_shader(Shader &shader)
137 {
138         if(find(shaders.begin(), shaders.end(), &shader)==shaders.end())
139         {
140                 glAttachObjectARB(id, shader.get_id());
141                 shaders.push_back(&shader);
142         }
143 }
144
145 void Program::detach_shader(Shader &shader)
146 {
147         list<Shader *>::iterator i = remove(shaders.begin(), shaders.end(), &shader);
148         if(i!=shaders.end())
149         {
150                 shaders.erase(i, shaders.end());
151                 glDetachObjectARB(id, shader.get_id());
152         }
153 }
154
155 void Program::add_standard_shaders(const StandardFeatures &features)
156 {
157         string flags = features.create_flags();
158         string vertex_src = process_standard_source(standard_vertex_src, flags);
159         string fragment_src = process_standard_source(standard_fragment_src, flags);
160         attach_shader(*new Shader(VERTEX_SHADER, vertex_src));
161         attach_shader(*new Shader(FRAGMENT_SHADER, fragment_src));
162 }
163
164 string Program::process_standard_source(const char **source, const string &flags)
165 {
166         string result;
167
168         for(unsigned i=0; source[i+1]; i+=2)
169         {
170                 if(source[i])
171                 {
172                         bool cond = true;
173                         char oper = '&';
174                         for(const char *c=source[i]; *c; ++c)
175                         {
176                                 if(*c>='a' && *c<='z')
177                                 {
178                                         bool found = (flags.find(*c)!=string::npos);
179                                         if(oper=='|')
180                                                 cond = (cond || found);
181                                         else if(oper=='!')
182                                                 cond = (cond && !found);
183                                         else if(oper=='&')
184                                                 cond = (cond && found);
185                                         oper = '&';
186                                 }
187                                 else
188                                         oper = *c;
189                         }
190
191                         if(!cond)
192                                 continue;
193                 }
194
195                 result += source[i+1];
196         }
197
198         return result;
199 }
200
201 void Program::set_del_shaders(bool ds)
202 {
203         del_shaders = ds;
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 CompileError(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 log[len+1];
247         glGetInfoLogARB(id, len+1, &len, log);
248         return string(log, len);
249 }
250
251 void Program::bind() const
252 {
253         if(!linked)
254                 throw InvalidState("Program is not linked");
255
256         if(!set_current(this))
257                 return;
258
259         glUseProgramObjectARB(id);
260 }
261
262 int Program::get_uniform_location(const string &n) const
263 {
264         map<string, UniformInfo>::const_iterator i = uniforms.find(n);
265         if(i==uniforms.end())
266                 return -1;
267
268         return i->second.location;
269 }
270
271 void Program::unbind()
272 {
273         if(!set_current(0))
274                 return;
275
276         glUseProgramObjectARB(0);
277 }
278
279
280 Program::StandardFeatures::StandardFeatures():
281         texture(false),
282         material(false),
283         lighting(false),
284         specular(false),
285         normalmap(false),
286         shadow(false)
287 { }
288
289 string Program::StandardFeatures::create_flags() const
290 {
291         string flags;
292         if(texture)
293                 flags += 't';
294         if(material)
295                 flags += 'm';
296         if(lighting)
297         {
298                 flags += 'l';
299                 if(specular)
300                         flags += 'p';
301                 if(normalmap)
302                         flags += 'n';
303         }
304         if(shadow)
305                 flags += 's';
306
307         return flags;
308 }
309
310
311 Program::Loader::Loader(Program &p):
312         DataFile::ObjectLoader<Program>(p)
313 {
314         obj.set_del_shaders(true);
315
316         add("attribute",       &Loader::attribute);
317         add("fragment_shader", &Loader::fragment_shader);
318         add("standard",        &Loader::standard);
319         add("vertex_shader",   &Loader::vertex_shader);
320 }
321
322 void Program::Loader::finish()
323 {
324         obj.link();
325 }
326
327 void Program::Loader::attribute(unsigned i, const string &n)
328 {
329         obj.bind_attribute(i, n);
330 }
331
332 void Program::Loader::fragment_shader(const string &src)
333 {
334         obj.attach_shader(*new Shader(FRAGMENT_SHADER, src));
335 }
336
337 void Program::Loader::standard()
338 {
339         StandardFeatures feat;
340         load_sub(feat);
341         obj.add_standard_shaders(feat);
342 }
343
344 void Program::Loader::vertex_shader(const string &src)
345 {
346         obj.attach_shader(*new Shader(VERTEX_SHADER, src));
347 }
348
349
350 Program::StandardFeatures::Loader::Loader(StandardFeatures &f):
351         DataFile::ObjectLoader<StandardFeatures>(f)
352 {
353         add("lighting",  &StandardFeatures::lighting);
354         add("material",  &StandardFeatures::material);
355         add("normalmap", &StandardFeatures::normalmap);
356         add("shadow",    &StandardFeatures::shadow);
357         add("specular",  &StandardFeatures::specular);
358         add("texture",   &StandardFeatures::texture);
359 }
360
361 } // namespace GL
362 } // namespace Msp