View.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "DebugRenderer.h"
  26. #include "Geometry.h"
  27. #include "Graphics.h"
  28. #include "Light.h"
  29. #include "Log.h"
  30. #include "Material.h"
  31. #include "OcclusionBuffer.h"
  32. #include "Octree.h"
  33. #include "OctreeQuery.h"
  34. #include "Renderer.h"
  35. #include "Profiler.h"
  36. #include "Scene.h"
  37. #include "ShaderVariation.h"
  38. #include "Sort.h"
  39. #include "Technique.h"
  40. #include "Texture2D.h"
  41. #include "TextureCube.h"
  42. #include "VertexBuffer.h"
  43. #include "View.h"
  44. #include "Zone.h"
  45. #include "DebugNew.h"
  46. static const Vector3 directions[] =
  47. {
  48. Vector3(1.0f, 0.0f, 0.0f),
  49. Vector3(-1.0f, 0.0f, 0.0f),
  50. Vector3(0.0f, 1.0f, 0.0f),
  51. Vector3(0.0f, -1.0f, 0.0f),
  52. Vector3(0.0f, 0.0f, 1.0f),
  53. Vector3(0.0f, 0.0f, -1.0f)
  54. };
  55. OBJECTTYPESTATIC(View);
  56. View::View(Context* context) :
  57. Object(context),
  58. graphics_(GetSubsystem<Graphics>()),
  59. renderer_(GetSubsystem<Renderer>()),
  60. octree_(0),
  61. camera_(0),
  62. zone_(0),
  63. renderTarget_(0),
  64. depthStencil_(0)
  65. {
  66. frame_.camera_ = 0;
  67. }
  68. View::~View()
  69. {
  70. }
  71. bool View::Define(RenderSurface* renderTarget, const Viewport& viewport)
  72. {
  73. if (!viewport.scene_ || !viewport.camera_)
  74. return false;
  75. // If scene is loading asynchronously, it is incomplete and should not be rendered
  76. if (viewport.scene_->IsAsyncLoading())
  77. return false;
  78. Octree* octree = viewport.scene_->GetComponent<Octree>();
  79. if (!octree)
  80. return false;
  81. octree_ = octree;
  82. camera_ = viewport.camera_;
  83. renderTarget_ = renderTarget;
  84. if (!renderTarget)
  85. depthStencil_ = 0;
  86. else
  87. depthStencil_ = renderTarget->GetLinkedDepthBuffer();
  88. zone_ = renderer_->GetDefaultZone();
  89. // Validate the rect and calculate size. If zero rect, use whole render target size
  90. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  91. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  92. if (viewport.rect_ != IntRect::ZERO)
  93. {
  94. screenRect_.left_ = Clamp(viewport.rect_.left_, 0, rtWidth - 1);
  95. screenRect_.top_ = Clamp(viewport.rect_.top_, 0, rtHeight - 1);
  96. screenRect_.right_ = Clamp(viewport.rect_.right_, screenRect_.left_ + 1, rtWidth);
  97. screenRect_.bottom_ = Clamp(viewport.rect_.bottom_, screenRect_.top_ + 1, rtHeight);
  98. }
  99. else
  100. screenRect_ = IntRect(0, 0, rtWidth, rtHeight);
  101. width_ = screenRect_.right_ - screenRect_.left_;
  102. height_ = screenRect_.bottom_ - screenRect_.top_;
  103. // Set possible quality overrides from the camera
  104. drawShadows_ = renderer_->GetDrawShadows();
  105. materialQuality_ = renderer_->GetMaterialQuality();
  106. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  107. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  108. if (viewOverrideFlags & VOF_LOW_MATERIAL_QUALITY)
  109. materialQuality_ = QUALITY_LOW;
  110. if (viewOverrideFlags & VOF_DISABLE_SHADOWS)
  111. drawShadows_ = false;
  112. if (viewOverrideFlags & VOF_DISABLE_OCCLUSION)
  113. maxOccluderTriangles_ = 0;
  114. return true;
  115. }
  116. void View::Update(const FrameInfo& frame)
  117. {
  118. if (!camera_ || !octree_)
  119. return;
  120. frame_.camera_ = camera_;
  121. frame_.timeStep_ = frame.timeStep_;
  122. frame_.frameNumber_ = frame.frameNumber_;
  123. frame_.viewSize_ = IntVector2(width_, height_);
  124. // Clear old light scissor cache, geometry, light, occluder & batch lists
  125. lightScissorCache_.Clear();
  126. geometries_.Clear();
  127. geometryDepthBounds_.Clear();
  128. lights_.Clear();
  129. occluders_.Clear();
  130. shadowOccluders_.Clear();
  131. baseQueue_.Clear();
  132. extraQueue_.Clear();
  133. transparentQueue_.Clear();
  134. lightQueues_.Clear();
  135. // Do not update if camera projection is illegal
  136. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  137. if (!camera_->IsProjectionValid())
  138. return;
  139. // Set automatic aspect ratio if required
  140. if (camera_->GetAutoAspectRatio())
  141. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  142. // Cache the camera frustum to avoid recalculating it constantly
  143. frustum_ = camera_->GetFrustum();
  144. // Reset shadow map allocations; they can be reused between views as each is rendered completely at a time
  145. renderer_->ResetShadowMapAllocations();
  146. GetDrawables();
  147. GetBatches();
  148. }
  149. void View::Render()
  150. {
  151. if (!octree_ || !camera_)
  152. return;
  153. // Forget parameter sources from the previous view
  154. graphics_->ClearParameterSources();
  155. // If stream offset is supported, write all instance transforms to a single large buffer
  156. // Else we must lock the instance buffer for each batch group
  157. if (renderer_->GetDynamicInstancing() && graphics_->GetStreamOffsetSupport())
  158. PrepareInstancingBuffer();
  159. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  160. // again to ensure correct projection will be used
  161. if (camera_->GetAutoAspectRatio())
  162. camera_->SetAspectRatio((float)(screenRect_.right_ - screenRect_.left_) / (float)(screenRect_.bottom_ - screenRect_.top_));
  163. graphics_->SetColorWrite(true);
  164. graphics_->SetFillMode(FILL_SOLID);
  165. graphics_->SetScissorTest(false);
  166. graphics_->SetStencilTest(false);
  167. // Bind the face selection and indirection cube maps for point light shadows
  168. graphics_->SetTexture(TU_FACESELECT, renderer_->GetFaceSelectCubeMap());
  169. graphics_->SetTexture(TU_INDIRECTION, renderer_->GetIndirectionCubeMap());
  170. // Calculate view-global shader parameters
  171. CalculateShaderParameters();
  172. // Reset the light optimization stencil reference value
  173. lightStencilValue_ = 1;
  174. // Render
  175. RenderBatches();
  176. graphics_->SetScissorTest(false);
  177. graphics_->SetStencilTest(false);
  178. graphics_->ResetStreamFrequencies();
  179. // If this is a main view, draw the associated debug geometry now
  180. if (!renderTarget_)
  181. {
  182. Scene* scene = static_cast<Scene*>(octree_->GetNode());
  183. if (scene)
  184. {
  185. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  186. if (debug)
  187. {
  188. debug->SetView(camera_);
  189. debug->Render();
  190. }
  191. }
  192. }
  193. // "Forget" the camera, octree and zone after rendering
  194. camera_ = 0;
  195. octree_ = 0;
  196. zone_ = 0;
  197. frame_.camera_ = 0;
  198. }
  199. void View::GetDrawables()
  200. {
  201. PROFILE(GetDrawables);
  202. Vector3 cameraPos = camera_->GetWorldPosition();
  203. // Get zones & find the zone camera is in
  204. PointOctreeQuery query(tempDrawables_, cameraPos, DRAWABLE_ZONE, camera_->GetViewMask());
  205. octree_->GetDrawables(query);
  206. int highestZonePriority = M_MIN_INT;
  207. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  208. {
  209. Zone* zone = static_cast<Zone*>(tempDrawables_[i]);
  210. if (zone->IsInside(cameraPos) && zone->GetPriority() > highestZonePriority)
  211. {
  212. zone_ = zone;
  213. highestZonePriority = zone->GetPriority();
  214. }
  215. }
  216. // If occlusion in use, get & render the occluders, then build the depth buffer hierarchy
  217. OcclusionBuffer* buffer = 0;
  218. if (maxOccluderTriangles_ > 0)
  219. {
  220. FrustumOctreeQuery query(occluders_, frustum_, DRAWABLE_GEOMETRY, camera_->GetViewMask(), true, false);
  221. octree_->GetDrawables(query);
  222. UpdateOccluders(occluders_, camera_);
  223. if (occluders_.Size())
  224. {
  225. buffer = renderer_->GetOrCreateOcclusionBuffer(camera_, maxOccluderTriangles_);
  226. DrawOccluders(buffer, occluders_);
  227. buffer->BuildDepthHierarchy();
  228. }
  229. }
  230. if (!buffer)
  231. {
  232. // Get geometries & lights without occlusion
  233. FrustumOctreeQuery query(tempDrawables_, frustum_, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  234. octree_->GetDrawables(query);
  235. }
  236. else
  237. {
  238. // Get geometries & lights using occlusion
  239. OccludedFrustumOctreeQuery query(tempDrawables_, frustum_, buffer, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT,
  240. camera_->GetViewMask());
  241. octree_->GetDrawables(query);
  242. }
  243. // Sort into geometries & lights, and build visible scene bounding boxes in world and view space
  244. sceneBox_.min_ = sceneBox_.max_ = Vector3::ZERO;
  245. sceneBox_.defined_ = false;
  246. sceneViewBox_.min_ = sceneViewBox_.max_ = Vector3::ZERO;
  247. sceneViewBox_.defined_ = false;
  248. Matrix3x4 view(camera_->GetInverseWorldTransform());
  249. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  250. {
  251. Drawable* drawable = tempDrawables_[i];
  252. drawable->UpdateDistance(frame_);
  253. // If draw distance non-zero, check it
  254. float maxDistance = drawable->GetDrawDistance();
  255. if (maxDistance > 0.0f && drawable->GetDistance() > maxDistance)
  256. continue;
  257. unsigned flags = drawable->GetDrawableFlags();
  258. if (flags & DRAWABLE_GEOMETRY)
  259. {
  260. drawable->ClearBasePass();
  261. drawable->MarkInView(frame_);
  262. drawable->UpdateGeometry(frame_);
  263. // Expand the scene bounding boxes. However, do not take "infinite" objects such as the skybox into account,
  264. // as the bounding boxes are also used for shadow focusing
  265. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  266. BoundingBox geomViewBox = geomBox.Transformed(view);
  267. if (geomBox.Size().LengthFast() < M_LARGE_VALUE)
  268. {
  269. sceneBox_.Merge(geomBox);
  270. sceneViewBox_.Merge(geomViewBox);
  271. }
  272. // Store depth info for split directional light queries
  273. GeometryDepthBounds bounds;
  274. bounds.min_ = geomViewBox.min_.z_;
  275. bounds.max_ = geomViewBox.max_.z_;
  276. geometryDepthBounds_.Push(bounds);
  277. geometries_.Push(drawable);
  278. }
  279. else if (flags & DRAWABLE_LIGHT)
  280. {
  281. Light* light = static_cast<Light*>(drawable);
  282. // Skip if light is culled by the zone
  283. if (!(light->GetViewMask() & zone_->GetViewMask()))
  284. continue;
  285. light->MarkInView(frame_);
  286. lights_.Push(light);
  287. }
  288. }
  289. // Sort the lights to brightest/closest first
  290. for (unsigned i = 0; i < lights_.Size(); ++i)
  291. lights_[i]->SetIntensitySortValue(cameraPos);
  292. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  293. }
  294. void View::GetBatches()
  295. {
  296. maxLightsDrawables_.Clear();
  297. lightQueueIndex_.Clear();
  298. bool fallback = graphics_->GetFallback();
  299. // Go through lights
  300. {
  301. PROFILE_MULTIPLE(GetLightBatches, lights_.Size());
  302. // Preallocate enough light queues so that we can store pointers to them without having to worry about the
  303. // vector reallocating itself
  304. lightQueues_.Resize(lights_.Size());
  305. unsigned lightQueueCount = 0;
  306. for (unsigned i = 0; i < lights_.Size(); ++i)
  307. {
  308. Light* light = lights_[i];
  309. unsigned shadowSplits = ProcessLight(light);
  310. if (litGeometries_.Empty())
  311. continue;
  312. // Initialize light queue. Store pointer-to-index mapping so that the queue can be found later
  313. LightBatchQueue& lightQueue = lightQueues_[lightQueueCount];
  314. lightQueueIndex_[light] = lightQueueCount;
  315. lightQueue.light_ = light;
  316. lightQueue.litBatches_.Clear();
  317. // Allocate shadow map now
  318. lightQueue.shadowMap_ = 0;
  319. if (shadowSplits > 0)
  320. {
  321. lightQueue.shadowMap_ = renderer_->GetShadowMap(light, camera_, width_, height_);
  322. // If did not manage to get a shadow map, convert the light to unshadowed
  323. if (!lightQueue.shadowMap_)
  324. shadowSplits = 0;
  325. }
  326. // Setup shadow batch queues
  327. lightQueue.shadowSplits_.Resize(shadowSplits);
  328. for (unsigned j = 0; j < shadowSplits; ++j)
  329. {
  330. ShadowBatchQueue& shadowQueue = lightQueue.shadowSplits_[j];
  331. Camera* shadowCamera = shadowCameras_[j];
  332. shadowQueue.shadowCamera_ = shadowCameras_[j];
  333. shadowQueue.nearSplit_ = shadowNearSplits_[j];
  334. shadowQueue.farSplit_ = shadowFarSplits_[j];
  335. // Setup the shadow split viewport and finalize shadow camera parameters
  336. shadowQueue.shadowViewport_ = GetShadowMapViewport(light, j, lightQueue.shadowMap_);
  337. FinalizeShadowCamera(shadowCamera, light, shadowQueue.shadowViewport_, shadowCasterBox_[j]);
  338. // Loop through shadow casters
  339. for (unsigned k = 0; k < shadowCasters_[j].Size(); ++k)
  340. {
  341. Drawable* drawable = shadowCasters_[j][k];
  342. unsigned numBatches = drawable->GetNumBatches();
  343. for (unsigned l = 0; l < numBatches; ++l)
  344. {
  345. Batch shadowBatch;
  346. drawable->GetBatch(frame_, l, shadowBatch);
  347. Technique* tech = GetTechnique(drawable, shadowBatch.material_);
  348. if (!shadowBatch.geometry_ || !tech)
  349. continue;
  350. Pass* pass = tech->GetPass(PASS_SHADOW);
  351. // Skip if material has no shadow pass
  352. if (!pass)
  353. continue;
  354. // Fill the rest of the batch
  355. shadowBatch.camera_ = shadowCamera;
  356. shadowBatch.distance_ = shadowCamera->GetDistance(drawable->GetWorldPosition());
  357. shadowBatch.lightQueue_ = &lightQueue;
  358. shadowBatch.hasPriority_ = !pass->GetAlphaTest() && !pass->GetAlphaMask();
  359. renderer_->SetBatchShaders(shadowBatch, tech, pass);
  360. shadowQueue.shadowBatches_.AddBatch(shadowBatch);
  361. }
  362. }
  363. }
  364. // Loop through lit geometries
  365. for (unsigned j = 0; j < litGeometries_.Size(); ++j)
  366. {
  367. Drawable* drawable = litGeometries_[j];
  368. drawable->AddLight(light);
  369. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  370. if (!drawable->GetMaxLights())
  371. GetLitBatches(drawable, lightQueue);
  372. else
  373. maxLightsDrawables_.Insert(drawable);
  374. }
  375. ++lightQueueCount;
  376. }
  377. // Resize the light queue vector now that final size is known
  378. lightQueues_.Resize(lightQueueCount);
  379. }
  380. // Process drawables with limited light count
  381. if (maxLightsDrawables_.Size())
  382. {
  383. PROFILE(GetMaxLightsBatches);
  384. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  385. {
  386. Drawable* drawable = *i;
  387. drawable->LimitLights();
  388. const PODVector<Light*>& lights = drawable->GetLights();
  389. for (unsigned i = 0; i < lights.Size(); ++i)
  390. {
  391. Light* light = lights[i];
  392. // Find the correct light queue again
  393. Map<Light*, unsigned>::Iterator j = lightQueueIndex_.Find(light);
  394. if (j != lightQueueIndex_.End())
  395. GetLitBatches(drawable, lightQueues_[j->second_]);
  396. }
  397. }
  398. }
  399. // Go through geometries for base pass batches
  400. {
  401. PROFILE(GetBaseBatches);
  402. for (unsigned i = 0; i < geometries_.Size(); ++i)
  403. {
  404. Drawable* drawable = geometries_[i];
  405. unsigned numBatches = drawable->GetNumBatches();
  406. for (unsigned j = 0; j < numBatches; ++j)
  407. {
  408. Batch baseBatch;
  409. drawable->GetBatch(frame_, j, baseBatch);
  410. Technique* tech = GetTechnique(drawable, baseBatch.material_);
  411. if (!baseBatch.geometry_ || !tech)
  412. continue;
  413. // Check here if the material technique refers to a render target texture with camera(s) attached
  414. // Only check this for the main view (null rendertarget)
  415. if (!renderTarget_ && baseBatch.material_ && baseBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_)
  416. CheckMaterialForAuxView(baseBatch.material_);
  417. // If object already has a lit base pass, can skip the unlit base pass
  418. if (drawable->HasBasePass(j))
  419. continue;
  420. // Fill the rest of the batch
  421. baseBatch.camera_ = camera_;
  422. baseBatch.distance_ = drawable->GetDistance();
  423. Pass* pass = 0;
  424. // Check for unlit base pass
  425. pass = tech->GetPass(PASS_BASE);
  426. if (pass)
  427. {
  428. renderer_->SetBatchShaders(baseBatch, tech, pass);
  429. if (pass->GetBlendMode() == BLEND_REPLACE)
  430. {
  431. baseBatch.hasPriority_ = !pass->GetAlphaTest() && !pass->GetAlphaMask();
  432. baseQueue_.AddBatch(baseBatch);
  433. }
  434. else
  435. {
  436. baseBatch.hasPriority_ = true;
  437. transparentQueue_.AddBatch(baseBatch, true);
  438. }
  439. continue;
  440. }
  441. else
  442. {
  443. // If no base pass, finally check for extra / custom pass
  444. pass = tech->GetPass(PASS_EXTRA);
  445. if (pass)
  446. {
  447. baseBatch.hasPriority_ = false;
  448. renderer_->SetBatchShaders(baseBatch, tech, pass);
  449. extraQueue_.AddBatch(baseBatch);
  450. }
  451. }
  452. }
  453. }
  454. }
  455. // All batches have been collected. Sort them now
  456. SortBatches();
  457. }
  458. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue)
  459. {
  460. Light* light = lightQueue.light_;
  461. Light* drawableFirstLight = drawable->GetLights()[0];
  462. // Shadows on transparencies can only be rendered if shadow maps are not reused
  463. bool allowTransparentShadows = !renderer_->reuseShadowMaps_;
  464. unsigned numBatches = drawable->GetNumBatches();
  465. for (unsigned i = 0; i < numBatches; ++i)
  466. {
  467. Batch litBatch;
  468. drawable->GetBatch(frame_, i, litBatch);
  469. Technique* tech = GetTechnique(drawable, litBatch.material_);
  470. if (!litBatch.geometry_ || !tech)
  471. continue;
  472. Pass* pass = 0;
  473. bool priority = false;
  474. // For the (first) directional light, check for lit base pass
  475. if (light == drawableFirstLight && light->GetLightType() == LIGHT_DIRECTIONAL)
  476. {
  477. if (!drawable->HasBasePass(i))
  478. {
  479. pass = tech->GetPass(PASS_LITBASE);
  480. if (pass)
  481. {
  482. priority = true;
  483. drawable->SetBasePass(i);
  484. }
  485. }
  486. }
  487. // If no lit base pass, get ordinary light pass
  488. if (!pass)
  489. pass = tech->GetPass(PASS_LIGHT);
  490. // Skip if material does not receive light at all
  491. if (!pass)
  492. continue;
  493. // Fill the rest of the batch
  494. litBatch.camera_ = camera_;
  495. litBatch.distance_ = drawable->GetDistance();
  496. litBatch.lightQueue_ = &lightQueue;
  497. litBatch.hasPriority_ = priority;
  498. // Check from the ambient pass whether the object is opaque or transparent
  499. Pass* ambientPass = tech->GetPass(PASS_BASE);
  500. if (!ambientPass || ambientPass->GetBlendMode() == BLEND_REPLACE)
  501. {
  502. renderer_->SetBatchShaders(litBatch, tech, pass);
  503. lightQueue.litBatches_.AddBatch(litBatch);
  504. }
  505. else
  506. {
  507. renderer_->SetBatchShaders(litBatch, tech, pass, allowTransparentShadows);
  508. transparentQueue_.AddBatch(litBatch, true);
  509. }
  510. }
  511. }
  512. void View::RenderBatches()
  513. {
  514. // If not reusing shadowmaps, render all of them first
  515. if (!renderer_->reuseShadowMaps_)
  516. {
  517. PROFILE(RenderShadowMaps);
  518. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  519. {
  520. LightBatchQueue& queue = lightQueues_[i];
  521. if (queue.shadowMap_)
  522. RenderShadowMap(queue);
  523. }
  524. }
  525. {
  526. // Render opaque objects' base passes
  527. PROFILE(RenderBasePass);
  528. graphics_->SetRenderTarget(0, renderTarget_);
  529. graphics_->SetDepthStencil(depthStencil_);
  530. graphics_->SetViewport(screenRect_);
  531. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, zone_->GetFogColor());
  532. RenderBatchQueue(baseQueue_);
  533. }
  534. {
  535. // Render shadow maps + opaque objects' shadowed additive lighting
  536. PROFILE(RenderLights);
  537. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  538. {
  539. LightBatchQueue& queue = lightQueues_[i];
  540. // If reusing shadowmaps, render each of them before the lit batches
  541. if (renderer_->reuseShadowMaps_ && queue.shadowMap_)
  542. RenderShadowMap(queue);
  543. graphics_->SetRenderTarget(0, renderTarget_);
  544. graphics_->SetDepthStencil(depthStencil_);
  545. graphics_->SetViewport(screenRect_);
  546. RenderLightBatchQueue(queue.litBatches_, queue.light_);
  547. }
  548. }
  549. graphics_->SetScissorTest(false);
  550. graphics_->SetStencilTest(false);
  551. graphics_->SetRenderTarget(0, renderTarget_);
  552. graphics_->SetDepthStencil(depthStencil_);
  553. graphics_->SetViewport(screenRect_);
  554. if (!extraQueue_.IsEmpty())
  555. {
  556. // Render extra / custom passes
  557. PROFILE(RenderExtraPass);
  558. RenderBatchQueue(extraQueue_);
  559. }
  560. if (!transparentQueue_.IsEmpty())
  561. {
  562. // Render transparent objects last (both base passes & additive lighting)
  563. PROFILE(RenderTransparent);
  564. RenderBatchQueue(transparentQueue_, true);
  565. }
  566. }
  567. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  568. {
  569. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  570. float halfViewSize = camera->GetHalfViewSize();
  571. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  572. Vector3 cameraPos = camera->GetWorldPosition();
  573. for (unsigned i = 0; i < occluders.Size(); ++i)
  574. {
  575. Drawable* occluder = occluders[i];
  576. occluder->UpdateDistance(frame_);
  577. bool erase = false;
  578. // Check occluder's draw distance (in main camera view)
  579. float maxDistance = occluder->GetDrawDistance();
  580. if (maxDistance > 0.0f && occluder->GetDistance() > maxDistance)
  581. erase = true;
  582. // Check that occluder is big enough on the screen
  583. const BoundingBox& box = occluder->GetWorldBoundingBox();
  584. float diagonal = (box.max_ - box.min_).LengthFast();
  585. float compare;
  586. if (!camera->IsOrthographic())
  587. compare = diagonal * halfViewSize / occluder->GetDistance();
  588. else
  589. compare = diagonal * invOrthoSize;
  590. if (compare < occluderSizeThreshold_)
  591. erase = true;
  592. if (!erase)
  593. {
  594. unsigned totalTriangles = 0;
  595. unsigned batches = occluder->GetNumBatches();
  596. Batch tempBatch;
  597. for (unsigned j = 0; j < batches; ++j)
  598. {
  599. occluder->GetBatch(frame_, j, tempBatch);
  600. if (tempBatch.geometry_)
  601. totalTriangles += tempBatch.geometry_->GetIndexCount() / 3;
  602. }
  603. // Store amount of triangles divided by screen size as a sorting key
  604. // (best occluders are big and have few triangles)
  605. occluder->SetSortValue((float)totalTriangles / compare);
  606. }
  607. else
  608. {
  609. occluders.Erase(occluders.Begin() + i);
  610. --i;
  611. }
  612. }
  613. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  614. if (occluders.Size())
  615. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  616. }
  617. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  618. {
  619. for (unsigned i = 0; i < occluders.Size(); ++i)
  620. {
  621. Drawable* occluder = occluders[i];
  622. if (i > 0)
  623. {
  624. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  625. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  626. continue;
  627. }
  628. occluder->UpdateGeometry(frame_);
  629. // Check for running out of triangles
  630. if (!occluder->DrawOcclusion(buffer))
  631. return;
  632. }
  633. }
  634. unsigned View::ProcessLight(Light* light)
  635. {
  636. // Check if light should be shadowed
  637. bool isShadowed = drawShadows_ && light->GetCastShadows() && light->GetShadowIntensity() < 1.0f;
  638. unsigned shadowSplits = 0;
  639. // If shadow distance non-zero, check it
  640. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  641. isShadowed = false;
  642. LightType type = light->GetLightType();
  643. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  644. litGeometries_.Clear();
  645. switch (type)
  646. {
  647. case LIGHT_DIRECTIONAL:
  648. for (unsigned i = 0; i < geometries_.Size(); ++i)
  649. {
  650. if (geometries_[i]->GetLightMask() & light->GetLightMask())
  651. litGeometries_.Push(geometries_[i]);
  652. }
  653. break;
  654. case LIGHT_SPOT:
  655. {
  656. FrustumOctreeQuery query(tempDrawables_, light->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask());
  657. octree_->GetDrawables(query);
  658. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  659. {
  660. if (tempDrawables_[i]->IsInView(frame_) && (tempDrawables_[i]->GetLightMask() & light->GetLightMask()))
  661. litGeometries_.Push(tempDrawables_[i]);
  662. }
  663. }
  664. break;
  665. case LIGHT_POINT:
  666. {
  667. SphereOctreeQuery query(tempDrawables_, Sphere(light->GetWorldPosition(), light->GetRange()), DRAWABLE_GEOMETRY,
  668. camera_->GetViewMask());
  669. octree_->GetDrawables(query);
  670. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  671. {
  672. if (tempDrawables_[i]->IsInView(frame_) && (tempDrawables_[i]->GetLightMask() & light->GetLightMask()))
  673. litGeometries_.Push(tempDrawables_[i]);
  674. }
  675. }
  676. break;
  677. }
  678. // If no lit geometries or not shadowed, no need to process shadow cameras
  679. if (litGeometries_.Empty() || !isShadowed)
  680. return 0;
  681. // Determine number of shadow cameras and setup their initial positions
  682. shadowSplits = SetupShadowCameras(light);
  683. // For a shadowed directional light, get occluders once using the whole (non-split) light frustum
  684. bool useOcclusion = false;
  685. OcclusionBuffer* buffer = 0;
  686. if (maxOccluderTriangles_ > 0 && isShadowed && light->GetLightType() == LIGHT_DIRECTIONAL)
  687. {
  688. // This shadow camera is never used for actually querying shadow casters, just occluders
  689. Camera* shadowCamera = renderer_->CreateShadowCamera();
  690. SetupDirLightShadowCamera(shadowCamera, light, 0.0f, Min(light->GetShadowCascade().GetShadowRange(), camera_->GetFarClip()),
  691. true);
  692. // Get occluders, which must be shadow-casting themselves
  693. FrustumOctreeQuery query(shadowOccluders_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask(),
  694. true, true);
  695. octree_->GetDrawables(query);
  696. UpdateOccluders(shadowOccluders_, shadowCamera);
  697. if (shadowOccluders_.Size())
  698. {
  699. // Shadow viewport is rectangular and consumes more CPU fillrate, so halve size
  700. buffer = renderer_->GetOrCreateOcclusionBuffer(shadowCamera, maxOccluderTriangles_, true);
  701. DrawOccluders(buffer, shadowOccluders_);
  702. buffer->BuildDepthHierarchy();
  703. useOcclusion = true;
  704. }
  705. }
  706. // Process each split for shadow casters
  707. bool hasShadowCasters = false;
  708. for (unsigned i = 0; i < shadowSplits; ++i)
  709. {
  710. shadowCasters_[i].Clear();
  711. shadowCasterBox_[i].defined_ = false;
  712. Camera* shadowCamera = shadowCameras_[i];
  713. if (!useOcclusion)
  714. {
  715. // For spot light (which has only one shadow split) we can optimize by reusing the query for
  716. // lit geometries, whose result still exists in tempDrawables_
  717. if (type != LIGHT_SPOT)
  718. {
  719. Frustum shadowCameraFrustum = shadowCamera->GetFrustum();
  720. // If a point light face, check that the face is visible: if not, there is no need to query and render
  721. // the shadow casters
  722. if (type == LIGHT_POINT)
  723. {
  724. BoundingBox shadowCameraBox(shadowCameraFrustum);
  725. if (frustum_.IsInsideFast(shadowCameraBox) == OUTSIDE)
  726. continue;
  727. }
  728. FrustumOctreeQuery query(tempDrawables_, shadowCameraFrustum, DRAWABLE_GEOMETRY, camera_->GetViewMask(),
  729. false, true);
  730. octree_->GetDrawables(query);
  731. }
  732. }
  733. else
  734. {
  735. OccludedFrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), buffer,
  736. DRAWABLE_GEOMETRY, camera_->GetViewMask(), false, true);
  737. octree_->GetDrawables(query);
  738. }
  739. // Check which shadow casters actually contribute to the shadowing
  740. ProcessShadowCasters(light, i, tempDrawables_, shadowCasterBox_[i]);
  741. if (shadowCasters_[i].Size())
  742. hasShadowCasters = true;
  743. }
  744. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map
  745. // yet, so the only cost is the shadow camera setup & queries
  746. if (!hasShadowCasters)
  747. shadowSplits = 0;
  748. return shadowSplits;
  749. }
  750. void View::ProcessShadowCasters(Light* light, unsigned splitIndex, const PODVector<Drawable*>& result, BoundingBox& shadowCasterBox)
  751. {
  752. Matrix3x4 lightView;
  753. Matrix4 lightProj;
  754. Camera* shadowCamera = shadowCameras_[splitIndex];
  755. lightView = shadowCamera->GetInverseWorldTransform();
  756. lightProj = shadowCamera->GetProjection();
  757. bool dirLight = shadowCamera->IsOrthographic();
  758. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  759. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  760. // frustum, so that shadow casters do not get rendered into unnecessary splits
  761. Frustum lightViewFrustum;
  762. if (!dirLight)
  763. lightViewFrustum = camera_->GetSplitFrustum(sceneViewBox_.min_.z_, sceneViewBox_.max_.z_).Transformed(lightView);
  764. else
  765. lightViewFrustum = camera_->GetSplitFrustum(Max(sceneViewBox_.min_.z_, shadowNearSplits_[splitIndex]),
  766. Min(sceneViewBox_.max_.z_, shadowFarSplits_[splitIndex])).Transformed(lightView);
  767. BoundingBox lightViewFrustumBox(lightViewFrustum);
  768. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  769. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  770. return;
  771. BoundingBox lightViewBox;
  772. BoundingBox lightProjBox;
  773. for (unsigned i = 0; i < result.Size(); ++i)
  774. {
  775. Drawable* drawable = static_cast<Drawable*>(result[i]);
  776. // In case this is a spot light query result reused for optimization, we may have non-shadowcasters included.
  777. // Check for that first
  778. if (!drawable->GetCastShadows())
  779. continue;
  780. drawable->UpdateDistance(frame_);
  781. // Check shadow distance
  782. float maxShadowDistance = drawable->GetShadowDistance();
  783. if (maxShadowDistance > 0.0f && drawable->GetDistance() > maxShadowDistance)
  784. continue;
  785. // Check light mask
  786. if (!(drawable->GetLightMask() & light->GetLightMask()))
  787. continue;
  788. // Project shadow caster bounding box to light view space for visibility check
  789. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  790. if (drawable->IsInView(frame_) || IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum,
  791. lightViewFrustumBox))
  792. {
  793. // Update geometry now if not updated yet
  794. if (!drawable->IsInView(frame_))
  795. {
  796. drawable->MarkInShadowView(frame_);
  797. drawable->UpdateGeometry(frame_);
  798. }
  799. // Merge to shadow caster bounding box and add to the list
  800. if (dirLight)
  801. shadowCasterBox.Merge(lightViewBox);
  802. else
  803. {
  804. lightProjBox = lightViewBox.Projected(lightProj);
  805. shadowCasterBox.Merge(lightProjBox);
  806. }
  807. shadowCasters_[splitIndex].Push(drawable);
  808. }
  809. }
  810. }
  811. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  812. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  813. {
  814. // If shadow caster is also an occluder, must let it be visible, because it has potentially already culled
  815. // away other shadow casters (could also check the actual shadow occluder vector, but that would be slower)
  816. if (drawable->IsOccluder())
  817. return true;
  818. if (shadowCamera->IsOrthographic())
  819. {
  820. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  821. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  822. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  823. }
  824. else
  825. {
  826. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  827. if (drawable->IsInView(frame_))
  828. return true;
  829. // For perspective lights, extrusion direction depends on the position of the shadow caster
  830. Vector3 center = lightViewBox.Center();
  831. Ray extrusionRay(center, center.Normalized());
  832. float extrusionDistance = shadowCamera->GetFarClip();
  833. float originalDistance = Clamp(center.LengthFast(), M_EPSILON, extrusionDistance);
  834. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  835. float sizeFactor = extrusionDistance / originalDistance;
  836. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  837. // than necessary, so the test will be conservative
  838. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  839. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  840. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  841. lightViewBox.Merge(extrudedBox);
  842. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  843. }
  844. }
  845. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  846. {
  847. unsigned width = shadowMap->GetWidth();
  848. unsigned height = shadowMap->GetHeight();
  849. int maxCascades = renderer_->GetMaxShadowCascades();
  850. switch (light->GetLightType())
  851. {
  852. case LIGHT_DIRECTIONAL:
  853. if (maxCascades == 1)
  854. return IntRect(0, 0, width, height);
  855. else if (maxCascades == 2)
  856. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  857. else
  858. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  859. (splitIndex / 2 + 1) * height / 2);
  860. case LIGHT_SPOT:
  861. return IntRect(0, 0, width, height);
  862. case LIGHT_POINT:
  863. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  864. (splitIndex / 2 + 1) * height / 3);
  865. }
  866. return IntRect();
  867. }
  868. void View::OptimizeLightByScissor(Light* light)
  869. {
  870. if (light)
  871. graphics_->SetScissorTest(true, GetLightScissor(light));
  872. else
  873. graphics_->SetScissorTest(false);
  874. }
  875. void View::OptimizeLightByStencil(Light* light)
  876. {
  877. if (light && renderer_->GetLightStencilMasking())
  878. {
  879. Geometry* geometry = renderer_->GetLightGeometry(light);
  880. if (geometry)
  881. {
  882. LightType type = light->GetLightType();
  883. // If the stencil value has wrapped, clear the whole stencil first
  884. if (!lightStencilValue_)
  885. {
  886. graphics_->Clear(CLEAR_STENCIL);
  887. lightStencilValue_ = 1;
  888. }
  889. Matrix3x4 view(camera_->GetInverseWorldTransform());
  890. Matrix4 projection(camera_->GetProjection());
  891. float lightDist;
  892. if (type == LIGHT_POINT)
  893. lightDist = Sphere(light->GetWorldPosition(), light->GetRange() * 1.25f).DistanceFast(camera_->GetWorldPosition());
  894. else
  895. lightDist = light->GetFrustum().Distance(camera_->GetWorldPosition());
  896. // If possible, render the stencil volume front faces. However, close to the near clip plane render back faces instead
  897. // to avoid clipping the front faces.
  898. if (lightDist < camera_->GetNearClip() * 2.0f)
  899. {
  900. graphics_->SetCullMode(CULL_CW);
  901. graphics_->SetDepthTest(CMP_GREATER);
  902. }
  903. else
  904. {
  905. graphics_->SetCullMode(CULL_CCW);
  906. graphics_->SetDepthTest(CMP_LESSEQUAL);
  907. }
  908. graphics_->SetColorWrite(false);
  909. graphics_->SetDepthWrite(false);
  910. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, lightStencilValue_);
  911. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  912. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  913. graphics_->SetShaderParameter(VSP_MODEL, light->GetVolumeTransform());
  914. geometry->Draw(graphics_);
  915. graphics_->ClearTransformSources();
  916. graphics_->SetColorWrite(true);
  917. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, lightStencilValue_);
  918. ++lightStencilValue_;
  919. return;
  920. }
  921. }
  922. graphics_->SetStencilTest(false);
  923. }
  924. const Rect& View::GetLightScissor(Light* light)
  925. {
  926. HashMap<Light*, Rect>::Iterator i = lightScissorCache_.Find(light);
  927. if (i != lightScissorCache_.End())
  928. return i->second_;
  929. Matrix3x4 view(camera_->GetInverseWorldTransform());
  930. Matrix4 projection(camera_->GetProjection());
  931. switch (light->GetLightType())
  932. {
  933. case LIGHT_POINT:
  934. {
  935. BoundingBox viewBox(light->GetWorldBoundingBox().Transformed(view));
  936. return lightScissorCache_[light] = viewBox.Projected(projection);
  937. }
  938. case LIGHT_SPOT:
  939. {
  940. Frustum viewFrustum(light->GetFrustum().Transformed(view));
  941. return lightScissorCache_[light] = viewFrustum.Projected(projection);
  942. }
  943. default:
  944. return lightScissorCache_[light] = Rect::FULL;
  945. }
  946. }
  947. unsigned View::SetupShadowCameras(Light* light)
  948. {
  949. LightType type = light->GetLightType();
  950. if (type == LIGHT_DIRECTIONAL)
  951. {
  952. const CascadeParameters& cascade = light->GetShadowCascade();
  953. int splits = 0;
  954. float nearSplit = camera_->GetNearClip();
  955. float farSplit;
  956. while (splits < renderer_->GetMaxShadowCascades())
  957. {
  958. // If split is completely beyond camera far clip, we are done
  959. if (nearSplit > camera_->GetFarClip())
  960. break;
  961. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  962. if (farSplit <= nearSplit)
  963. break;
  964. // Setup the shadow camera for the split
  965. Camera* shadowCamera = renderer_->CreateShadowCamera();
  966. shadowCameras_[splits] = shadowCamera;
  967. shadowNearSplits_[splits] = nearSplit;
  968. shadowFarSplits_[splits] = farSplit;
  969. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit, false);
  970. nearSplit = farSplit;
  971. ++splits;
  972. }
  973. return splits;
  974. }
  975. if (type == LIGHT_SPOT)
  976. {
  977. Camera* shadowCamera = renderer_->CreateShadowCamera();
  978. shadowCameras_[0] = shadowCamera;
  979. Node* cameraNode = shadowCamera->GetNode();
  980. cameraNode->SetTransform(light->GetWorldPosition(), light->GetWorldRotation());
  981. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  982. shadowCamera->SetFarClip(light->GetRange());
  983. shadowCamera->SetFov(light->GetFov());
  984. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  985. return 1;
  986. }
  987. if (type == LIGHT_POINT)
  988. {
  989. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  990. {
  991. Camera* shadowCamera = renderer_->CreateShadowCamera();
  992. shadowCameras_[i] = shadowCamera;
  993. Node* cameraNode = shadowCamera->GetNode();
  994. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  995. cameraNode->SetPosition(light->GetWorldPosition());
  996. cameraNode->SetDirection(directions[i]);
  997. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  998. shadowCamera->SetFarClip(light->GetRange());
  999. shadowCamera->SetFov(90.0f);
  1000. shadowCamera->SetAspectRatio(1.0f);
  1001. }
  1002. return MAX_CUBEMAP_FACES;
  1003. }
  1004. return 0;
  1005. }
  1006. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit, bool shadowOcclusion)
  1007. {
  1008. Node* cameraNode = shadowCamera->GetNode();
  1009. float extrusionDistance = camera_->GetFarClip();
  1010. const FocusParameters& parameters = light->GetShadowFocus();
  1011. // Calculate initial position & rotation
  1012. Vector3 lightWorldDirection = light->GetWorldRotation() * Vector3::FORWARD;
  1013. Vector3 pos = camera_->GetWorldPosition() - extrusionDistance * lightWorldDirection;
  1014. cameraNode->SetTransform(pos, light->GetWorldRotation());
  1015. // Calculate main camera shadowed frustum in light's view space
  1016. farSplit = Min(farSplit, camera_->GetFarClip());
  1017. // Use the scene Z bounds to limit frustum size if applicable
  1018. if (shadowOcclusion || parameters.focus_)
  1019. {
  1020. nearSplit = Max(sceneViewBox_.min_.z_, nearSplit);
  1021. farSplit = Min(sceneViewBox_.max_.z_, farSplit);
  1022. }
  1023. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  1024. frustumVolume_.Define(splitFrustum);
  1025. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  1026. if (!shadowOcclusion && parameters.focus_)
  1027. {
  1028. PROFILE(ClipFrustumVolume);
  1029. BoundingBox litGeometriesBox;
  1030. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1031. {
  1032. // Skip "infinite" objects like the skybox
  1033. const BoundingBox& geomBox = geometries_[i]->GetWorldBoundingBox();
  1034. if (geomBox.Size().LengthFast() < M_LARGE_VALUE)
  1035. {
  1036. if (geometryDepthBounds_[i].min_ <= farSplit && geometryDepthBounds_[i].max_ >= nearSplit &&
  1037. (geometries_[i]->GetLightMask() & light->GetLightMask()))
  1038. litGeometriesBox.Merge(geomBox);
  1039. }
  1040. }
  1041. if (litGeometriesBox.defined_)
  1042. {
  1043. frustumVolume_.Clip(litGeometriesBox);
  1044. // If volume became empty, restore it to avoid zero size
  1045. if (frustumVolume_.Empty())
  1046. frustumVolume_.Define(splitFrustum);
  1047. }
  1048. }
  1049. // Transform frustum volume to light space
  1050. Matrix3x4 lightView(shadowCamera->GetInverseWorldTransform());
  1051. frustumVolume_.Transform(lightView);
  1052. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  1053. BoundingBox shadowBox;
  1054. if (shadowOcclusion || !parameters.nonUniform_)
  1055. shadowBox.Define(Sphere(frustumVolume_));
  1056. else
  1057. shadowBox.Define(frustumVolume_);
  1058. shadowCamera->SetOrthographic(true);
  1059. shadowCamera->SetAspectRatio(1.0f);
  1060. shadowCamera->SetNearClip(0.0f);
  1061. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1062. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  1063. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  1064. }
  1065. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1066. const BoundingBox& shadowCasterBox)
  1067. {
  1068. const FocusParameters& parameters = light->GetShadowFocus();
  1069. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1070. LightType type = light->GetLightType();
  1071. if (type == LIGHT_DIRECTIONAL)
  1072. {
  1073. BoundingBox shadowBox;
  1074. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1075. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  1076. shadowBox.min_.y_ = -shadowBox.max_.y_;
  1077. shadowBox.min_.x_ = -shadowBox.max_.x_;
  1078. // Requantize and snap to shadow map texels
  1079. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  1080. }
  1081. if (type == LIGHT_SPOT)
  1082. {
  1083. if (parameters.focus_)
  1084. {
  1085. float viewSizeX = Max(fabsf(shadowCasterBox.min_.x_), fabsf(shadowCasterBox.max_.x_));
  1086. float viewSizeY = Max(fabsf(shadowCasterBox.min_.y_), fabsf(shadowCasterBox.max_.y_));
  1087. float viewSize = Max(viewSizeX, viewSizeY);
  1088. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  1089. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  1090. float quantize = parameters.quantize_ * invOrthoSize;
  1091. float minView = parameters.minView_ * invOrthoSize;
  1092. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  1093. if (viewSize < 1.0f)
  1094. shadowCamera->SetZoom(1.0f / viewSize);
  1095. }
  1096. }
  1097. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  1098. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  1099. if (shadowCamera->GetZoom() >= 1.0f)
  1100. {
  1101. if (light->GetLightType() != LIGHT_POINT)
  1102. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  1103. else
  1104. {
  1105. #ifdef USE_OPENGL
  1106. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  1107. #else
  1108. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  1109. #endif
  1110. }
  1111. }
  1112. }
  1113. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1114. const BoundingBox& viewBox)
  1115. {
  1116. Node* cameraNode = shadowCamera->GetNode();
  1117. const FocusParameters& parameters = light->GetShadowFocus();
  1118. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1119. float minX = viewBox.min_.x_;
  1120. float minY = viewBox.min_.y_;
  1121. float maxX = viewBox.max_.x_;
  1122. float maxY = viewBox.max_.y_;
  1123. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  1124. Vector2 viewSize(maxX - minX, maxY - minY);
  1125. // Quantize size to reduce swimming
  1126. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  1127. if (parameters.nonUniform_)
  1128. {
  1129. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1130. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  1131. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1132. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  1133. }
  1134. else if (parameters.focus_)
  1135. {
  1136. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  1137. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1138. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1139. viewSize.y_ = viewSize.x_;
  1140. }
  1141. shadowCamera->SetOrthoSize(viewSize);
  1142. // Center shadow camera to the view space bounding box
  1143. Vector3 pos(shadowCamera->GetWorldPosition());
  1144. Quaternion rot(shadowCamera->GetWorldRotation());
  1145. Vector3 adjust(center.x_, center.y_, 0.0f);
  1146. cameraNode->Translate(rot * adjust);
  1147. // If the shadow map viewport is known, snap to whole texels
  1148. if (shadowMapWidth > 0.0f)
  1149. {
  1150. Vector3 viewPos(rot.Inverse() * cameraNode->GetWorldPosition());
  1151. // Take into account that shadow map border will not be used
  1152. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  1153. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  1154. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  1155. cameraNode->Translate(rot * snap);
  1156. }
  1157. }
  1158. Technique* View::GetTechnique(Drawable* drawable, Material*& material)
  1159. {
  1160. if (!material)
  1161. material = renderer_->GetDefaultMaterial();
  1162. if (!material)
  1163. return 0;
  1164. float lodDistance = drawable->GetLodDistance();
  1165. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  1166. if (techniques.Empty())
  1167. return 0;
  1168. // Check for suitable technique. Techniques should be ordered like this:
  1169. // Most distant & highest quality
  1170. // Most distant & lowest quality
  1171. // Second most distant & highest quality
  1172. // ...
  1173. for (unsigned i = 0; i < techniques.Size(); ++i)
  1174. {
  1175. const TechniqueEntry& entry = techniques[i];
  1176. Technique* technique = entry.technique_;
  1177. if (!technique || (technique->IsSM3() && !graphics_->GetSM3Support()) || materialQuality_ < entry.qualityLevel_)
  1178. continue;
  1179. if (lodDistance >= entry.lodDistance_)
  1180. return technique;
  1181. }
  1182. // If no suitable technique found, fallback to the last
  1183. return techniques.Back().technique_;
  1184. }
  1185. void View::CheckMaterialForAuxView(Material* material)
  1186. {
  1187. const Vector<SharedPtr<Texture> >& textures = material->GetTextures();
  1188. for (unsigned i = 0; i < textures.Size(); ++i)
  1189. {
  1190. // Have to check cube & 2D textures separately
  1191. Texture* texture = textures[i];
  1192. if (texture)
  1193. {
  1194. if (texture->GetType() == Texture2D::GetTypeStatic())
  1195. {
  1196. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1197. RenderSurface* target = tex2D->GetRenderSurface();
  1198. if (target)
  1199. {
  1200. const Viewport& viewport = target->GetViewport();
  1201. if (viewport.scene_ && viewport.camera_)
  1202. renderer_->AddView(target, viewport);
  1203. }
  1204. }
  1205. else if (texture->GetType() == TextureCube::GetTypeStatic())
  1206. {
  1207. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1208. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1209. {
  1210. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  1211. if (target)
  1212. {
  1213. const Viewport& viewport = target->GetViewport();
  1214. if (viewport.scene_ && viewport.camera_)
  1215. renderer_->AddView(target, viewport);
  1216. }
  1217. }
  1218. }
  1219. }
  1220. }
  1221. // Set frame number so that we can early-out next time we come across this material on the same frame
  1222. material->MarkForAuxView(frame_.frameNumber_);
  1223. }
  1224. void View::SortBatches()
  1225. {
  1226. PROFILE(SortBatches);
  1227. baseQueue_.SortFrontToBack();
  1228. extraQueue_.SortFrontToBack();
  1229. transparentQueue_.SortBackToFront();
  1230. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1231. {
  1232. for (unsigned j = 0; j < lightQueues_[i].shadowSplits_.Size(); ++j)
  1233. lightQueues_[i].shadowSplits_[j].shadowBatches_.SortFrontToBack();
  1234. lightQueues_[i].litBatches_.SortFrontToBack();
  1235. }
  1236. }
  1237. void View::PrepareInstancingBuffer()
  1238. {
  1239. PROFILE(PrepareInstancingBuffer);
  1240. unsigned totalInstances = 0;
  1241. totalInstances += baseQueue_.GetNumInstances(renderer_);
  1242. totalInstances += extraQueue_.GetNumInstances(renderer_);
  1243. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1244. {
  1245. for (unsigned j = 0; j < lightQueues_[i].shadowSplits_.Size(); ++j)
  1246. totalInstances += lightQueues_[i].shadowSplits_[j].shadowBatches_.GetNumInstances(renderer_);
  1247. totalInstances += lightQueues_[i].litBatches_.GetNumInstances(renderer_);
  1248. }
  1249. // If fail to set buffer size, fall back to per-group locking
  1250. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  1251. {
  1252. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  1253. unsigned freeIndex = 0;
  1254. void* lockedData = instancingBuffer->Lock(0, totalInstances, LOCK_DISCARD);
  1255. if (lockedData)
  1256. {
  1257. baseQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1258. extraQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1259. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1260. {
  1261. for (unsigned j = 0; j < lightQueues_[i].shadowSplits_.Size(); ++j)
  1262. lightQueues_[i].shadowSplits_[j].shadowBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  1263. lightQueues_[i].litBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  1264. }
  1265. instancingBuffer->Unlock();
  1266. }
  1267. }
  1268. }
  1269. void View::CalculateShaderParameters()
  1270. {
  1271. Time* time = GetSubsystem<Time>();
  1272. float farClip = camera_->GetFarClip();
  1273. float nearClip = camera_->GetNearClip();
  1274. float fogStart = Min(zone_->GetFogStart(), farClip);
  1275. float fogEnd = Min(zone_->GetFogEnd(), farClip);
  1276. if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON))
  1277. fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
  1278. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  1279. Vector4 fogParams(fogStart / farClip, fogEnd / farClip, 1.0f / (fogRange / farClip), 0.0f);
  1280. Vector4 elapsedTime((time->GetTotalMSec() & 0x3fffff) / 1000.0f, 0.0f, 0.0f, 0.0f);
  1281. Vector4 depthMode = Vector4::ZERO;
  1282. if (camera_->IsOrthographic())
  1283. {
  1284. depthMode.x_ = 1.0f;
  1285. #ifdef USE_OPENGL
  1286. depthMode.z_ = 0.5f;
  1287. depthMode.w_ = 0.5f;
  1288. #else
  1289. depthMode.z_ = 1.0f;
  1290. #endif
  1291. }
  1292. else
  1293. depthMode.w_ = 1.0f / camera_->GetFarClip();
  1294. shaderParameters_.Clear();
  1295. shaderParameters_[VSP_DEPTHMODE] = depthMode;
  1296. shaderParameters_[VSP_ELAPSEDTIME] = elapsedTime;
  1297. shaderParameters_[PSP_AMBIENTCOLOR] = zone_->GetAmbientColor().ToVector4();
  1298. shaderParameters_[PSP_ELAPSEDTIME] = elapsedTime;
  1299. shaderParameters_[PSP_FOGCOLOR] = zone_->GetFogColor().ToVector4(),
  1300. shaderParameters_[PSP_FOGPARAMS] = fogParams;
  1301. }
  1302. void View::RenderBatchQueue(const BatchQueue& queue, bool useScissor)
  1303. {
  1304. if (useScissor)
  1305. graphics_->SetScissorTest(false);
  1306. graphics_->SetStencilTest(false);
  1307. // Priority instanced
  1308. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedPriorityBatchGroups_.Begin(); i !=
  1309. queue.sortedPriorityBatchGroups_.End(); ++i)
  1310. {
  1311. BatchGroup* group = *i;
  1312. group->Draw(graphics_, renderer_, shaderParameters_);
  1313. }
  1314. // Priority non-instanced
  1315. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1316. {
  1317. Batch* batch = *i;
  1318. batch->Draw(graphics_, renderer_, shaderParameters_);
  1319. }
  1320. // Non-priority instanced
  1321. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBatchGroups_.Begin(); i != queue.sortedBatchGroups_.End(); ++i)
  1322. {
  1323. BatchGroup* group = *i;
  1324. if (useScissor && group->lightQueue_)
  1325. OptimizeLightByScissor(group->lightQueue_->light_);
  1326. group->Draw(graphics_, renderer_, shaderParameters_);
  1327. }
  1328. // Non-priority non-instanced
  1329. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1330. {
  1331. Batch* batch = *i;
  1332. // For the transparent queue, both priority and non-priority batches are copied here, so check the flag
  1333. if (useScissor)
  1334. {
  1335. if (!batch->hasPriority_ && batch->lightQueue_)
  1336. OptimizeLightByScissor(batch->lightQueue_->light_);
  1337. else
  1338. graphics_->SetScissorTest(false);
  1339. }
  1340. batch->Draw(graphics_, renderer_, shaderParameters_);
  1341. }
  1342. }
  1343. void View::RenderLightBatchQueue(const BatchQueue& queue, Light* light)
  1344. {
  1345. graphics_->SetScissorTest(false);
  1346. graphics_->SetStencilTest(false);
  1347. // Priority instanced
  1348. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedPriorityBatchGroups_.Begin(); i !=
  1349. queue.sortedPriorityBatchGroups_.End(); ++i)
  1350. {
  1351. BatchGroup* group = *i;
  1352. group->Draw(graphics_, renderer_, shaderParameters_);
  1353. }
  1354. // Priority non-instanced
  1355. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1356. {
  1357. Batch* batch = *i;
  1358. batch->Draw(graphics_, renderer_, shaderParameters_);
  1359. }
  1360. // All base passes have been drawn. Optimize at this point by both stencil volume and scissor
  1361. OptimizeLightByStencil(light);
  1362. OptimizeLightByScissor(light);
  1363. // Non-priority instanced
  1364. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBatchGroups_.Begin(); i != queue.sortedBatchGroups_.End(); ++i)
  1365. {
  1366. BatchGroup* group = *i;
  1367. group->Draw(graphics_, renderer_, shaderParameters_);
  1368. }
  1369. // Non-priority non-instanced
  1370. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1371. {
  1372. Batch* batch = *i;
  1373. batch->Draw(graphics_, renderer_, shaderParameters_);
  1374. }
  1375. }
  1376. void View::RenderShadowMap(const LightBatchQueue& queue)
  1377. {
  1378. PROFILE(RenderShadowMap);
  1379. Texture2D* shadowMap = queue.shadowMap_;
  1380. graphics_->SetTexture(TU_SHADOWMAP, 0);
  1381. if (!graphics_->GetFallback())
  1382. {
  1383. graphics_->SetColorWrite(false);
  1384. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  1385. graphics_->SetDepthStencil(shadowMap);
  1386. graphics_->Clear(CLEAR_DEPTH);
  1387. }
  1388. else
  1389. {
  1390. graphics_->SetColorWrite(true);
  1391. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface());
  1392. graphics_->SetDepthStencil(shadowMap->GetRenderSurface()->GetLinkedDepthBuffer());
  1393. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH, Color::WHITE);
  1394. }
  1395. // Set shadow depth bias
  1396. BiasParameters parameters = queue.light_->GetShadowBias();
  1397. // Adjust the light's constant depth bias according to global shadow map resolution
  1398. unsigned shadowMapSize = renderer_->GetShadowMapSize();
  1399. if (shadowMapSize <= 512)
  1400. parameters.constantBias_ *= 2.0f;
  1401. else if (shadowMapSize >= 2048)
  1402. parameters.constantBias_ *= 0.5f;
  1403. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  1404. // Render each of the splits
  1405. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  1406. {
  1407. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  1408. if (!shadowQueue.shadowBatches_.IsEmpty())
  1409. {
  1410. graphics_->SetViewport(shadowQueue.shadowViewport_);
  1411. // Set a scissor rectangle to match possible shadow map size reduction by out-zooming
  1412. // However, do not do this for point lights, which need to render continuously across cube faces
  1413. float width = (float)(shadowQueue.shadowViewport_.right_ - shadowQueue.shadowViewport_.left_);
  1414. if (queue.light_->GetLightType() != LIGHT_POINT)
  1415. {
  1416. float zoom = Min(shadowQueue.shadowCamera_->GetZoom(), width - 2.0f / width);
  1417. Rect zoomRect(Vector2(-1.0f, -1.0f) * zoom, Vector2(1.0f, 1.0f) * zoom);
  1418. graphics_->SetScissorTest(true, zoomRect, false);
  1419. }
  1420. else
  1421. graphics_->SetScissorTest(false);
  1422. // Draw instanced and non-instanced shadow casters
  1423. RenderBatchQueue(shadowQueue.shadowBatches_);
  1424. }
  1425. }
  1426. graphics_->SetColorWrite(true);
  1427. graphics_->SetDepthBias(0.0f, 0.0f);
  1428. graphics_->SetScissorTest(false);
  1429. }