vtkShadowMapPass.cxx 11.4 KB
Newer Older
Ken Martin's avatar
Ken Martin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkShadowMapPass.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkShadowMapPass.h"
#include "vtkObjectFactory.h"

Ken Martin's avatar
Ken Martin committed
19 20
#include "vtkAbstractTransform.h" // for helper classes stack and concatenation
#include "vtkCamera.h"
Ken Martin's avatar
Ken Martin committed
21
#include "vtkFrameBufferObject.h"
Ken Martin's avatar
Ken Martin committed
22 23 24 25 26 27
#include "vtkImageData.h"
#include "vtkImageExport.h"
#include "vtkImplicitHalo.h"
#include "vtkImplicitSum.h"
#include "vtkInformation.h"
#include "vtkInformationDoubleVectorKey.h"
Ken Martin's avatar
Ken Martin committed
28 29 30
#include "vtkInformationIntegerKey.h"
#include "vtkInformationIntegerVectorKey.h"
#include "vtkLight.h"
Ken Martin's avatar
Ken Martin committed
31 32 33 34 35 36 37 38 39 40
#include "vtkLightCollection.h"
#include "vtkLightsPass.h"
#include "vtkMath.h"
#include "vtkMatrixToLinearTransform.h"
#include "vtkNew.h"
#include "vtkOpaquePass.h"
#include "vtkOpenGLCamera.h"
#include "vtkOpenGLError.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenGLRenderer.h"
Ken Martin's avatar
Ken Martin committed
41
#include "vtkPerspectiveTransform.h"
Ken Martin's avatar
Ken Martin committed
42 43
#include "vtkRenderPassCollection.h"
#include "vtkRenderState.h"
Ken Martin's avatar
Ken Martin committed
44
#include "vtkSampleFunction.h"
Ken Martin's avatar
Ken Martin committed
45 46 47 48 49 50
#include "vtkSequencePass.h"
#include "vtkShadowMapBakerPass.h"
#include "vtkTextureObject.h"
#include "vtkTextureUnitManager.h"
#include "vtkTransform.h"
#include "vtk_glew.h"
Ken Martin's avatar
Ken Martin committed
51 52 53 54 55

// debugging
#include "vtkTimerLog.h"
//#include "vtkBreakPoint.h"

Ken Martin's avatar
Ken Martin committed
56
#include <cassert>
57
#include <sstream>
Ken Martin's avatar
Ken Martin committed
58 59 60 61 62 63 64 65 66
#include "vtkStdString.h"


// to be able to dump intermediate passes into png files for debugging.
// only for vtkShadowMapPass developers.
//#define VTK_SHADOW_MAP_PASS_DEBUG
//#define DONT_DUPLICATE_LIGHTS


Ken Martin's avatar
Ken Martin committed
67 68 69
vtkStandardNewMacro(vtkShadowMapPass);
vtkCxxSetObjectMacro(vtkShadowMapPass,ShadowMapBakerPass,
                     vtkShadowMapBakerPass);
Ken Martin's avatar
Ken Martin committed
70
vtkCxxSetObjectMacro(vtkShadowMapPass,OpaqueSequence,
Ken Martin's avatar
Ken Martin committed
71 72 73 74 75 76 77 78 79 80
                     vtkRenderPass);

vtkInformationKeyMacro(vtkShadowMapPass,ShadowMapTextures,IntegerVector);
vtkInformationKeyMacro(vtkShadowMapPass,ShadowMapTransforms,DoubleVector);


// ----------------------------------------------------------------------------
vtkShadowMapPass::vtkShadowMapPass()
{
  this->ShadowMapBakerPass=0;
Ken Martin's avatar
Ken Martin committed
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

  vtkNew<vtkSequencePass> seqP;
  vtkNew<vtkLightsPass> lightP;
  vtkNew<vtkOpaquePass> opaqueP;
  vtkNew<vtkRenderPassCollection> rpc;
  rpc->AddItem(lightP.Get());
  rpc->AddItem(opaqueP.Get());
  seqP->SetPasses(rpc.Get());

  this->OpaqueSequence=0;
  this->SetOpaqueSequence(seqP.Get());

  vtkNew<vtkShadowMapBakerPass> bp;
  this->ShadowMapBakerPass = 0;
  this->SetShadowMapBakerPass(bp.Get());
Ken Martin's avatar
Ken Martin committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109

  this->IntensityMap=0;
  this->IntensitySource=0;
  this->IntensityExporter=0;
  this->Halo=0;
}

