]> git.tdb.fi Git - libs/gl.git/blobdiff - source/program.cpp
Complete rewrite of extension handling
[libs/gl.git] / source / program.cpp
index ef1f4c8a63fc0696f363bf21e10b60cb8fe4b80f..adbb5c4cfd1a4ccf7ffd3fe41dc75646c33a1a6c 100644 (file)
-/* $Id$
-
-This file is part of libmspgl
-Copyright © 2007 Mikko Rasa, Mikkosoft Productions
-Distributed under the LGPL
-*/
-
 #include <algorithm>
+#include <cstring>
+#include <msp/core/hash.h>
+#include <msp/core/maputils.h>
+#include <msp/strings/format.h>
 #include "arb_shader_objects.h"
+#include "arb_uniform_buffer_object.h"
 #include "arb_vertex_shader.h"
-#include "except.h"
-#include "extension.h"
+#include "buffer.h"
+#include "error.h"
 #include "program.h"
 #include "shader.h"
 
 using namespace std;
 
+namespace {
+
+const char *standard_vertex_src[] =
+{
+       "n",   "attribute vec3 tangent;\n",
+       "n",   "attribute vec3 binormal;\n",
+       "t|n", "varying vec2 v_texcoord;\n",
+       "s",   "varying vec3 v_shadowcoord;\n",
+       "!lm", "varying vec4 v_color;\n",
+       "l!n", "varying vec3 v_normal;\n",
+       "l",   "varying vec3 v_light_dir;\n",
+       "p|e", "varying vec3 v_eye_dir;\n",
+       "r",   "vec4 transform_vertex(vec4);\n",
+       "lr",  "vec3 transform_normal(vec3);\n",
+        0,    "void main()\n",
+        0,    "{\n",
+       "r",   "\tvec4 eye_pos = transform_vertex(gl_Vertex);\n",
+       "!r",  "\tvec4 eye_pos = gl_ModelViewMatrix*gl_Vertex;\n",
+        0,    "\tgl_Position = gl_ProjectionMatrix*eye_pos;\n",
+       "lr",  "\tvec3 eye_normal = transform_normal(gl_Normal);\n",
+       "l!r", "\tvec3 eye_normal = gl_NormalMatrix*gl_Normal;\n",
+       "l!n", "\tv_normal = eye_normal;\n",
+       "nr",  "\tvec3 eye_tangent = transform_normal(tangent);\n",
+       "n!r", "\tvec3 eye_tangent = gl_NormalMatrix*tangent;\n",
+       "nr",  "\tvec3 eye_binormal = transform_normal(binormal);\n",
+       "n!r", "\tvec3 eye_binormal = gl_NormalMatrix*binormal;\n",
+       "l",   "\tvec3 eye_light_dir = normalize(gl_LightSource[0].position.xyz-eye_pos.xyz*gl_LightSource[0].position.w);\n",
+       "n",   "\tv_light_dir = vec3(dot(eye_tangent, eye_light_dir), dot(eye_binormal, eye_light_dir), dot(eye_normal, eye_light_dir));\n",
+       "l!n", "\tv_light_dir = eye_light_dir;\n",
+       "p|e", "\tvec3 eye_dir = -normalize(eye_pos.xyz);\n",
+       "p|en",  "\tv_eye_dir = vec3(dot(eye_tangent, eye_dir), dot(eye_binormal, eye_dir), dot(eye_normal, eye_dir));\n",
+       "p|e!n", "\tv_eye_dir = eye_dir;\n",
+       "t|n", "\tv_texcoord = gl_MultiTexCoord0.xy;\n",
+       "s",   "\tv_shadowcoord = vec3(dot(gl_EyePlaneS[3], eye_pos), dot(gl_EyePlaneT[3], eye_pos), dot(gl_EyePlaneR[3], eye_pos));\n",
+       "!lm", "\tv_color = gl_Color;\n",
+        0,    "}",
+       0, 0
+};
+
+const char *standard_fragment_src[] =
+{
+       "t",   "uniform sampler2D texture;\n",
+       "n",   "uniform sampler2D normalmap;\n",
+       "s",   "uniform sampler2DShadow shadow;\n",
+       "e",   "uniform samplerCube environment;\n",
+       "e",   "uniform float reflectivity;\n",
+       "t|n", "varying vec2 v_texcoord;\n",
+       "s",   "varying vec3 v_shadowcoord;\n",
+       "!lm", "varying vec4 v_color;\n",
+       "l!n", "varying vec3 v_normal;\n",
+       "l",   "varying vec3 v_light_dir;\n",
+       "p|e", "varying vec3 v_eye_dir;\n",
+        0,    "void main()\n",
+        0,    "{\n",
+       "n",   "\tvec3 n_normal = texture2D(normalmap, v_texcoord).xyz*2.0-1.0;\n",
+       "l!n", "\tvec3 n_normal = normalize(v_normal);\n",
+       "l",   "\tfloat l_diffuse = max(dot(n_normal, normalize(v_light_dir)), 0.0);\n",
+       "p",   "\tvec3 half_dir = normalize(v_eye_dir+v_light_dir);\n",
+       "p",   "\tfloat l_specular = pow(max(dot(half_dir, n_normal), 0.0), gl_FrontMaterial.shininess);\n",
+       "s",   "\tfloat l_shadow = shadow2D(shadow, v_shadowcoord).r;\n",
+       /* XXX This is incorrect with normal mapping, since the vectors are in TBN
+       space but environment map is expected to be in eye space */
+       "e",   "\tvec4 reflection = textureCube(environment, n_normal*(dot(n_normal, v_eye_dir)*2.0)-v_eye_dir);\n",
+       "t",   "\tvec4 tex_sample = texture2D(texture, v_texcoord);\n",
+        0,    "\tgl_FragColor.rgb = ",
+       "!t!l!m", "vec3(1.0)",
+       "t",     "tex_sample.rgb",
+       "l|mt",  "*",
+       "!lm",   "v_color.rgb",
+       "l",     "((l_diffuse",
+       "lm",    "*gl_FrontLightProduct[0].diffuse.rgb",
+       "p",     "+l_specular",
+       "pm",    "*gl_FrontLightProduct[0].specular.rgb",
+       "l",     ")",
+       "s",     "*l_shadow",
+       "lm",    "+gl_FrontLightModelProduct.sceneColor.rgb",
+       "l",     ")",
+       "e",     "+reflection.rgb*reflectivity",
+        0,      ";\n",
+        0,    "\tgl_FragColor.a = ",
+       "!m",    "1.0",
+       "!lm",   "v_color.a",
+       "lm",    "gl_FrontMaterial.diffuse.a",
+       "t",     "*tex_sample.a",
+        0,      ";\n",
+        0,    "}\n",
+       0, 0
+};
+
+}
+
 namespace Msp {
 namespace GL {
 
-Program::Program():
-       del_shaders(false)
+Program::Program()
 {
        init();
 }
 
-Program::Program(const string &vert, const string &frag):
-       del_shaders(true)
+Program::Program(const StandardFeatures &features)
 {
        init();
 
-       attach_shader(*new Shader(VERTEX_SHADER, vert));
-       attach_shader(*new Shader(FRAGMENT_SHADER, frag));
+       add_standard_shaders(features);
+       if(!features.transform)
+               link();
+}
+
+Program::Program(const string &vert, const string &frag)
+{
+       init();
+
+       attach_shader_owned(new Shader(VERTEX_SHADER, vert));
+       attach_shader_owned(new Shader(FRAGMENT_SHADER, frag));
        link();
 }
 
 void Program::init()
 {
-       static RequireExtension _ext("GL_ARB_shader_objects");
+       static Require _req(ARB_shader_objects);
 
        linked = false;
-       id = glCreateProgramObjectARB();
+       id = glCreateProgram();
 }
 
 Program::~Program()
 {
-       if(del_shaders)
-       {
-               for(list<Shader *>::iterator i=shaders.begin(); i!=shaders.end(); ++i)
-                       delete *i;
-       }
-       glDeleteObjectARB(id);
+       for(ShaderList::iterator i=owned_data.begin(); i!=owned_data.end(); ++i)
+               delete *i;
+       glDeleteProgram(id);
 }
 
 void Program::attach_shader(Shader &shader)
 {
        if(find(shaders.begin(), shaders.end(), &shader)==shaders.end())
        {
-               glAttachObjectARB(id, shader.get_id());
+               glAttachShader(id, shader.get_id());
                shaders.push_back(&shader);
        }
 }
 
+void Program::attach_shader_owned(Shader *shader)
+{
+       attach_shader(*shader);
+       if(find(owned_data.begin(), owned_data.end(), shader)==owned_data.end())
+               owned_data.push_back(shader);
+}
+
 void Program::detach_shader(Shader &shader)
 {
-       list<Shader *>::iterator i = remove(shaders.begin(), shaders.end(), &shader);
+       ShaderList::iterator i = remove(shaders.begin(), shaders.end(), &shader);
        if(i!=shaders.end())
        {
                shaders.erase(i, shaders.end());
-               glDetachObjectARB(id, shader.get_id());
+               glDetachShader(id, shader.get_id());
        }
 }
 
-void Program::set_del_shaders(bool ds)
+void Program::add_standard_shaders(const StandardFeatures &features)
 {
-       del_shaders = ds;
+       string flags = features.create_flags();
+       string vertex_src = process_standard_source(standard_vertex_src, flags);
+       string fragment_src = process_standard_source(standard_fragment_src, flags);
+       attach_shader_owned(new Shader(VERTEX_SHADER, vertex_src));
+       attach_shader_owned(new Shader(FRAGMENT_SHADER, fragment_src));
+}
+
+string Program::process_standard_source(const char **source, const string &flags)
+{
+       string result;
+
+       for(unsigned i=0; source[i+1]; i+=2)
+       {
+               if(source[i])
+               {
+                       bool cond = true;
+                       char oper = '&';
+                       for(const char *c=source[i]; *c; ++c)
+                       {
+                               if(*c>='a' && *c<='z')
+                               {
+                                       bool found = (flags.find(*c)!=string::npos);
+                                       if(oper=='|')
+                                               cond = (cond || found);
+                                       else if(oper=='!')
+                                               cond = (cond && !found);
+                                       else if(oper=='&')
+                                               cond = (cond && found);
+                                       oper = '&';
+                               }
+                               else
+                                       oper = *c;
+                       }
+
+                       if(!cond)
+                               continue;
+               }
+
+               result += source[i+1];
+       }
+
+       return result;
 }
 
 void Program::bind_attribute(unsigned index, const string &name)
 {
-       static RequireExtension _ext("GL_ARB_vertex_shader");
-       glBindAttribLocationARB(id, index, name.c_str());
+       static Require _req(ARB_vertex_shader);
+       glBindAttribLocation(id, index, name.c_str());
 }
 
 void Program::link()
 {
-       for(list<Shader *>::iterator i=shaders.begin(); i!=shaders.end(); ++i)
-               if(!(*i)->get_compiled())
+       for(ShaderList::iterator i=shaders.begin(); i!=shaders.end(); ++i)
+               if(!(*i)->is_compiled())
                        (*i)->compile();
 
-       glLinkProgramARB(id);
-       if(!(linked = get_param(GL_LINK_STATUS)))
-               throw CompileError(get_info_log());
+       uniforms.clear();
+
+       glLinkProgram(id);
+       int value;
+       glGetProgramiv(id, GL_LINK_STATUS, &value);
+       if(!(linked = value))
+               throw compile_error(get_info_log());
+
+       glGetProgramiv(id, GL_ACTIVE_UNIFORMS, &value);
+       unsigned count = value;
+       vector<UniformInfo *> uniforms_by_index(count);
+       for(unsigned i=0; i<count; ++i)
+       {
+               char name[128];
+               int len = 0;
+               int size;
+               GLenum type;
+               glGetActiveUniform(id, i, 128, &len, &size, &type, name);
+               if(len && strncmp(name, "gl_", 3))
+               {
+                       UniformInfo &info = uniforms[name];
+                       info.block = 0;
+                       info.name = name;
+                       info.size = size;
+                       info.array_stride = 0;
+                       info.matrix_stride = 0;
+                       info.type = type;
+                       uniforms_by_index[i] = &info;
+               }
+       }
+
+       if(ARB_uniform_buffer_object)
+       {
+               glGetProgramiv(id, GL_ACTIVE_UNIFORM_BLOCKS, &value);
+               count = value;
+               for(unsigned i=0; i<count; ++i)
+               {
+                       char name[128];
+                       int len;
+                       glGetActiveUniformBlockName(id, i, 128, &len, name);
+                       UniformBlockInfo &info = uniform_blocks[name];
+                       info.name = name;
+
+                       glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_DATA_SIZE, &value);
+                       info.data_size = value;
+
+                       glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &value);
+                       vector<int> indices(value);
+                       glGetActiveUniformBlockiv(id, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &indices[0]);
+                       for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
+                       {
+                               if(!uniforms_by_index[*j])
+                                       throw logic_error("Program::link");
+                               info.uniforms.push_back(uniforms_by_index[*j]);
+                               uniforms_by_index[*j]->block = &info;
+                       }
+
+                       vector<unsigned> indices2(indices.begin(), indices.end());
+                       vector<int> values(indices.size());
+                       glGetActiveUniformsiv(id, indices.size(), &indices2[0], GL_UNIFORM_OFFSET, &values[0]);
+                       for(unsigned j=0; j<indices.size(); ++j)
+                               uniforms_by_index[indices[j]]->location = values[j];
+
+                       indices2.clear();
+                       for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
+                               if(uniforms_by_index[*j]->size>1)
+                                       indices2.push_back(*j);
+                       if(!indices2.empty())
+                       {
+                               glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_ARRAY_STRIDE, &values[0]);
+                               for(unsigned j=0; j<indices2.size(); ++j)
+                                       uniforms_by_index[indices[j]]->array_stride = values[j];
+                       }
+
+                       indices2.clear();
+                       for(vector<int>::iterator j=indices.begin(); j!=indices.end(); ++j)
+                       {
+                               GLenum t = uniforms_by_index[*j]->type;
+                               if(t==GL_FLOAT_MAT4 || t==GL_FLOAT_MAT3 || t==GL_FLOAT_MAT2 ||
+                                       t==GL_FLOAT_MAT2x3 || t==GL_FLOAT_MAT2x4 || t==GL_FLOAT_MAT3x2 ||
+                                       t==GL_FLOAT_MAT3x4 || t==GL_FLOAT_MAT4x2 || t==GL_FLOAT_MAT4x3)
+                                       indices2.push_back(*j);
+                       }
+                       if(!indices2.empty())
+                       {
+                               glGetActiveUniformsiv(id, indices2.size(), &indices2[0], GL_UNIFORM_MATRIX_STRIDE, &values[0]);
+                               for(unsigned j=0; j<indices2.size(); ++j)
+                                       uniforms_by_index[indices[j]]->matrix_stride = values[j];
+                       }
+
+                       sort(info.uniforms.begin(), info.uniforms.end(), uniform_location_compare);
+                       info.layout_hash = compute_layout_hash(info.uniforms);
+                       info.bind_point = info.layout_hash%BufferRange::get_n_uniform_buffer_bindings();
+                       glUniformBlockBinding(id, i, info.bind_point);
+               }
+       }
+
+       vector<const UniformInfo *> blockless_uniforms;
+       for(UniformMap::iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
+               if(!i->second.block)
+               {
+                       i->second.location = glGetUniformLocation(id, i->second.name.c_str());
+                       blockless_uniforms.push_back(&i->second);
+               }
+
+       uniform_layout_hash = compute_layout_hash(blockless_uniforms);
 }
 
