3 This file is part of libmspgl
4 Copyright © 2009 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
14 #include "shadowmap.h"
22 ShadowMap::ShadowMap(unsigned s, const Scene &c, const Light &l):
29 depth_buf.set_min_filter(LINEAR);
30 depth_buf.set_compare_enabled(true);
31 depth_buf.set_compare_func(LEQUAL);
32 depth_buf.set_wrap(CLAMP_TO_EDGE);
33 depth_buf.storage(DEPTH_COMPONENT, size, size);
34 depth_buf.image(0, DEPTH_COMPONENT, UNSIGNED_BYTE, 0);
35 fbo.attach(DEPTH_ATTACHMENT, depth_buf, 0);
38 void ShadowMap::set_target(const Vector3 &t, float r)
44 void ShadowMap::set_texture_unit(unsigned u)
49 void ShadowMap::prepare()
51 Vector4 lpos = light.get_position();
54 /* XXX Not really proper way to support positional lights, but good
55 enough when the light source is far away */
59 float d = sqrt(lpos.x*lpos.x+lpos.y*lpos.y+lpos.z*lpos.z);
66 if(abs(lpos.z)>=abs(lpos.x) && abs(lpos.z)>=abs(lpos.y))
68 float d = sqrt(lpos.x*lpos.x+lpos.z*lpos.z);
71 matrix[8] = -lpos.x/d;
72 matrix[1] = -lpos.x*lpos.y/d;
74 matrix[9] = -lpos.z*lpos.y/d;
78 float d = sqrt(lpos.x*lpos.x+lpos.y*lpos.y);
79 matrix[0] = -lpos.y/d;
82 matrix[1] = -lpos.x*lpos.z/d;
83 matrix[5] = -lpos.y*lpos.z/d;
91 matrix[12] = -(target.x*matrix[0]+target.y*matrix[4]+target.z*matrix[8]);
92 matrix[13] = -(target.x*matrix[1]+target.y*matrix[5]+target.z*matrix[9]);
93 matrix[14] = -(target.x*matrix[2]+target.y*matrix[6]+target.z*matrix[10]);
100 MatrixStack::Push push_mv(MatrixStack::modelview());
101 MatrixStack::Push push_proj(MatrixStack::projection());
103 MatrixStack::projection() = Matrix::ortho(-radius, radius, -radius, radius, -radius, radius);
104 MatrixStack::modelview() = matrix;
106 Bind bind_fbo(fbo, true);
107 fbo.clear(DEPTH_BUFFER_BIT);
108 scene.render("shadow");
111 depth_buf.bind_to(unit);
112 float diam = radius*2;
113 float s_eq[4] = { matrix[0]/diam, matrix[4]/diam, matrix[8]/diam, matrix[12]/diam+0.5 };
114 float t_eq[4] = { matrix[1]/diam, matrix[5]/diam, matrix[9]/diam, matrix[13]/diam+0.5 };
115 float r_eq[4] = { -matrix[2]/diam, -matrix[6]/diam, -matrix[10]/diam, 0.5-matrix[14]/diam-4.0/size };
116 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
117 glTexGenfv(GL_S, GL_EYE_PLANE, s_eq);
118 enable(GL_TEXTURE_GEN_S);
119 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
120 glTexGenfv(GL_T, GL_EYE_PLANE, t_eq);
121 enable(GL_TEXTURE_GEN_T);
122 glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
123 glTexGenfv(GL_R, GL_EYE_PLANE, r_eq);
124 enable(GL_TEXTURE_GEN_R);
126 TexUnit::activate(0);
129 void ShadowMap::cleanup()
131 Texture::unbind_from(unit);
132 disable(GL_TEXTURE_GEN_S);
133 disable(GL_TEXTURE_GEN_T);
134 disable(GL_TEXTURE_GEN_R);
135 TexUnit::activate(0);