View.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685
  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 (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.priorityBatchGroups_.Begin(); i !=
  1309. queue.priorityBatchGroups_.End(); ++i)
  1310. {
  1311. const BatchGroup& group = i->second_;
  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 (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.batchGroups_.Begin(); i !=
  1322. queue.batchGroups_.End(); ++i)
  1323. {
  1324. const BatchGroup& group = i->second_;
  1325. if (useScissor && group.lightQueue_)
  1326. OptimizeLightByScissor(group.lightQueue_->light_);
  1327. group.Draw(graphics_, renderer_, shaderParameters_);
  1328. }
  1329. // Non-priority non-instanced
  1330. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1331. {
  1332. Batch* batch = *i;
  1333. // For the transparent queue, both priority and non-priority batches are copied here, so check the flag
  1334. if (useScissor)
  1335. {
  1336. if (!batch->hasPriority_ && batch->lightQueue_)
  1337. OptimizeLightByScissor(batch->lightQueue_->light_);
  1338. else
  1339. graphics_->SetScissorTest(false);
  1340. }
  1341. batch->Draw(graphics_, renderer_, shaderParameters_);
  1342. }
  1343. }
  1344. void View::RenderLightBatchQueue(const BatchQueue& queue, Light* light)
  1345. {
  1346. graphics_->SetScissorTest(false);
  1347. graphics_->SetStencilTest(false);
  1348. // Priority instanced
  1349. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.priorityBatchGroups_.Begin(); i !=
  1350. queue.priorityBatchGroups_.End(); ++i)
  1351. {
  1352. const BatchGroup& group = i->second_;
  1353. group.Draw(graphics_, renderer_, shaderParameters_);
  1354. }
  1355. // Priority non-instanced
  1356. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1357. {
  1358. Batch* batch = *i;
  1359. batch->Draw(graphics_, renderer_, shaderParameters_);
  1360. }
  1361. // All base passes have been drawn. Optimize at this point by both stencil volume and scissor
  1362. OptimizeLightByStencil(light);
  1363. OptimizeLightByScissor(light);
  1364. // Non-priority instanced
  1365. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.batchGroups_.Begin(); i !=
  1366. queue.batchGroups_.End(); ++i)
  1367. {
  1368. const BatchGroup& group = i->second_;
  1369. group.Draw(graphics_, renderer_, shaderParameters_);
  1370. }
  1371. // Non-priority non-instanced
  1372. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1373. {
  1374. Batch* batch = *i;
  1375. batch->Draw(graphics_, renderer_, shaderParameters_);
  1376. }
  1377. }
  1378. void View::RenderShadowMap(const LightBatchQueue& queue)
  1379. {
  1380. PROFILE(RenderShadowMap);
  1381. Texture2D* shadowMap = queue.shadowMap_;
  1382. graphics_->SetTexture(TU_SHADOWMAP, 0);
  1383. if (!graphics_->GetFallback())
  1384. {
  1385. graphics_->SetColorWrite(false);
  1386. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  1387. graphics_->SetDepthStencil(shadowMap);
  1388. graphics_->Clear(CLEAR_DEPTH);
  1389. }
  1390. else
  1391. {
  1392. graphics_->SetColorWrite(true);
  1393. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface());
  1394. graphics_->SetDepthStencil(shadowMap->GetRenderSurface()->GetLinkedDepthBuffer());
  1395. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH, Color::WHITE);
  1396. }
  1397. // Set shadow depth bias
  1398. BiasParameters parameters = queue.light_->GetShadowBias();
  1399. // Adjust the light's constant depth bias according to global shadow map resolution
  1400. unsigned shadowMapSize = renderer_->GetShadowMapSize();
  1401. if (shadowMapSize <= 512)
  1402. parameters.constantBias_ *= 2.0f;
  1403. else if (shadowMapSize >= 2048)
  1404. parameters.constantBias_ *= 0.5f;
  1405. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  1406. // Render each of the splits
  1407. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  1408. {
  1409. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  1410. if (!shadowQueue.shadowBatches_.IsEmpty())
  1411. {
  1412. graphics_->SetViewport(shadowQueue.shadowViewport_);
  1413. // Set a scissor rectangle to match possible shadow map size reduction by out-zooming
  1414. // However, do not do this for point lights, which need to render continuously across cube faces
  1415. float width = (float)(shadowQueue.shadowViewport_.right_ - shadowQueue.shadowViewport_.left_);
  1416. if (queue.light_->GetLightType() != LIGHT_POINT)
  1417. {
  1418. float zoom = Min(shadowQueue.shadowCamera_->GetZoom(), width - 2.0f / width);
  1419. Rect zoomRect(Vector2(-1.0f, -1.0f) * zoom, Vector2(1.0f, 1.0f) * zoom);
  1420. graphics_->SetScissorTest(true, zoomRect, false);
  1421. }
  1422. else
  1423. graphics_->SetScissorTest(false);
  1424. // Draw instanced and non-instanced shadow casters
  1425. RenderBatchQueue(shadowQueue.shadowBatches_);
  1426. }
  1427. }
  1428. graphics_->SetColorWrite(true);
  1429. graphics_->SetDepthBias(0.0f, 0.0f);
  1430. graphics_->SetScissorTest(false);
  1431. }