-int Program::get_param(GLenum param) const
+unsigned Program::compute_layout_hash(const vector<const UniformInfo *> &uniforms)
 {
-       int value;
-       glGetObjectParameterivARB(id, param, &value);
-       return value;
+       string layout_descriptor;
+       for(vector<const UniformInfo *>::const_iterator i = uniforms.begin(); i!=uniforms.end(); ++i)
+               layout_descriptor += format("%d:%s:%x:%d\n", (*i)->location, (*i)->name, (*i)->type, (*i)->size);
+       return hash32(layout_descriptor);
 }
 
-string Program::get_info_log() const
+bool Program::uniform_location_compare(const UniformInfo *uni1, const UniformInfo *uni2)
 {
-       GLsizei len = get_param(GL_INFO_LOG_LENGTH);
-       char log[len+1];
-       glGetInfoLogARB(id, len+1, &len, log);
-       return string(log, len);
+       return uni1->location<uni2->location;
 }
 
-void Program::bind() const
+string Program::get_info_log() const
 {
-       if(!linked)
-               throw InvalidState("Program is not linked");
+       GLsizei len = 0;
+       glGetProgramiv(id, GL_INFO_LOG_LENGTH, &len);
+       char *buf = new char[len+1];
+       glGetProgramInfoLog(id, len+1, &len, buf);
+       string log(buf, len);
+       delete[] buf;
+       return log;
+}
 
