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

Revision 3011, 17.6 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
19static CGprogram sCgShadowProgram;
20static CGparameter sShadowParam;
21
22
23static Polyhedron *polyhedron = NULL;
24static Polyhedron *lightPoly = NULL;
25
26
27static void PrintGLerror(char *msg)
28{
29        GLenum errCode;
30        const GLubyte *errStr;
31       
32        if ((errCode = glGetError()) != GL_NO_ERROR)
33        {
34                errStr = gluErrorString(errCode);
35                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
36        }
37}
38
39
40static Polyhedron *CreatePolyhedron(const Matrix4x4 &lightMatrix,
41                                                                        const AxisAlignedBox3 &sceneBox)
42{
43        Frustum frustum(lightMatrix);
44
45        vector<Plane3> clipPlanes;
46
47        for (int i = 0; i < 6; ++ i)
48        {
49                ////////////
50                //-- normalize the coefficients
51
52                // the clipping planes look outward the frustum,
53                // so distances > 0 mean that a point is outside
54                const float invLength = -1.0f / Magnitude(frustum.mClipPlanes[i].mNormal);
55
56                frustum.mClipPlanes[i].mD *= invLength;
57                frustum.mClipPlanes[i].mNormal *= invLength;
58        }
59
60        // first create near plane because of precision issues
61        clipPlanes.push_back(frustum.mClipPlanes[4]);
62
63        clipPlanes.push_back(frustum.mClipPlanes[0]);
64        clipPlanes.push_back(frustum.mClipPlanes[1]);
65        clipPlanes.push_back(frustum.mClipPlanes[2]);
66        clipPlanes.push_back(frustum.mClipPlanes[3]);
67        clipPlanes.push_back(frustum.mClipPlanes[5]);
68
69        return Polyhedron::CreatePolyhedron(clipPlanes, sceneBox);
70}
71
72
73static void GrabDepthBuffer(float *data, GLuint depthTexture)
74{
75        glEnable(GL_TEXTURE_2D);
76        glBindTexture(GL_TEXTURE_2D, depthTexture);
77
78        glGetTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_FLOAT, data);
79
80        glBindTexture(GL_TEXTURE_2D, 0);
81        glDisable(GL_TEXTURE_2D);
82}
83
84
85static void ExportDepthBuffer(float *data, int size)
86{
87        ilInit();
88        assert(ilGetError() == IL_NO_ERROR);
89
90        ILstring filename = ILstring("shadow.tga");
91        ilRegisterType(IL_FLOAT);
92
93        const int depth = 1;
94        const int bpp = 1;
95
96        if (!ilTexImage(size, size, depth, bpp, IL_LUMINANCE, IL_FLOAT, data))
97        {
98                cerr << "IL error " << ilGetError() << endl;
99       
100                ilShutDown();
101                assert(ilGetError() == IL_NO_ERROR);
102
103                return;
104        }
105
106        if (!ilSaveImage(filename))
107        {
108                cerr << "TGA write error " << ilGetError() << endl;
109        }
110
111        ilShutDown();
112        assert(ilGetError() == IL_NO_ERROR);
113
114        cout << "exported depth buffer" << endl;
115}
116
117
118
119static AxisAlignedBox3 GetExtremalPoints(const Matrix4x4 &m,
120                                                                                 const VertexArray &pts)
121{
122        AxisAlignedBox3 extremalPoints;
123        extremalPoints.Initialize();
124
125        VertexArray::const_iterator it, it_end = pts.end();
126               
127        for (it = pts.begin(); it != it_end; ++ it)
128        {
129                Vector3 pt = *it;
130                pt = m * pt;
131
132                extremalPoints.Include(pt);
133        }
134
135        return extremalPoints;
136}
137
138
139ShadowMap::ShadowMap(DirectionalLight *light
140                                         , int size,
141                                         const AxisAlignedBox3 &sceneBox,
142                                         Camera *cam):
143mSceneBox(sceneBox), mSize(size), mCamera(cam), mLight(light)
144{
145        mFbo = new FrameBufferObject(size, size, FrameBufferObject::DEPTH_32, true);
146
147        // need a color buffer to keep opengl happy
148        mFbo->AddColorBuffer(ColorBufferObject::RGB_UBYTE,
149                                 ColorBufferObject::WRAP_CLAMP_TO_EDGE,
150                                                 ColorBufferObject::FILTER_NEAREST);
151
152
153        mShadowCam = new Camera(mSize, mSize);
154        mShadowCam->SetOrtho(true);
155}
156
157
158ShadowMap::~ShadowMap()
159{
160        DEL_PTR(mFbo);
161        DEL_PTR(mShadowCam);
162}
163
164
165static void DrawPolyhedron(Polyhedron *poly, const Vector3 &color)
166{
167        if (!poly) return;
168
169        for (size_t i = 0; i < poly->NumPolygons(); ++ i)
170        {
171                glColor3f(color.x, color.y, color.z);
172
173                glBegin(GL_LINE_LOOP);
174
175                Polygon3 *p = poly->GetPolygons()[i];
176
177                for (size_t j = 0; j < p->mVertices.size(); ++ j)
178                {
179                        Vector3 v = p->mVertices[j];
180                        glVertex3d(v.x, v.y, v.z);
181                }
182
183                glEnd();
184        }
185}
186
187
188void ShadowMap::VisualizeFrustra()
189{
190        DrawPolyhedron(lightPoly, Vector3(1, 0, 1));
191        DrawPolyhedron(polyhedron, Vector3(0, 1, 0));
192}
193
194
195// z0 is the point that lies on the parallel plane to the near plane through e (A)
196//and on the near plane of the C frustum (the plane z = bZmax) and on the line x = e.x
197Vector3 ShadowMap::GetLightSpaceZ0(const Matrix4x4 &lightSpace,
198                                                                   const Vector3 &e,
199                                                                   const float maxZ,
200                                                                   const Vector3 &eyeDir) const
201{
202        // to calculate the parallel plane to the near plane through e we
203        // calculate the plane A with the three points
204        Plane3 planeA(e, eyeDir);
205
206        planeA.Transform(lightSpace);
207       
208        // get the parameters of A from the plane equation n dot d = 0
209        const float d = planeA.mD;
210        const Vector3 n = planeA.mNormal;
211       
212        // transform to light space
213        const Vector3 e_ls = lightSpace * e;
214
215        Vector3 z0;
216
217        z0.x = e_ls.x;
218        z0.y = (d - n.z * maxZ - n.x * e_ls.x) / n.y;
219        z0.z = maxZ;
220
221        return z0;
222        //return V3(e_ls.x(),(d-n.z()*b_lsZmax-n.x()*e_ls.x())/n.y(),b_lsZmax);
223}
224
225
226float ShadowMap::ComputeNOpt(const Matrix4x4 &lightSpace,
227                                                         const AxisAlignedBox3 &extremalPoints,
228                                                         const VertexArray &body) const
229{
230        const Vector3 nearPt = GetNearCameraPointE(body);
231        const Vector3 eyeDir = mCamera->GetDirection();
232
233        Matrix4x4 eyeView;
234        mCamera->GetModelViewMatrix(eyeView);
235
236        const Matrix4x4 invLightSpace = Invert(lightSpace);
237
238        const Vector3 z0_ls = GetLightSpaceZ0(lightSpace, nearPt, extremalPoints.Max().z, eyeDir);
239        const Vector3 z1_ls = Vector3(z0_ls.x, z0_ls.y, extremalPoints.Min().z);
240       
241        // transform back to world space
242        const Vector3 z0_ws = invLightSpace * z0_ls;
243        const Vector3 z1_ws = invLightSpace * z1_ls;
244
245        // transform to eye space
246        const Vector3 z0_es = eyeView * z0_ws;
247        const Vector3 z1_es = eyeView * z1_ws;
248
249        const float z0 = z0_es.z;
250        const float z1 = z1_es.z;
251
252        cout << "z0 ls: " << z0_ls << " z1 ls: " << z1_ls << endl;
253        cout << "z0: " << z0_es << " z1: " << z1_es << endl;
254
255        const float d = fabs(extremalPoints.Max()[2] - extremalPoints.Min()[2]);
256
257        const float n = d / (sqrt(z1 / z0) - 1.0f);
258
259        return n;
260}
261
262
263float ShadowMap::ComputeN(const AxisAlignedBox3 &extremalPoints) const
264{
265        const float nearPlane = mCamera->GetNear();
266       
267        const float d = fabs(extremalPoints.Max()[2] - extremalPoints.Min()[2]);
268       
269        const float dotProd = DotProd(mCamera->GetDirection(), mShadowCam->GetDirection());
270        const float sinGamma = sin(fabs(acos(dotProd)));
271
272        // test for values close to zero
273        if (sinGamma < 1e-6f) return 1e6f;
274       
275        const float scale = 2.0f;
276        return scale * (nearPlane + sqrt(nearPlane * (nearPlane + d * sinGamma))) /  sinGamma;
277}
278
279
280Matrix4x4 ShadowMap::CalcLispSMTransform(const Matrix4x4 &lightSpace,
281                                                                                 const AxisAlignedBox3 &extremalPoints,
282                                                                                 const VertexArray &body
283                                                                                 )
284{
285        AxisAlignedBox3 bounds_ls = GetExtremalPoints(lightSpace, body);
286
287        ///////////////
288        //-- We apply the lispsm algorithm in order to calculate an optimal light projection matrix
289        //-- first find the free parameter values n, and P (the projection center), and the projection depth
290
291        const float n = ComputeN(bounds_ls);
292        //const float n = ComputeNOpt(lightSpace, extremalPoints, body); cout << "n: " << n << endl;
293
294        if (n >= 1e6f) // light direction nearly parallel to view => switch to uniform
295                return IdentityMatrix();
296
297        const Vector3 nearPt = GetNearCameraPointE(body);
298       
299        //get the coordinates of the near camera point in light space
300        const Vector3 lsNear = lightSpace * nearPt;
301
302        // the start point has the x and y coordinate of e, the z coord of the near plane of the light volume
303        const Vector3 startPt = Vector3(lsNear.x, lsNear.y, bounds_ls.Max().z);
304       
305        // the new projection center
306        const Vector3 projCenter = startPt + Vector3::UNIT_Z() * n;
307
308        //construct a translation that moves to the projection center
309        const Matrix4x4 projectionCenter = TranslationMatrix(-projCenter);
310
311        // light space y size
312        const float d = fabs(bounds_ls.Max()[2] - bounds_ls.Min()[2]);
313
314        const float dy = fabs(bounds_ls.Max()[1] - bounds_ls.Min()[1]);
315        const float dx = fabs(bounds_ls.Max()[0] - bounds_ls.Min()[0]);
316
317       
318
319        //////////
320        //-- now apply these values to construct the perspective lispsm matrix
321
322        Matrix4x4 matLispSM;
323       
324        matLispSM = GetFrustum(-1.0, 1.0, -1.0, 1.0, n, n + d);
325
326        // translate to the projection center
327        matLispSM = projectionCenter * matLispSM;
328
329        // transform into OpenGL right handed system
330        Matrix4x4 refl = ScaleMatrix(1.0f, 1.0f, -1.0f);
331        matLispSM *= refl;
332       
333        return matLispSM;
334}
335
336#if 0
337Vector3 ShadowMap::GetNearCameraPointE(const VertexArray &pts) const
338{
339        float maxDist = -1e25f;
340        Vector3 nearest = Vector3::ZERO();
341
342        Matrix4x4 eyeView;
343        mCamera->GetModelViewMatrix(eyeView);
344
345        VertexArray newPts;
346        polyhedron->CollectVertices(newPts);
347       
348        //the LVS volume is always in front of the camera
349        VertexArray::const_iterator it, it_end = pts.end();     
350
351        for (it = pts.begin(); it != it_end; ++ it)
352        {
353                Vector3 pt = *it;
354                Vector3 ptE = eyeView * pt;
355               
356                if (ptE.z > 0) cerr <<"should not happen " << ptE.z << endl;
357                else
358                if (ptE.z > maxDist)
359                {
360                        cout << " d " << ptE.z;
361       
362                        maxDist = ptE.z;
363                        nearest = pt;
364                }
365        }
366
367        //      return Invert(eyeView) * nearest;
368        return nearest;
369}
370
371#else
372
373Vector3 ShadowMap::GetNearCameraPointE(const VertexArray &pts) const
374{
375        VertexArray newPts;
376        polyhedron->CollectVertices(newPts);
377
378        Vector3 nearest = Vector3::ZERO();
379        float minDist = 1e25f;
380
381        const Vector3 camPos = mCamera->GetPosition();
382
383        VertexArray::const_iterator it, it_end = newPts.end();
384
385        for (it = newPts.begin(); it != it_end; ++ it)
386        {
387                Vector3 pt = *it;
388
389                const float dist = SqrDistance(pt, camPos);
390
391                if (dist < minDist)
392                {
393                        minDist = dist;
394                        nearest = pt;
395                }
396        }
397
398        return nearest;
399}
400
401#endif
402
403Vector3 ShadowMap::GetProjViewDir(const Matrix4x4 &lightSpace,
404                                                                  const VertexArray &pts) const
405{
406        //get the point in the LVS volume that is nearest to the camera
407        const Vector3 e = GetNearCameraPointE(pts);
408
409        //construct edge to transform into light-space
410        const Vector3 b = e + mCamera->GetDirection();
411        //transform to light-space
412        const Vector3 e_lp = lightSpace * e;
413        const Vector3 b_lp = lightSpace * b;
414
415        Vector3 projDir(b_lp - e_lp);
416
417        //project the view direction into the shadow map plane
418        projDir.y = .0f;
419
420        return Normalize(projDir);
421}
422
423
424bool ShadowMap::CalcLightProjection(Matrix4x4 &lightProj)
425{
426        ///////////////////
427        //-- First step: calc frustum clipped by scene box
428
429        DEL_PTR(polyhedron);
430        polyhedron = CalcClippedFrustum(mSceneBox);
431
432        if (!polyhedron) return false; // something is wrong
433
434        // include the part of the light volume that "sees" the frustum
435        // we only require frustum vertices
436
437        VertexArray frustumPoints;
438        IncludeLightVolume(*polyhedron, frustumPoints, mLight->GetDirection(), mSceneBox);
439
440
441        ///////////////
442        //-- transform points from world view to light view and calculate extremal points
443
444        Matrix4x4 lightView;
445        mShadowCam->GetModelViewMatrix(lightView);
446
447        const AxisAlignedBox3 extremalPoints = GetExtremalPoints(lightView, frustumPoints);
448
449        // we use directional lights, so the projection can be set to identity
450        lightProj = IdentityMatrix();
451
452        // switch coordinate system to that used in the lispsm algorithm for calculations
453        Matrix4x4 transform2LispSM = ZeroMatrix();
454
455        transform2LispSM.x[0][0] =  1.0f;
456        transform2LispSM.x[1][2] =  -1.0f; // y => -z
457        transform2LispSM.x[2][1] =  1.0f; // z => y
458        transform2LispSM.x[3][3] =  1.0f;
459
460
461        //switch to the lightspace used in the article
462        lightProj *= transform2LispSM;
463
464        const Vector3 projViewDir = GetProjViewDir(lightView * lightProj, frustumPoints);
465
466        //do DirectionalLight Space Perspective shadow mapping
467        //rotate the lightspace so that the projected light view always points upwards
468        //calculate a frame matrix that uses the projViewDir[lightspace] as up vector
469        //look(from position, into the direction of the projected direction, with unchanged up-vector)
470        //const Matrix4x4 frame = MyLookAt2(Vector3::ZERO(), projViewDir, Vector3::UNIT_Y());
471        const Matrix4x4 frame = LookAt(Vector3::ZERO(), projViewDir, Vector3::UNIT_Y());
472
473        lightProj *= frame;
474
475        const Matrix4x4 matLispSM =
476                CalcLispSMTransform(lightView * lightProj, extremalPoints, frustumPoints);
477
478        lightProj *= matLispSM;
479
480        // change back to GL coordinate system
481        Matrix4x4 transformToGL = ZeroMatrix();
482       
483        transformToGL.x[0][0] =   1.0f;
484        transformToGL.x[1][2] =   1.0f; // z => y
485        transformToGL.x[2][1] =  -1.0f; // y => -z
486        transformToGL.x[3][3] =   1.0f;
487
488        lightProj *= transformToGL;
489
490        AxisAlignedBox3 lightPts = GetExtremalPoints(lightView * lightProj, frustumPoints);
491
492        // focus projection matrix on the extremal points => scale to unit cube
493        Matrix4x4 scaleTranslate = GetFittingProjectionMatrix(lightPts);
494
495        lightProj = lightProj * scaleTranslate;
496
497        Matrix4x4 mymat = lightView * lightProj;
498
499        AxisAlignedBox3 lightPtsNew = GetExtremalPoints(mymat, frustumPoints);
500
501        // we have to flip the signs in order to tranform to opengl right handed system
502        Matrix4x4 refl = ScaleMatrix(1, 1, -1);
503        lightProj *= refl;
504       
505        return true;
506}
507
508
509Polyhedron *ShadowMap::CalcClippedFrustum(const AxisAlignedBox3 &box) const
510{
511        Polyhedron *p = mCamera->ComputeFrustum();
512       
513        Polyhedron *clippedPolyhedron = box.CalcIntersection(*p);
514
515        DEL_PTR(p);
516       
517        return clippedPolyhedron;
518}
519
520
521//calculates the up vector for the light coordinate frame
522static Vector3 CalcUpVec(const Vector3 viewDir, const Vector3 lightDir)
523{
524        //we do what gluLookAt does...
525        //left is the normalized vector perpendicular to lightDir and viewDir
526        //this means left is the normalvector of the yz-plane from the paper
527        Vector3 left = CrossProd(lightDir, viewDir);
528       
529        //we now can calculate the rotated(in the yz-plane) viewDir vector
530        //and use it as up vector in further transformations
531        Vector3 up = CrossProd(left, lightDir);
532
533        return Normalize(up);
534}
535
536
537void ShadowMap::GetTextureMatrix(Matrix4x4 &m) const
538{
539        m = mTextureMatrix;
540}
541
542 
543unsigned int ShadowMap::GetDepthTexture() const
544{
545        return mFbo->GetDepthTex();
546}
547
548unsigned int ShadowMap::GetShadowColorTexture() const
549{
550        return mFbo->GetColorBuffer(0)->GetTexture();
551       
552}
553
554
555void ShadowMap::IncludeLightVolume(const Polyhedron &polyhedron,
556                                                                   VertexArray &frustumPoints,
557                                                                   const Vector3 lightDir,
558                                                                   const AxisAlignedBox3 &sceneBox
559                                                                   )
560{
561        // we don't need closed form anymore => just store vertices
562        VertexArray vertices;
563        polyhedron.CollectVertices(vertices);
564
565        // we 'look' at each point and calculate intersections of rays with scene bounding box
566        VertexArray::const_iterator it, it_end = vertices.end();
567
568        for (it = vertices.begin(); it != it_end; ++ it)
569        {
570                Vector3 v  = *it;
571
572                frustumPoints.push_back(v);
573               
574                // hack: start at point which is guaranteed to be outside of box
575                v -= Magnitude(mSceneBox.Diagonal()) * lightDir;
576
577                SimpleRay ray(v, lightDir);
578
579                float tNear, tFar;
580
581                if (sceneBox.Intersects(ray, tNear, tFar))
582                {
583                        Vector3 newpt = ray.Extrap(tNear);
584                        frustumPoints.push_back(newpt);                 
585                }
586        }
587}
588
589
590void ShadowMap::ComputeShadowMap(RenderTraverser *renderer, const Matrix4x4 &projView)
591{
592        mFbo->Bind();
593       
594        glDrawBuffers(1, mrt);
595
596        glPushAttrib(GL_VIEWPORT_BIT);
597        glViewport(0, 0, mSize, mSize);
598
599        glDisable(GL_LIGHTING);
600        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
601
602        glShadeModel(GL_FLAT);
603
604
605        /////////////
606        //-- render scene into shadow map
607
608        _Render(renderer);
609
610
611        //////////////
612        //-- compute texture matrix
613
614        static Matrix4x4 biasMatrix(0.5f, 0.0f, 0.0f, 0.5f,
615                                                                0.0f, 0.5f, 0.0f, 0.5f,
616                                                                0.0f, 0.0f, 0.5f, 0.5f,
617                                                                0.0f, 0.0f, 0.0f, 1.0f);
618
619        mTextureMatrix = mLightProjView * biasMatrix;
620
621        glPopAttrib();
622       
623        glShadeModel(GL_SMOOTH);
624        glEnable(GL_LIGHTING);
625        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
626
627#if 0
628        float *data = new float[mSize * mSize];
629
630        GrabDepthBuffer(data, mFbo->GetDepthTex());
631        ExportDepthBuffer(data, mSize);
632
633        delete [] data;
634       
635        PrintGLerror("shadow map");
636#endif
637       
638        FrameBufferObject::Release();
639}
640
641
642void ShadowMap::RenderShadowView(RenderTraverser *renderer, const Matrix4x4 &projView)
643{
644        glEnable(GL_LIGHTING);
645       
646        _Render(renderer);
647       
648        /*glDisable(GL_LIGHTING);
649        glDisable(GL_DEPTH_TEST);
650
651        //glLineWidth(2);
652        Polyhedron *hpoly = CreatePolyhedron(projView, mSceneBox);
653        DrawPoly(hpoly, Vector3(1, 1, 1));
654
655        DEL_PTR(hpoly);
656
657        glEnable(GL_LIGHTING);
658        glEnable(GL_DEPTH_TEST);*/
659
660        glDisable(GL_POLYGON_OFFSET_FILL);
661}
662
663
664void ShadowMap::_Render(RenderTraverser *renderer)
665{
666        const Vector3 dir = mLight->GetDirection();
667
668        mShadowCam->SetDirection(dir);
669
670        // set position so that we can see the whole scene
671        Vector3 pos = mSceneBox.Center();
672        pos -= dir * Magnitude(mSceneBox.Diagonal() * 0.5f);
673
674        mShadowCam->SetPosition(mCamera->GetPosition());
675
676        Vector3 upVec = CalcUpVec(mCamera->GetDirection(), dir);
677        Matrix4x4 lightView = LookAt(mShadowCam->GetPosition(), dir, upVec);
678
679        mShadowCam->mViewOrientation = lightView;
680
681        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
682
683        glPolygonOffset(5.0f, 100.0f);
684        glEnable(GL_POLYGON_OFFSET_FILL);
685       
686        Matrix4x4 lightProj;
687        CalcLightProjection(lightProj);
688
689        glMatrixMode(GL_PROJECTION);
690        glPushMatrix();
691        glLoadMatrixf((float *)lightProj.x);
692
693        mLightProjView = lightView * lightProj;
694
695        DEL_PTR(lightPoly);
696        lightPoly = CreatePolyhedron(mLightProjView, mSceneBox);
697
698        glMatrixMode(GL_MODELVIEW);
699        glPushMatrix();
700       
701        mShadowCam->SetupCameraView();
702
703       
704        /////////////
705        //-- render scene into shadow map
706
707        renderer->RenderScene();
708
709
710        glMatrixMode(GL_PROJECTION);
711        glPopMatrix();
712
713        glMatrixMode(GL_MODELVIEW);
714        glPopMatrix();
715
716       
717        glDisable(GL_POLYGON_OFFSET_FILL);
718}
719} // namespace
Note: See TracBrowser for help on using the repository browser.