首先確定陰影的最基本原理:
陰影是以光源作為攝像機(叫作Camera_light),光照方向作為攝像機的look的方向,然后把這個攝像機看到的場景物渲染到紋理,這個紋理就叫shadowmap。
在這里我把場景的攝像機叫Camera_scene
在渲染場景的時候,接收shadowmap的物體根據自身的坐標計算出對應的shadowmap的紋理坐標已經把shadowmap貼上去。
然后shadowmap都面臨很多的問題,例如分辨率差,模糊等,解決這些問題有很多種算法,如PSM,CSM等。無論是何種算法,最核心的問題就是要解決shadowmap的攝像機參數。
在nvidia的sdk和很多引擎的代碼中,都有一個叫casterAABB的東西,可能很多人一開始寫shadowmap的時候不太理解這個是干什么用的。
casterAABB是指:以當前場景看到的所有接收shadowmap物體的總AABB與Camera_scene的view空間所轉換的AABB的交集。
這個casterAABB的作用是計算Camera_light的攝像機參數,使shadowmap的分辨率達到最清楚。
下面是計算的代碼:
ISceneManager* pScene = ENGINE_INST->GetSceneMgr();
//首先取得當前pScene的frustum,然后轉成世界坐標的AABB
AABBBox3Df frustumInViewAABB;
GetAABBFromProjectMatrix(frustumInViewAABB, pScene->GetCamera()->GetProjectionMatrix());
AABBBox3Df shadowArea = m_casterAABB;
m_casterAABB.Intersection(shadowArea, frustumInViewAABB);
Vector3Df centerPos = shadowArea.GetCenter();
Matrix4f matInvView;
pScene->GetCamera()->GetViewMatrix().GetInverse(matInvView);
Vector3Df vecLookAt;
matInvView.TransformCoord(centerPos, vecLookAt); //這個時候centerPos是world空間的坐標
m_pCamera->SetLookAt(vecLookAt);
m_pCamera->SetPosition(vecLookAt - m_directionLight * m_fDisLightToTarget);
m_pCamera->BuildViewMatrix();
const Matrix4f& cameraLightView = m_pCamera->GetViewMatrix();
Matrix4f matCameraToLight = matInvView * cameraLightView;
matCameraToLight.TransformBox(shadowArea);
f32 fWidth = shadowArea.MaxEdge.x - shadowArea.MinEdge.x;
f32 fheight = shadowArea.MaxEdge.y - shadowArea.MinEdge.y;
f32 fDis = shadowArea.MaxEdge.z - shadowArea.MinEdge.z;
matCameraToLight.TransformBox(m_casterAABB);
m_pCamera->SetViewport(m_casterAABB.MinEdge.z, shadowArea.MaxEdge.z, AIR::PI / 4, fWidth, fheight, false);
接下來就是shadowmap的最常規做法了,渲染到紋理,設置渲染狀態等,這里就不再介紹了。