]> git.tdb.fi Git - libs/gl.git/blob - source/light.cpp
Remove ambient color from Light
[libs/gl.git] / source / light.cpp
1 #include <stdexcept>
2 #include "light.h"
3 #include "misc.h"
4
5 using namespace std;
6
7 namespace Msp {
8 namespace GL {
9
10 unsigned Light::current_unit = 0;
11 vector<const Light *> Light::current_lights(1);
12
13 Light::Light():
14         diffuse(1),
15         specular(1),
16         position(0, 0, 1, 0),
17         spot_dir(0, 0, -1),
18         spot_exp(0),
19         spot_cutoff(180)
20 {
21         attenuation[0] = 1;
22         attenuation[1] = 0;
23         attenuation[2] = 0;
24 }
25
26 void Light::set_diffuse(const Color &c)
27 {
28         diffuse = c;
29 }
30
31 void Light::set_specular(const Color &c)
32 {
33         specular = c;
34 }
35
36 void Light::set_position(const Vector4 &p)
37 {
38         position = p;
39 }
40
41 void Light::set_spot_direction(const Vector3 &d)
42 {
43         spot_dir = d;
44 }
45
46 void Light::set_spot_exponent(float e)
47 {
48         spot_exp = e;
49 }
50
51 void Light::set_spot_cutoff(float c)
52 {
53         spot_cutoff = c;
54 }
55
56 void Light::set_attenuation(float c, float l, float q)
57 {
58         attenuation[0] = c;
59         attenuation[1] = l;
60         attenuation[2] = q;
61 }
62
63 void Light::bind() const
64 {
65         if(current_lights[current_unit]!=this)
66         {
67                 GLenum l = GL_LIGHT0+current_unit;
68                 enable(l);
69                 glLightfv(l, GL_DIFFUSE, &diffuse.r);
70                 glLightfv(l, GL_SPECULAR, &specular.r);
71                 glLightfv(l, GL_POSITION, &position.x);
72                 glLightfv(l, GL_SPOT_DIRECTION, &spot_dir.x);
73                 glLightf(l, GL_SPOT_EXPONENT, spot_exp);
74                 glLightf(l, GL_SPOT_CUTOFF, spot_cutoff);
75                 glLightf(l, GL_CONSTANT_ATTENUATION, attenuation[0]);
76                 glLightf(l, GL_LINEAR_ATTENUATION, attenuation[1]);
77                 glLightf(l, GL_QUADRATIC_ATTENUATION, attenuation[2]);
78                 current_lights[current_unit] = this;
79         }
80 }
81
82 void Light::bind_to(unsigned i) const
83 {
84         activate(i);
85         bind();
86 }
87
88 void Light::activate(unsigned i)
89 {
90         static unsigned max_lights = get_i(GL_MAX_LIGHTS);
91
92         if(i>=max_lights)
93                 throw out_of_range("Light::activate");
94
95         if(i>=current_lights.size())
96                 current_lights.resize(i+1);
97
98         current_unit = i;
99 }
100
101 void Light::unbind()
102 {
103         if(current_lights[current_unit])
104         {
105                 disable(GL_LIGHT0+current_unit);
106                 current_lights[current_unit] = 0;
107         }
108 }
109
110 void Light::unbind_from(unsigned i)
111 {
112         activate(i);
113         unbind();
114 }
115
116 } // namespace GL
117 } // namespace Msp