View.cpp 95 KB

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