// ----------------------------------------------------------------------------
vtkShadowMapPass::~vtkShadowMapPass()
{
  if(this->ShadowMapBakerPass!=0)
    {
    this->ShadowMapBakerPass->Delete();
    }
Ken Martin's avatar
Ken Martin committed
110
  if(this->OpaqueSequence!=0)
Ken Martin's avatar
Ken Martin committed
111
    {
Ken Martin's avatar
Ken Martin committed
112
    this->OpaqueSequence->Delete();
Ken Martin's avatar
Ken Martin committed
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
    }

  if(this->IntensityMap!=0)
    {
    vtkErrorMacro(<<"IntensityMap should have been deleted in ReleaseGraphicsResources().");
    }

  if(this->IntensitySource!=0)
    {
    this->IntensitySource->Delete();
    }

  if(this->IntensityExporter!=0)
    {
    this->IntensityExporter->Delete();
    }

  if(this->Halo!=0)
    {
    this->Halo->Delete();
    }
}

// ----------------------------------------------------------------------------
void vtkShadowMapPass::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "ShadowMapBackerPass: ";
  if(this->ShadowMapBakerPass!=0)
    {
    this->ShadowMapBakerPass->PrintSelf(os,indent);
    }
  else
    {
    os << "(none)" <<endl;
    }
Ken Martin's avatar
Ken Martin committed
150 151
  os << indent << "OpaqueSequence: ";
  if(this->OpaqueSequence!=0)
Ken Martin's avatar
Ken Martin committed
152
    {
Ken Martin's avatar
Ken Martin committed
153
    this->OpaqueSequence->PrintSelf(os,indent);
Ken Martin's avatar
Ken Martin committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
    }
  else
    {
    os << "(none)" <<endl;
    }
}

