source: GTP/trunk/App/Demos/Vis/FriendlyCulling/src/ShadowMapping.cpp @ 2917

Revision 2917, 10.7 KB checked in by mattausch, 16 years ago (diff)
Line 
1#include "ShadowMapping.h"
2#include "FrameBufferObject.h"
3#include "RenderState.h"
4#include "RenderTraverser.h"
5#include "Light.h"
6#include "Polygon3.h"
7#include "Polyhedron.h"
8
9#include <IL/il.h>
10#include <assert.h>
11
12
13using namespace std;
14
15
16namespace CHCDemoEngine
17{
18
19
20static Polyhedron *polyhedron = NULL;
21
22
23static void PrintGLerror(char *msg)
24{
25        GLenum errCode;
26        const GLubyte *errStr;
27       
28        if ((errCode = glGetError()) != GL_NO_ERROR)
29        {
30                errStr = gluErrorString(errCode);
31                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
32        }
33}
34
35
36
37static CGprogram sCgShadowProgram;
38static CGparameter sShadowParam;
39
40
41static void GrabDepthBuffer(float *data, GLuint depthTexture)
42{
43        glEnable(GL_TEXTURE_2D);
44        glBindTexture(GL_TEXTURE_2D, depthTexture);
45
46        glGetTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_FLOAT, data);
47
48        glBindTexture(GL_TEXTURE_2D, 0);
49        glDisable(GL_TEXTURE_2D);
50}
51
52
53static void ExportDepthBuffer(float *data, int size)
54{
55        ilInit();
56        assert(ilGetError() == IL_NO_ERROR);
57
58        ILstring filename = ILstring("shadow.tga");
59        ilRegisterType(IL_FLOAT);
60
61        const int depth = 1;
62        const int bpp = 1;
63
64        if (!ilTexImage(size, size, depth, bpp, IL_LUMINANCE, IL_FLOAT, data))
65        {
66                cerr << "IL error " << ilGetError() << endl;
67       
68                ilShutDown();
69                assert(ilGetError() == IL_NO_ERROR);
70
71                return;
72        }
73
74        if (!ilSaveImage(filename))
75        {
76                cerr << "TGA write error " << ilGetError() << endl;
77        }
78
79        ilShutDown();
80        assert(ilGetError() == IL_NO_ERROR);
81
82        cout << "exported depth buffer" << endl;
83}
84
85
86
87ShadowMap::ShadowMap(Light *light, int size, const AxisAlignedBox3 &sceneBox, Camera *cam):
88mSceneBox(sceneBox), mSize(size), mCamera(cam), mLight(light)
89{
90        mFbo = new FrameBufferObject(size, size, FrameBufferObject::DEPTH_32, true);
91        // the diffuse color buffer
92        mFbo->AddColorBuffer(ColorBufferObject::BUFFER_UBYTE, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR, false);
93
94        mShadowCam = new Camera(mSceneBox.Size().x * 0.5f, mSceneBox.Size().y * 0.5f);
95        mShadowCam->SetOrtho(true);
96}
97
98
99ShadowMap::~ShadowMap()
100{
101        DEL_PTR(mFbo);
102        DEL_PTR(mShadowCam);
103}
104
105
106void ShadowMap::DrawPolys()
107{
108        if (!polyhedron) return;
109
110        for (size_t i = 0; i < polyhedron->NumPolygons(); ++ i)
111        {
112                float r = (float)i / polyhedron->NumPolygons();
113                float g = 1;
114                float b = 1;
115
116                glColor3f(r, g, b);
117
118                glBegin(GL_LINE_LOOP);
119
120                Polygon3 *poly = polyhedron->GetPolygons()[i];
121
122                for (size_t j = 0; j < poly->mVertices.size(); ++ j)
123                {
124                        Vector3 v = poly->mVertices[j];
125                        glVertex3d(v.x, v.y, v.z);
126                }
127
128                glEnd();
129        }
130}
131
132
133void ShadowMap::IncludeLightVolume(const Polyhedron &polyhedron,
134                                                                   VertexArray &frustumPoints,
135                                                                   const Vector3 lightDir,
136                                                                   const AxisAlignedBox3 &sceneBox
137                                                                   )
138{
139        // we don't need closed form anymore => just store vertices
140        VertexArray vertices;
141        polyhedron.CollectVertices(vertices);
142
143        // we 'look' at each point and calculate intersections of rays with scene bounding box
144        VertexArray::const_iterator it, it_end = vertices.end();
145
146        for (it = vertices.begin(); it != it_end; ++ it)
147        {
148                Vector3 v  = *it;
149
150                frustumPoints.push_back(v);
151               
152                // hack: get point surely outside of box
153                v -= Magnitude(mSceneBox.Diagonal()) * lightDir;
154
155                SimpleRay ray(v, lightDir);
156
157                float tNear, tFar;
158
159                if (sceneBox.Intersects(ray, tNear, tFar))
160                {
161                        Vector3 newpt = ray.Extrap(tNear);
162                        frustumPoints.push_back(newpt);                 
163                }
164        }
165}
166
167
168float ShadowMap::ComputeN() const
169{
170        const float n = mShadowCam->GetNear();
171        const float f = mShadowCam->GetFar();
172
173        const float d = fabs(f - n);
174       
175        const float dotProd = DotProd(mCamera->GetDirection(), mShadowCam->GetDirection());
176        const float sinGamma = sin(fabs(acos(dotProd)));
177
178        return (n + sqrt(n * (n + d * sinGamma))) /  sinGamma;
179}
180
181
182Matrix4x4 ShadowMap::CalcLispSMTransform(const Matrix4x4 &lightProjView, const AxisAlignedBox3 &extremalPoints)
183{
184        Matrix4x4 lispMtx;
185
186        ///////////////
187        //-- We apply the lispsm algorithm in order to calculate an optimal light projection matrix
188
189        const float n = 1e20f;//ComputeN();
190
191        cout << "n: " << n << endl;
192
193        const Vector3 nearPt = mShadowCam->GetNear() * mShadowCam->GetDirection() + mShadowCam->GetPosition();
194
195        //get the coordinates of the near camera point in light space
196        const Vector3 lsNear = lightProjView * nearPt;
197
198        //c start has the x and y coordinate of e, the z coord of B.min()
199        const Vector3 startPt = Vector3(lsNear.x, lsNear.y, extremalPoints.Min().y);
200
201        // the new projection center
202        const Vector3 unit_y = Vector3(0, 1, 0);
203        Vector3 projCenter = startPt - unit_y * n;
204
205        //construct a translation that moves to the projection center
206        const Matrix4x4 projectionCenter = TranslationMatrix(-projCenter);
207
208        // light space y size
209        const float d = fabs(extremalPoints.Max()[2] - extremalPoints.Min()[2]);
210
211        lispMtx = GetFrustum(-1.0, 1.0, -1.0, 1.0, n, n + d);
212
213        cout << "lispsm\n" << lispMtx << endl;
214
215        lispMtx *= projectionCenter;
216
217        // transform into OpenGL right handed system
218        Matrix4x4 scale = ScaleMatrix(1.0f, 1.0f, -1.0f);
219
220        lispMtx *= scale;
221       
222        return IdentityMatrix();
223}
224
225
226bool ShadowMap::CalcLightProjection(Matrix4x4 &lightProj)
227{
228        DEL_PTR(polyhedron);
229
230
231        ///////////////////
232        //-- First step: calc frustum clipped by scene box
233
234        polyhedron = CalcClippedFrustum(mSceneBox);
235
236        if (!polyhedron) return false; // something is wrong
237
238        // include the part of the light volume that "sees" the frustum
239        // we only require frustum vertices
240
241        VertexArray frustumPoints;
242        IncludeLightVolume(*polyhedron, frustumPoints, mShadowCam->GetDirection(), mSceneBox);
243
244
245        ///////////////
246        //-- transform points from world view to light view and calculate extremal points
247
248        AxisAlignedBox3 extremalPoints;
249        extremalPoints.Initialize();
250
251        Matrix4x4 lightView;
252        mShadowCam->GetModelViewMatrix(lightView);
253
254        VertexArray::const_iterator it, it_end = frustumPoints.end();
255               
256        for (it = frustumPoints.begin(); it != it_end; ++ it)
257        {
258                Vector3 pt = *it;
259                pt = lightView * pt;
260
261                extremalPoints.Include(pt);
262        }
263
264        lightProj = IdentityMatrix(); // we use directional lights
265
266        Matrix4x4 shadowView;
267        mShadowCam->GetModelViewMatrix(shadowView);
268
269        //do Light Space Perspective shadow mapping
270        //rotate the lightspace so that the proj light view always points upwards
271        //calculate a frame matrix that uses the projViewDir[light-space] as up vector
272        //look(from position, into the direction of the projected direction, with unchanged up-vector)
273        //lightProj = Math::look<REAL>(M4(),V3::ZERO(),projViewDir,V3::UNIT_Y())*lightProj
274
275        const Matrix4x4 matLispSM =
276                CalcLispSMTransform(shadowView * lightProj, extremalPoints);
277
278        lightProj *= matLispSM;
279
280        // focus projection matrix on the extremal points => scale to unit cube
281        lightProj *= GetFittingProjectionMatrix(extremalPoints);
282
283        // we have to flip the signs in order tp opengl style projection matrix
284        Matrix4x4 scale = ScaleMatrix(-1, -1, -1);
285        lightProj *= scale;
286       
287        return true;
288}
289
290
291Polyhedron *ShadowMap::CalcClippedFrustum(const AxisAlignedBox3 &box) const
292{
293        Vector3 ftl, ftr, fbl, fbr;
294        Vector3 ntl, ntr, nbl, nbr;
295
296        VertexArray sides[6];
297
298        mCamera->ComputePoints(ftl, ftr, fbl, fbr, ntl, ntr, nbl, nbr);
299
300        for (int i = 0; i < 6; ++ i)
301                sides[i].resize(4);
302       
303        // left, right
304        sides[0][0] = ftl; sides[0][1] = fbl; sides[0][2] = nbl; sides[0][3] = ntl;
305        sides[1][0] = fbr; sides[1][1] = ftr; sides[1][2] = ntr; sides[1][3] = nbr;
306        // bottom, top
307        sides[2][0] = fbl; sides[2][1] = fbr; sides[2][2] = nbr; sides[2][3] = nbl;
308        sides[3][0] = ftr; sides[3][1] = ftl; sides[3][2] = ntl; sides[3][3] = ntr;
309        // near, far
310        sides[4][0] = ntr; sides[4][1] = ntl; sides[4][2] = nbl; sides[4][3] = nbr;
311        sides[5][0] = ftl; sides[5][1] = ftr; sides[5][2] = fbr; sides[5][3] = fbl;
312
313        //////////
314        //-- compute polyhedron
315
316        PolygonContainer polygons;
317
318        for (int i = 0; i < 6; ++ i)
319        {
320                Polygon3 *poly = new Polygon3(sides[i]);
321                polygons.push_back(poly);
322        }
323
324        Polyhedron *p = new Polyhedron(polygons);
325        Polyhedron *clippedPolyhedron = box.CalcIntersection(*p);
326       
327        DEL_PTR(p);
328       
329
330        return clippedPolyhedron;
331}
332
333
334void ShadowMap::ComputeShadowMap(RenderTraverser *renderer, const Matrix4x4 &projView)
335{
336        const float xlen = Magnitude(mSceneBox.Diagonal() * 0.5f);
337        const float ylen = Magnitude(mSceneBox.Diagonal() * 0.5f);
338       
339        const Vector3 dir = mLight->GetDirection();
340        //const Vector3 dir(0, 0, 1);
341
342        mShadowCam->SetDirection(dir);
343       
344        //cout << "lightdir: " << mShadowCam->GetDirection() << endl;
345
346        // set position so that we can see the whole scene
347        Vector3 pos = mSceneBox.Center();
348
349        //Matrix4x4 camView;
350        //mCamera->GetModelViewMatrix(camView);
351
352        pos -= dir * Magnitude(mSceneBox.Diagonal() * 0.5f);
353        mShadowCam->SetPosition(pos);
354
355        mFbo->Bind();
356       
357        glDrawBuffers(1, mrt);
358
359        glPushAttrib(GL_VIEWPORT_BIT);
360        glViewport(0, 0, mSize, mSize);
361
362        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
363
364        glDisable(GL_LIGHTING);
365        glDisable(GL_TEXTURE_2D);
366        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
367
368        glPolygonOffset(1.0f, 2000.0f);
369        glEnable(GL_POLYGON_OFFSET_FILL);
370
371        glShadeModel(GL_FLAT);
372        glEnable(GL_DEPTH_TEST);
373
374        // setup projection
375        /*glMatrixMode(GL_PROJECTION);
376        glLoadIdentity();
377        glOrtho(+xlen, -xlen, +ylen, -ylen, 0.0f, Magnitude(mSceneBox.Diagonal()));
378
379        Matrix4x4 dummyMat;
380        glGetFloatv(GL_PROJECTION_MATRIX, (float *)dummyMat.x);
381        cout << "old:\n" << dummyMat << endl;
382        */
383
384        Matrix4x4 lightView, lightProj;
385
386        mShadowCam->GetModelViewMatrix(lightView);
387        CalcLightProjection(lightProj);
388
389        glMatrixMode(GL_PROJECTION);
390        glPushMatrix();
391        glLoadMatrixf((float *)lightProj.x);
392
393        mLightProjView = lightView * lightProj;
394
395        //cout << "new:\n" << lightProj << endl;
396
397        glMatrixMode(GL_MODELVIEW);
398        glPushMatrix();
399        glLoadIdentity();
400
401        mShadowCam->SetupCameraView();
402
403
404        //////////////
405        //-- compute texture matrix
406        static Matrix4x4 biasMatrix(0.5f, 0.0f, 0.0f, 0.5f,
407                                                                0.0f, 0.5f, 0.0f, 0.5f,
408                                                                0.0f, 0.0f, 0.5f, 0.5f,
409                                                                0.0f, 0.0f, 0.0f, 1.0f);
410
411        mTextureMatrix = mLightProjView * biasMatrix;
412
413
414
415
416        /////////////
417        //-- render scene into shadow map
418
419        renderer->RenderScene();
420
421       
422        glDisable(GL_POLYGON_OFFSET_FILL);
423        glMatrixMode(GL_MODELVIEW);
424        glPopMatrix();
425
426        glMatrixMode(GL_PROJECTION);
427        glPopMatrix();
428
429        glPopAttrib();
430#if 0
431        float *data = new float[mSize * mSize];
432
433        GrabDepthBuffer(data, mFbo->GetDepthTex());
434        ExportDepthBuffer(data, mSize);
435
436        delete [] data;
437       
438        PrintGLerror("shadow map");
439#endif
440        FrameBufferObject::Release();
441}
442
443
444void ShadowMap::GetTextureMatrix(Matrix4x4 &m) const
445{
446        m = mTextureMatrix;
447}
448
449 
450unsigned int ShadowMap::GetShadowTexture() const
451{
452        return mFbo->GetDepthTex();
453}
454
455
456
457} // namespace
Note: See TracBrowser for help on using the repository browser.