-       glUseProgramObjectARB(id);
-       cur_prog = this;
+const Program::UniformBlockInfo &Program::get_uniform_block_info(const string &name) const
+{
+       return get_item(uniform_blocks, name);
 }
 
-int Program::get_uniform_location(const string &n) const
+const Program::UniformInfo &Program::get_uniform_info(const string &name) const
 {
-       return glGetUniformLocationARB(id, n.c_str());
+       return get_item(uniforms, name);
 }
 
-void Program::unbind()
+int Program::get_uniform_location(const string &n) const
 {
-       if(cur_prog)
+       UniformMap::const_iterator i = uniforms.find(n);
+       if(i==uniforms.end())
        {
-               glUseProgramObjectARB(0);
-               cur_prog = 0;
+               if(n[n.size()-1]==']')
+               {
+                       string::size_type open_bracket = n.rfind('[');
+                       if(open_bracket!=string::npos)
+                       {
+                               /* The requested name looks like an array.  glGetActiveUniform only
+                               gives us the first element of the array, so try to look that up and
+                               add an offset. */
+                               unsigned offset = lexical_cast<unsigned>(n.substr(open_bracket+1, n.size()-2-open_bracket));
+                               i = uniforms.find(n.substr(0, open_bracket)+"[0]");
+                               if(i!=uniforms.end() && !i->second.block && offset<i->second.size)
+                                       return i->second.location+offset;
+                       }
+               }
+               return -1;
        }
+
+       return i->second.block ? -1 : i->second.location;
 }
 