// ----------------------------------------------------------------------------
// Description:
// Perform rendering according to a render state \p s.
// \pre s_exists: s!=0
void vtkShadowMapPass::Render(const vtkRenderState *s)
{
  assert("pre: s_exists" && s!=0);

  vtkOpenGLClearErrorMacro();

  this->NumberOfRenderedProps=0;

  vtkOpenGLRenderer *r = static_cast<vtkOpenGLRenderer *>(s->GetRenderer());
  vtkOpenGLCamera *cam = static_cast<vtkOpenGLCamera *>(r->GetActiveCamera());
  vtkOpenGLRenderWindow *context = static_cast<vtkOpenGLRenderWindow *>(
    r->GetRenderWindow());

  if(this->ShadowMapBakerPass != 0 &&
Ken Martin's avatar
Ken Martin committed
179
     this->OpaqueSequence != 0)
Ken Martin's avatar
Ken Martin committed
180 181 182 183 184 185 186
    {
     // Test for Hardware support. If not supported, just render the delegate.
    bool supported=vtkFrameBufferObject::IsSupported(context);

    if(!supported)
      {
      vtkErrorMacro("FBOs are not supported by the context. Cannot use shadow mapping.");
Ken Martin's avatar
Ken Martin committed
187
      this->OpaqueSequence->Render(s);
Ken Martin's avatar
Ken Martin committed
188
      this->NumberOfRenderedProps+=
Ken Martin's avatar
Ken Martin committed
189
        this->OpaqueSequence->GetNumberOfRenderedProps();
Ken Martin's avatar
Ken Martin committed
190 191 192 193 194
      return;
      }

    if(!this->ShadowMapBakerPass->GetHasShadows())
      {
Ken Martin's avatar
Ken Martin committed
195
      this->OpaqueSequence->Render(s);
Ken Martin's avatar
Ken Martin committed
196
      this->NumberOfRenderedProps+=
Ken Martin's avatar
Ken Martin committed
197
        this->OpaqueSequence->GetNumberOfRenderedProps();
Ken Martin's avatar
Ken Martin committed
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
      return;
      }

    vtkLightCollection *lights=r->GetLights();
    std::vector<int> shadowTextureUnits;
    shadowTextureUnits.resize(lights->GetNumberOfItems());

    // get the shadow maps and activate them
    int shadowingLightIndex = 0;
    int lightIndex = 0;
    vtkLight *light = 0;
    for (lights->InitTraversal(), light = lights->GetNextItem();
          light != 0; light = lights->GetNextItem(), lightIndex++)
      {
      shadowTextureUnits[lightIndex] = -1;
      if(light->GetSwitch() &&
         this->ShadowMapBakerPass->LightCreatesShadow(light) )
        {
        vtkTextureObject *map=
Ken Martin's avatar
Ken Martin committed
217
          (*this->ShadowMapBakerPass->GetShadowMaps())[
Ken Martin's avatar
Ken Martin committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
            static_cast<size_t>(shadowingLightIndex)];
        // activate the texture map
        map->Activate();
        shadowTextureUnits[lightIndex] = map->GetTextureUnit();
        // create some extra shader code for this light

        shadowingLightIndex++;
        }
      }

    vtkMatrix4x4 *tmp = vtkMatrix4x4::New();
    vtkMatrix4x4 *mat = vtkMatrix4x4::New();
    vtkPerspectiveTransform *transform = vtkPerspectiveTransform::New();

    vtkMatrix4x4 *wcdc;
    vtkMatrix4x4 *wcvc;
    vtkMatrix3x3 *norms;
    vtkMatrix4x4 *vcdc;
    cam->GetKeyMatrices(r,wcvc,norms,vcdc,wcdc);

    mat->DeepCopy(wcvc);
    mat->Transpose();
    mat->Invert();

    vtkMatrixToLinearTransform *viewCamera_Inv
      = vtkMatrixToLinearTransform::New();
    viewCamera_Inv->SetInput(mat);
    mat->Delete();

    // identity. pre-multiply mode
    transform->Translate(0.5,0.5,0.5); // bias
    transform->Scale(0.5,0.5,0.5); // scale

    shadowingLightIndex = 0;
    std::vector<double> shadowTransforms;
    for (lights->InitTraversal(), light = lights->GetNextItem(), lightIndex = 0;
          light != 0; light = lights->GetNextItem(), lightIndex++)
      {
      if (shadowTextureUnits[lightIndex] >= 0)
        {
        vtkCamera *lightCamera=
Ken Martin's avatar
Ken Martin committed
259
          (*this->ShadowMapBakerPass->GetLightCameras())[
Ken Martin's avatar
Ken Martin committed
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
          static_cast<size_t>(shadowingLightIndex)];
        transform->Push();
        transform->Concatenate(
          lightCamera->GetProjectionTransformObject(1,-1,1));
        transform->Concatenate(lightCamera->GetViewTransformObject());
        transform->Concatenate(viewCamera_Inv);
        transform->GetMatrix(tmp);
        transform->Pop();
        tmp->Transpose();
        for (int i = 0; i < 16; i++)
          {
          shadowTransforms.push_back(*(tmp->Element[0] + i));
          }
        ++shadowingLightIndex;
        }
      }

    // set the prop keys
    int c = s->GetPropArrayCount();
    for (int i = 0; i < c; i++)
      {
      vtkProp *p=s->GetPropArray()[i];
      vtkInformation *info = p->GetPropertyKeys();
      if (!info)
        {
        info = vtkInformation::New();
        p->SetPropertyKeys(info);
        info->Delete();
        }
      info->Set(vtkShadowMapPass::ShadowMapTextures(),
        &(shadowTextureUnits[0]),
        static_cast<int>(shadowTextureUnits.size()));
      info->Set(vtkShadowMapPass::ShadowMapTransforms(),
        &(shadowTransforms[0]),
        static_cast<int>(shadowTransforms.size()));
      }

    viewCamera_Inv->Delete();
    transform->Delete();
    tmp->Delete();

    // render with shadows
    // note this time we use the list of props after culling.
Ken Martin's avatar
Ken Martin committed
303
    this->OpaqueSequence->Render(s);
Ken Martin's avatar
Ken Martin committed
304
    this->NumberOfRenderedProps+=
Ken Martin's avatar
Ken Martin committed
305
      this->OpaqueSequence->GetNumberOfRenderedProps();
Ken Martin's avatar
Ken Martin committed
306 307 308 309 310 311 312 313 314 315

    // now deactivate the shadow maps
    shadowingLightIndex = 0;
    for (lights->InitTraversal(), light = lights->GetNextItem(), lightIndex = 0;
          light != 0; light = lights->GetNextItem(), lightIndex++)
      {
      if(light->GetSwitch() &&
         this->ShadowMapBakerPass->LightCreatesShadow(light) )
        {
        vtkTextureObject *map=
Ken Martin's avatar
Ken Martin committed
316
          (*this->ShadowMapBakerPass->GetShadowMaps())[
Ken Martin's avatar
Ken Martin committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
            static_cast<size_t>(shadowingLightIndex)];
        // activate the texture map
        map->Deactivate();
        shadowingLightIndex++;
        }
      }

#ifdef VTK_SHADOW_MAP_PASS_DEBUG
    cout << "finish after rendering geometry without shadowing lights" << endl;
    glFinish();
#endif

    }
  else
    {
Ken Martin's avatar
Ken Martin committed
332
    vtkWarningMacro(<<" no ShadowMapBakerPass or no OpaqueSequence on the ShadowMapBakerPass.");
Ken Martin's avatar
Ken Martin committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
    }

  vtkOpenGLCheckErrorMacro("failed after Render");
}

