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

Revision 2916, 11.4 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)
183{/*
184        Matrix4x4 lispMtx = IdentityMatrix();
185
186        const float dotProd = DotProd(mCamera->GetDirection(), mShadowCam->GetDirection());
187        const float sinGamma = sqrt(1.0f - dotProd * dotProd);
188
189
190        ///////////////////
191        //-- First step: calc frustum clipped by scene box
192
193        DEL_PTR(polyhedron);
194        polyhedron = CalcClippedFrustum(mSceneBox);
195
196        if (!polyhedron) return false; // something is wrong
197
198        // include the part of the light volume that "sees" the frustum
199        // we only require frustum vertices
200
201        VertexArray frustumPoints;
202        IncludeLightVolume(*polyhedron, frustumPoints, mShadowCam->GetDirection(), mSceneBox);
203
204
205        ///////////////
206        //-- transform points from world view to light view and calculate extremal points
207
208        AxisAlignedBox3 extremalPoints;
209        extremalPoints.Initialize();
210
211        Matrix4x4 lightView;
212        mShadowCam->GetModelViewMatrix(lightView);
213
214        VertexArray::const_iterator it, it_end = frustumPoints.end();
215               
216        for (it = frustumPoints.begin(); it != it_end; ++ it)
217        {
218                Vector3 pt = *it;
219                pt = lightView * pt;
220
221                extremalPoints.Include(pt);
222        }
223
224
225        ///////////////
226        //-- We apply the lispsm algorithm in order to calculate an optimal light projection matrix
227
228        const float n = 1e20f;//ComputeN();
229
230        cout << "n: " << n << endl;
231
232        const Vector3 nearPt = mShadowCam->GetNear() * mShadowCam->GetDirection() + mShadowCam->GetPosition();
233
234        //get the coordinates of the near camera point in light space
235        const Vector3 lsNear = lightView * nearPt;
236
237        //c start has the x and y coordinate of e, the z coord of B.min()
238        const Vector3 startPt = Vector3(lsNear.x, lsNear.y, extremalPoints.Min().y);
239
240        // the new projection center
241        const Vector3 unit_y = Vector3(0, 1, 0);
242        Vector3 projCenter = startPt - unit_y * n;
243
244        //construct a translation that moves to the projection center
245        const Matrix4x4 projectionCenter = TranslationMatrix(-projCenter);
246
247        // light space y size
248        const float d = fabs(extremalPoints.Max()[2] - extremalPoints.Min()[2]);
249
250        lightProj = GetFrustum(-1.0, 1.0, -1.0, 1.0, n, n + d);
251
252        cout << "here4\n" << lightProj << endl;
253
254        // transform into OpenGL right handed system
255        Matrix4x4 scale = ScaleMatrix(1.0f, 1.0f, -1.0f);
256
257        lightProj = projectionCenter * scale * lightProj;
258
259        Vector3 pmax = extremalPoints.Max();
260        Vector3 pmin = extremalPoints.Min();
261
262        cout << "min: " << lightProj * pmin << endl;
263        cout << "max: " << lightProj * pmax << endl;
264       
265*/
266        return IdentityMatrix();
267}
268
269
270bool ShadowMap::CalcLightProjection(Matrix4x4 &lightProj)
271{
272        DEL_PTR(polyhedron);
273
274
275        ///////////////////
276        //-- First step: calc frustum clipped by scene box
277
278        polyhedron = CalcClippedFrustum(mSceneBox);
279
280        if (!polyhedron) return false; // something is wrong
281
282        // include the part of the light volume that "sees" the frustum
283        // we only require frustum vertices
284
285        VertexArray frustumPoints;
286        IncludeLightVolume(*polyhedron, frustumPoints, mShadowCam->GetDirection(), mSceneBox);
287
288
289        ///////////////
290        //-- transform points from world view to light view and calculate extremal points
291
292        AxisAlignedBox3 extremalPoints;
293        extremalPoints.Initialize();
294
295        Matrix4x4 lightView;
296        mShadowCam->GetModelViewMatrix(lightView);
297
298        VertexArray::const_iterator it, it_end = frustumPoints.end();
299               
300        for (it = frustumPoints.begin(); it != it_end; ++ it)
301        {
302                Vector3 pt = *it;
303                pt = lightView * pt;
304
305                extremalPoints.Include(pt);
306        }
307
308        //Matrix4x4 m = CalcLispSMTransform(lightProj);
309
310        // focus projection matrix on the extremal points
311        lightProj = GetFittingProjectionMatrix(extremalPoints);
312
313        //Matrix4x4 scale = ScaleMatrix(1, 1, -1); lightProj *= scale;
314       
315        return true;
316}
317
318
319Polyhedron *ShadowMap::CalcClippedFrustum(const AxisAlignedBox3 &box) const
320{
321        Vector3 ftl, ftr, fbl, fbr;
322        Vector3 ntl, ntr, nbl, nbr;
323
324        VertexArray sides[6];
325
326        mCamera->ComputePoints(ftl, ftr, fbl, fbr, ntl, ntr, nbl, nbr);
327
328        for (int i = 0; i < 6; ++ i)
329                sides[i].resize(4);
330       
331        // left, right
332        sides[0][0] = ftl; sides[0][1] = fbl; sides[0][2] = nbl; sides[0][3] = ntl;
333        sides[1][0] = fbr; sides[1][1] = ftr; sides[1][2] = ntr; sides[1][3] = nbr;
334        // bottom, top
335        sides[2][0] = fbl; sides[2][1] = fbr; sides[2][2] = nbr; sides[2][3] = nbl;
336        sides[3][0] = ftr; sides[3][1] = ftl; sides[3][2] = ntl; sides[3][3] = ntr;
337        // near, far
338        sides[4][0] = ntr; sides[4][1] = ntl; sides[4][2] = nbl; sides[4][3] = nbr;
339        sides[5][0] = ftl; sides[5][1] = ftr; sides[5][2] = fbr; sides[5][3] = fbl;
340
341        //sides[4][0] = ntl; sides[4][1] = ntr; sides[4][2] = nbr; sides[4][3] = nbl;
342        //sides[5][0] = ftr; sides[5][1] = ftl; sides[5][2] = fbl; sides[5][3] = fbr;
343
344
345
346        //////////
347        //-- compute polyhedron
348
349        PolygonContainer polygons;
350
351        for (int i = 0; i < 6; ++ i)
352        {
353                Polygon3 *poly = new Polygon3(sides[i]);
354                polygons.push_back(poly);
355        }
356
357        Polyhedron *p = new Polyhedron(polygons);
358        Polyhedron *clippedPolyhedron = box.CalcIntersection(*p);
359       
360        DEL_PTR(p);
361       
362
363        return clippedPolyhedron;
364}
365
366
367void ShadowMap::ComputeShadowMap(RenderTraverser *renderer, const Matrix4x4 &projView)
368{
369        const float xlen = Magnitude(mSceneBox.Diagonal() * 0.5f);
370        const float ylen = Magnitude(mSceneBox.Diagonal() * 0.5f);
371       
372        const Vector3 dir = mLight->GetDirection();
373        //const Vector3 dir(0, 0, 1);
374
375        mShadowCam->SetDirection(dir);
376       
377        //cout << "lightdir: " << mShadowCam->GetDirection() << endl;
378
379        // set position so that we can see the whole scene
380        Vector3 pos = mSceneBox.Center();
381
382        //Matrix4x4 camView;
383        //mCamera->GetModelViewMatrix(camView);
384
385        pos -= dir * Magnitude(mSceneBox.Diagonal() * 0.5f);
386        mShadowCam->SetPosition(pos);
387
388        mFbo->Bind();
389       
390        glDrawBuffers(1, mrt);
391
392        glPushAttrib(GL_VIEWPORT_BIT);
393        glViewport(0, 0, mSize, mSize);
394
395        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
396
397        glDisable(GL_LIGHTING);
398        glDisable(GL_TEXTURE_2D);
399        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
400
401        glPolygonOffset(1.0f, 2000.0f);
402        glEnable(GL_POLYGON_OFFSET_FILL);
403
404        glShadeModel(GL_FLAT);
405        glEnable(GL_DEPTH_TEST);
406
407        // setup projection
408        /*glMatrixMode(GL_PROJECTION);
409        glLoadIdentity();
410        glOrtho(+xlen, -xlen, +ylen, -ylen, 0.0f, Magnitude(mSceneBox.Diagonal()));
411
412        Matrix4x4 dummyMat;
413        glGetFloatv(GL_PROJECTION_MATRIX, (float *)dummyMat.x);
414        cout << "old:\n" << dummyMat << endl;
415        */
416
417        Matrix4x4 lightView, lightProj;
418
419        mShadowCam->GetModelViewMatrix(lightView);
420        CalcLightProjection(lightProj);
421
422        glMatrixMode(GL_PROJECTION);
423        glPushMatrix();
424        glLoadMatrixf((float *)lightProj.x);
425
426        cout << "new:\n" << lightProj << endl;
427
428        glMatrixMode(GL_MODELVIEW);
429        glPushMatrix();
430        glLoadIdentity();
431
432        mShadowCam->SetupCameraView();
433
434        mLightProjView = lightView * lightProj;
435
436
437        //////////////
438        //-- compute texture matrix
439        static Matrix4x4 biasMatrix(0.5f, 0.0f, 0.0f, 0.5f,
440                                                                0.0f, 0.5f, 0.0f, 0.5f,
441                                                                0.0f, 0.0f, 0.5f, 0.5f,
442                                                                0.0f, 0.0f, 0.0f, 1.0f);
443
444        mTextureMatrix = mLightProjView * biasMatrix;
445
446
447
448
449        /////////////
450        //-- render scene into shadow map
451
452        renderer->RenderScene();
453
454       
455        glDisable(GL_POLYGON_OFFSET_FILL);
456        glMatrixMode(GL_MODELVIEW);
457        glPopMatrix();
458
459        glMatrixMode(GL_PROJECTION);
460        glPopMatrix();
461
462        glPopAttrib();
463#if 0
464        float *data = new float[mSize * mSize];
465
466        GrabDepthBuffer(data, mFbo->GetDepthTex());
467        ExportDepthBuffer(data, mSize);
468
469        delete [] data;
470       
471        PrintGLerror("shadow map");
472#endif
473        FrameBufferObject::Release();
474}
475
476
477void ShadowMap::GetTextureMatrix(Matrix4x4 &m) const
478{
479        m = mTextureMatrix;
480}
481
482 
483unsigned int ShadowMap::GetShadowTexture() const
484{
485        return mFbo->GetDepthTex();
486}
487
488
489
490} // namespace
Note: See TracBrowser for help on using the repository browser.