View.cpp 95 KB

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