3 This file is part of libmspgl
4 Copyright © 2009 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
13 #include "projection.h"
15 #include "shadowmap.h"
23 ShadowMap::ShadowMap(unsigned s, const Scene &c, const Light &l):
30 depth_buf.set_min_filter(LINEAR);
31 depth_buf.storage(DEPTH_COMPONENT, size, size, 0);
32 depth_buf.image(0, DEPTH_COMPONENT, UNSIGNED_BYTE, 0);
33 depth_buf.parameter(GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE);
34 depth_buf.parameter(GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);
35 depth_buf.parameter(GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
36 depth_buf.parameter(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
37 depth_buf.parameter(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
38 fbo.attach(DEPTH_ATTACHMENT, depth_buf, 0);
39 draw_buffer(NO_BUFFER);
40 Framebuffer::unbind();
44 void ShadowMap::set_target(const Vector3 &t, float r)
50 void ShadowMap::set_texture_unit(unsigned u)
55 void ShadowMap::prepare()
57 const Vector4 &lpos=light.get_position();
59 throw Exception("Non-directional lights not supported at the moment");
62 if(abs(lpos.z)>=abs(lpos.x) && abs(lpos.z)>=abs(lpos.y))
64 float d=sqrt(lpos.x*lpos.x+lpos.z*lpos.z);
68 matrix[1]=-lpos.x*lpos.y/d;
70 matrix[9]=-lpos.z*lpos.y/d;
74 float d=sqrt(lpos.x*lpos.x+lpos.y*lpos.y);
78 matrix[1]=-lpos.x*lpos.z/d;
79 matrix[5]=-lpos.y*lpos.z/d;
87 matrix[12]=-(target.x*matrix[0]+target.y*matrix[4]+target.z*matrix[8]);
88 matrix[13]=-(target.x*matrix[1]+target.y*matrix[5]+target.z*matrix[9]);
89 matrix[14]=-(target.x*matrix[2]+target.y*matrix[6]+target.z*matrix[10]);
96 matrix_mode(PROJECTION);
99 ortho(-radius, radius, -radius, radius, -radius, radius);
100 matrix_mode(MODELVIEW);
104 const Framebuffer *old_fbo=Framebuffer::current();
106 clear(DEPTH_BUFFER_BIT);
107 scene.render("shadow");
109 matrix_mode(PROJECTION);
111 matrix_mode(MODELVIEW);
116 Framebuffer::unbind();
119 depth_buf.bind_to(unit);
121 float s_eq[4]={ matrix[0]/diam, matrix[4]/diam, matrix[8]/diam, matrix[12]/diam+0.5 };
122 float t_eq[4]={ matrix[1]/diam, matrix[5]/diam, matrix[9]/diam, matrix[13]/diam+0.5 };
123 float r_eq[4]={ -matrix[2]/diam, -matrix[6]/diam, -matrix[10]/diam, 0.5-matrix[14]/diam-4.0/size };
124 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
125 glTexGenfv(GL_S, GL_EYE_PLANE, s_eq);
126 enable(GL_TEXTURE_GEN_S);
127 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
128 glTexGenfv(GL_T, GL_EYE_PLANE, t_eq);
129 enable(GL_TEXTURE_GEN_T);
130 glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
131 glTexGenfv(GL_R, GL_EYE_PLANE, r_eq);
132 enable(GL_TEXTURE_GEN_R);
134 TexUnit::activate(0);
137 void ShadowMap::cleanup()
139 TexUnit::activate(unit);
141 disable(GL_TEXTURE_GEN_S);
142 disable(GL_TEXTURE_GEN_T);
143 disable(GL_TEXTURE_GEN_R);
144 TexUnit::activate(0);