View.cpp 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255
  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 "Technique.h"
  39. #include "Texture2D.h"
  40. #include "TextureCube.h"
  41. #include "Time.h"
  42. #include "VertexBuffer.h"
  43. #include "View.h"
  44. #include "Zone.h"
  45. #include "DebugNew.h"
  46. static const String aaVariation[] = {
  47. "",
  48. "Ortho"
  49. };
  50. static const Vector3 directions[] =
  51. {
  52. Vector3::RIGHT,
  53. Vector3::LEFT,
  54. Vector3::UP,
  55. Vector3::DOWN,
  56. Vector3::FORWARD,
  57. Vector3::BACK,
  58. };
  59. OBJECTTYPESTATIC(View);
  60. View::View(Context* context) :
  61. Object(context),
  62. graphics_(GetSubsystem<Graphics>()),
  63. renderer_(GetSubsystem<Renderer>()),
  64. octree_(0),
  65. camera_(0),
  66. zone_(0),
  67. renderTarget_(0),
  68. depthStencil_(0),
  69. jitterCounter_(0)
  70. {
  71. frame_.camera_ = 0;
  72. }
  73. View::~View()
  74. {
  75. }
  76. bool View::Define(RenderSurface* renderTarget, const Viewport& viewport)
  77. {
  78. if ((!viewport.scene_) || (!viewport.camera_))
  79. return false;
  80. // If scene is loading asynchronously, it is incomplete and should not be rendered
  81. if (viewport.scene_->IsAsyncLoading())
  82. return false;
  83. Octree* octree = viewport.scene_->GetComponent<Octree>();
  84. if (!octree)
  85. return false;
  86. mode_ = graphics_->GetRenderMode();
  87. // In deferred mode, check for the render texture being too large
  88. if ((mode_ != RENDER_FORWARD) && (renderTarget))
  89. {
  90. if ((renderTarget->GetWidth() > graphics_->GetWidth()) || (renderTarget->GetHeight() > graphics_->GetHeight()))
  91. {
  92. // Display message only once per rendertarget, do not spam each frame
  93. if (gBufferErrorDisplayed_.Find(renderTarget) == gBufferErrorDisplayed_.End())
  94. {
  95. gBufferErrorDisplayed_.Insert(renderTarget);
  96. LOGERROR("Render texture is larger than the G-buffer, can not render");
  97. }
  98. return false;
  99. }
  100. }
  101. octree_ = octree;
  102. camera_ = viewport.camera_;
  103. renderTarget_ = renderTarget;
  104. // If not rendering to the back buffer, get the depth buffer linked to the color render target
  105. if (renderTarget)
  106. depthStencil_ = renderTarget->GetLinkedDepthBuffer();
  107. else
  108. depthStencil_ = 0;
  109. zone_ = renderer_->GetDefaultZone();
  110. // Validate the rect and calculate size. If zero rect, use whole render target size
  111. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  112. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  113. if (viewport.rect_ != IntRect::ZERO)
  114. {
  115. screenRect_.left_ = Clamp(viewport.rect_.left_, 0, rtWidth - 1);
  116. screenRect_.top_ = Clamp(viewport.rect_.top_, 0, rtHeight - 1);
  117. screenRect_.right_ = Clamp(viewport.rect_.right_, screenRect_.left_ + 1, rtWidth);
  118. screenRect_.bottom_ = Clamp(viewport.rect_.bottom_, screenRect_.top_ + 1, rtHeight);
  119. }
  120. else
  121. screenRect_ = IntRect(0, 0, rtWidth, rtHeight);
  122. width_ = screenRect_.right_ - screenRect_.left_;
  123. height_ = screenRect_.bottom_ - screenRect_.top_;
  124. // Set possible quality overrides from the camera
  125. drawShadows_ = renderer_->GetDrawShadows();
  126. materialQuality_ = renderer_->GetMaterialQuality();
  127. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  128. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  129. if (viewOverrideFlags & VOF_LOW_MATERIAL_QUALITY)
  130. materialQuality_ = QUALITY_LOW;
  131. if (viewOverrideFlags & VOF_DISABLE_SHADOWS)
  132. drawShadows_ = false;
  133. if (viewOverrideFlags & VOF_DISABLE_OCCLUSION)
  134. maxOccluderTriangles_ = 0;
  135. return true;
  136. }
  137. void View::Update(const FrameInfo& frame)
  138. {
  139. if ((!camera_) || (!octree_))
  140. return;
  141. frame_.camera_ = camera_;
  142. frame_.timeStep_ = frame.timeStep_;
  143. frame_.frameNumber_ = frame.frameNumber_;
  144. frame_.viewSize_ = IntVector2(width_, height_);
  145. // Clear old light scissor cache, geometry, light, occluder & batch lists
  146. lightScissorCache_.Clear();
  147. geometries_.Clear();
  148. geometryDepthBounds_.Clear();
  149. lights_.Clear();
  150. occluders_.Clear();
  151. shadowOccluders_.Clear();
  152. gBufferQueue_.Clear();
  153. baseQueue_.Clear();
  154. extraQueue_.Clear();
  155. transparentQueue_.Clear();
  156. noShadowLightQueue_.Clear();
  157. lightQueues_.Clear();
  158. // Set automatic aspect ratio if required
  159. if (camera_->GetAutoAspectRatio())
  160. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  161. // Reset projection jitter if was used last frame
  162. camera_->SetProjectionOffset(Vector2::ZERO);
  163. // Reset shadow map use count; they can be reused between views as each is rendered completely at a time
  164. renderer_->ResetShadowMapUseCount();
  165. GetDrawables();
  166. GetBatches();
  167. }
  168. void View::Render()
  169. {
  170. if ((!octree_) || (!camera_))
  171. return;
  172. // If stream offset is supported, write all instance transforms to a single large buffer
  173. // Else we must lock the instance buffer for each batch group
  174. if ((renderer_->GetDynamicInstancing()) && (graphics_->GetStreamOffsetSupport()))
  175. PrepareInstancingBuffer();
  176. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  177. // again to ensure correct projection will be used
  178. if (camera_->GetAutoAspectRatio())
  179. camera_->SetAspectRatio((float)(screenRect_.right_ - screenRect_.left_) / (float)(screenRect_.bottom_ - screenRect_.top_));
  180. // Set the "view texture" to ensure the rendertarget will not be bound as a texture during rendering
  181. if (renderTarget_)
  182. graphics_->SetViewTexture(renderTarget_->GetParentTexture());
  183. else
  184. graphics_->SetViewTexture(0);
  185. graphics_->SetFillMode(FILL_SOLID);
  186. // Calculate view-global shader parameters
  187. CalculateShaderParameters();
  188. // If not reusing shadowmaps, render all of them first
  189. if (!renderer_->reuseShadowMaps_)
  190. {
  191. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  192. {
  193. LightBatchQueue& queue = lightQueues_[i];
  194. if (queue.light_->GetShadowMap())
  195. RenderShadowMap(queue);
  196. }
  197. }
  198. if (mode_ == RENDER_FORWARD)
  199. RenderBatchesForward();
  200. else
  201. RenderBatchesDeferred();
  202. graphics_->SetViewTexture(0);
  203. // If this is a main view, draw the associated debug geometry now
  204. if (!renderTarget_)
  205. {
  206. Scene* scene = static_cast<Scene*>(octree_->GetNode());
  207. if (scene)
  208. {
  209. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  210. if (debug)
  211. {
  212. debug->SetView(camera_);
  213. debug->Render();
  214. }
  215. }
  216. }
  217. // "Forget" the camera, octree and zone after rendering
  218. camera_ = 0;
  219. octree_ = 0;
  220. zone_ = 0;
  221. frame_.camera_ = 0;
  222. }
  223. void View::GetDrawables()
  224. {
  225. PROFILE(GetDrawables);
  226. Vector3 cameraPos = camera_->GetWorldPosition();
  227. // Get zones & find the zone camera is in
  228. PODVector<Zone*> zones;
  229. PointOctreeQuery query(reinterpret_cast<PODVector<Drawable*>& >(zones), cameraPos, DRAWABLE_ZONE);
  230. octree_->GetDrawables(query);
  231. int highestZonePriority = M_MIN_INT;
  232. for (unsigned i = 0; i < zones.Size(); ++i)
  233. {
  234. Zone* zone = zones[i];
  235. if ((zone->IsInside(cameraPos)) && (zone->GetPriority() > highestZonePriority))
  236. {
  237. zone_ = zone;
  238. highestZonePriority = zone->GetPriority();
  239. }
  240. }
  241. // If occlusion in use, get & render the occluders, then build the depth buffer hierarchy
  242. bool useOcclusion = false;
  243. OcclusionBuffer* buffer = 0;
  244. if (maxOccluderTriangles_ > 0)
  245. {
  246. FrustumOctreeQuery query(occluders_, camera_->GetFrustum(), DRAWABLE_GEOMETRY, true, false);
  247. octree_->GetDrawables(query);
  248. UpdateOccluders(occluders_, camera_);
  249. if (occluders_.Size())
  250. {
  251. buffer = renderer_->GetOrCreateOcclusionBuffer(camera_, maxOccluderTriangles_);
  252. DrawOccluders(buffer, occluders_);
  253. buffer->BuildDepthHierarchy();
  254. useOcclusion = true;
  255. }
  256. }
  257. if (!useOcclusion)
  258. {
  259. // Get geometries & lights without occlusion
  260. FrustumOctreeQuery query(tempDrawables_, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  261. octree_->GetDrawables(query);
  262. }
  263. else
  264. {
  265. // Get geometries & lights using occlusion
  266. OccludedFrustumOctreeQuery query(tempDrawables_, camera_->GetFrustum(), buffer, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  267. octree_->GetDrawables(query);
  268. }
  269. // Sort into geometries & lights, and build visible scene bounding boxes in world and view space
  270. sceneBox_.min_ = sceneBox_.max_ = Vector3::ZERO;
  271. sceneBox_.defined_ = false;
  272. sceneViewBox_.min_ = sceneViewBox_.max_ = Vector3::ZERO;
  273. sceneViewBox_.defined_ = false;
  274. Matrix3x4 view(camera_->GetInverseWorldTransform());
  275. unsigned cameraViewMask = camera_->GetViewMask();
  276. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  277. {
  278. Drawable* drawable = tempDrawables_[i];
  279. // Check view mask
  280. if (!(cameraViewMask & drawable->GetViewMask()))
  281. continue;
  282. drawable->UpdateDistance(frame_);
  283. // If draw distance non-zero, check it
  284. float maxDistance = drawable->GetDrawDistance();
  285. if ((maxDistance > 0.0f) && (drawable->GetDistance() > maxDistance))
  286. continue;
  287. unsigned flags = drawable->GetDrawableFlags();
  288. if (flags & DRAWABLE_GEOMETRY)
  289. {
  290. drawable->ClearBasePass();
  291. drawable->MarkInView(frame_);
  292. drawable->UpdateGeometry(frame_);
  293. // Expand the scene bounding boxes
  294. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  295. BoundingBox geoview_Box = geomBox.Transformed(view);
  296. sceneBox_.Merge(geomBox);
  297. sceneViewBox_.Merge(geoview_Box);
  298. // Store depth info to speed up split directional light queries
  299. GeometryDepthBounds bounds;
  300. bounds.min_ = geoview_Box.min_.z_;
  301. bounds.max_ = geoview_Box.max_.z_;
  302. geometryDepthBounds_.Push(bounds);
  303. geometries_.Push(drawable);
  304. }
  305. else if (flags & DRAWABLE_LIGHT)
  306. {
  307. Light* light = static_cast<Light*>(drawable);
  308. // Skip if light is culled by the zone
  309. if (!(light->GetViewMask() & zone_->GetViewMask()))
  310. continue;
  311. light->MarkInView(frame_);
  312. lights_.Push(light);
  313. }
  314. }
  315. // Sort the lights to brightest/closest first
  316. for (unsigned i = 0; i < lights_.Size(); ++i)
  317. lights_[i]->SetIntensitySortValue(cameraPos);
  318. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  319. }
  320. void View::GetBatches()
  321. {
  322. HashSet<LitTransparencyCheck> litTransparencies;
  323. HashSet<Drawable*> maxLightsDrawables;
  324. Map<Light*, unsigned> lightQueueIndex;
  325. PassType gBufferPass = PASS_DEFERRED;
  326. PassType additionalPass = PASS_EXTRA;
  327. if (mode_ == RENDER_PREPASS)
  328. {
  329. gBufferPass = PASS_PREPASS;
  330. additionalPass = PASS_MATERIAL;
  331. }
  332. // Go through lights
  333. {
  334. PROFILE_MULTIPLE(GetLightBatches, lights_.Size());
  335. unsigned lightQueueCount = 0;
  336. for (unsigned i = 0; i < lights_.Size(); ++i)
  337. {
  338. Light* light = lights_[i];
  339. unsigned splits = ProcessLight(light);
  340. if (!splits)
  341. continue;
  342. // Prepare lit object + shadow caster queues for each split
  343. if (lightQueues_.Size() < lightQueueCount + splits)
  344. lightQueues_.Resize(lightQueueCount + splits);
  345. unsigned prevLightQueueCount = lightQueueCount;
  346. for (unsigned j = 0; j < splits; ++j)
  347. {
  348. Light* SplitLight = splitLights_[j];
  349. LightBatchQueue& lightQueue = lightQueues_[lightQueueCount];
  350. lightQueue.light_ = SplitLight;
  351. lightQueue.shadowBatches_.Clear();
  352. lightQueue.litBatches_.Clear();
  353. lightQueue.volumeBatches_.Clear();
  354. lightQueue.lastSplit_ = false;
  355. // Loop through shadow casters
  356. Camera* shadowCamera = SplitLight->GetShadowCamera();
  357. for (unsigned k = 0; k < shadowCasters_[j].Size(); ++k)
  358. {
  359. Drawable* drawable = shadowCasters_[j][k];
  360. unsigned numBatches = drawable->GetNumBatches();
  361. for (unsigned l = 0; l < numBatches; ++l)
  362. {
  363. Batch shadowBatch;
  364. drawable->GetBatch(frame_, l, shadowBatch);
  365. Technique* tech = GetTechnique(drawable, shadowBatch.material_);
  366. if ((!shadowBatch.geometry_) || (!tech))
  367. continue;
  368. Pass* pass = tech->GetPass(PASS_SHADOW);
  369. // Skip if material has no shadow pass
  370. if (!pass)
  371. continue;
  372. // Fill the rest of the batch
  373. shadowBatch.camera_ = shadowCamera;
  374. shadowBatch.distance_ = shadowCamera->GetDistance(drawable->GetWorldPosition());
  375. shadowBatch.light_ = SplitLight;
  376. shadowBatch.hasPriority_ = (!pass->GetAlphaTest()) && (!pass->GetAlphaMask());
  377. renderer_->SetBatchShaders(shadowBatch, tech, pass);
  378. lightQueue.shadowBatches_.AddBatch(shadowBatch);
  379. }
  380. }
  381. // Loop through lit geometries
  382. if (litGeometries_[j].Size())
  383. {
  384. bool storeLightQueue = true;
  385. for (unsigned k = 0; k < litGeometries_[j].Size(); ++k)
  386. {
  387. Drawable* drawable = litGeometries_[j][k];
  388. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  389. if (!drawable->GetMaxLights())
  390. GetLitBatches(drawable, light, SplitLight, &lightQueue, litTransparencies, gBufferPass);
  391. else
  392. {
  393. drawable->AddLight(SplitLight);
  394. maxLightsDrawables.Insert(drawable);
  395. }
  396. }
  397. // Store the light queue, and light volume batch in deferred mode
  398. if (mode_ != RENDER_FORWARD)
  399. {
  400. Batch volumeBatch;
  401. volumeBatch.geometry_ = renderer_->GetLightGeometry(SplitLight);
  402. volumeBatch.worldTransform_ = &SplitLight->GetVolumeTransform(*camera_);
  403. volumeBatch.overrideView_ = SplitLight->GetLightType() == LIGHT_DIRECTIONAL;
  404. volumeBatch.camera_ = camera_;
  405. volumeBatch.light_ = SplitLight;
  406. volumeBatch.distance_ = SplitLight->GetDistance();
  407. renderer_->SetLightVolumeShaders(volumeBatch);
  408. // If light is a split point light, it must be treated as shadowed in any case for correct stencil clearing
  409. if ((SplitLight->GetShadowMap()) || (SplitLight->GetLightType() == LIGHT_SPLITPOINT))
  410. lightQueue.volumeBatches_.Push(volumeBatch);
  411. else
  412. {
  413. storeLightQueue = false;
  414. noShadowLightQueue_.AddBatch(volumeBatch, true);
  415. }
  416. }
  417. if (storeLightQueue)
  418. {
  419. lightQueueIndex[SplitLight] = lightQueueCount;
  420. ++lightQueueCount;
  421. }
  422. }
  423. }
  424. // Mark the last split
  425. if (lightQueueCount != prevLightQueueCount)
  426. lightQueues_[lightQueueCount - 1].lastSplit_ = true;
  427. }
  428. // Resize the light queue vector now that final size is known
  429. lightQueues_.Resize(lightQueueCount);
  430. }
  431. // Process drawables with limited light count
  432. if (maxLightsDrawables.Size())
  433. {
  434. PROFILE(GetMaxLightsBatches);
  435. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables.Begin(); i != maxLightsDrawables.End(); ++i)
  436. {
  437. Drawable* drawable = *i;
  438. drawable->LimitLights();
  439. const PODVector<Light*>& lights = drawable->GetLights();
  440. for (unsigned i = 0; i < lights.Size(); ++i)
  441. {
  442. Light* SplitLight = lights[i];
  443. Light* light = SplitLight->GetOriginalLight();
  444. if (!light)
  445. light = SplitLight;
  446. // Find the correct light queue again
  447. LightBatchQueue* queue = 0;
  448. Map<Light*, unsigned>::Iterator j = lightQueueIndex.Find(SplitLight);
  449. if (j != lightQueueIndex.End())
  450. queue = &lightQueues_[j->second_];
  451. GetLitBatches(drawable, light, SplitLight, queue, litTransparencies, gBufferPass);
  452. }
  453. }
  454. }
  455. // Go through geometries for base pass batches
  456. {
  457. PROFILE(GetBaseBatches);
  458. for (unsigned i = 0; i < geometries_.Size(); ++i)
  459. {
  460. Drawable* drawable = geometries_[i];
  461. unsigned numBatches = drawable->GetNumBatches();
  462. for (unsigned j = 0; j < numBatches; ++j)
  463. {
  464. Batch baseBatch;
  465. drawable->GetBatch(frame_, j, baseBatch);
  466. Technique* tech = GetTechnique(drawable, baseBatch.material_);
  467. if ((!baseBatch.geometry_) || (!tech))
  468. continue;
  469. // Check here if the material technique refers to a render target texture with camera(s) attached
  470. // Only check this for the main view (null rendertarget)
  471. if ((!renderTarget_) && (baseBatch.material_) && (baseBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_))
  472. CheckMaterialForAuxView(baseBatch.material_);
  473. // If object already has a lit base pass, can skip the unlit base pass
  474. if (drawable->HasBasePass(j))
  475. continue;
  476. // Fill the rest of the batch
  477. baseBatch.camera_ = camera_;
  478. baseBatch.distance_ = drawable->GetDistance();
  479. Pass* pass = 0;
  480. // In deferred mode, check for a G-buffer batch first
  481. if (mode_ != RENDER_FORWARD)
  482. {
  483. pass = tech->GetPass(gBufferPass);
  484. if (pass)
  485. {
  486. renderer_->SetBatchShaders(baseBatch, tech, pass);
  487. baseBatch.hasPriority_ = (!pass->GetAlphaTest()) && (!pass->GetAlphaMask());
  488. gBufferQueue_.AddBatch(baseBatch);
  489. // Check also for an additional pass. In light prepass mode this actually renders the visible geometry
  490. pass = tech->GetPass(additionalPass);
  491. if (pass)
  492. {
  493. renderer_->SetBatchShaders(baseBatch, tech, pass);
  494. baseQueue_.AddBatch(baseBatch);
  495. }
  496. continue;
  497. }
  498. }
  499. // Then check for forward rendering base pass
  500. pass = tech->GetPass(PASS_BASE);
  501. if (pass)
  502. {
  503. renderer_->SetBatchShaders(baseBatch, tech, pass);
  504. if (pass->GetBlendMode() == BLEND_REPLACE)
  505. {
  506. baseBatch.hasPriority_ = (!pass->GetAlphaTest()) && (!pass->GetAlphaMask());
  507. baseQueue_.AddBatch(baseBatch);
  508. }
  509. else
  510. {
  511. baseBatch.hasPriority_ = true;
  512. transparentQueue_.AddBatch(baseBatch, true);
  513. }
  514. continue;
  515. }
  516. else
  517. {
  518. // If no base pass, finally check for extra / custom pass
  519. pass = tech->GetPass(PASS_EXTRA);
  520. if (pass)
  521. {
  522. baseBatch.hasPriority_ = false;
  523. renderer_->SetBatchShaders(baseBatch, tech, pass);
  524. extraQueue_.AddBatch(baseBatch);
  525. }
  526. }
  527. }
  528. }
  529. }
  530. // All batches have been collected. Sort them now
  531. SortBatches();
  532. }
  533. void View::GetLitBatches(Drawable* drawable, Light* light, Light* SplitLight, LightBatchQueue* lightQueue,
  534. HashSet<LitTransparencyCheck>& litTransparencies, PassType gBufferPass)
  535. {
  536. bool splitPointLight = SplitLight->GetLightType() == LIGHT_SPLITPOINT;
  537. // Whether to allow shadows for transparencies, or for forward lit objects in deferred mode
  538. bool allowShadows = (!renderer_->reuseShadowMaps_) && (!splitPointLight);
  539. unsigned numBatches = drawable->GetNumBatches();
  540. for (unsigned i = 0; i < numBatches; ++i)
  541. {
  542. Batch litBatch;
  543. drawable->GetBatch(frame_, i, litBatch);
  544. Technique* tech = GetTechnique(drawable, litBatch.material_);
  545. if ((!litBatch.geometry_) || (!tech))
  546. continue;
  547. // If material uses opaque G-buffer rendering, skip
  548. if ((mode_ != RENDER_FORWARD) && (tech->HasPass(gBufferPass)))
  549. continue;
  550. Pass* pass = 0;
  551. bool priority = false;
  552. // For directional light, check for lit base pass
  553. if (SplitLight->GetLightType() == LIGHT_DIRECTIONAL)
  554. {
  555. if (!drawable->HasBasePass(i))
  556. {
  557. pass = tech->GetPass(PASS_LITBASE);
  558. if (pass)
  559. {
  560. priority = true;
  561. drawable->SetBasePass(i);
  562. }
  563. }
  564. }
  565. // If no first light pass, get ordinary light pass
  566. if (!pass)
  567. pass = tech->GetPass(PASS_LIGHT);
  568. // Skip if material does not receive light at all
  569. if (!pass)
  570. continue;
  571. // Fill the rest of the batch
  572. litBatch.camera_ = camera_;
  573. litBatch.distance_ = drawable->GetDistance();
  574. litBatch.light_ = SplitLight;
  575. litBatch.hasPriority_ = priority;
  576. // Check from the ambient pass whether the object is opaque
  577. Pass* ambientPass = tech->GetPass(PASS_BASE);
  578. if ((!ambientPass) || (ambientPass->GetBlendMode() == BLEND_REPLACE))
  579. {
  580. if (mode_ == RENDER_FORWARD)
  581. {
  582. if (lightQueue)
  583. {
  584. renderer_->SetBatchShaders(litBatch, tech, pass);
  585. lightQueue->litBatches_.AddBatch(litBatch);
  586. }
  587. }
  588. else
  589. {
  590. renderer_->SetBatchShaders(litBatch, tech, pass, allowShadows);
  591. baseQueue_.AddBatch(litBatch);
  592. }
  593. }
  594. else
  595. {
  596. if (splitPointLight)
  597. {
  598. // Check if already lit
  599. LitTransparencyCheck check(light, drawable, i);
  600. if (litTransparencies.Find(check) != litTransparencies.End())
  601. continue;
  602. // Use the original light instead of the split one, to choose correct scissor
  603. litBatch.light_ = light;
  604. litTransparencies.Insert(check);
  605. }
  606. renderer_->SetBatchShaders(litBatch, tech, pass, allowShadows);
  607. transparentQueue_.AddBatch(litBatch, true);
  608. }
  609. }
  610. }
  611. void View::RenderBatchesForward()
  612. {
  613. {
  614. // Render opaque objects' base passes
  615. PROFILE(RenderBasePass);
  616. graphics_->ClearLastParameterSources();
  617. graphics_->SetColorWrite(true);
  618. graphics_->SetStencilTest(false);
  619. graphics_->SetRenderTarget(0, renderTarget_);
  620. graphics_->SetDepthStencil(depthStencil_);
  621. graphics_->SetViewport(screenRect_);
  622. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, zone_->GetFogColor());
  623. RenderBatchQueue(baseQueue_);
  624. }
  625. {
  626. // Render shadow maps + opaque objects' shadowed additive lighting
  627. PROFILE(RenderLights);
  628. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  629. {
  630. LightBatchQueue& queue = lightQueues_[i];
  631. // If reusing shadowmaps, render each of them before the lit batches
  632. if ((renderer_->reuseShadowMaps_) && (queue.light_->GetShadowMap()))
  633. RenderShadowMap(queue);
  634. graphics_->ClearLastParameterSources();
  635. graphics_->SetRenderTarget(0, renderTarget_);
  636. graphics_->SetDepthStencil(depthStencil_);
  637. graphics_->SetViewport(screenRect_);
  638. RenderForwardLightBatchQueue(queue.litBatches_, queue.light_);
  639. // Clear the stencil buffer after the last split
  640. if (queue.lastSplit_)
  641. {
  642. LightType type = queue.light_->GetLightType();
  643. if ((type == LIGHT_SPLITPOINT) || (type == LIGHT_DIRECTIONAL))
  644. DrawSplitLightToStencil(*camera_, queue.light_, true);
  645. }
  646. }
  647. }
  648. {
  649. // Render extra / custom passes
  650. PROFILE(RenderExtraPass);
  651. graphics_->ClearLastParameterSources();
  652. graphics_->SetRenderTarget(0, renderTarget_);
  653. graphics_->SetDepthStencil(depthStencil_);
  654. graphics_->SetViewport(screenRect_);
  655. RenderBatchQueue(extraQueue_);
  656. }
  657. {
  658. // Render transparent objects last (both base passes & additive lighting)
  659. PROFILE(RenderTransparent);
  660. RenderBatchQueue(transparentQueue_, true);
  661. }
  662. }
  663. void View::RenderBatchesDeferred()
  664. {
  665. bool deferred = mode_ != RENDER_PREPASS;
  666. Texture2D* diffBuffer = graphics_->GetDiffBuffer();
  667. Texture2D* normalBuffer = graphics_->GetNormalBuffer();
  668. Texture2D* depthBuffer = graphics_->GetDepthBuffer();
  669. // Check for temporal antialiasing in deferred mode. Only use it on the main view (null rendertarget)
  670. bool temporalAA = (!renderTarget_) && (graphics_->GetMultiSample() > 0);
  671. if (temporalAA)
  672. {
  673. ++jitterCounter_;
  674. if (jitterCounter_ > 3)
  675. jitterCounter_ = 2;
  676. Vector2 jitter(-0.25f, -0.25f);
  677. if (jitterCounter_ & 1)
  678. jitter = -jitter;
  679. jitter.x_ /= width_;
  680. jitter.y_ /= height_;
  681. camera_->SetProjectionOffset(jitter);
  682. }
  683. RenderSurface* renderBuffer = temporalAA ? graphics_->GetScreenBuffer(jitterCounter_ & 1)->GetRenderSurface() : renderTarget_;
  684. // Set shader parameters needed only in deferred rendering
  685. Vector3 nearVector, farVector;
  686. camera_->GetFrustumSize(nearVector, farVector);
  687. Vector4 viewportParams(farVector.x_, farVector.y_, farVector.z_, 0.0f);
  688. float gBufferWidth = (float)diffBuffer->GetWidth();
  689. float gBufferHeight = (float)diffBuffer->GetHeight();
  690. float widthRange = 0.5f * width_ / gBufferWidth;
  691. float heightRange = 0.5f * height_ / gBufferHeight;
  692. Vector4 bufferUVOffset((0.5f + (float)screenRect_.left_) / gBufferWidth + widthRange,
  693. (0.5f + (float)screenRect_.top_) / gBufferHeight + heightRange, widthRange, heightRange);
  694. Vector4 viewportSize((float)screenRect_.left_ / gBufferWidth, (float)screenRect_.top_ / gBufferHeight,
  695. (float)screenRect_.right_ / gBufferWidth, (float)screenRect_.bottom_ / gBufferHeight);
  696. shaderParameters_[VSP_FRUSTUMSIZE] = viewportParams;
  697. shaderParameters_[VSP_GBUFFEROFFSETS] = bufferUVOffset;
  698. shaderParameters_[PSP_GBUFFEROFFSETS] = bufferUVOffset;
  699. shaderParameters_[PSP_GBUFFERVIEWPORT] = viewportSize;
  700. {
  701. // Render G-buffer
  702. PROFILE(RenderGBuffer);
  703. graphics_->ClearLastParameterSources();
  704. // Use always the default depth stencil, so that it matches the G-buffer size, and is in the expected format
  705. // Enable depth rendertarget only if hardware depth not supported
  706. graphics_->SetColorWrite(true);
  707. graphics_->SetScissorTest(false);
  708. graphics_->SetStencilTest(false);
  709. graphics_->ResetDepthStencil();
  710. if (deferred)
  711. {
  712. graphics_->SetRenderTarget(0, diffBuffer);
  713. graphics_->SetRenderTarget(1, normalBuffer);
  714. graphics_->SetRenderTarget(2, depthBuffer);
  715. }
  716. else
  717. {
  718. graphics_->SetRenderTarget(0, normalBuffer);
  719. graphics_->SetRenderTarget(1, depthBuffer);
  720. }
  721. graphics_->SetViewport(screenRect_);
  722. // Clear only depth and stencil at first, render the G-buffer batches
  723. graphics_->Clear(CLEAR_DEPTH | CLEAR_STENCIL);
  724. RenderBatchQueue(gBufferQueue_);
  725. // Then fill the untouched parts of the G-buffer with defaults: black diffuse + specular (deferred only), far depth
  726. graphics_->SetAlphaTest(false);
  727. graphics_->SetBlendMode(BLEND_REPLACE);
  728. graphics_->SetDepthTest(CMP_LESSEQUAL);
  729. graphics_->SetDepthWrite(false);
  730. if (deferred)
  731. {
  732. graphics_->ResetRenderTarget(2);
  733. graphics_->SetRenderTarget(1, depthBuffer);
  734. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("Deferred/GBufferFill"),
  735. renderer_->GetPixelShader("Deferred/GBufferFill"), false, shaderParameters_);
  736. }
  737. else
  738. {
  739. graphics_->ResetRenderTarget(1);
  740. graphics_->SetRenderTarget(0, depthBuffer);
  741. graphics_->SetViewport(screenRect_);
  742. // The stencil shader writes color 1.0, which equals far depth
  743. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("Stencil"),
  744. renderer_->GetPixelShader("Stencil"), false, shaderParameters_);
  745. }
  746. }
  747. if (deferred)
  748. {
  749. // Render ambient color & fog
  750. graphics_->ClearLastParameterSources();
  751. graphics_->SetDepthTest(CMP_ALWAYS);
  752. graphics_->SetRenderTarget(0, renderBuffer);
  753. graphics_->ResetRenderTarget(1);
  754. graphics_->ResetRenderTarget(2);
  755. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  756. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  757. graphics_->SetViewport(screenRect_);
  758. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("Deferred/Ambient"),
  759. renderer_->GetPixelShader("Deferred/Ambient"), false, shaderParameters_);
  760. }
  761. else
  762. {
  763. // Light prepass: reset the light accumulation buffer with black color
  764. graphics_->SetRenderTarget(0, diffBuffer);
  765. graphics_->ResetRenderTarget(1);
  766. graphics_->SetViewport(screenRect_);
  767. graphics_->Clear(CLEAR_COLOR);
  768. }
  769. {
  770. // Render lights
  771. PROFILE(RenderLights);
  772. // Shadowed lights
  773. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  774. {
  775. LightBatchQueue& queue = lightQueues_[i];
  776. // If reusing shadowmaps, render each of them before the lit batches
  777. if ((renderer_->reuseShadowMaps_) && (queue.light_->GetShadowMap()))
  778. RenderShadowMap(queue);
  779. // Light volume batches are not sorted as there should be only one of them
  780. if (queue.volumeBatches_.Size())
  781. {
  782. graphics_->ClearLastParameterSources();
  783. if (deferred)
  784. {
  785. graphics_->SetRenderTarget(0, renderBuffer);
  786. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  787. }
  788. else
  789. graphics_->SetRenderTarget(0, diffBuffer);
  790. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  791. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  792. graphics_->ResetDepthStencil();
  793. graphics_->SetViewport(screenRect_);
  794. for (unsigned j = 0; j < queue.volumeBatches_.Size(); ++j)
  795. {
  796. renderer_->SetupLightBatch(queue.volumeBatches_[j]);
  797. queue.volumeBatches_[j].Draw(graphics_, shaderParameters_);
  798. }
  799. // If was the last split of a split point light, clear the stencil by rendering the point light again
  800. if ((queue.lastSplit_) && (queue.light_->GetLightType() == LIGHT_SPLITPOINT))
  801. DrawSplitLightToStencil(*camera_, queue.light_, true);
  802. }
  803. }
  804. // Non-shadowed lights
  805. if (noShadowLightQueue_.sortedBatches_.Size())
  806. {
  807. graphics_->ClearLastParameterSources();
  808. if (deferred)
  809. {
  810. graphics_->SetRenderTarget(0, renderBuffer);
  811. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  812. }
  813. else
  814. graphics_->SetRenderTarget(0, diffBuffer);
  815. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  816. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  817. graphics_->ResetDepthStencil();
  818. graphics_->SetViewport(screenRect_);
  819. for (unsigned i = 0; i < noShadowLightQueue_.sortedBatches_.Size(); ++i)
  820. {
  821. renderer_->SetupLightBatch(*noShadowLightQueue_.sortedBatches_[i]);
  822. noShadowLightQueue_.sortedBatches_[i]->Draw(graphics_, shaderParameters_);
  823. }
  824. }
  825. }
  826. {
  827. // Render base passes
  828. PROFILE(RenderBasePass);
  829. graphics_->ClearLastParameterSources();
  830. graphics_->SetStencilTest(false);
  831. graphics_->SetRenderTarget(0, renderBuffer);
  832. graphics_->SetTexture(TU_DIFFBUFFER, 0);
  833. graphics_->SetTexture(TU_NORMALBUFFER, 0);
  834. graphics_->SetTexture(TU_DEPTHBUFFER, 0);
  835. graphics_->SetViewport(screenRect_);
  836. if (!deferred)
  837. graphics_->Clear(CLEAR_COLOR, zone_->GetFogColor());
  838. // Remember to bind the light buffer in prepass mode
  839. RenderBatchQueue(baseQueue_, true, !deferred);
  840. }
  841. {
  842. // Render extra / custom passes
  843. PROFILE(RenderExtraPass);
  844. RenderBatchQueue(extraQueue_);
  845. }
  846. {
  847. // Render transparent objects last (both ambient & additive lighting)
  848. PROFILE(RenderTransparent);
  849. RenderBatchQueue(transparentQueue_, true);
  850. }
  851. // Render temporal antialiasing now if enabled
  852. if (temporalAA)
  853. {
  854. PROFILE(RenderTemporalAA);
  855. // Disable averaging if it is the first frame rendered in this view
  856. float thisFrameWeight = jitterCounter_ < 2 ? 1.0f : 0.5f;
  857. Vector4 depthMode = Vector4::ZERO;
  858. if (camera_->IsOrthographic())
  859. depthMode.z_ = 1.0f;
  860. else
  861. depthMode.w_ = 1.0f / camera_->GetFarClip();
  862. graphics_->SetAlphaTest(false);
  863. graphics_->SetBlendMode(BLEND_REPLACE);
  864. graphics_->SetDepthTest(CMP_ALWAYS);
  865. graphics_->SetDepthWrite(false);
  866. graphics_->SetScissorTest(false);
  867. graphics_->SetStencilTest(false);
  868. graphics_->SetRenderTarget(0, renderTarget_);
  869. graphics_->SetViewport(screenRect_);
  870. graphics_->SetTexture(TU_DIFFBUFFER, graphics_->GetScreenBuffer(jitterCounter_ & 1));
  871. graphics_->SetTexture(TU_NORMALBUFFER, graphics_->GetScreenBuffer((jitterCounter_ + 1) & 1));
  872. graphics_->SetTexture(TU_DEPTHBUFFER, graphics_->GetDepthBuffer());
  873. graphics_->SetShaderParameter(VSP_CAMERAROT, camera_->GetWorldTransform().RotationMatrix());
  874. graphics_->SetShaderParameter(VSP_DEPTHMODE, depthMode);
  875. graphics_->SetShaderParameter(PSP_CAMERAPOS, camera_->GetWorldPosition());
  876. graphics_->SetShaderParameter(PSP_ANTIALIASWEIGHTS, Vector4(thisFrameWeight, 1.0f - thisFrameWeight, 0.0f, 0.0f));
  877. graphics_->SetShaderParameter(PSP_SAMPLEOFFSETS, Vector4(1.0f / gBufferWidth, 1.0f / gBufferHeight, 0.0f, 0.0f));
  878. graphics_->SetShaderParameter(PSP_VIEWPROJ, camera_->GetProjection(false) * lastCameraView_);
  879. unsigned index = camera_->IsOrthographic() ? 1 : 0;
  880. String shaderName = "TemporalAA_" + aaVariation[index];
  881. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader(shaderName),
  882. renderer_->GetPixelShader(shaderName), false, shaderParameters_);
  883. // Store view transform for next frame
  884. lastCameraView_ = camera_->GetInverseWorldTransform();
  885. }
  886. }
  887. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  888. {
  889. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  890. float halfViewSize = camera->GetHalfViewSize();
  891. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  892. Vector3 cameraPos = camera->GetWorldPosition();
  893. unsigned cameraViewMask = camera->GetViewMask();
  894. for (unsigned i = 0; i < occluders.Size(); ++i)
  895. {
  896. Drawable* occluder = occluders[i];
  897. occluder->UpdateDistance(frame_);
  898. bool erase = false;
  899. // Check view mask
  900. if (!(cameraViewMask & occluder->GetViewMask()))
  901. erase = true;
  902. // Check occluder's draw distance (in main camera view)
  903. float maxDistance = occluder->GetDrawDistance();
  904. if ((maxDistance > 0.0f) && (occluder->GetDistance() > maxDistance))
  905. erase = true;
  906. // Check that occluder is big enough on the screen
  907. const BoundingBox& box = occluder->GetWorldBoundingBox();
  908. float diagonal = (box.max_ - box.min_).LengthFast();
  909. float compare;
  910. if (!camera->IsOrthographic())
  911. compare = diagonal * halfViewSize / occluder->GetDistance();
  912. else
  913. compare = diagonal * invOrthoSize;
  914. if (compare < occluderSizeThreshold_)
  915. erase = true;
  916. if (!erase)
  917. {
  918. unsigned totalTriangles = 0;
  919. unsigned batches = occluder->GetNumBatches();
  920. Batch tempBatch;
  921. for (unsigned j = 0; j < batches; ++j)
  922. {
  923. occluder->GetBatch(frame_, j, tempBatch);
  924. if (tempBatch.geometry_)
  925. totalTriangles += tempBatch.geometry_->GetIndexCount() / 3;
  926. }
  927. // Store amount of triangles divided by screen size as a sorting key
  928. // (best occluders are big and have few triangles)
  929. occluder->SetSortValue((float)totalTriangles / compare);
  930. }
  931. else
  932. {
  933. occluders.Erase(occluders.Begin() + i);
  934. --i;
  935. }
  936. }
  937. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  938. if (occluders.Size())
  939. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  940. }
  941. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  942. {
  943. for (unsigned i = 0; i < occluders.Size(); ++i)
  944. {
  945. Drawable* occluder = occluders[i];
  946. if (i > 0)
  947. {
  948. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  949. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  950. continue;
  951. }
  952. occluder->UpdateGeometry(frame_);
  953. // Check for running out of triangles
  954. if (!occluder->DrawOcclusion(buffer))
  955. return;
  956. }
  957. }
  958. unsigned View::ProcessLight(Light* light)
  959. {
  960. unsigned numLitGeometries = 0;
  961. unsigned numShadowCasters = 0;
  962. unsigned numSplits;
  963. // Check if light should be shadowed
  964. bool isShadowed = (drawShadows_) && (light->GetCastShadows());
  965. // If shadow distance non-zero, check it
  966. if ((isShadowed) && (light->GetShadowDistance() > 0.0f) && (light->GetDistance() > light->GetShadowDistance()))
  967. isShadowed = false;
  968. // If light has no ramp textures defined, set defaults
  969. if ((light->GetLightType() != LIGHT_DIRECTIONAL) && (!light->GetRampTexture()))
  970. light->SetRampTexture(renderer_->GetDefaultLightRamp());
  971. if ((light->GetLightType() == LIGHT_SPOT) && (!light->GetShapeTexture()))
  972. light->SetShapeTexture(renderer_->GetDefaultLightSpot());
  973. // Split the light if necessary
  974. if (isShadowed)
  975. numSplits = SplitLight(light);
  976. else
  977. {
  978. // No splitting, use the original light
  979. splitLights_[0] = light;
  980. numSplits = 1;
  981. }
  982. // For a shadowed directional light, get occluders once using the whole (non-split) light frustum
  983. bool useOcclusion = false;
  984. OcclusionBuffer* buffer = 0;
  985. if ((maxOccluderTriangles_ > 0) && (isShadowed) && (light->GetLightType() == LIGHT_DIRECTIONAL))
  986. {
  987. // This shadow camera is never used for actually querying shadow casters, just occluders
  988. Camera* shadowCamera = renderer_->CreateShadowCamera();
  989. light->SetShadowCamera(shadowCamera);
  990. SetupShadowCamera(light, true);
  991. // Get occluders, which must be shadow-casting themselves
  992. FrustumOctreeQuery query(shadowOccluders_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY, true, true);
  993. octree_->GetDrawables(query);
  994. UpdateOccluders(shadowOccluders_, shadowCamera);
  995. if (shadowOccluders_.Size())
  996. {
  997. // Shadow viewport is rectangular and consumes more CPU fillrate, so halve size
  998. buffer = renderer_->GetOrCreateOcclusionBuffer(shadowCamera, maxOccluderTriangles_, true);
  999. DrawOccluders(buffer, shadowOccluders_);
  1000. buffer->BuildDepthHierarchy();
  1001. useOcclusion = true;
  1002. }
  1003. }
  1004. // Process each split for shadow camera update, lit geometries, and shadow casters
  1005. for (unsigned i = 0; i < numSplits; ++i)
  1006. {
  1007. litGeometries_[i].Clear();
  1008. shadowCasters_[i].Clear();
  1009. }
  1010. for (unsigned i = 0; i < numSplits; ++i)
  1011. {
  1012. Light* split = splitLights_[i];
  1013. LightType type = split->GetLightType();
  1014. bool isSplitShadowed = (isShadowed) && (split->GetCastShadows());
  1015. Camera* shadowCamera = 0;
  1016. // If shadow casting, choose the shadow map & update shadow camera
  1017. if (isSplitShadowed)
  1018. {
  1019. shadowCamera = renderer_->CreateShadowCamera();
  1020. split->SetShadowMap(renderer_->GetShadowMap(splitLights_[i]->GetShadowResolution()));
  1021. // Check if managed to get a shadow map. Otherwise must convert to non-shadowed
  1022. if (split->GetShadowMap())
  1023. {
  1024. split->SetShadowCamera(shadowCamera);
  1025. SetupShadowCamera(split);
  1026. }
  1027. else
  1028. {
  1029. isSplitShadowed = false;
  1030. split->SetShadowCamera(0);
  1031. }
  1032. }
  1033. else
  1034. {
  1035. split->SetShadowCamera(0);
  1036. split->SetShadowMap(0);
  1037. }
  1038. BoundingBox geometryBox;
  1039. BoundingBox shadowCasterBox;
  1040. switch (type)
  1041. {
  1042. case LIGHT_DIRECTIONAL:
  1043. // Loop through visible geometries and check if they belong to this split
  1044. {
  1045. float nearSplit = split->GetNearSplit() - split->GetNearFadeRange();
  1046. float farSplit = split->GetFarSplit();
  1047. // If split extends to the whole visible frustum, no depth check necessary
  1048. bool optimize = (nearSplit <= camera_->GetNearClip()) && (farSplit >= camera_->GetFarClip());
  1049. // If whole visible scene is outside the split, can reject trivially
  1050. if ((sceneViewBox_.min_.z_ > farSplit) || (sceneViewBox_.max_.z_ < nearSplit))
  1051. {
  1052. split->SetShadowMap(0);
  1053. continue;
  1054. }
  1055. bool generateBoxes = (isSplitShadowed) && (split->GetShadowFocus().focus_);
  1056. Matrix3x4 lightView;
  1057. if (shadowCamera)
  1058. lightView = shadowCamera->GetInverseWorldTransform();
  1059. if (!optimize)
  1060. {
  1061. for (unsigned j = 0; j < geometries_.Size(); ++j)
  1062. {
  1063. Drawable* drawable = geometries_[j];
  1064. const GeometryDepthBounds& bounds = geometryDepthBounds_[j];
  1065. // Check bounds and light mask
  1066. if ((bounds.min_ <= farSplit) && (bounds.max_ >= nearSplit) && (drawable->GetLightMask() &
  1067. split->GetLightMask()))
  1068. {
  1069. litGeometries_[i].Push(drawable);
  1070. if (generateBoxes)
  1071. geometryBox.Merge(drawable->GetWorldBoundingBox().Transformed(lightView));
  1072. }
  1073. }
  1074. }
  1075. else
  1076. {
  1077. for (unsigned j = 0; j < geometries_.Size(); ++j)
  1078. {
  1079. Drawable* drawable = geometries_[j];
  1080. // Need to check light mask only
  1081. if (drawable->GetLightMask() & split->GetLightMask())
  1082. {
  1083. litGeometries_[i].Push(drawable);
  1084. if (generateBoxes)
  1085. geometryBox.Merge(drawable->GetWorldBoundingBox().Transformed(lightView));
  1086. }
  1087. }
  1088. }
  1089. }
  1090. // Then get shadow casters by shadow camera frustum query. Use occlusion because of potentially many geometries
  1091. if ((isSplitShadowed) && (litGeometries_[i].Size()))
  1092. {
  1093. Camera* shadowCamera = split->GetShadowCamera();
  1094. if (!useOcclusion)
  1095. {
  1096. // Get potential shadow casters without occlusion
  1097. FrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY);
  1098. octree_->GetDrawables(query);
  1099. }
  1100. else
  1101. {
  1102. // Get potential shadow casters with occlusion
  1103. OccludedFrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), buffer,
  1104. DRAWABLE_GEOMETRY);
  1105. octree_->GetDrawables(query);
  1106. }
  1107. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, false, isSplitShadowed);
  1108. }
  1109. break;
  1110. case LIGHT_POINT:
  1111. {
  1112. SphereOctreeQuery query(tempDrawables_, Sphere(split->GetWorldPosition(), split->GetRange()), DRAWABLE_GEOMETRY);
  1113. octree_->GetDrawables(query);
  1114. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, true, false);
  1115. }
  1116. break;
  1117. case LIGHT_SPOT:
  1118. case LIGHT_SPLITPOINT:
  1119. {
  1120. FrustumOctreeQuery query(tempDrawables_, splitLights_[i]->GetFrustum(), DRAWABLE_GEOMETRY);
  1121. octree_->GetDrawables(query);
  1122. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, true, isSplitShadowed);
  1123. }
  1124. break;
  1125. }
  1126. // Optimization: if a particular split has no shadow casters, render as unshadowed
  1127. if (!shadowCasters_[i].Size())
  1128. split->SetShadowMap(0);
  1129. // Focus shadow camera as applicable
  1130. if (split->GetShadowMap())
  1131. {
  1132. if (split->GetShadowFocus().focus_)
  1133. FocusShadowCamera(split, geometryBox, shadowCasterBox);
  1134. // Set a zoom factor to ensure that we do not render to the shadow map border
  1135. // (clamp addressing is necessary because border mode /w hardware shadow maps is not supported by all GPUs)
  1136. Camera* shadowCamera = split->GetShadowCamera();
  1137. Texture2D* shadowMap = split->GetShadowMap();
  1138. if (shadowCamera->GetZoom() >= 1.0f)
  1139. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((float)(shadowMap->GetWidth() - 2) / (float)shadowMap->GetWidth()));
  1140. }
  1141. // Update count of total lit geometries & shadow casters
  1142. numLitGeometries += litGeometries_[i].Size();
  1143. numShadowCasters += shadowCasters_[i].Size();
  1144. }
  1145. // If no lit geometries at all, no need to process further
  1146. if (!numLitGeometries)
  1147. numSplits = 0;
  1148. // If no shadow casters at all, concatenate lit geometries into one & return the original light
  1149. else if (!numShadowCasters)
  1150. {
  1151. if (numSplits > 1)
  1152. {
  1153. // Make sure there are no duplicates
  1154. HashSet<Drawable*> allLitGeometries;
  1155. for (unsigned i = 0; i < numSplits; ++i)
  1156. {
  1157. for (Vector<Drawable*>::Iterator j = litGeometries_[i].Begin(); j != litGeometries_[i].End(); ++j)
  1158. allLitGeometries.Insert(*j);
  1159. }
  1160. litGeometries_[0].Resize(allLitGeometries.Size());
  1161. unsigned index = 0;
  1162. for (HashSet<Drawable*>::Iterator i = allLitGeometries.Begin(); i != allLitGeometries.End(); ++i)
  1163. litGeometries_[0][index++] = *i;
  1164. }
  1165. splitLights_[0] = light;
  1166. splitLights_[0]->SetShadowMap(0);
  1167. numSplits = 1;
  1168. }
  1169. return numSplits;
  1170. }
  1171. void View::ProcessLightQuery(unsigned splitIndex, const PODVector<Drawable*>& result, BoundingBox& geometryBox,
  1172. BoundingBox& shadowCasterBox, bool getLitGeometries, bool GetShadowCasters)
  1173. {
  1174. Light* light = splitLights_[splitIndex];
  1175. Matrix3x4 lightView;
  1176. Matrix4 lightProj;
  1177. Frustum lightViewFrustum;
  1178. BoundingBox lightViewFrustumBox;
  1179. bool mergeBoxes = (light->GetLightType() != LIGHT_SPLITPOINT) && (light->GetShadowMap()) && (light->GetShadowFocus().focus_);
  1180. bool projectBoxes = false;
  1181. Camera* shadowCamera = light->GetShadowCamera();
  1182. if (shadowCamera)
  1183. {
  1184. bool projectBoxes = !shadowCamera->IsOrthographic();
  1185. lightView = shadowCamera->GetInverseWorldTransform();
  1186. lightProj = shadowCamera->GetProjection();
  1187. // Transform scene frustum into shadow camera's view space for shadow caster visibility check
  1188. // For point & spot lights, we can use the whole scene frustum. For directional lights, use the
  1189. // intersection of the scene frustum and the split frustum, so that shadow casters do not get
  1190. // rendered into unnecessary splits
  1191. if (light->GetLightType() != LIGHT_DIRECTIONAL)
  1192. lightViewFrustum = camera_->GetSplitFrustum(sceneViewBox_.min_.z_, sceneViewBox_.max_.z_).Transformed(lightView);
  1193. else
  1194. lightViewFrustum = camera_->GetSplitFrustum(Max(sceneViewBox_.min_.z_, light->GetNearSplit() - light->GetNearFadeRange()),
  1195. Min(sceneViewBox_.max_.z_, light->GetFarSplit())).Transformed(lightView);
  1196. lightViewFrustumBox.Define(lightViewFrustum);
  1197. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1198. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1199. GetShadowCasters = false;
  1200. }
  1201. else
  1202. GetShadowCasters = false;
  1203. BoundingBox lightViewBox;
  1204. BoundingBox lightProjBox;
  1205. for (unsigned i = 0; i < result.Size(); ++i)
  1206. {
  1207. Drawable* drawable = static_cast<Drawable*>(result[i]);
  1208. drawable->UpdateDistance(frame_);
  1209. bool boxGenerated = false;
  1210. // If draw distance non-zero, check it
  1211. float maxDistance = drawable->GetDrawDistance();
  1212. if ((maxDistance > 0.0f) && (drawable->GetDistance() > maxDistance))
  1213. continue;
  1214. // Check light mask
  1215. if (!(drawable->GetLightMask() & light->GetLightMask()))
  1216. continue;
  1217. // Get lit geometry only if inside main camera frustum this frame
  1218. if ((getLitGeometries) && (drawable->IsInView(frame_)))
  1219. {
  1220. if (mergeBoxes)
  1221. {
  1222. // Transform bounding box into light view space, and to projection space if needed
  1223. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1224. if (!projectBoxes)
  1225. geometryBox.Merge(lightViewBox);
  1226. else
  1227. {
  1228. lightProjBox = lightViewBox.Projected(lightProj);
  1229. geometryBox.Merge(lightProjBox);
  1230. }
  1231. boxGenerated = true;
  1232. }
  1233. litGeometries_[splitIndex].Push(drawable);
  1234. }
  1235. // Shadow caster need not be inside main camera frustum: in that case try to detect whether
  1236. // the shadow projection intersects the view
  1237. if ((GetShadowCasters) && (drawable->GetCastShadows()))
  1238. {
  1239. // If shadow distance non-zero, check it
  1240. float maxShadowDistance = drawable->GetShadowDistance();
  1241. if ((maxShadowDistance > 0.0f) && (drawable->GetDistance() > maxShadowDistance))
  1242. continue;
  1243. if (!boxGenerated)
  1244. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1245. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1246. {
  1247. if (mergeBoxes)
  1248. {
  1249. if (!projectBoxes)
  1250. shadowCasterBox.Merge(lightViewBox);
  1251. else
  1252. {
  1253. if (!boxGenerated)
  1254. lightProjBox = lightViewBox.Projected(lightProj);
  1255. shadowCasterBox.Merge(lightProjBox);
  1256. }
  1257. }
  1258. // Update geometry now if not updated yet
  1259. if (!drawable->IsInView(frame_))
  1260. {
  1261. drawable->MarkInShadowView(frame_);
  1262. drawable->UpdateGeometry(frame_);
  1263. }
  1264. shadowCasters_[splitIndex].Push(drawable);
  1265. }
  1266. }
  1267. }
  1268. }
  1269. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  1270. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  1271. {
  1272. // If shadow caster is also an occluder, must let it be visible, because it has potentially already culled
  1273. // away other shadow casters (could also check the actual shadow occluder vector, but that would be slower)
  1274. if (drawable->IsOccluder())
  1275. return true;
  1276. if (shadowCamera->IsOrthographic())
  1277. {
  1278. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  1279. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  1280. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1281. }
  1282. else
  1283. {
  1284. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  1285. if (drawable->IsInView(frame_))
  1286. return true;
  1287. // For perspective lights, extrusion direction depends on the position of the shadow caster
  1288. Vector3 center = lightViewBox.Center();
  1289. Ray extrusionRay(center, center.Normalized());
  1290. float extrusionDistance = shadowCamera->GetFarClip();
  1291. float originalDistance = Clamp(center.LengthFast(), M_EPSILON, extrusionDistance);
  1292. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  1293. float sizeFactor = extrusionDistance / originalDistance;
  1294. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  1295. // than necessary, so the test will be conservative
  1296. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  1297. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  1298. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  1299. lightViewBox.Merge(extrudedBox);
  1300. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1301. }
  1302. }
  1303. void View::SetupShadowCamera(Light* light, bool shadowOcclusion)
  1304. {
  1305. Camera* shadowCamera = light->GetShadowCamera();
  1306. Node* cameraNode = shadowCamera->GetNode();
  1307. const FocusParameters& parameters = light->GetShadowFocus();
  1308. // Reset zoom
  1309. shadowCamera->SetZoom(1.0f);
  1310. switch(light->GetLightType())
  1311. {
  1312. case LIGHT_DIRECTIONAL:
  1313. {
  1314. float extrusionDistance = camera_->GetFarClip();
  1315. // Calculate initial position & rotation
  1316. Vector3 lightWorldDirection = light->GetWorldRotation() * Vector3::FORWARD;
  1317. Vector3 pos = camera_->GetWorldPosition() - extrusionDistance * lightWorldDirection;
  1318. Quaternion rot(Vector3::FORWARD, lightWorldDirection);
  1319. cameraNode->SetTransform(pos, rot);
  1320. // Calculate main camera shadowed frustum in light's view space
  1321. float sceneMaxZ = camera_->GetFarClip();
  1322. // When shadow focusing is enabled, use the scene far Z to limit maximum frustum size
  1323. if ((shadowOcclusion) || (parameters.focus_))
  1324. sceneMaxZ = Min(sceneViewBox_.max_.z_, sceneMaxZ);
  1325. Matrix3x4 lightView(shadowCamera->GetInverseWorldTransform());
  1326. Frustum lightViewSplitFrustum = camera_->GetSplitFrustum(light->GetNearSplit() - light->GetNearFadeRange(),
  1327. Min(light->GetFarSplit(), sceneMaxZ)).Transformed(lightView);
  1328. // Fit the frustum inside a bounding box. If uniform size, use a sphere instead
  1329. BoundingBox shadowBox;
  1330. if ((!shadowOcclusion) && (parameters.nonUniform_))
  1331. shadowBox.Define(lightViewSplitFrustum);
  1332. else
  1333. {
  1334. Sphere shadowSphere;
  1335. shadowSphere.Define(lightViewSplitFrustum);
  1336. shadowBox.Define(shadowSphere);
  1337. }
  1338. shadowCamera->SetOrthographic(true);
  1339. shadowCamera->SetNearClip(0.0f);
  1340. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1341. // Center shadow camera on the bounding box, snap to whole texels
  1342. QuantizeDirShadowCamera(light, shadowBox);
  1343. }
  1344. break;
  1345. case LIGHT_SPOT:
  1346. case LIGHT_SPLITPOINT:
  1347. {
  1348. cameraNode->SetTransform(light->GetWorldPosition(), light->GetWorldRotation());
  1349. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1350. shadowCamera->SetFarClip(light->GetRange());
  1351. shadowCamera->SetOrthographic(false);
  1352. shadowCamera->SetFov(light->GetFov());
  1353. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1354. // For spot lights, zoom out shadowmap if far away (reduces fillrate)
  1355. if ((light->GetLightType() == LIGHT_SPOT) && (parameters.zoomOut_))
  1356. {
  1357. // Make sure the out-zooming does not start while we are inside the spot
  1358. float distance = Max((camera_->GetInverseWorldTransform() * light->GetWorldPosition()).z_ - light->GetRange(), 1.0f);
  1359. float lightPixels = (((float)height_ * light->GetRange() * camera_->GetZoom() * 0.5f) / distance);
  1360. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  1361. if (lightPixels < SHADOW_MIN_PIXELS)
  1362. lightPixels = SHADOW_MIN_PIXELS;
  1363. float zoolevel_ = Min(lightPixels / (float)light->GetShadowMap()->GetHeight(), 1.0f);
  1364. shadowCamera->SetZoom(zoolevel_);
  1365. }
  1366. }
  1367. break;
  1368. }
  1369. }
  1370. void View::FocusShadowCamera(Light* light, const BoundingBox& geometryBox, const BoundingBox& shadowCasterBox)
  1371. {
  1372. // If either no geometries or no shadow casters, do nothing
  1373. if ((!geometryBox.defined_) || (!shadowCasterBox.defined_))
  1374. return;
  1375. Camera* shadowCamera = light->GetShadowCamera();
  1376. const FocusParameters& parameters = light->GetShadowFocus();
  1377. switch (light->GetLightType())
  1378. {
  1379. case LIGHT_DIRECTIONAL:
  1380. {
  1381. BoundingBox combinedBox;
  1382. combinedBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1383. combinedBox.max_.x_ = shadowCamera->GetAspectRatio() * combinedBox.max_.y_;
  1384. combinedBox.min_.y_ = -combinedBox.max_.y_;
  1385. combinedBox.min_.x_ = -combinedBox.max_.x_;
  1386. combinedBox.Intersect(geometryBox);
  1387. combinedBox.Intersect(shadowCasterBox);
  1388. QuantizeDirShadowCamera(light, combinedBox);
  1389. }
  1390. break;
  1391. case LIGHT_SPOT:
  1392. // Can not move, but can zoom the shadow camera. Check for out-zooming (distant shadow map), do nothing in that case
  1393. if (shadowCamera->GetZoom() >= 1.0f)
  1394. {
  1395. BoundingBox combinedBox(-1.0f, 1.0f);
  1396. combinedBox.Intersect(geometryBox);
  1397. combinedBox.Intersect(shadowCasterBox);
  1398. float viewSizeX = Max(fabsf(combinedBox.min_.x_), fabsf(combinedBox.max_.x_));
  1399. float viewSizeY = Max(fabsf(combinedBox.min_.y_), fabsf(combinedBox.max_.y_));
  1400. float viewSize = Max(viewSizeX, viewSizeY);
  1401. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  1402. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  1403. float quantize = parameters.quantize_ * invOrthoSize;
  1404. float minView = parameters.minView_ * invOrthoSize;
  1405. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  1406. if (viewSize < 1.0f)
  1407. shadowCamera->SetZoom(1.0f / viewSize);
  1408. }
  1409. break;
  1410. }
  1411. }
  1412. void View::QuantizeDirShadowCamera(Light* light, const BoundingBox& viewBox)
  1413. {
  1414. Camera* shadowCamera = light->GetShadowCamera();
  1415. Node* cameraNode = shadowCamera->GetNode();
  1416. const FocusParameters& parameters = light->GetShadowFocus();
  1417. float minX = viewBox.min_.x_;
  1418. float minY = viewBox.min_.y_;
  1419. float maxX = viewBox.max_.x_;
  1420. float maxY = viewBox.max_.y_;
  1421. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  1422. Vector2 viewSize(maxX - minX, maxY - minY);
  1423. // Quantize size to reduce swimming
  1424. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  1425. if (parameters.nonUniform_)
  1426. {
  1427. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1428. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  1429. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1430. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  1431. }
  1432. else if (parameters.focus_)
  1433. {
  1434. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  1435. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1436. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1437. viewSize.y_ = viewSize.x_;
  1438. }
  1439. shadowCamera->SetOrthoSize(viewSize);
  1440. // Center shadow camera to the view space bounding box
  1441. Vector3 pos = shadowCamera->GetWorldPosition();
  1442. Quaternion rot = shadowCamera->GetWorldRotation();
  1443. Vector3 adjust(center.x_, center.y_, 0.0f);
  1444. cameraNode->Translate(rot * adjust);
  1445. // If there is a shadow map, snap to its whole texels
  1446. Texture2D* shadowMap = light->GetShadowMap();
  1447. if (shadowMap)
  1448. {
  1449. Vector3 viewPos(rot.Inverse() * shadowCamera->GetWorldPosition());
  1450. // Take into account that shadow map border will not be used
  1451. float invActualSize = 1.0f / (float)(shadowMap->GetWidth() - 2);
  1452. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  1453. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  1454. cameraNode->Translate(rot * snap);
  1455. }
  1456. }
  1457. void View::OptimizeLightByScissor(Light* light)
  1458. {
  1459. if (light)
  1460. graphics_->SetScissorTest(true, GetLightScissor(light));
  1461. else
  1462. graphics_->SetScissorTest(false);
  1463. }
  1464. const Rect& View::GetLightScissor(Light* light)
  1465. {
  1466. Map<Light*, Rect>::Iterator i = lightScissorCache_.Find(light);
  1467. if (i != lightScissorCache_.End())
  1468. return i->second_;
  1469. Matrix3x4 view(camera_->GetInverseWorldTransform());
  1470. Matrix4 projection(camera_->GetProjection());
  1471. switch (light->GetLightType())
  1472. {
  1473. case LIGHT_POINT:
  1474. {
  1475. BoundingBox viewBox = light->GetWorldBoundingBox().Transformed(view);
  1476. return lightScissorCache_[light] = viewBox.Projected(projection);
  1477. }
  1478. case LIGHT_SPOT:
  1479. case LIGHT_SPLITPOINT:
  1480. {
  1481. Frustum viewFrustum = light->GetFrustum().Transformed(view);
  1482. return lightScissorCache_[light] = viewFrustum.Projected(projection);
  1483. }
  1484. default:
  1485. return lightScissorCache_[light] = Rect::FULL;
  1486. }
  1487. }
  1488. unsigned View::SplitLight(Light* light)
  1489. {
  1490. LightType type = light->GetLightType();
  1491. if (type == LIGHT_DIRECTIONAL)
  1492. {
  1493. const CascadeParameters& cascade = light->GetShadowCascade();
  1494. unsigned splits = cascade.splits_;
  1495. if (splits > MAX_LIGHT_SPLITS - 1)
  1496. splits = MAX_LIGHT_SPLITS;
  1497. // Orthographic view actually has near clip 0, but clamp it to a theoretical minimum
  1498. float farClip = Min(cascade.shadowRange_, camera_->GetFarClip()); // Shadow range end
  1499. float nearClip = Max(camera_->GetNearClip(), M_MIN_NEARCLIP); // Shadow range start
  1500. bool CreateExtraSplit = farClip < camera_->GetFarClip();
  1501. // Practical split scheme (Zhang et al.)
  1502. unsigned i;
  1503. for (i = 0; i < splits; ++i)
  1504. {
  1505. // Set a minimum for the fade range to avoid boundary artifacts (missing lighting)
  1506. float splitFadeRange = Max(cascade.splitFadeRange_, 0.001f);
  1507. float iPerM = (float)i / (float)splits;
  1508. float log = nearClip * powf(farClip / nearClip, iPerM);
  1509. float uniform = nearClip + (farClip - nearClip) * iPerM;
  1510. float nearSplit = log * cascade.lambda_ + uniform * (1.0f - cascade.lambda_);
  1511. float nearFadeRange = nearSplit * splitFadeRange;
  1512. iPerM = (float)(i + 1) / (float)splits;
  1513. log = nearClip * powf(farClip / nearClip, iPerM);
  1514. uniform = nearClip + (farClip - nearClip) * iPerM;
  1515. float farSplit = log * cascade.lambda_ + uniform * (1.0f - cascade.lambda_);
  1516. float farFadeRange = farSplit * splitFadeRange;
  1517. // If split is completely beyond camera far clip, we are done
  1518. if ((nearSplit - nearFadeRange) > camera_->GetFarClip())
  1519. break;
  1520. Light* SplitLight = renderer_->CreateSplitLight(light);
  1521. splitLights_[i] = SplitLight;
  1522. // Though the near clip was previously clamped, use the real near clip value for the first split,
  1523. // so that there are no unlit portions
  1524. if (i)
  1525. SplitLight->SetNearSplit(nearSplit);
  1526. else
  1527. SplitLight->SetNearSplit(camera_->GetNearClip());
  1528. SplitLight->SetNearFadeRange(nearFadeRange);
  1529. SplitLight->SetFarSplit(farSplit);
  1530. // The final split will not fade
  1531. if ((CreateExtraSplit) || (i < splits - 1))
  1532. SplitLight->SetFarFadeRange(farFadeRange);
  1533. // Create an extra unshadowed split if necessary
  1534. if ((CreateExtraSplit) && (i == splits - 1))
  1535. {
  1536. Light* SplitLight = renderer_->CreateSplitLight(light);
  1537. splitLights_[i + 1] = SplitLight;
  1538. SplitLight->SetNearSplit(farSplit);
  1539. SplitLight->SetNearFadeRange(farFadeRange);
  1540. SplitLight->SetCastShadows(false);
  1541. }
  1542. }
  1543. if (CreateExtraSplit)
  1544. return i + 1;
  1545. else
  1546. return i;
  1547. }
  1548. if (type == LIGHT_POINT)
  1549. {
  1550. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1551. {
  1552. Light* SplitLight = renderer_->CreateSplitLight(light);
  1553. Node* lightNode = SplitLight->GetNode();
  1554. splitLights_[i] = SplitLight;
  1555. SplitLight->SetLightType(LIGHT_SPLITPOINT);
  1556. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1557. lightNode->SetDirection(directions[i]);
  1558. SplitLight->SetFov(90.0f);
  1559. SplitLight->SetAspectRatio(1.0f);
  1560. }
  1561. return MAX_CUBEMAP_FACES;
  1562. }
  1563. // A spot light does not actually need splitting. However, we may be rendering several views,
  1564. // and in some the light might be unshadowed, so better create an unique copy
  1565. Light* SplitLight = renderer_->CreateSplitLight(light);
  1566. splitLights_[0] = SplitLight;
  1567. return 1;
  1568. }
  1569. Technique* View::GetTechnique(Drawable* drawable, Material*& material)
  1570. {
  1571. if (!material)
  1572. material = renderer_->GetDefaultMaterial();
  1573. if (!material)
  1574. return 0;
  1575. float lodDistance = drawable->GetLodDistance();
  1576. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  1577. if (techniques.Empty())
  1578. return 0;
  1579. // Check for suitable technique. Techniques should be ordered like this:
  1580. // Most distant & highest quality
  1581. // Most distant & lowest quality
  1582. // Second most distant & highest quality
  1583. // ...
  1584. for (unsigned i = 0; i < techniques.Size(); ++i)
  1585. {
  1586. const TechniqueEntry& entry = techniques[i];
  1587. Technique* technique = entry.technique_;
  1588. if ((!technique) || ((technique->IsSM3()) && (!graphics_->GetSM3Support())) || (materialQuality_ < entry.qualityLevel_))
  1589. continue;
  1590. if (lodDistance >= entry.lodDistance_)
  1591. return technique;
  1592. }
  1593. // If no suitable technique found, fallback to the last
  1594. return techniques.Back().technique_;
  1595. }
  1596. void View::CheckMaterialForAuxView(Material* material)
  1597. {
  1598. const Vector<SharedPtr<Texture> >& textures = material->GetTextures();
  1599. for (unsigned i = 0; i < textures.Size(); ++i)
  1600. {
  1601. // Have to check cube & 2D textures separately
  1602. Texture* texture = textures[i];
  1603. if (texture)
  1604. {
  1605. if (texture->GetType() == Texture2D::GetTypeStatic())
  1606. {
  1607. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1608. RenderSurface* target = tex2D->GetRenderSurface();
  1609. if (target)
  1610. {
  1611. const Viewport& viewport = target->GetViewport();
  1612. if ((viewport.scene_) && (viewport.camera_))
  1613. renderer_->AddView(target, viewport);
  1614. }
  1615. }
  1616. else if (texture->GetType() == TextureCube::GetTypeStatic())
  1617. {
  1618. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1619. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1620. {
  1621. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  1622. if (target)
  1623. {
  1624. const Viewport& viewport = target->GetViewport();
  1625. if ((viewport.scene_) && (viewport.camera_))
  1626. renderer_->AddView(target, viewport);
  1627. }
  1628. }
  1629. }
  1630. }
  1631. }
  1632. // Set frame number so that we can early-out next time we come across this material on the same frame
  1633. material->MarkForAuxView(frame_.frameNumber_);
  1634. }
  1635. void View::SortBatches()
  1636. {
  1637. PROFILE(SortBatches);
  1638. if (mode_ != RENDER_FORWARD)
  1639. {
  1640. gBufferQueue_.SortFrontToBack();
  1641. noShadowLightQueue_.SortFrontToBack();
  1642. }
  1643. baseQueue_.SortFrontToBack();
  1644. extraQueue_.SortFrontToBack();
  1645. transparentQueue_.SortBackToFront();
  1646. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1647. {
  1648. lightQueues_[i].shadowBatches_.SortFrontToBack();
  1649. lightQueues_[i].litBatches_.SortFrontToBack();
  1650. }
  1651. }
  1652. void View::PrepareInstancingBuffer()
  1653. {
  1654. PROFILE(PrepareInstancingBuffer);
  1655. unsigned totalInstances = 0;
  1656. if (mode_ != RENDER_FORWARD)
  1657. totalInstances += gBufferQueue_.GetNumInstances();
  1658. totalInstances += baseQueue_.GetNumInstances();
  1659. totalInstances += extraQueue_.GetNumInstances();
  1660. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1661. {
  1662. totalInstances += lightQueues_[i].shadowBatches_.GetNumInstances();
  1663. totalInstances += lightQueues_[i].litBatches_.GetNumInstances();
  1664. }
  1665. // If fail to set buffer size, fall back to per-group locking
  1666. if ((totalInstances) && (renderer_->ResizeInstancingBuffer(totalInstances)))
  1667. {
  1668. unsigned freeIndex = 0;
  1669. void* lockedData = renderer_->instancingBuffer_->Lock(0, totalInstances, LOCK_DISCARD);
  1670. if (lockedData)
  1671. {
  1672. if (mode_ != RENDER_FORWARD)
  1673. gBufferQueue_.SetTransforms(lockedData, freeIndex);
  1674. baseQueue_.SetTransforms(lockedData, freeIndex);
  1675. extraQueue_.SetTransforms(lockedData, freeIndex);
  1676. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1677. {
  1678. lightQueues_[i].shadowBatches_.SetTransforms(lockedData, freeIndex);
  1679. lightQueues_[i].litBatches_.SetTransforms(lockedData, freeIndex);
  1680. }
  1681. renderer_->instancingBuffer_->Unlock();
  1682. }
  1683. }
  1684. }
  1685. void View::CalculateShaderParameters()
  1686. {
  1687. Time* time = GetSubsystem<Time>();
  1688. float fogStart = zone_->GetFogStart();
  1689. float fogEnd = zone_->GetFogEnd();
  1690. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  1691. float farClip = camera_->GetFarClip();
  1692. float nearClip = camera_->GetNearClip();
  1693. Vector4 fogParams(fogStart / farClip, fogEnd / farClip, 1.0f / (fogRange / farClip), 0.0f);
  1694. Vector4 elapsedTime((time->GetTotalMSec() & 0x3fffff) / 1000.0f, 0.0f, 0.0f, 0.0f);
  1695. shaderParameters_.Clear();
  1696. shaderParameters_[VSP_ELAPSEDTIME] = elapsedTime;
  1697. shaderParameters_[PSP_AMBIENTCOLOR] = zone_->GetAmbientColor().ToVector4();
  1698. shaderParameters_[PSP_ELAPSEDTIME] = elapsedTime;
  1699. shaderParameters_[PSP_FOGCOLOR] = zone_->GetFogColor().ToVector4(),
  1700. shaderParameters_[PSP_FOGPARAMS] = fogParams;
  1701. }
  1702. void View::DrawSplitLightToStencil(Camera& camera, Light* light, bool clear)
  1703. {
  1704. graphics_->ClearTransformSources();
  1705. Matrix3x4 view(camera.GetInverseWorldTransform());
  1706. switch (light->GetLightType())
  1707. {
  1708. case LIGHT_SPLITPOINT:
  1709. if (!clear)
  1710. {
  1711. Matrix4 projection(camera.GetProjection());
  1712. const Matrix3x4& model = light->GetVolumeTransform(camera);
  1713. float lightExtent = light->GetVolumeExtent();
  1714. float lightViewDist = (light->GetWorldPosition() - camera.GetWorldPosition()).LengthFast();
  1715. bool drawBackFaces = lightViewDist < (lightExtent + camera.GetNearClip());
  1716. graphics_->SetAlphaTest(false);
  1717. graphics_->SetColorWrite(false);
  1718. graphics_->SetDepthWrite(false);
  1719. graphics_->SetCullMode(drawBackFaces ? CULL_CW : CULL_CCW);
  1720. graphics_->SetDepthTest(drawBackFaces ? CMP_GREATER : CMP_LESS);
  1721. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1722. graphics_->SetShaderParameter(VSP_MODEL, model);
  1723. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1724. // Draw the faces to stencil which we should draw (where no light has not been rendered yet)
  1725. graphics_->SetStencilTest(true, CMP_EQUAL, OP_INCR, OP_KEEP, OP_KEEP, 0);
  1726. renderer_->spotLightGeometry_->Draw(graphics_);
  1727. // Draw the other faces to stencil to mark where we should not draw ("frees up" the pixels for other faces)
  1728. graphics_->SetCullMode(drawBackFaces ? CULL_CCW : CULL_CW);
  1729. graphics_->SetStencilTest(true, CMP_EQUAL, OP_DECR, OP_KEEP, OP_KEEP, 1);
  1730. renderer_->spotLightGeometry_->Draw(graphics_);
  1731. // Now set stencil test for rendering the lit geometries (also marks the pixels so that they will not be used again)
  1732. graphics_->SetStencilTest(true, CMP_EQUAL, OP_INCR, OP_KEEP, OP_KEEP, 1);
  1733. graphics_->SetColorWrite(true);
  1734. }
  1735. else
  1736. {
  1737. // Clear stencil with a scissored clear operation
  1738. OptimizeLightByScissor(light->GetOriginalLight());
  1739. graphics_->Clear(CLEAR_STENCIL);
  1740. graphics_->SetScissorTest(false);
  1741. graphics_->SetStencilTest(false);
  1742. }
  1743. break;
  1744. case LIGHT_DIRECTIONAL:
  1745. // If light encompasses whole frustum, no drawing to frustum necessary
  1746. if ((light->GetNearSplit() <= camera.GetNearClip()) && (light->GetFarSplit() >= camera.GetFarClip()))
  1747. return;
  1748. else
  1749. {
  1750. if (!clear)
  1751. {
  1752. // Get projection without jitter offset to ensure the whole screen is filled
  1753. Matrix4 projection(camera.GetProjection(false));
  1754. Matrix3x4 nearTransform(light->GetDirLightTransform(camera, true));
  1755. Matrix3x4 farTransform(light->GetDirLightTransform(camera, false));
  1756. graphics_->SetAlphaTest(false);
  1757. graphics_->SetColorWrite(false);
  1758. graphics_->SetDepthWrite(false);
  1759. graphics_->SetCullMode(CULL_NONE);
  1760. // If the split begins at the near plane (first split), draw at split far plane
  1761. if (light->GetNearSplit() <= camera.GetNearClip())
  1762. {
  1763. graphics_->SetDepthTest(CMP_GREATEREQUAL);
  1764. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1765. graphics_->SetShaderParameter(VSP_MODEL, farTransform);
  1766. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1767. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_ZERO, OP_ZERO, 1);
  1768. }
  1769. // Otherwise draw at split near plane
  1770. else
  1771. {
  1772. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1773. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1774. graphics_->SetShaderParameter(VSP_MODEL, nearTransform);
  1775. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1776. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_ZERO, OP_ZERO, 1);
  1777. }
  1778. renderer_->dirLightGeometry_->Draw(graphics_);
  1779. graphics_->SetColorWrite(true);
  1780. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 1);
  1781. }
  1782. else
  1783. {
  1784. // Clear the whole stencil
  1785. graphics_->SetScissorTest(false);
  1786. graphics_->Clear(CLEAR_STENCIL);
  1787. graphics_->SetStencilTest(false);
  1788. }
  1789. }
  1790. break;
  1791. }
  1792. }
  1793. void View::RenderBatchQueue(const BatchQueue& queue, bool useScissor, bool useLightBuffer)
  1794. {
  1795. Texture2D* diffBuffer = 0;
  1796. VertexBuffer* instancingBuffer = 0;
  1797. if (useLightBuffer)
  1798. diffBuffer = graphics_->GetDiffBuffer();
  1799. if (renderer_->GetDynamicInstancing())
  1800. instancingBuffer = renderer_->instancingBuffer_;
  1801. graphics_->SetScissorTest(false);
  1802. graphics_->SetStencilTest(false);
  1803. // Priority instanced
  1804. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.priorityBatchGroups_.Begin(); i !=
  1805. queue.priorityBatchGroups_.End(); ++i)
  1806. {
  1807. const BatchGroup& group = i->second_;
  1808. if ((useLightBuffer) && (!group.light_))
  1809. graphics_->SetTexture(TU_LIGHTBUFFER, diffBuffer);
  1810. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1811. }
  1812. // Priority non-instanced
  1813. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1814. {
  1815. Batch* batch = *i;
  1816. if ((useLightBuffer) && (!batch->light_))
  1817. graphics_->SetTexture(TU_LIGHTBUFFER, diffBuffer);
  1818. batch->Draw(graphics_, shaderParameters_);
  1819. }
  1820. // Non-priority instanced
  1821. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.batchGroups_.Begin(); i !=
  1822. queue.batchGroups_.End(); ++i)
  1823. {
  1824. const BatchGroup& group = i->second_;
  1825. if ((useScissor) && (group.light_))
  1826. OptimizeLightByScissor(group.light_);
  1827. else
  1828. graphics_->SetScissorTest(false);
  1829. if ((useLightBuffer) && (!group.light_))
  1830. graphics_->SetTexture(TU_LIGHTBUFFER, diffBuffer);
  1831. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1832. }
  1833. // Non-priority non-instanced
  1834. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1835. {
  1836. Batch* batch = *i;
  1837. // For the transparent queue, both priority and non-priority batches are copied here, so check the flag
  1838. if ((useScissor) && (batch->light_) && (!batch->hasPriority_))
  1839. OptimizeLightByScissor(batch->light_);
  1840. else
  1841. graphics_->SetScissorTest(false);
  1842. if ((useLightBuffer) && (!batch->light_))
  1843. graphics_->SetTexture(TU_LIGHTBUFFER, diffBuffer);
  1844. batch->Draw(graphics_, shaderParameters_);
  1845. }
  1846. }
  1847. void View::RenderForwardLightBatchQueue(const BatchQueue& queue, Light* light)
  1848. {
  1849. VertexBuffer* instancingBuffer = 0;
  1850. if (renderer_->GetDynamicInstancing())
  1851. instancingBuffer = renderer_->instancingBuffer_;
  1852. graphics_->SetScissorTest(false);
  1853. graphics_->SetStencilTest(false);
  1854. // Priority instanced
  1855. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.priorityBatchGroups_.Begin(); i !=
  1856. queue.priorityBatchGroups_.End(); ++i)
  1857. {
  1858. const BatchGroup& group = i->second_;
  1859. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1860. }
  1861. // Priority non-instanced
  1862. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1863. {
  1864. Batch* batch = *i;
  1865. batch->Draw(graphics_, shaderParameters_);
  1866. }
  1867. // All base passes have been drawn. Optimize at this point by both scissor and stencil
  1868. if (light)
  1869. {
  1870. OptimizeLightByScissor(light);
  1871. LightType type = light->GetLightType();
  1872. if ((type == LIGHT_SPLITPOINT) || (type == LIGHT_DIRECTIONAL))
  1873. DrawSplitLightToStencil(*camera_, light);
  1874. }
  1875. // Non-priority instanced
  1876. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.batchGroups_.Begin(); i !=
  1877. queue.batchGroups_.End(); ++i)
  1878. {
  1879. const BatchGroup& group = i->second_;
  1880. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1881. }
  1882. // Non-priority non-instanced
  1883. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1884. {
  1885. Batch* batch = *i;
  1886. batch->Draw(graphics_, shaderParameters_);
  1887. }
  1888. }
  1889. void View::RenderShadowMap(const LightBatchQueue& queue)
  1890. {
  1891. PROFILE(RenderShadowMap);
  1892. Texture2D* shadowMap = queue.light_->GetShadowMap();
  1893. graphics_->ClearLastParameterSources();
  1894. graphics_->SetColorWrite(false);
  1895. graphics_->SetStencilTest(false);
  1896. graphics_->SetTexture(TU_SHADOWMAP, 0);
  1897. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  1898. graphics_->SetDepthStencil(shadowMap);
  1899. graphics_->Clear(CLEAR_DEPTH);
  1900. // Set shadow depth bias
  1901. BiasParameters parameters = queue.light_->GetShadowBias();
  1902. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  1903. // Set a scissor rectangle to match possible shadow map size reduction by out-zooming
  1904. // However, do not do this for point lights
  1905. if (queue.light_->GetLightType() != LIGHT_SPLITPOINT)
  1906. {
  1907. float zoom = Min(queue.light_->GetShadowCamera()->GetZoom(),
  1908. (float)(shadowMap->GetWidth() - 2) / (float)shadowMap->GetWidth());
  1909. Rect zoorect_(Vector2(-1.0f, -1.0f) * zoom, Vector2(1.0f, 1.0f) * zoom);
  1910. graphics_->SetScissorTest(true, zoorect_, false);
  1911. }
  1912. else
  1913. graphics_->SetScissorTest(false);
  1914. // Draw instanced and non-instanced shadow casters
  1915. RenderBatchQueue(queue.shadowBatches_);
  1916. graphics_->SetColorWrite(true);
  1917. graphics_->SetDepthBias(0.0f, 0.0f);
  1918. }