-void Program::maybe_bind()
+void Program::bind() const
 {
-       if(cur_prog!=this)
-               bind();
+       if(!linked)
+               throw invalid_operation("Program::bind");
+
+       if(!set_current(this))
+               return;
+
+       glUseProgram(id);
 }
 
-const Program *Program::cur_prog = 0;
+void Program::unbind()
+{
+       if(!set_current(0))
+               return;
+
+       glUseProgram(0);
+}
+
+
+Program::StandardFeatures::StandardFeatures():
+       texture(false),
+       material(false),
+       lighting(false),
+       specular(false),
+       normalmap(false),
+       shadow(false),
+       reflection(false),
+       transform(false)
+{ }
+
+string Program::StandardFeatures::create_flags() const
+{
+       string flags;
+       if(texture)
+               flags += 't';
+       if(material)
+               flags += 'm';
+       if(lighting)
+       {
+               flags += 'l';
+               if(specular)
+                       flags += 'p';
+               if(normalmap)
+                       flags += 'n';
+       }
+       if(shadow)
+               flags += 's';
+       if(reflection)
+               flags += 'e';
+       if(transform)
+               flags += 'r';
+
+       return flags;
+}
 
 
 Program::Loader::Loader(Program &p):
        DataFile::ObjectLoader<Program>(p)
 {
-       obj.set_del_shaders(true);
-
-       add("vertex_shader",   &Loader::vertex_shader);
-       add("fragment_shader", &Loader::fragment_shader);
        add("attribute",       &Loader::attribute);
+       add("fragment_shader", &Loader::fragment_shader);
+       add("standard",        &Loader::standard);
+       add("vertex_shader",   &Loader::vertex_shader);
 }
 
