View.cpp 64 KB

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