// ----------------------------------------------------------------------------
void vtkShadowMapPass::BuildSpotLightIntensityMap()
{
   if(this->IntensitySource==0)
     {
     this->IntensitySource=vtkSampleFunction::New();
     this->IntensityExporter=vtkImageExport::New();
     this->Halo=vtkImplicitHalo::New();

     vtkImplicitSum *scale=vtkImplicitSum::New();
     scale->AddFunction(this->Halo,255.0);
     scale->SetNormalizeByWeight(false);
     this->IntensitySource->SetImplicitFunction(scale);
     scale->Delete();
     }
   unsigned int resolution=this->ShadowMapBakerPass->GetResolution();

   this->Halo->SetRadius(resolution/2.0);
   this->Halo->SetCenter(resolution/2.0,
                         resolution/2.0,0.0);
   this->Halo->SetFadeOut(0.1);

   this->IntensitySource->SetOutputScalarType(VTK_UNSIGNED_CHAR);
   this->IntensitySource->SetSampleDimensions(
     static_cast<int>(resolution),
     static_cast<int>(resolution),1);
   this->IntensitySource->SetModelBounds(0.0,resolution-1.0,
                                         0.0,resolution-1.0,
                                         0.0,0.0);
   this->IntensitySource->SetComputeNormals(false);

   this->IntensityExporter->SetInputConnection(
     this->IntensitySource->GetOutputPort());
}

// ----------------------------------------------------------------------------
// Description:
// Release graphics resources and ask components to release their own
// resources.
// \pre w_exists: w!=0
void vtkShadowMapPass::ReleaseGraphicsResources(vtkWindow *w)
{
  assert("pre: w_exists" && w!=0);
  if(this->ShadowMapBakerPass!=0)
    {
    this->ShadowMapBakerPass->ReleaseGraphicsResources(w);
    }

  if(this->IntensityMap!=0)
    {
    this->IntensityMap->Delete();
    this->IntensityMap=0;
    }
}