-void Program::Loader::vertex_shader(const string &src)
+void Program::Loader::finish()
+{
+       obj.link();
+}
+
+void Program::Loader::attribute(unsigned i, const string &n)
 {
-       obj.attach_shader(*new Shader(VERTEX_SHADER, src));
+       obj.bind_attribute(i, n);
 }
 
 void Program::Loader::fragment_shader(const string &src)
 {
-       obj.attach_shader(*new Shader(FRAGMENT_SHADER, src));
+       obj.attach_shader_owned(new Shader(FRAGMENT_SHADER, src));
 }
 
-void Program::Loader::attribute(unsigned i, const string &n)
+void Program::Loader::standard()
 {
-       obj.bind_attribute(i, n);
+       StandardFeatures feat;
+       load_sub(feat);
+       obj.add_standard_shaders(feat);
 }
 
-void Program::Loader::finish()
+void Program::Loader::vertex_shader(const string &src)
 {
-       obj.link();
+       obj.attach_shader_owned(new Shader(VERTEX_SHADER, src));
+}
+
+
+Program::StandardFeatures::Loader::Loader(StandardFeatures &f):
+       DataFile::ObjectLoader<StandardFeatures>(f)
+{
+       add("lighting",  &StandardFeatures::lighting);
+       add("material",  &StandardFeatures::material);
+       add("normalmap", &StandardFeatures::normalmap);
+       add("shadow",    &StandardFeatures::shadow);
+       add("specular",  &StandardFeatures::specular);
+       add("texture",   &StandardFeatures::texture);
+       add("transform", &StandardFeatures::transform);
 }
 
 } // namespace GL