]> git.tdb.fi Git - libs/gl.git/blob - source/material.cpp
Give materials the capability to automatically create a suitable shader
[libs/gl.git] / source / material.cpp
1 #include <msp/core/hash.h>
2 #include <msp/strings/format.h>
3 #include "basicmaterial.h"
4 #include "gl.h"
5 #include "resources.h"
6 #include "texturing.h"
7 #include "uniform.h"
8
9 using namespace std;
10
11 namespace Msp {
12 namespace GL {
13
14 Program *Material::create_compatible_shader() const
15 {
16         return new Program(create_program_source());
17 }
18
19 const Program *Material::create_compatible_shader(DataFile::Collection &coll) const
20 {
21         string source = create_program_source();
22         string name = format("_material_%016x.glsl", hash64(source));
23         Program *shprog = coll.find<Program>(name);
24         if(shprog)
25                 return shprog;
26
27         shprog = new Program(create_program_source());
28         try
29         {
30                 coll.add(name, shprog);
31         }
32         catch(...)
33         {
34                 delete shprog;
35                 throw;
36         }
37
38         return shprog;
39 }
40
41 void Material::attach_texture_to(const Texture *tex, Texturing &texturing, ProgramData &tex_shdata, const string &name) const
42 {
43         if(!tex)
44                 return;
45
46         int unit = -1;
47
48         if(const Uniform *uni = tex_shdata.find_uniform(name))
49                 if(const Uniform1i *uni_int = dynamic_cast<const Uniform1i *>(uni))
50                         unit = uni_int->get();
51
52         if(unit<0)
53                 unit = texturing.find_free_unit(name);
54         if(unit<0)
55                 throw runtime_error("no free texunit");
56
57         texturing.attach(unit, *tex);
58         tex_shdata.uniform(name, unit);
59 }
60
61 Material::MaterialRegistry &Material::get_material_registry()
62 {
63         static MaterialRegistry registry;
64         static bool initialized = false;
65         if(!initialized)
66         {
67                 registry.register_type<BasicMaterial>("basic");
68         }
69         return registry;
70 }
71
72
73 DataFile::Loader::ActionMap Material::GenericLoader::shared_actions;
74
75 Material::GenericLoader::GenericLoader(DataFile::Collection *c):
76         coll(c)
77 {
78         set_actions(shared_actions);
79 }
80
81 void Material::GenericLoader::init_actions()
82 {
83         get_material_registry().add_all(*this);
84 }
85
86 } // namespace GL
87 } // namespace Msp