View.cpp 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 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 "Renderer.h"
  34. #include "ResourceCache.h"
  35. #include "PostProcess.h"
  36. #include "Profiler.h"
  37. #include "Scene.h"
  38. #include "ShaderVariation.h"
  39. #include "Skybox.h"
  40. #include "Sort.h"
  41. #include "Technique.h"
  42. #include "Texture2D.h"
  43. #include "TextureCube.h"
  44. #include "VertexBuffer.h"
  45. #include "View.h"
  46. #include "WorkQueue.h"
  47. #include "Zone.h"
  48. #include "DebugNew.h"
  49. static const Vector3 directions[] =
  50. {
  51. Vector3(1.0f, 0.0f, 0.0f),
  52. Vector3(-1.0f, 0.0f, 0.0f),
  53. Vector3(0.0f, 1.0f, 0.0f),
  54. Vector3(0.0f, -1.0f, 0.0f),
  55. Vector3(0.0f, 0.0f, 1.0f),
  56. Vector3(0.0f, 0.0f, -1.0f)
  57. };
  58. static const int CHECK_DRAWABLES_PER_WORK_ITEM = 64;
  59. static const float LIGHT_INTENSITY_THRESHOLD = 0.001f;
  60. /// %Frustum octree query for shadowcasters.
  61. class ShadowCasterOctreeQuery : public OctreeQuery
  62. {
  63. public:
  64. /// Construct with frustum and query parameters.
  65. ShadowCasterOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  66. unsigned viewMask = DEFAULT_VIEWMASK) :
  67. OctreeQuery(result, drawableFlags, viewMask),
  68. frustum_(frustum)
  69. {
  70. }
  71. /// Intersection test for an octant.
  72. virtual Intersection TestOctant(const BoundingBox& box, bool inside)
  73. {
  74. if (inside)
  75. return INSIDE;
  76. else
  77. return frustum_.IsInside(box);
  78. }
  79. /// Intersection test for drawables.
  80. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  81. {
  82. while (start != end)
  83. {
  84. Drawable* drawable = *start;
  85. if ((drawable->GetDrawableFlags() & drawableFlags_) && drawable->GetCastShadows() && drawable->IsVisible() &&
  86. (drawable->GetViewMask() & viewMask_))
  87. {
  88. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  89. result_.Push(drawable);
  90. }
  91. ++start;
  92. }
  93. }
  94. /// Frustum.
  95. Frustum frustum_;
  96. };
  97. /// %Frustum octree query for zones and occluders.
  98. class ZoneOccluderOctreeQuery : public OctreeQuery
  99. {
  100. public:
  101. /// Construct with frustum and query parameters.
  102. ZoneOccluderOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  103. unsigned viewMask = DEFAULT_VIEWMASK) :
  104. OctreeQuery(result, drawableFlags, viewMask),
  105. frustum_(frustum)
  106. {
  107. }
  108. /// Intersection test for an octant.
  109. virtual Intersection TestOctant(const BoundingBox& box, bool inside)
  110. {
  111. if (inside)
  112. return INSIDE;
  113. else
  114. return frustum_.IsInside(box);
  115. }
  116. /// Intersection test for drawables.
  117. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  118. {
  119. while (start != end)
  120. {
  121. Drawable* drawable = *start;
  122. unsigned char flags = drawable->GetDrawableFlags();
  123. if ((flags == DRAWABLE_ZONE || (flags == DRAWABLE_GEOMETRY && drawable->IsOccluder())) && drawable->IsVisible() &&
  124. (drawable->GetViewMask() & viewMask_))
  125. {
  126. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  127. result_.Push(drawable);
  128. }
  129. ++start;
  130. }
  131. }
  132. /// Frustum.
  133. Frustum frustum_;
  134. };
  135. /// %Frustum octree query with occlusion.
  136. class OccludedFrustumOctreeQuery : public OctreeQuery
  137. {
  138. public:
  139. /// Construct with frustum, occlusion buffer and query parameters.
  140. OccludedFrustumOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, OcclusionBuffer* buffer, unsigned char
  141. drawableFlags = DRAWABLE_ANY, unsigned viewMask = DEFAULT_VIEWMASK) :
  142. OctreeQuery(result, drawableFlags, viewMask),
  143. frustum_(frustum),
  144. buffer_(buffer)
  145. {
  146. }
  147. /// Intersection test for an octant.
  148. virtual Intersection TestOctant(const BoundingBox& box, bool inside)
  149. {
  150. if (inside)
  151. return buffer_->IsVisible(box) ? INSIDE : OUTSIDE;
  152. else
  153. {
  154. Intersection result = frustum_.IsInside(box);
  155. if (result != OUTSIDE && !buffer_->IsVisible(box))
  156. result = OUTSIDE;
  157. return result;
  158. }
  159. }
  160. /// Intersection test for drawables. Note: drawable occlusion is performed later in worker threads.
  161. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  162. {
  163. while (start != end)
  164. {
  165. Drawable* drawable = *start;
  166. if ((drawable->GetDrawableFlags() & drawableFlags_) && drawable->IsVisible() &&
  167. (drawable->GetViewMask() & viewMask_))
  168. {
  169. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  170. result_.Push(drawable);
  171. }
  172. ++start;
  173. }
  174. }
  175. /// Frustum.
  176. Frustum frustum_;
  177. /// Occlusion buffer.
  178. OcclusionBuffer* buffer_;
  179. };
  180. void CheckVisibilityWork(const WorkItem* item, unsigned threadIndex)
  181. {
  182. View* view = reinterpret_cast<View*>(item->aux_);
  183. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  184. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  185. OcclusionBuffer* buffer = view->occlusionBuffer_;
  186. while (start != end)
  187. {
  188. Drawable* drawable = *start;
  189. unsigned char flags = drawable->GetDrawableFlags();
  190. ++start;
  191. if (flags & DRAWABLE_ZONE)
  192. continue;
  193. drawable->UpdateDistance(view->frame_);
  194. // If draw distance non-zero, check it
  195. float maxDistance = drawable->GetDrawDistance();
  196. if (maxDistance > 0.0f && drawable->GetDistance() > maxDistance)
  197. continue;
  198. if (buffer && drawable->IsOccludee() && !buffer->IsVisible(drawable->GetWorldBoundingBox()))
  199. continue;
  200. drawable->MarkInView(view->frame_);
  201. // For geometries, clear lights and find new zone if necessary
  202. if (flags & DRAWABLE_GEOMETRY)
  203. {
  204. drawable->ClearLights();
  205. if (!drawable->GetZone() && !view->cameraZoneOverride_)
  206. view->FindZone(drawable, threadIndex);
  207. }
  208. }
  209. }
  210. void ProcessLightWork(const WorkItem* item, unsigned threadIndex)
  211. {
  212. View* view = reinterpret_cast<View*>(item->aux_);
  213. LightQueryResult* query = reinterpret_cast<LightQueryResult*>(item->start_);
  214. view->ProcessLight(*query, threadIndex);
  215. }
  216. void UpdateDrawableGeometriesWork(const WorkItem* item, unsigned threadIndex)
  217. {
  218. const FrameInfo& frame = *(reinterpret_cast<FrameInfo*>(item->aux_));
  219. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  220. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  221. while (start != end)
  222. {
  223. Drawable* drawable = *start;
  224. drawable->UpdateGeometry(frame);
  225. ++start;
  226. }
  227. }
  228. void SortBatchQueueFrontToBackWork(const WorkItem* item, unsigned threadIndex)
  229. {
  230. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  231. queue->SortFrontToBack();
  232. }
  233. void SortBatchQueueBackToFrontWork(const WorkItem* item, unsigned threadIndex)
  234. {
  235. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  236. queue->SortBackToFront();
  237. }
  238. void SortLightQueueWork(const WorkItem* item, unsigned threadIndex)
  239. {
  240. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  241. start->litBatches_.SortFrontToBack();
  242. }
  243. void SortShadowQueueWork(const WorkItem* item, unsigned threadIndex)
  244. {
  245. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  246. for (unsigned i = 0; i < start->shadowSplits_.Size(); ++i)
  247. start->shadowSplits_[i].shadowBatches_.SortFrontToBack();
  248. }
  249. OBJECTTYPESTATIC(View);
  250. View::View(Context* context) :
  251. Object(context),
  252. graphics_(GetSubsystem<Graphics>()),
  253. renderer_(GetSubsystem<Renderer>()),
  254. octree_(0),
  255. camera_(0),
  256. cameraZone_(0),
  257. farClipZone_(0),
  258. renderTarget_(0)
  259. {
  260. frame_.camera_ = 0;
  261. // Create octree query vectors for each thread
  262. tempDrawables_.Resize(GetSubsystem<WorkQueue>()->GetNumThreads() + 1);
  263. tempZones_.Resize(GetSubsystem<WorkQueue>()->GetNumThreads() + 1);
  264. }
  265. View::~View()
  266. {
  267. }
  268. bool View::Define(RenderSurface* renderTarget, Viewport* viewport)
  269. {
  270. Scene* scene = viewport->GetScene();
  271. Camera* camera = viewport->GetCamera();
  272. if (!scene || !camera)
  273. return false;
  274. // If scene is loading asynchronously, it is incomplete and should not be rendered
  275. if (scene->IsAsyncLoading())
  276. return false;
  277. Octree* octree = scene->GetComponent<Octree>();
  278. if (!octree)
  279. return false;
  280. renderMode_ = renderer_->GetRenderMode();
  281. octree_ = octree;
  282. camera_ = camera;
  283. renderTarget_ = renderTarget;
  284. // Get active post-processing effects on the viewport
  285. const Vector<SharedPtr<PostProcess> >& postProcesses = viewport->GetPostProcesses();
  286. postProcesses_.Clear();
  287. for (Vector<SharedPtr<PostProcess> >::ConstIterator i = postProcesses.Begin(); i != postProcesses.End(); ++i)
  288. {
  289. PostProcess* effect = i->Get();
  290. if (effect && effect->IsActive())
  291. postProcesses_.Push(*i);
  292. }
  293. // Validate the rect and calculate size. If zero rect, use whole rendertarget size
  294. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  295. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  296. const IntRect& rect = viewport->GetRect();
  297. if (rect != IntRect::ZERO)
  298. {
  299. viewRect_.left_ = Clamp(rect.left_, 0, rtWidth - 1);
  300. viewRect_.top_ = Clamp(rect.top_, 0, rtHeight - 1);
  301. viewRect_.right_ = Clamp(rect.right_, viewRect_.left_ + 1, rtWidth);
  302. viewRect_.bottom_ = Clamp(rect.bottom_, viewRect_.top_ + 1, rtHeight);
  303. }
  304. else
  305. viewRect_ = IntRect(0, 0, rtWidth, rtHeight);
  306. viewSize_ = IntVector2(viewRect_.right_ - viewRect_.left_, viewRect_.bottom_ - viewRect_.top_);
  307. rtSize_ = IntVector2(rtWidth, rtHeight);
  308. // On OpenGL flip the viewport if rendering to a texture for consistent UV addressing with Direct3D9
  309. #ifdef USE_OPENGL
  310. if (renderTarget_)
  311. {
  312. viewRect_.bottom_ = rtSize_.y_ - viewRect_.top_;
  313. viewRect_.top_ = viewRect_.bottom_ - viewSize_.y_;
  314. }
  315. #endif
  316. drawShadows_ = renderer_->GetDrawShadows();
  317. materialQuality_ = renderer_->GetMaterialQuality();
  318. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  319. // Set possible quality overrides from the camera
  320. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  321. if (viewOverrideFlags & VO_LOW_MATERIAL_QUALITY)
  322. materialQuality_ = QUALITY_LOW;
  323. if (viewOverrideFlags & VO_DISABLE_SHADOWS)
  324. drawShadows_ = false;
  325. if (viewOverrideFlags & VO_DISABLE_OCCLUSION)
  326. maxOccluderTriangles_ = 0;
  327. return true;
  328. }
  329. void View::Update(const FrameInfo& frame)
  330. {
  331. if (!camera_ || !octree_)
  332. return;
  333. frame_.camera_ = camera_;
  334. frame_.timeStep_ = frame.timeStep_;
  335. frame_.frameNumber_ = frame.frameNumber_;
  336. frame_.viewSize_ = viewSize_;
  337. // Clear screen buffers, geometry, light, occluder & batch lists
  338. screenBuffers_.Clear();
  339. geometries_.Clear();
  340. allGeometries_.Clear();
  341. geometryDepthBounds_.Clear();
  342. lights_.Clear();
  343. zones_.Clear();
  344. occluders_.Clear();
  345. baseQueue_.Clear();
  346. preAlphaQueue_.Clear();
  347. gbufferQueue_.Clear();
  348. alphaQueue_.Clear();
  349. postAlphaQueue_.Clear();
  350. lightQueues_.Clear();
  351. vertexLightQueues_.Clear();
  352. // Do not update if camera projection is illegal
  353. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  354. if (!camera_->IsProjectionValid())
  355. return;
  356. // Set automatic aspect ratio if required
  357. if (camera_->GetAutoAspectRatio())
  358. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  359. GetDrawables();
  360. GetBatches();
  361. UpdateGeometries();
  362. }
  363. void View::Render()
  364. {
  365. if (!octree_ || !camera_)
  366. return;
  367. // Allocate screen buffers for post-processing and blitting as necessary
  368. AllocateScreenBuffers();
  369. // Forget parameter sources from the previous view
  370. graphics_->ClearParameterSources();
  371. // If stream offset is supported, write all instance transforms to a single large buffer
  372. // Else we must lock the instance buffer for each batch group
  373. if (renderer_->GetDynamicInstancing() && graphics_->GetStreamOffsetSupport())
  374. PrepareInstancingBuffer();
  375. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  376. // again to ensure correct projection will be used
  377. if (camera_->GetAutoAspectRatio())
  378. camera_->SetAspectRatio((float)(viewSize_.x_) / (float)(viewSize_.y_));
  379. graphics_->SetColorWrite(true);
  380. graphics_->SetFillMode(FILL_SOLID);
  381. // Bind the face selection and indirection cube maps for point light shadows
  382. graphics_->SetTexture(TU_FACESELECT, renderer_->GetFaceSelectCubeMap());
  383. graphics_->SetTexture(TU_INDIRECTION, renderer_->GetIndirectionCubeMap());
  384. // Set "view texture" to prevent destination texture sampling in case we do not render to the destination directly
  385. // ie. when using deferred rendering and/or doing post-processing
  386. if (renderTarget_)
  387. graphics_->SetViewTexture(renderTarget_->GetParentTexture());
  388. // On OpenGL, flip the projection if rendering to a texture so that the texture can be addressed in the same way
  389. // as a render texture produced on Direct3D9
  390. #ifdef USE_OPENGL
  391. if (renderTarget_)
  392. camera_->SetFlipVertical(true);
  393. #endif
  394. // Render
  395. if (renderMode_ == RENDER_FORWARD)
  396. RenderBatchesForward();
  397. else
  398. RenderBatchesDeferred();
  399. #ifdef USE_OPENGL
  400. camera_->SetFlipVertical(false);
  401. #endif
  402. graphics_->SetViewTexture(0);
  403. graphics_->SetScissorTest(false);
  404. graphics_->SetStencilTest(false);
  405. graphics_->ResetStreamFrequencies();
  406. // Run post-processes or framebuffer blitting now
  407. if (screenBuffers_.Size())
  408. {
  409. if (postProcesses_.Size())
  410. RunPostProcesses();
  411. else
  412. BlitFramebuffer();
  413. }
  414. // If this is a main view, draw the associated debug geometry now
  415. if (!renderTarget_)
  416. {
  417. DebugRenderer* debug = octree_->GetComponent<DebugRenderer>();
  418. if (debug)
  419. {
  420. debug->SetView(camera_);
  421. debug->Render();
  422. }
  423. }
  424. // "Forget" the camera, octree and zone after rendering
  425. camera_ = 0;
  426. octree_ = 0;
  427. cameraZone_ = 0;
  428. farClipZone_ = 0;
  429. occlusionBuffer_ = 0;
  430. frame_.camera_ = 0;
  431. }
  432. void View::GetDrawables()
  433. {
  434. PROFILE(GetDrawables);
  435. WorkQueue* queue = GetSubsystem<WorkQueue>();
  436. PODVector<Drawable*>& tempDrawables = tempDrawables_[0];
  437. // Get zones and occluders first
  438. {
  439. ZoneOccluderOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_ZONE);
  440. octree_->GetDrawables(query);
  441. }
  442. highestZonePriority_ = M_MIN_INT;
  443. int bestPriority = M_MIN_INT;
  444. Vector3 cameraPos = camera_->GetWorldPosition();
  445. // Get default zone first in case we do not have zones defined
  446. Zone* defaultZone = renderer_->GetDefaultZone();
  447. cameraZone_ = farClipZone_ = defaultZone;
  448. for (PODVector<Drawable*>::ConstIterator i = tempDrawables.Begin(); i != tempDrawables.End(); ++i)
  449. {
  450. Drawable* drawable = *i;
  451. unsigned char flags = drawable->GetDrawableFlags();
  452. if (flags & DRAWABLE_ZONE)
  453. {
  454. Zone* zone = static_cast<Zone*>(drawable);
  455. zones_.Push(zone);
  456. int priority = zone->GetPriority();
  457. if (priority > highestZonePriority_)
  458. highestZonePriority_ = priority;
  459. if (zone->IsInside(cameraPos) && priority > bestPriority)
  460. {
  461. cameraZone_ = zone;
  462. bestPriority = priority;
  463. }
  464. }
  465. else
  466. occluders_.Push(drawable);
  467. }
  468. // Determine the zone at far clip distance. If not found, or camera zone has override mode, use camera zone
  469. cameraZoneOverride_ = cameraZone_->GetOverride();
  470. if (!cameraZoneOverride_)
  471. {
  472. Vector3 farClipPos = cameraPos + camera_->GetNode()->GetWorldDirection() * Vector3(0, 0, camera_->GetFarClip());
  473. bestPriority = M_MIN_INT;
  474. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  475. {
  476. int priority = (*i)->GetPriority();
  477. if ((*i)->IsInside(farClipPos) && priority > bestPriority)
  478. {
  479. farClipZone_ = *i;
  480. bestPriority = priority;
  481. }
  482. }
  483. }
  484. if (farClipZone_ == defaultZone)
  485. farClipZone_ = cameraZone_;
  486. // If occlusion in use, get & render the occluders
  487. occlusionBuffer_ = 0;
  488. if (maxOccluderTriangles_ > 0)
  489. {
  490. UpdateOccluders(occluders_, camera_);
  491. if (occluders_.Size())
  492. {
  493. PROFILE(DrawOcclusion);
  494. occlusionBuffer_ = renderer_->GetOcclusionBuffer(camera_);
  495. DrawOccluders(occlusionBuffer_, occluders_);
  496. }
  497. }
  498. // Get lights and geometries. Coarse occlusion for octants is used at this point
  499. if (occlusionBuffer_)
  500. {
  501. OccludedFrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), occlusionBuffer_, DRAWABLE_GEOMETRY |
  502. DRAWABLE_LIGHT);
  503. octree_->GetDrawables(query);
  504. }
  505. else
  506. {
  507. FrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  508. octree_->GetDrawables(query);
  509. }
  510. // Check drawable occlusion and find zones for moved drawables in worker threads
  511. {
  512. WorkItem item;
  513. item.workFunction_ = CheckVisibilityWork;
  514. item.aux_ = this;
  515. PODVector<Drawable*>::Iterator start = tempDrawables.Begin();
  516. while (start != tempDrawables.End())
  517. {
  518. PODVector<Drawable*>::Iterator end = tempDrawables.End();
  519. if (end - start > CHECK_DRAWABLES_PER_WORK_ITEM)
  520. end = start + CHECK_DRAWABLES_PER_WORK_ITEM;
  521. item.start_ = &(*start);
  522. item.end_ = &(*end);
  523. queue->AddWorkItem(item);
  524. start = end;
  525. }
  526. queue->Complete();
  527. }
  528. // Sort into geometries & lights, and build visible scene bounding boxes in world and view space
  529. sceneBox_.min_ = sceneBox_.max_ = Vector3::ZERO;
  530. sceneBox_.defined_ = false;
  531. sceneViewBox_.min_ = sceneViewBox_.max_ = Vector3::ZERO;
  532. sceneViewBox_.defined_ = false;
  533. Matrix3x4 view(camera_->GetInverseWorldTransform());
  534. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  535. {
  536. Drawable* drawable = tempDrawables[i];
  537. unsigned char flags = drawable->GetDrawableFlags();
  538. if (flags & DRAWABLE_ZONE || !drawable->IsInView(frame_))
  539. continue;
  540. if (flags & DRAWABLE_GEOMETRY)
  541. {
  542. // Expand the scene bounding boxes. However, do not take skyboxes into account, as they have undefinedly large size
  543. // and the bounding boxes are also used for shadow focusing
  544. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  545. BoundingBox geomViewBox = geomBox.Transformed(view);
  546. if (drawable->GetType() != Skybox::GetTypeStatic())
  547. {
  548. sceneBox_.Merge(geomBox);
  549. sceneViewBox_.Merge(geomViewBox);
  550. }
  551. // Store depth info for split directional light queries
  552. GeometryDepthBounds bounds;
  553. bounds.min_ = geomViewBox.min_.z_;
  554. bounds.max_ = geomViewBox.max_.z_;
  555. geometryDepthBounds_.Push(bounds);
  556. geometries_.Push(drawable);
  557. allGeometries_.Push(drawable);
  558. }
  559. else if (flags & DRAWABLE_LIGHT)
  560. {
  561. Light* light = static_cast<Light*>(drawable);
  562. // Skip lights which are so dim that they can not contribute to a rendertarget
  563. if (light->GetColor().Intensity() > LIGHT_INTENSITY_THRESHOLD)
  564. lights_.Push(light);
  565. }
  566. }
  567. sceneFrustum_ = camera_->GetSplitFrustum(sceneViewBox_.min_.z_, sceneViewBox_.max_.z_);
  568. // Sort the lights to brightest/closest first
  569. for (unsigned i = 0; i < lights_.Size(); ++i)
  570. {
  571. Light* light = lights_[i];
  572. light->SetIntensitySortValue(camera_->GetDistance(light->GetWorldPosition()));
  573. light->SetLightQueue(0);
  574. }
  575. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  576. }
  577. void View::GetBatches()
  578. {
  579. WorkQueue* queue = GetSubsystem<WorkQueue>();
  580. PODVector<Light*> vertexLights;
  581. // Process lit geometries and shadow casters for each light
  582. {
  583. PROFILE(ProcessLights);
  584. lightQueryResults_.Resize(lights_.Size());
  585. WorkItem item;
  586. item.workFunction_ = ProcessLightWork;
  587. item.aux_ = this;
  588. for (unsigned i = 0; i < lightQueryResults_.Size(); ++i)
  589. {
  590. LightQueryResult& query = lightQueryResults_[i];
  591. query.light_ = lights_[i];
  592. item.start_ = &query;
  593. queue->AddWorkItem(item);
  594. }
  595. // Ensure all lights have been processed before proceeding
  596. queue->Complete();
  597. }
  598. // Build light queues and lit batches
  599. {
  600. PROFILE(GetLightBatches);
  601. maxLightsDrawables_.Clear();
  602. // Preallocate light queues: per-pixel lights which have lit geometries
  603. unsigned numLightQueues = 0;
  604. unsigned usedLightQueues = 0;
  605. for (Vector<LightQueryResult>::ConstIterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  606. {
  607. if (!i->light_->GetPerVertex() && i->litGeometries_.Size())
  608. ++numLightQueues;
  609. }
  610. lightQueues_.Resize(numLightQueues);
  611. for (Vector<LightQueryResult>::Iterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  612. {
  613. LightQueryResult& query = *i;
  614. // If light has no affected geometries, no need to process further
  615. if (query.litGeometries_.Empty())
  616. continue;
  617. Light* light = query.light_;
  618. // Per-pixel light
  619. if (!light->GetPerVertex())
  620. {
  621. unsigned shadowSplits = query.numSplits_;
  622. // Initialize light queue. Store light-to-queue mapping so that the queue can be found later
  623. LightBatchQueue& lightQueue = lightQueues_[usedLightQueues++];
  624. light->SetLightQueue(&lightQueue);
  625. lightQueue.light_ = light;
  626. lightQueue.litBatches_.Clear();
  627. lightQueue.volumeBatches_.Clear();
  628. // Allocate shadow map now
  629. lightQueue.shadowMap_ = 0;
  630. if (shadowSplits > 0)
  631. {
  632. lightQueue.shadowMap_ = renderer_->GetShadowMap(light, camera_, viewSize_.x_, viewSize_.y_);
  633. // If did not manage to get a shadow map, convert the light to unshadowed
  634. if (!lightQueue.shadowMap_)
  635. shadowSplits = 0;
  636. }
  637. // Setup shadow batch queues
  638. lightQueue.shadowSplits_.Resize(shadowSplits);
  639. for (unsigned j = 0; j < shadowSplits; ++j)
  640. {
  641. ShadowBatchQueue& shadowQueue = lightQueue.shadowSplits_[j];
  642. Camera* shadowCamera = query.shadowCameras_[j];
  643. shadowQueue.shadowCamera_ = shadowCamera;
  644. shadowQueue.nearSplit_ = query.shadowNearSplits_[j];
  645. shadowQueue.farSplit_ = query.shadowFarSplits_[j];
  646. // Setup the shadow split viewport and finalize shadow camera parameters
  647. shadowQueue.shadowViewport_ = GetShadowMapViewport(light, j, lightQueue.shadowMap_);
  648. FinalizeShadowCamera(shadowCamera, light, shadowQueue.shadowViewport_, query.shadowCasterBox_[j]);
  649. // Loop through shadow casters
  650. for (PODVector<Drawable*>::ConstIterator k = query.shadowCasters_.Begin() + query.shadowCasterBegin_[j];
  651. k < query.shadowCasters_.Begin() + query.shadowCasterEnd_[j]; ++k)
  652. {
  653. Drawable* drawable = *k;
  654. if (!drawable->IsInView(frame_, false))
  655. {
  656. drawable->MarkInView(frame_, false);
  657. allGeometries_.Push(drawable);
  658. }
  659. Zone* zone = GetZone(drawable);
  660. unsigned numBatches = drawable->GetNumBatches();
  661. for (unsigned l = 0; l < numBatches; ++l)
  662. {
  663. Batch shadowBatch;
  664. drawable->GetBatch(shadowBatch, frame_, l);
  665. Technique* tech = GetTechnique(drawable, shadowBatch.material_);
  666. if (!shadowBatch.geometry_ || !tech)
  667. continue;
  668. Pass* pass = tech->GetPass(PASS_SHADOW);
  669. // Skip if material has no shadow pass
  670. if (!pass)
  671. continue;
  672. // Fill the rest of the batch
  673. shadowBatch.camera_ = shadowCamera;
  674. shadowBatch.zone_ = zone;
  675. shadowBatch.lightQueue_ = &lightQueue;
  676. FinalizeBatch(shadowBatch, tech, pass);
  677. shadowQueue.shadowBatches_.AddBatch(shadowBatch);
  678. }
  679. }
  680. }
  681. // Process lit geometries
  682. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  683. {
  684. Drawable* drawable = *j;
  685. drawable->AddLight(light);
  686. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  687. if (!drawable->GetMaxLights())
  688. GetLitBatches(drawable, lightQueue);
  689. else
  690. maxLightsDrawables_.Insert(drawable);
  691. }
  692. // In deferred modes, store the light volume batch now
  693. if (renderMode_ != RENDER_FORWARD)
  694. {
  695. Batch volumeBatch;
  696. volumeBatch.geometry_ = renderer_->GetLightGeometry(light);
  697. volumeBatch.worldTransform_ = &light->GetVolumeTransform(camera_);
  698. volumeBatch.overrideView_ = light->GetLightType() == LIGHT_DIRECTIONAL;
  699. volumeBatch.camera_ = camera_;
  700. volumeBatch.lightQueue_ = &lightQueue;
  701. volumeBatch.distance_ = light->GetDistance();
  702. volumeBatch.material_ = 0;
  703. volumeBatch.pass_ = 0;
  704. volumeBatch.zone_ = 0;
  705. renderer_->SetLightVolumeBatchShaders(volumeBatch);
  706. lightQueue.volumeBatches_.Push(volumeBatch);
  707. }
  708. }
  709. // Per-vertex light
  710. else
  711. {
  712. // Add the vertex light to lit drawables. It will be processed later during base pass batch generation
  713. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  714. {
  715. Drawable* drawable = *j;
  716. drawable->AddVertexLight(light);
  717. }
  718. }
  719. }
  720. }
  721. // Process drawables with limited per-pixel light count
  722. if (maxLightsDrawables_.Size())
  723. {
  724. PROFILE(GetMaxLightsBatches);
  725. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  726. {
  727. Drawable* drawable = *i;
  728. drawable->LimitLights();
  729. const PODVector<Light*>& lights = drawable->GetLights();
  730. for (unsigned i = 0; i < lights.Size(); ++i)
  731. {
  732. Light* light = lights[i];
  733. // Find the correct light queue again
  734. LightBatchQueue* queue = light->GetLightQueue();
  735. if (queue)
  736. GetLitBatches(drawable, *queue);
  737. }
  738. }
  739. }
  740. // Build base pass batches
  741. {
  742. PROFILE(GetBaseBatches);
  743. hasZeroLightMask_ = false;
  744. for (PODVector<Drawable*>::ConstIterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  745. {
  746. Drawable* drawable = *i;
  747. Zone* zone = GetZone(drawable);
  748. unsigned numBatches = drawable->GetNumBatches();
  749. const PODVector<Light*>& drawableVertexLights = drawable->GetVertexLights();
  750. if (!drawableVertexLights.Empty())
  751. drawable->LimitVertexLights();
  752. for (unsigned j = 0; j < numBatches; ++j)
  753. {
  754. Batch baseBatch;
  755. drawable->GetBatch(baseBatch, frame_, j);
  756. Technique* tech = GetTechnique(drawable, baseBatch.material_);
  757. if (!baseBatch.geometry_ || !tech)
  758. continue;
  759. // Check here if the material technique refers to a rendertarget texture with camera(s) attached
  760. // Only check this for the main view (null rendertarget)
  761. if (baseBatch.material_ && baseBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_ && !renderTarget_)
  762. CheckMaterialForAuxView(baseBatch.material_);
  763. // Fill the rest of the batch
  764. baseBatch.camera_ = camera_;
  765. baseBatch.zone_ = zone;
  766. baseBatch.isBase_ = true;
  767. Pass* pass = 0;
  768. // In deferred modes check for G-buffer and material passes first
  769. if (renderMode_ == RENDER_PREPASS)
  770. {
  771. pass = tech->GetPass(PASS_PREPASS);
  772. if (pass)
  773. {
  774. // If the opaque object has a zero lightmask, have to skip light buffer optimization
  775. if (!hasZeroLightMask_ && (!(GetLightMask(drawable) & 0xff)))
  776. hasZeroLightMask_ = true;
  777. // Allow G-buffer pass instancing only if lightmask matches zone lightmask
  778. baseBatch.lightMask_ = GetLightMask(drawable);
  779. FinalizeBatch(baseBatch, tech, pass, baseBatch.lightMask_ == (zone->GetLightMask() & 0xff));
  780. gbufferQueue_.AddBatch(baseBatch);
  781. pass = tech->GetPass(PASS_MATERIAL);
  782. }
  783. }
  784. if (renderMode_ == RENDER_DEFERRED)
  785. pass = tech->GetPass(PASS_DEFERRED);
  786. // Next check for forward base pass
  787. if (!pass)
  788. {
  789. // Skip if a lit base pass already exists (only in forward rendering)
  790. if (j < 32 && drawable->HasBasePass(j))
  791. continue;
  792. pass = tech->GetPass(PASS_BASE);
  793. }
  794. if (pass)
  795. {
  796. // Check for vertex lights (both forward unlit, light pre-pass material pass, and deferred G-buffer)
  797. if (!drawableVertexLights.Empty())
  798. {
  799. // For a deferred opaque batch, check if the vertex lights include converted per-pixel lights, and remove
  800. // them to prevent double-lighting
  801. if (renderMode_ != RENDER_FORWARD && pass->GetBlendMode() == BLEND_REPLACE)
  802. {
  803. vertexLights.Clear();
  804. for (unsigned i = 0; i < drawableVertexLights.Size(); ++i)
  805. {
  806. if (drawableVertexLights[i]->GetPerVertex())
  807. vertexLights.Push(drawableVertexLights[i]);
  808. }
  809. }
  810. else
  811. vertexLights = drawableVertexLights;
  812. if (!vertexLights.Empty())
  813. {
  814. // Find a vertex light queue. If not found, create new
  815. unsigned long long hash = GetVertexLightQueueHash(vertexLights);
  816. HashMap<unsigned long long, LightBatchQueue>::Iterator i = vertexLightQueues_.Find(hash);
  817. if (i == vertexLightQueues_.End())
  818. {
  819. i = vertexLightQueues_.Insert(MakePair(hash, LightBatchQueue()));
  820. i->second_.light_ = 0;
  821. i->second_.shadowMap_ = 0;
  822. i->second_.vertexLights_ = vertexLights;
  823. }
  824. baseBatch.lightQueue_ = &(i->second_);
  825. }
  826. }
  827. // Check whether batch is opaque or transparent
  828. if (pass->GetBlendMode() == BLEND_REPLACE)
  829. {
  830. if (pass->GetType() != PASS_DEFERRED)
  831. {
  832. FinalizeBatch(baseBatch, tech, pass);
  833. baseQueue_.AddBatch(baseBatch);
  834. }
  835. else
  836. {
  837. // Allow G-buffer pass instancing only if lightmask matches zone lightmask
  838. baseBatch.lightMask_ = GetLightMask(drawable);
  839. FinalizeBatch(baseBatch, tech, pass, baseBatch.lightMask_ == (baseBatch.zone_->GetLightMask() & 0xff));
  840. gbufferQueue_.AddBatch(baseBatch);
  841. }
  842. }
  843. else
  844. {
  845. // Transparent batches can not be instanced
  846. FinalizeBatch(baseBatch, tech, pass, false);
  847. alphaQueue_.AddBatch(baseBatch);
  848. }
  849. continue;
  850. }
  851. // If no pass found so far, finally check for pre-alpha / post-alpha custom passes
  852. pass = tech->GetPass(PASS_PREALPHA);
  853. if (pass)
  854. {
  855. FinalizeBatch(baseBatch, tech, pass);
  856. preAlphaQueue_.AddBatch(baseBatch);
  857. continue;
  858. }
  859. pass = tech->GetPass(PASS_POSTALPHA);
  860. if (pass)
  861. {
  862. // Post-alpha pass is treated similarly as alpha, and is not instanced
  863. FinalizeBatch(baseBatch, tech, pass, false);
  864. postAlphaQueue_.AddBatch(baseBatch);
  865. continue;
  866. }
  867. }
  868. }
  869. }
  870. }
  871. void View::UpdateGeometries()
  872. {
  873. PROFILE(UpdateGeometries);
  874. WorkQueue* queue = GetSubsystem<WorkQueue>();
  875. // Sort batches
  876. {
  877. WorkItem item;
  878. item.workFunction_ = SortBatchQueueFrontToBackWork;
  879. item.start_ = &baseQueue_;
  880. queue->AddWorkItem(item);
  881. item.start_ = &preAlphaQueue_;
  882. queue->AddWorkItem(item);
  883. if (renderMode_ != RENDER_FORWARD)
  884. {
  885. item.start_ = &gbufferQueue_;
  886. queue->AddWorkItem(item);
  887. }
  888. item.workFunction_ = SortBatchQueueBackToFrontWork;
  889. item.start_ = &alphaQueue_;
  890. queue->AddWorkItem(item);
  891. item.start_ = &postAlphaQueue_;
  892. queue->AddWorkItem(item);
  893. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  894. {
  895. item.workFunction_ = SortLightQueueWork;
  896. item.start_ = &(*i);
  897. queue->AddWorkItem(item);
  898. if ((*i).shadowSplits_.Size())
  899. {
  900. item.workFunction_ = SortShadowQueueWork;
  901. queue->AddWorkItem(item);
  902. }
  903. }
  904. }
  905. // Update geometries. Split into threaded and non-threaded updates.
  906. {
  907. nonThreadedGeometries_.Clear();
  908. threadedGeometries_.Clear();
  909. for (PODVector<Drawable*>::Iterator i = allGeometries_.Begin(); i != allGeometries_.End(); ++i)
  910. {
  911. UpdateGeometryType type = (*i)->GetUpdateGeometryType();
  912. if (type == UPDATE_MAIN_THREAD)
  913. nonThreadedGeometries_.Push(*i);
  914. else if (type == UPDATE_WORKER_THREAD)
  915. threadedGeometries_.Push(*i);
  916. }
  917. if (threadedGeometries_.Size())
  918. {
  919. WorkItem item;
  920. item.workFunction_ = UpdateDrawableGeometriesWork;
  921. item.aux_ = const_cast<FrameInfo*>(&frame_);
  922. PODVector<Drawable*>::Iterator start = threadedGeometries_.Begin();
  923. while (start != threadedGeometries_.End())
  924. {
  925. PODVector<Drawable*>::Iterator end = threadedGeometries_.End();
  926. if (end - start > DRAWABLES_PER_WORK_ITEM)
  927. end = start + DRAWABLES_PER_WORK_ITEM;
  928. item.start_ = &(*start);
  929. item.end_ = &(*end);
  930. queue->AddWorkItem(item);
  931. start = end;
  932. }
  933. }
  934. // While the work queue is processed, update non-threaded geometries
  935. for (PODVector<Drawable*>::ConstIterator i = nonThreadedGeometries_.Begin(); i != nonThreadedGeometries_.End(); ++i)
  936. (*i)->UpdateGeometry(frame_);
  937. }
  938. // Finally ensure all threaded work has completed
  939. queue->Complete();
  940. }
  941. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue)
  942. {
  943. Light* light = lightQueue.light_;
  944. Zone* zone = GetZone(drawable);
  945. bool hasAmbientGradient = zone->GetAmbientGradient() && zone->GetAmbientStartColor() != zone->GetAmbientEndColor();
  946. // Shadows on transparencies can only be rendered if shadow maps are not reused
  947. bool allowTransparentShadows = !renderer_->GetReuseShadowMaps();
  948. bool allowLitBase = light == drawable->GetFirstLight() && drawable->GetVertexLights().Empty() && !hasAmbientGradient;
  949. unsigned numBatches = drawable->GetNumBatches();
  950. for (unsigned i = 0; i < numBatches; ++i)
  951. {
  952. Batch litBatch;
  953. drawable->GetBatch(litBatch, frame_, i);
  954. Technique* tech = GetTechnique(drawable, litBatch.material_);
  955. if (!litBatch.geometry_ || !tech)
  956. continue;
  957. // Do not create pixel lit forward passes for materials that render into the G-buffer
  958. if ((renderMode_ == RENDER_PREPASS && tech->HasPass(PASS_PREPASS)) || (renderMode_ == RENDER_DEFERRED &&
  959. tech->HasPass(PASS_DEFERRED)))
  960. continue;
  961. Pass* pass = 0;
  962. // Check for lit base pass. Because it uses the replace blend mode, it must be ensured to be the first light
  963. // Also vertex lighting or ambient gradient require the non-lit base pass, so skip in those cases
  964. if (i < 32 && allowLitBase)
  965. {
  966. pass = tech->GetPass(PASS_LITBASE);
  967. if (pass)
  968. {
  969. litBatch.isBase_ = true;
  970. drawable->SetBasePass(i);
  971. }
  972. }
  973. // If no lit base pass, get ordinary light pass
  974. if (!pass)
  975. pass = tech->GetPass(PASS_LIGHT);
  976. // Skip if material does not receive light at all
  977. if (!pass)
  978. continue;
  979. // Fill the rest of the batch
  980. litBatch.camera_ = camera_;
  981. litBatch.lightQueue_ = &lightQueue;
  982. litBatch.zone_ = zone;
  983. // Check from the ambient pass whether the object is opaque or transparent
  984. Pass* ambientPass = tech->GetPass(PASS_BASE);
  985. if (!ambientPass || ambientPass->GetBlendMode() == BLEND_REPLACE)
  986. {
  987. FinalizeBatch(litBatch, tech, pass);
  988. lightQueue.litBatches_.AddBatch(litBatch);
  989. }
  990. else
  991. {
  992. // Transparent batches can not be instanced
  993. FinalizeBatch(litBatch, tech, pass, false, allowTransparentShadows);
  994. alphaQueue_.AddBatch(litBatch);
  995. }
  996. }
  997. }
  998. void View::RenderBatchesForward()
  999. {
  1000. // If using hardware multisampling with post-processing, render to the backbuffer first and then resolve
  1001. bool resolve = screenBuffers_.Size() && !renderTarget_ && graphics_->GetMultiSample() > 1;
  1002. RenderSurface* renderTarget = (screenBuffers_.Size() && !resolve) ? screenBuffers_[0]->GetRenderSurface() : renderTarget_;
  1003. RenderSurface* depthStencil = GetDepthStencil(renderTarget);
  1004. // If not reusing shadowmaps, render all of them first
  1005. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  1006. {
  1007. PROFILE(RenderShadowMaps);
  1008. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1009. {
  1010. if (i->shadowMap_)
  1011. RenderShadowMap(*i);
  1012. }
  1013. }
  1014. graphics_->SetRenderTarget(0, renderTarget);
  1015. graphics_->SetDepthStencil(depthStencil);
  1016. graphics_->SetViewport(viewRect_);
  1017. graphics_->Clear(CLEAR_DEPTH | CLEAR_STENCIL);
  1018. // Render opaque object unlit base pass
  1019. if (!baseQueue_.IsEmpty())
  1020. {
  1021. PROFILE(RenderBase);
  1022. baseQueue_.Draw(graphics_, renderer_);
  1023. }
  1024. // Render shadow maps + opaque objects' additive lighting
  1025. if (!lightQueues_.Empty())
  1026. {
  1027. PROFILE(RenderLights);
  1028. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1029. {
  1030. // If reusing shadowmaps, render each of them before the lit batches
  1031. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1032. {
  1033. RenderShadowMap(*i);
  1034. graphics_->SetRenderTarget(0, renderTarget);
  1035. graphics_->SetDepthStencil(depthStencil);
  1036. graphics_->SetViewport(viewRect_);
  1037. }
  1038. i->litBatches_.Draw(i->light_, graphics_, renderer_);
  1039. }
  1040. }
  1041. graphics_->SetScissorTest(false);
  1042. graphics_->SetStencilTest(false);
  1043. // At this point clear the parts of viewport not occupied by opaque geometry with fog color
  1044. graphics_->SetAlphaTest(false);
  1045. graphics_->SetBlendMode(BLEND_REPLACE);
  1046. graphics_->SetColorWrite(true);
  1047. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1048. graphics_->SetDepthWrite(false);
  1049. graphics_->SetScissorTest(false);
  1050. graphics_->SetStencilTest(false);
  1051. graphics_->SetShaders(renderer_->GetVertexShader("Basic"), renderer_->GetPixelShader("Basic"));
  1052. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, farClipZone_->GetFogColor());
  1053. graphics_->ClearParameterSource(PSP_MATDIFFCOLOR);
  1054. DrawFullscreenQuad(camera_, false);
  1055. // Render pre-alpha custom pass
  1056. if (!preAlphaQueue_.IsEmpty())
  1057. {
  1058. PROFILE(RenderPreAlpha);
  1059. preAlphaQueue_.Draw(graphics_, renderer_);
  1060. }
  1061. // Render transparent objects (both base passes & additive lighting)
  1062. if (!alphaQueue_.IsEmpty())
  1063. {
  1064. PROFILE(RenderAlpha);
  1065. alphaQueue_.Draw(graphics_, renderer_, true);
  1066. }
  1067. // Render post-alpha custom pass
  1068. if (!postAlphaQueue_.IsEmpty())
  1069. {
  1070. PROFILE(RenderPostAlpha);
  1071. postAlphaQueue_.Draw(graphics_, renderer_);
  1072. }
  1073. // Resolve multisampled backbuffer now if necessary
  1074. if (resolve)
  1075. graphics_->ResolveToTexture(screenBuffers_[0], viewRect_);
  1076. }
  1077. void View::RenderBatchesDeferred()
  1078. {
  1079. // If not reusing shadowmaps, render all of them first
  1080. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  1081. {
  1082. PROFILE(RenderShadowMaps);
  1083. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1084. {
  1085. if (i->shadowMap_)
  1086. RenderShadowMap(*i);
  1087. }
  1088. }
  1089. bool hwDepth = graphics_->GetHardwareDepthSupport();
  1090. // In light prepass mode the albedo buffer is used for light accumulation instead
  1091. Texture2D* albedoBuffer = renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, Graphics::GetRGBAFormat());
  1092. Texture2D* normalBuffer = renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, Graphics::GetRGBAFormat());
  1093. Texture2D* depthBuffer = renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, hwDepth ? Graphics::GetDepthStencilFormat() :
  1094. Graphics::GetLinearDepthFormat());
  1095. RenderSurface* renderTarget = screenBuffers_.Size() ? screenBuffers_[0]->GetRenderSurface() : renderTarget_;
  1096. RenderSurface* depthStencil = hwDepth ? depthBuffer->GetRenderSurface() : renderer_->GetDepthStencil(rtSize_.x_, rtSize_.y_);
  1097. if (renderMode_ == RENDER_PREPASS)
  1098. {
  1099. graphics_->SetRenderTarget(0, normalBuffer);
  1100. if (!hwDepth)
  1101. graphics_->SetRenderTarget(1, depthBuffer);
  1102. }
  1103. else
  1104. {
  1105. graphics_->SetRenderTarget(0, renderTarget);
  1106. graphics_->SetRenderTarget(1, albedoBuffer);
  1107. graphics_->SetRenderTarget(2, normalBuffer);
  1108. if (!hwDepth)
  1109. graphics_->SetRenderTarget(3, depthBuffer);
  1110. }
  1111. graphics_->SetDepthStencil(depthStencil);
  1112. graphics_->SetViewport(viewRect_);
  1113. graphics_->Clear(CLEAR_DEPTH | CLEAR_STENCIL);
  1114. // Render G-buffer batches
  1115. if (!gbufferQueue_.IsEmpty())
  1116. {
  1117. PROFILE(RenderGBuffer);
  1118. gbufferQueue_.Draw(graphics_, renderer_, false, true);
  1119. }
  1120. // Clear the light accumulation buffer (light pre-pass only.) However, skip the clear if the first light is a directional
  1121. // light with full mask
  1122. RenderSurface* lightRenderTarget = renderMode_ == RENDER_PREPASS ? albedoBuffer->GetRenderSurface() : renderTarget;
  1123. if (renderMode_ == RENDER_PREPASS)
  1124. {
  1125. bool optimizeLightBuffer = !hasZeroLightMask_ && !lightQueues_.Empty() && lightQueues_.Front().light_->GetLightType() ==
  1126. LIGHT_DIRECTIONAL && (lightQueues_.Front().light_->GetLightMask() & 0xff) == 0xff;
  1127. graphics_->SetRenderTarget(0, lightRenderTarget);
  1128. graphics_->ResetRenderTarget(1);
  1129. graphics_->SetDepthStencil(depthStencil);
  1130. graphics_->SetViewport(viewRect_);
  1131. if (!optimizeLightBuffer)
  1132. graphics_->Clear(CLEAR_COLOR);
  1133. }
  1134. else
  1135. {
  1136. graphics_->ResetRenderTarget(1);
  1137. graphics_->ResetRenderTarget(2);
  1138. graphics_->ResetRenderTarget(3);
  1139. }
  1140. // Render shadow maps + light volumes
  1141. if (!lightQueues_.Empty())
  1142. {
  1143. PROFILE(RenderLights);
  1144. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1145. {
  1146. // If reusing shadowmaps, render each of them before the lit batches
  1147. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1148. {
  1149. RenderShadowMap(*i);
  1150. graphics_->SetRenderTarget(0, lightRenderTarget);
  1151. graphics_->SetDepthStencil(depthStencil);
  1152. graphics_->SetViewport(viewRect_);
  1153. }
  1154. if (renderMode_ == RENDER_DEFERRED)
  1155. graphics_->SetTexture(TU_ALBEDOBUFFER, albedoBuffer);
  1156. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  1157. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  1158. for (unsigned j = 0; j < i->volumeBatches_.Size(); ++j)
  1159. {
  1160. SetupLightVolumeBatch(i->volumeBatches_[j]);
  1161. i->volumeBatches_[j].Draw(graphics_, renderer_);
  1162. }
  1163. }
  1164. }
  1165. graphics_->SetTexture(TU_ALBEDOBUFFER, 0);
  1166. graphics_->SetTexture(TU_NORMALBUFFER, 0);
  1167. graphics_->SetTexture(TU_DEPTHBUFFER, 0);
  1168. if (renderMode_ == RENDER_PREPASS)
  1169. {
  1170. graphics_->SetRenderTarget(0, renderTarget);
  1171. graphics_->SetDepthStencil(depthStencil);
  1172. graphics_->SetViewport(viewRect_);
  1173. }
  1174. // At this point clear the parts of viewport not occupied by opaque geometry with fog color
  1175. graphics_->SetAlphaTest(false);
  1176. graphics_->SetBlendMode(BLEND_REPLACE);
  1177. graphics_->SetColorWrite(true);
  1178. graphics_->SetDepthTest(CMP_ALWAYS);
  1179. graphics_->SetDepthWrite(false);
  1180. graphics_->SetScissorTest(false);
  1181. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 0);
  1182. graphics_->SetShaders(renderer_->GetVertexShader("Basic"), renderer_->GetPixelShader("Basic"));
  1183. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, farClipZone_->GetFogColor());
  1184. graphics_->ClearParameterSource(PSP_MATDIFFCOLOR);
  1185. DrawFullscreenQuad(camera_, false);
  1186. // Render opaque objects with deferred lighting result (light pre-pass only)
  1187. if (!baseQueue_.IsEmpty())
  1188. {
  1189. PROFILE(RenderBase);
  1190. graphics_->SetTexture(TU_LIGHTBUFFER, renderMode_ == RENDER_PREPASS ? albedoBuffer : 0);
  1191. baseQueue_.Draw(graphics_, renderer_);
  1192. graphics_->SetTexture(TU_LIGHTBUFFER, 0);
  1193. }
  1194. // Render pre-alpha custom pass
  1195. if (!preAlphaQueue_.IsEmpty())
  1196. {
  1197. PROFILE(RenderPreAlpha);
  1198. preAlphaQueue_.Draw(graphics_, renderer_);
  1199. }
  1200. // Render transparent objects (both base passes & additive lighting)
  1201. if (!alphaQueue_.IsEmpty())
  1202. {
  1203. PROFILE(RenderAlpha);
  1204. alphaQueue_.Draw(graphics_, renderer_, true);
  1205. }
  1206. // Render post-alpha custom pass
  1207. if (!postAlphaQueue_.IsEmpty())
  1208. {
  1209. PROFILE(RenderPostAlpha);
  1210. postAlphaQueue_.Draw(graphics_, renderer_);
  1211. }
  1212. }
  1213. void View::AllocateScreenBuffers()
  1214. {
  1215. unsigned neededBuffers = 0;
  1216. #ifdef USE_OPENGL
  1217. // Due to FBO limitations, in OpenGL deferred modes need to render to texture first and then blit to the backbuffer
  1218. // Also, if rendering to a texture with deferred rendering, it must be RGBA to comply with the rest of the buffers.
  1219. if (renderMode_ != RENDER_FORWARD && (!renderTarget_ || (renderMode_ == RENDER_DEFERRED &&
  1220. renderTarget_->GetParentTexture()->GetFormat() != Graphics::GetRGBAFormat())))
  1221. neededBuffers = 1;
  1222. #endif
  1223. unsigned postProcessPasses = 0;
  1224. for (unsigned i = 0; i < postProcesses_.Size(); ++i)
  1225. postProcessPasses += postProcesses_[i]->GetNumPasses();
  1226. // If more than one post-process pass, need 2 buffers for ping-pong rendering
  1227. if (postProcessPasses)
  1228. neededBuffers = Min((int)postProcessPasses, 2);
  1229. unsigned format = Graphics::GetRGBFormat();
  1230. #ifdef USE_OPENGL
  1231. if (renderMode_ == RENDER_DEFERRED)
  1232. format = Graphics::GetRGBAFormat();
  1233. #endif
  1234. // Allocate screen buffers with filtering active in case the post-processing effects need that
  1235. for (unsigned i = 0; i < neededBuffers; ++i)
  1236. screenBuffers_.Push(renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, format, true));
  1237. }
  1238. void View::BlitFramebuffer()
  1239. {
  1240. // Blit the final image to destination rendertarget
  1241. /// \todo Depth is reset to far plane, so geometry drawn after the view can not be depth tested
  1242. graphics_->SetAlphaTest(false);
  1243. graphics_->SetBlendMode(BLEND_REPLACE);
  1244. graphics_->SetDepthTest(CMP_ALWAYS);
  1245. graphics_->SetDepthWrite(true);
  1246. graphics_->SetScissorTest(false);
  1247. graphics_->SetStencilTest(false);
  1248. graphics_->SetRenderTarget(0, renderTarget_);
  1249. graphics_->SetDepthStencil(GetDepthStencil(renderTarget_));
  1250. graphics_->SetViewport(viewRect_);
  1251. String shaderName = "CopyFramebuffer";
  1252. graphics_->SetShaders(renderer_->GetVertexShader(shaderName), renderer_->GetPixelShader(shaderName));
  1253. float rtWidth = (float)rtSize_.x_;
  1254. float rtHeight = (float)rtSize_.y_;
  1255. float widthRange = 0.5f * viewSize_.x_ / rtWidth;
  1256. float heightRange = 0.5f * viewSize_.y_ / rtHeight;
  1257. #ifdef USE_OPENGL
  1258. Vector4 bufferUVOffset(((float)viewRect_.left_) / rtWidth + widthRange,
  1259. 1.0f - (((float)viewRect_.top_) / rtHeight + heightRange), widthRange, heightRange);
  1260. #else
  1261. Vector4 bufferUVOffset((0.5f + (float)viewRect_.left_) / rtWidth + widthRange,
  1262. (0.5f + (float)viewRect_.top_) / rtHeight + heightRange, widthRange, heightRange);
  1263. #endif
  1264. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  1265. graphics_->SetTexture(TU_DIFFUSE, screenBuffers_[0]);
  1266. DrawFullscreenQuad(camera_, false);
  1267. }
  1268. void View::RunPostProcesses()
  1269. {
  1270. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1271. // Ping-pong buffer indices for read and write
  1272. unsigned readRtIndex = 0;
  1273. unsigned writeRtIndex = screenBuffers_.Size() - 1;
  1274. graphics_->SetAlphaTest(false);
  1275. graphics_->SetBlendMode(BLEND_REPLACE);
  1276. graphics_->SetDepthTest(CMP_ALWAYS);
  1277. graphics_->SetScissorTest(false);
  1278. graphics_->SetStencilTest(false);
  1279. for (unsigned i = 0; i < postProcesses_.Size(); ++i)
  1280. {
  1281. PostProcess* effect = postProcesses_[i];
  1282. // For each effect, rendertargets can be re-used. Allocate them now
  1283. renderer_->SaveScreenBufferAllocations();
  1284. const HashMap<StringHash, PostProcessRenderTarget>& renderTargetInfos = effect->GetRenderTargets();
  1285. HashMap<StringHash, Texture2D*> renderTargets;
  1286. for (HashMap<StringHash, PostProcessRenderTarget>::ConstIterator j = renderTargetInfos.Begin(); j !=
  1287. renderTargetInfos.End(); ++j)
  1288. {
  1289. unsigned width = j->second_.size_.x_;
  1290. unsigned height = j->second_.size_.y_;
  1291. if (j->second_.sizeDivisor_)
  1292. {
  1293. width = viewSize_.x_ / width;
  1294. height = viewSize_.y_ / height;
  1295. }
  1296. renderTargets[j->first_] = renderer_->GetScreenBuffer(width, height, j->second_.format_, j->second_.filtered_);
  1297. }
  1298. // Run each effect pass
  1299. for (unsigned j = 0; j < effect->GetNumPasses(); ++j)
  1300. {
  1301. PostProcessPass* pass = effect->GetPass(j);
  1302. bool lastPass = (i == postProcesses_.Size() - 1) && (j == effect->GetNumPasses() - 1);
  1303. bool swapBuffers = false;
  1304. // Write depth on the last pass only
  1305. graphics_->SetDepthWrite(lastPass);
  1306. // Set output rendertarget
  1307. RenderSurface* rt = 0;
  1308. String output = pass->GetOutput().ToLower();
  1309. if (output == "viewport")
  1310. {
  1311. if (!lastPass)
  1312. {
  1313. rt = screenBuffers_[writeRtIndex]->GetRenderSurface();
  1314. swapBuffers = true;
  1315. }
  1316. else
  1317. rt = renderTarget_;
  1318. graphics_->SetRenderTarget(0, rt);
  1319. graphics_->SetDepthStencil(GetDepthStencil(rt));
  1320. graphics_->SetViewport(viewRect_);
  1321. }
  1322. else
  1323. {
  1324. HashMap<StringHash, Texture2D*>::ConstIterator k = renderTargets.Find(StringHash(output));
  1325. if (k != renderTargets.End())
  1326. rt = k->second_->GetRenderSurface();
  1327. else
  1328. continue; // Skip pass if rendertarget can not be found
  1329. graphics_->SetRenderTarget(0, rt);
  1330. graphics_->SetDepthStencil(GetDepthStencil(rt));
  1331. graphics_->SetViewport(IntRect(0, 0, rt->GetWidth(), rt->GetHeight()));
  1332. }
  1333. // Set shaders, shader parameters and textures
  1334. graphics_->SetShaders(renderer_->GetVertexShader(pass->GetVertexShader()),
  1335. renderer_->GetPixelShader(pass->GetPixelShader()));
  1336. const HashMap<StringHash, Vector4>& globalParameters = effect->GetShaderParameters();
  1337. for (HashMap<StringHash, Vector4>::ConstIterator k = globalParameters.Begin(); k != globalParameters.End(); ++k)
  1338. graphics_->SetShaderParameter(k->first_, k->second_);
  1339. const HashMap<StringHash, Vector4>& parameters = pass->GetShaderParameters();
  1340. for (HashMap<StringHash, Vector4>::ConstIterator k = parameters.Begin(); k != parameters.End(); ++k)
  1341. graphics_->SetShaderParameter(k->first_, k->second_);
  1342. float rtWidth = (float)rtSize_.x_;
  1343. float rtHeight = (float)rtSize_.y_;
  1344. float widthRange = 0.5f * viewSize_.x_ / rtWidth;
  1345. float heightRange = 0.5f * viewSize_.y_ / rtHeight;
  1346. #ifdef USE_OPENGL
  1347. Vector4 bufferUVOffset(((float)viewRect_.left_) / rtWidth + widthRange,
  1348. 1.0f - (((float)viewRect_.top_) / rtHeight + heightRange), widthRange, heightRange);
  1349. #else
  1350. Vector4 bufferUVOffset((0.5f + (float)viewRect_.left_) / rtWidth + widthRange,
  1351. (0.5f + (float)viewRect_.top_) / rtHeight + heightRange, widthRange, heightRange);
  1352. #endif
  1353. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  1354. graphics_->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector4(1.0f / rtWidth, 1.0f / rtHeight, 0.0f, 0.0f));
  1355. // Set per-rendertarget inverse size / offset shader parameters as necessary
  1356. for (HashMap<StringHash, PostProcessRenderTarget>::ConstIterator k = renderTargetInfos.Begin(); k !=
  1357. renderTargetInfos.End(); ++k)
  1358. {
  1359. String invSizeName = k->second_.name_ + "InvSize";
  1360. String offsetsName = k->second_.name_ + "Offsets";
  1361. float width = (float)renderTargets[k->first_]->GetWidth();
  1362. float height = (float)renderTargets[k->first_]->GetHeight();
  1363. graphics_->SetShaderParameter(StringHash(invSizeName), Vector4(1.0f / width, 1.0f / height, 0.0f, 0.0f));
  1364. #ifdef USE_OPENGL
  1365. graphics_->SetShaderParameter(StringHash(offsetsName), Vector4::ZERO);
  1366. #else
  1367. graphics_->SetShaderParameter(StringHash(offsetsName), Vector4(0.5f / width, 0.5f / height, 0.0f, 0.0f));
  1368. #endif
  1369. }
  1370. const String* textureNames = pass->GetTextures();
  1371. for (unsigned k = 0; k < MAX_MATERIAL_TEXTURE_UNITS; ++k)
  1372. {
  1373. if (!textureNames[k].Empty())
  1374. {
  1375. // Texture may either refer to a rendertarget or to a texture resource
  1376. if (!textureNames[k].Compare("viewport", false))
  1377. graphics_->SetTexture(k, screenBuffers_[readRtIndex]);
  1378. else
  1379. {
  1380. HashMap<StringHash, Texture2D*>::ConstIterator l = renderTargets.Find(StringHash(textureNames[k]));
  1381. if (l != renderTargets.End())
  1382. graphics_->SetTexture(k, l->second_);
  1383. else
  1384. {
  1385. // If requesting a texture fails, clear the texture name to prevent redundant attempts
  1386. Texture2D* texture = cache->GetResource<Texture2D>(textureNames[k]);
  1387. if (texture)
  1388. graphics_->SetTexture(k, texture);
  1389. else
  1390. pass->SetTexture((TextureUnit)k, String());
  1391. }
  1392. }
  1393. }
  1394. }
  1395. DrawFullscreenQuad(camera_, false);
  1396. // Swap the ping-pong buffer sides now if necessary
  1397. if (swapBuffers)
  1398. Swap(readRtIndex, writeRtIndex);
  1399. }
  1400. // Forget the rendertargets allocated during this effect
  1401. renderer_->RestoreScreenBufferAllocations();
  1402. }
  1403. }
  1404. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  1405. {
  1406. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  1407. float halfViewSize = camera->GetHalfViewSize();
  1408. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  1409. Vector3 cameraPos = camera->GetWorldPosition();
  1410. for (PODVector<Drawable*>::Iterator i = occluders.Begin(); i != occluders.End();)
  1411. {
  1412. Drawable* occluder = *i;
  1413. bool erase = false;
  1414. if (!occluder->IsInView(frame_, false))
  1415. occluder->UpdateDistance(frame_);
  1416. // Check occluder's draw distance (in main camera view)
  1417. float maxDistance = occluder->GetDrawDistance();
  1418. if (maxDistance > 0.0f && occluder->GetDistance() > maxDistance)
  1419. erase = true;
  1420. else
  1421. {
  1422. // Check that occluder is big enough on the screen
  1423. const BoundingBox& box = occluder->GetWorldBoundingBox();
  1424. float diagonal = box.Size().Length();
  1425. float compare;
  1426. if (!camera->IsOrthographic())
  1427. compare = diagonal * halfViewSize / occluder->GetDistance();
  1428. else
  1429. compare = diagonal * invOrthoSize;
  1430. if (compare < occluderSizeThreshold_)
  1431. erase = true;
  1432. else
  1433. {
  1434. // Store amount of triangles divided by screen size as a sorting key
  1435. // (best occluders are big and have few triangles)
  1436. occluder->SetSortValue((float)occluder->GetNumOccluderTriangles() / compare);
  1437. }
  1438. }
  1439. if (erase)
  1440. i = occluders.Erase(i);
  1441. else
  1442. ++i;
  1443. }
  1444. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  1445. if (occluders.Size())
  1446. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  1447. }
  1448. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  1449. {
  1450. buffer->SetMaxTriangles(maxOccluderTriangles_);
  1451. buffer->Clear();
  1452. for (unsigned i = 0; i < occluders.Size(); ++i)
  1453. {
  1454. Drawable* occluder = occluders[i];
  1455. if (i > 0)
  1456. {
  1457. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  1458. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  1459. continue;
  1460. }
  1461. // Check for running out of triangles
  1462. if (!occluder->DrawOcclusion(buffer))
  1463. break;
  1464. }
  1465. buffer->BuildDepthHierarchy();
  1466. }
  1467. void View::ProcessLight(LightQueryResult& query, unsigned threadIndex)
  1468. {
  1469. Light* light = query.light_;
  1470. LightType type = light->GetLightType();
  1471. const Frustum& frustum = camera_->GetFrustum();
  1472. // Check if light should be shadowed
  1473. bool isShadowed = drawShadows_ && light->GetCastShadows() && !light->GetPerVertex() && light->GetShadowIntensity() < 1.0f;
  1474. // If shadow distance non-zero, check it
  1475. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  1476. isShadowed = false;
  1477. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  1478. PODVector<Drawable*>& tempDrawables = tempDrawables_[threadIndex];
  1479. query.litGeometries_.Clear();
  1480. switch (type)
  1481. {
  1482. case LIGHT_DIRECTIONAL:
  1483. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1484. {
  1485. if (GetLightMask(geometries_[i]) & light->GetLightMask())
  1486. query.litGeometries_.Push(geometries_[i]);
  1487. }
  1488. break;
  1489. case LIGHT_SPOT:
  1490. {
  1491. FrustumOctreeQuery octreeQuery(tempDrawables, light->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1492. octree_->GetDrawables(octreeQuery);
  1493. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1494. {
  1495. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1496. query.litGeometries_.Push(tempDrawables[i]);
  1497. }
  1498. }
  1499. break;
  1500. case LIGHT_POINT:
  1501. {
  1502. SphereOctreeQuery octreeQuery(tempDrawables, Sphere(light->GetWorldPosition(), light->GetRange()),
  1503. DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1504. octree_->GetDrawables(octreeQuery);
  1505. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1506. {
  1507. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1508. query.litGeometries_.Push(tempDrawables[i]);
  1509. }
  1510. }
  1511. break;
  1512. }
  1513. // If no lit geometries or not shadowed, no need to process shadow cameras
  1514. if (query.litGeometries_.Empty() || !isShadowed)
  1515. {
  1516. query.numSplits_ = 0;
  1517. return;
  1518. }
  1519. // Determine number of shadow cameras and setup their initial positions
  1520. SetupShadowCameras(query);
  1521. // Process each split for shadow casters
  1522. query.shadowCasters_.Clear();
  1523. for (unsigned i = 0; i < query.numSplits_; ++i)
  1524. {
  1525. Camera* shadowCamera = query.shadowCameras_[i];
  1526. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1527. query.shadowCasterBegin_[i] = query.shadowCasterEnd_[i] = query.shadowCasters_.Size();
  1528. // For point light check that the face is visible: if not, can skip the split
  1529. if (type == LIGHT_POINT && frustum.IsInsideFast(BoundingBox(shadowCameraFrustum)) == OUTSIDE)
  1530. continue;
  1531. // For directional light check that the split is inside the visible scene: if not, can skip the split
  1532. if (type == LIGHT_DIRECTIONAL)
  1533. {
  1534. if (sceneViewBox_.min_.z_ > query.shadowFarSplits_[i])
  1535. continue;
  1536. if (sceneViewBox_.max_.z_ < query.shadowNearSplits_[i])
  1537. continue;
  1538. }
  1539. // Reuse lit geometry query for all except directional lights
  1540. if (type == LIGHT_DIRECTIONAL)
  1541. {
  1542. ShadowCasterOctreeQuery query(tempDrawables, shadowCameraFrustum, DRAWABLE_GEOMETRY,
  1543. camera_->GetViewMask());
  1544. octree_->GetDrawables(query);
  1545. }
  1546. // Check which shadow casters actually contribute to the shadowing
  1547. ProcessShadowCasters(query, tempDrawables, i);
  1548. }
  1549. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  1550. // only cost has been the shadow camera setup & queries
  1551. if (query.shadowCasters_.Empty())
  1552. query.numSplits_ = 0;
  1553. }
  1554. void View::ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex)
  1555. {
  1556. Light* light = query.light_;
  1557. Matrix3x4 lightView;
  1558. Matrix4 lightProj;
  1559. Camera* shadowCamera = query.shadowCameras_[splitIndex];
  1560. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1561. lightView = shadowCamera->GetInverseWorldTransform();
  1562. lightProj = shadowCamera->GetProjection();
  1563. LightType type = light->GetLightType();
  1564. query.shadowCasterBox_[splitIndex].defined_ = false;
  1565. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  1566. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  1567. // frustum, so that shadow casters do not get rendered into unnecessary splits
  1568. Frustum lightViewFrustum;
  1569. if (type != LIGHT_DIRECTIONAL)
  1570. lightViewFrustum = sceneFrustum_.Transformed(lightView);
  1571. else
  1572. lightViewFrustum = camera_->GetSplitFrustum(Max(sceneViewBox_.min_.z_, query.shadowNearSplits_[splitIndex]),
  1573. Min(sceneViewBox_.max_.z_, query.shadowFarSplits_[splitIndex])).Transformed(lightView);
  1574. BoundingBox lightViewFrustumBox(lightViewFrustum);
  1575. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1576. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1577. return;
  1578. BoundingBox lightViewBox;
  1579. BoundingBox lightProjBox;
  1580. for (PODVector<Drawable*>::ConstIterator i = drawables.Begin(); i != drawables.End(); ++i)
  1581. {
  1582. Drawable* drawable = *i;
  1583. // In case this is a point or spot light query result reused for optimization, we may have non-shadowcasters included.
  1584. // Check for that first
  1585. if (!drawable->GetCastShadows())
  1586. continue;
  1587. // For point light, check that this drawable is inside the split shadow camera frustum
  1588. if (type == LIGHT_POINT && shadowCameraFrustum.IsInsideFast(drawable->GetWorldBoundingBox()) == OUTSIDE)
  1589. continue;
  1590. // Note: as lights are processed threaded, it is possible a drawable's UpdateDistance() function is called several
  1591. // times. However, this should not cause problems as no scene modification happens at this point.
  1592. if (!drawable->IsInView(frame_, false))
  1593. drawable->UpdateDistance(frame_);
  1594. // Check shadow distance
  1595. float maxShadowDistance = drawable->GetShadowDistance();
  1596. if (maxShadowDistance > 0.0f && drawable->GetDistance() > maxShadowDistance)
  1597. continue;
  1598. // Check shadow mask
  1599. if (!(GetShadowMask(drawable) & light->GetLightMask()))
  1600. continue;
  1601. // Project shadow caster bounding box to light view space for visibility check
  1602. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1603. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1604. {
  1605. // Merge to shadow caster bounding box and add to the list
  1606. if (type == LIGHT_DIRECTIONAL)
  1607. query.shadowCasterBox_[splitIndex].Merge(lightViewBox);
  1608. else
  1609. {
  1610. lightProjBox = lightViewBox.Projected(lightProj);
  1611. query.shadowCasterBox_[splitIndex].Merge(lightProjBox);
  1612. }
  1613. query.shadowCasters_.Push(drawable);
  1614. }
  1615. }
  1616. query.shadowCasterEnd_[splitIndex] = query.shadowCasters_.Size();
  1617. }
  1618. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  1619. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  1620. {
  1621. if (shadowCamera->IsOrthographic())
  1622. {
  1623. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  1624. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  1625. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1626. }
  1627. else
  1628. {
  1629. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  1630. if (drawable->IsInView(frame_))
  1631. return true;
  1632. // For perspective lights, extrusion direction depends on the position of the shadow caster
  1633. Vector3 center = lightViewBox.Center();
  1634. Ray extrusionRay(center, center.Normalized());
  1635. float extrusionDistance = shadowCamera->GetFarClip();
  1636. float originalDistance = Clamp(center.Length(), M_EPSILON, extrusionDistance);
  1637. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  1638. float sizeFactor = extrusionDistance / originalDistance;
  1639. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  1640. // than necessary, so the test will be conservative
  1641. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  1642. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  1643. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  1644. lightViewBox.Merge(extrudedBox);
  1645. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1646. }
  1647. }
  1648. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  1649. {
  1650. unsigned width = shadowMap->GetWidth();
  1651. unsigned height = shadowMap->GetHeight();
  1652. int maxCascades = renderer_->GetMaxShadowCascades();
  1653. // Due to instruction count limits, deferred modes in SM2.0 can only support up to 3 cascades
  1654. #ifndef USE_OPENGL
  1655. if (renderMode_ != RENDER_FORWARD && !graphics_->GetSM3Support())
  1656. maxCascades = Max(maxCascades, 3);
  1657. #endif
  1658. switch (light->GetLightType())
  1659. {
  1660. case LIGHT_DIRECTIONAL:
  1661. if (maxCascades == 1)
  1662. return IntRect(0, 0, width, height);
  1663. else if (maxCascades == 2)
  1664. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  1665. else
  1666. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  1667. (splitIndex / 2 + 1) * height / 2);
  1668. case LIGHT_SPOT:
  1669. return IntRect(0, 0, width, height);
  1670. case LIGHT_POINT:
  1671. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  1672. (splitIndex / 2 + 1) * height / 3);
  1673. }
  1674. return IntRect();
  1675. }
  1676. void View::SetupShadowCameras(LightQueryResult& query)
  1677. {
  1678. Light* light = query.light_;
  1679. LightType type = light->GetLightType();
  1680. int splits = 0;
  1681. if (type == LIGHT_DIRECTIONAL)
  1682. {
  1683. const CascadeParameters& cascade = light->GetShadowCascade();
  1684. float nearSplit = camera_->GetNearClip();
  1685. float farSplit;
  1686. while (splits < renderer_->GetMaxShadowCascades())
  1687. {
  1688. // If split is completely beyond camera far clip, we are done
  1689. if (nearSplit > camera_->GetFarClip())
  1690. break;
  1691. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  1692. if (farSplit <= nearSplit)
  1693. break;
  1694. // Setup the shadow camera for the split
  1695. Camera* shadowCamera = renderer_->GetShadowCamera();
  1696. query.shadowCameras_[splits] = shadowCamera;
  1697. query.shadowNearSplits_[splits] = nearSplit;
  1698. query.shadowFarSplits_[splits] = farSplit;
  1699. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit);
  1700. nearSplit = farSplit;
  1701. ++splits;
  1702. }
  1703. }
  1704. if (type == LIGHT_SPOT)
  1705. {
  1706. Camera* shadowCamera = renderer_->GetShadowCamera();
  1707. query.shadowCameras_[0] = shadowCamera;
  1708. Node* cameraNode = shadowCamera->GetNode();
  1709. cameraNode->SetTransform(light->GetWorldPosition(), light->GetWorldRotation());
  1710. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1711. shadowCamera->SetFarClip(light->GetRange());
  1712. shadowCamera->SetFov(light->GetFov());
  1713. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1714. splits = 1;
  1715. }
  1716. if (type == LIGHT_POINT)
  1717. {
  1718. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1719. {
  1720. Camera* shadowCamera = renderer_->GetShadowCamera();
  1721. query.shadowCameras_[i] = shadowCamera;
  1722. Node* cameraNode = shadowCamera->GetNode();
  1723. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1724. cameraNode->SetPosition(light->GetWorldPosition());
  1725. cameraNode->SetDirection(directions[i]);
  1726. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1727. shadowCamera->SetFarClip(light->GetRange());
  1728. shadowCamera->SetFov(90.0f);
  1729. shadowCamera->SetAspectRatio(1.0f);
  1730. }
  1731. splits = MAX_CUBEMAP_FACES;
  1732. }
  1733. query.numSplits_ = splits;
  1734. }
  1735. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit)
  1736. {
  1737. Node* cameraNode = shadowCamera->GetNode();
  1738. float extrusionDistance = camera_->GetFarClip();
  1739. const FocusParameters& parameters = light->GetShadowFocus();
  1740. // Calculate initial position & rotation
  1741. Vector3 lightWorldDirection = light->GetWorldRotation() * Vector3::FORWARD;
  1742. Vector3 pos = camera_->GetWorldPosition() - extrusionDistance * lightWorldDirection;
  1743. cameraNode->SetTransform(pos, light->GetWorldRotation());
  1744. // Calculate main camera shadowed frustum in light's view space
  1745. farSplit = Min(farSplit, camera_->GetFarClip());
  1746. // Use the scene Z bounds to limit frustum size if applicable
  1747. if (parameters.focus_)
  1748. {
  1749. nearSplit = Max(sceneViewBox_.min_.z_, nearSplit);
  1750. farSplit = Min(sceneViewBox_.max_.z_, farSplit);
  1751. }
  1752. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  1753. Polyhedron frustumVolume;
  1754. frustumVolume.Define(splitFrustum);
  1755. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  1756. if (parameters.focus_)
  1757. {
  1758. BoundingBox litGeometriesBox;
  1759. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1760. {
  1761. // Skip skyboxes as they have undefinedly large bounding box size
  1762. if (geometries_[i]->GetType() == Skybox::GetTypeStatic())
  1763. continue;
  1764. if (geometryDepthBounds_[i].min_ <= farSplit && geometryDepthBounds_[i].max_ >= nearSplit &&
  1765. (GetLightMask(geometries_[i]) & light->GetLightMask()))
  1766. litGeometriesBox.Merge(geometries_[i]->GetWorldBoundingBox());
  1767. }
  1768. if (litGeometriesBox.defined_)
  1769. {
  1770. frustumVolume.Clip(litGeometriesBox);
  1771. // If volume became empty, restore it to avoid zero size
  1772. if (frustumVolume.Empty())
  1773. frustumVolume.Define(splitFrustum);
  1774. }
  1775. }
  1776. // Transform frustum volume to light space
  1777. Matrix3x4 lightView(shadowCamera->GetInverseWorldTransform());
  1778. frustumVolume.Transform(lightView);
  1779. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  1780. BoundingBox shadowBox;
  1781. if (!parameters.nonUniform_)
  1782. shadowBox.Define(Sphere(frustumVolume));
  1783. else
  1784. shadowBox.Define(frustumVolume);
  1785. shadowCamera->SetOrthographic(true);
  1786. shadowCamera->SetAspectRatio(1.0f);
  1787. shadowCamera->SetNearClip(0.0f);
  1788. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1789. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  1790. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  1791. }
  1792. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1793. const BoundingBox& shadowCasterBox)
  1794. {
  1795. const FocusParameters& parameters = light->GetShadowFocus();
  1796. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1797. LightType type = light->GetLightType();
  1798. if (type == LIGHT_DIRECTIONAL)
  1799. {
  1800. BoundingBox shadowBox;
  1801. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1802. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  1803. shadowBox.min_.y_ = -shadowBox.max_.y_;
  1804. shadowBox.min_.x_ = -shadowBox.max_.x_;
  1805. // Requantize and snap to shadow map texels
  1806. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  1807. }
  1808. if (type == LIGHT_SPOT)
  1809. {
  1810. if (parameters.focus_)
  1811. {
  1812. float viewSizeX = Max(fabsf(shadowCasterBox.min_.x_), fabsf(shadowCasterBox.max_.x_));
  1813. float viewSizeY = Max(fabsf(shadowCasterBox.min_.y_), fabsf(shadowCasterBox.max_.y_));
  1814. float viewSize = Max(viewSizeX, viewSizeY);
  1815. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  1816. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  1817. float quantize = parameters.quantize_ * invOrthoSize;
  1818. float minView = parameters.minView_ * invOrthoSize;
  1819. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  1820. if (viewSize < 1.0f)
  1821. shadowCamera->SetZoom(1.0f / viewSize);
  1822. }
  1823. }
  1824. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  1825. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  1826. if (shadowCamera->GetZoom() >= 1.0f)
  1827. {
  1828. if (light->GetLightType() != LIGHT_POINT)
  1829. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  1830. else
  1831. {
  1832. #ifdef USE_OPENGL
  1833. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  1834. #else
  1835. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  1836. #endif
  1837. }
  1838. }
  1839. }
  1840. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1841. const BoundingBox& viewBox)
  1842. {
  1843. Node* cameraNode = shadowCamera->GetNode();
  1844. const FocusParameters& parameters = light->GetShadowFocus();
  1845. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1846. float minX = viewBox.min_.x_;
  1847. float minY = viewBox.min_.y_;
  1848. float maxX = viewBox.max_.x_;
  1849. float maxY = viewBox.max_.y_;
  1850. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  1851. Vector2 viewSize(maxX - minX, maxY - minY);
  1852. // Quantize size to reduce swimming
  1853. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  1854. if (parameters.nonUniform_)
  1855. {
  1856. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1857. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  1858. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1859. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  1860. }
  1861. else if (parameters.focus_)
  1862. {
  1863. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  1864. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1865. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1866. viewSize.y_ = viewSize.x_;
  1867. }
  1868. shadowCamera->SetOrthoSize(viewSize);
  1869. // Center shadow camera to the view space bounding box
  1870. Vector3 pos(shadowCamera->GetWorldPosition());
  1871. Quaternion rot(shadowCamera->GetWorldRotation());
  1872. Vector3 adjust(center.x_, center.y_, 0.0f);
  1873. cameraNode->Translate(rot * adjust);
  1874. // If the shadow map viewport is known, snap to whole texels
  1875. if (shadowMapWidth > 0.0f)
  1876. {
  1877. Vector3 viewPos(rot.Inverse() * cameraNode->GetWorldPosition());
  1878. // Take into account that shadow map border will not be used
  1879. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  1880. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  1881. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  1882. cameraNode->Translate(rot * snap);
  1883. }
  1884. }
  1885. void View::FindZone(Drawable* drawable, unsigned threadIndex)
  1886. {
  1887. Vector3 center = drawable->GetWorldBoundingBox().Center();
  1888. int bestPriority = M_MIN_INT;
  1889. Zone* newZone = 0;
  1890. // If bounding box center is in view, can use the visible zones. Else must query via the octree
  1891. if (camera_->GetFrustum().IsInside(center))
  1892. {
  1893. // First check if the last zone remains a conclusive result
  1894. Zone* lastZone = drawable->GetLastZone();
  1895. if (lastZone && lastZone->IsInside(center) && (drawable->GetZoneMask() & lastZone->GetZoneMask()) &&
  1896. lastZone->GetPriority() >= highestZonePriority_)
  1897. newZone = lastZone;
  1898. else
  1899. {
  1900. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  1901. {
  1902. int priority = (*i)->GetPriority();
  1903. if ((*i)->IsInside(center) && (drawable->GetZoneMask() & (*i)->GetZoneMask()) && priority > bestPriority)
  1904. {
  1905. newZone = *i;
  1906. bestPriority = priority;
  1907. }
  1908. }
  1909. }
  1910. }
  1911. else
  1912. {
  1913. PODVector<Zone*>& tempZones = tempZones_[threadIndex];
  1914. PointOctreeQuery query(reinterpret_cast<PODVector<Drawable*>&>(tempZones), center, DRAWABLE_ZONE);
  1915. octree_->GetDrawables(query);
  1916. bestPriority = M_MIN_INT;
  1917. for (PODVector<Zone*>::Iterator i = tempZones.Begin(); i != tempZones.End(); ++i)
  1918. {
  1919. int priority = (*i)->GetPriority();
  1920. if ((*i)->IsInside(center) && (drawable->GetZoneMask() & (*i)->GetZoneMask()) && priority > bestPriority)
  1921. {
  1922. newZone = *i;
  1923. bestPriority = priority;
  1924. }
  1925. }
  1926. }
  1927. drawable->SetZone(newZone);
  1928. }
  1929. Zone* View::GetZone(Drawable* drawable)
  1930. {
  1931. if (cameraZoneOverride_)
  1932. return cameraZone_;
  1933. Zone* drawableZone = drawable->GetZone();
  1934. return drawableZone ? drawableZone : cameraZone_;
  1935. }
  1936. unsigned View::GetLightMask(Drawable* drawable)
  1937. {
  1938. return drawable->GetLightMask() & GetZone(drawable)->GetLightMask();
  1939. }
  1940. unsigned View::GetShadowMask(Drawable* drawable)
  1941. {
  1942. return drawable->GetShadowMask() & GetZone(drawable)->GetShadowMask();
  1943. }
  1944. unsigned long long View::GetVertexLightQueueHash(const PODVector<Light*>& vertexLights)
  1945. {
  1946. unsigned long long hash = 0;
  1947. for (PODVector<Light*>::ConstIterator i = vertexLights.Begin(); i != vertexLights.End(); ++i)
  1948. hash += (unsigned long long)(*i);
  1949. return hash;
  1950. }
  1951. Technique* View::GetTechnique(Drawable* drawable, Material*& material)
  1952. {
  1953. if (!material)
  1954. material = renderer_->GetDefaultMaterial();
  1955. if (!material)
  1956. return 0;
  1957. float lodDistance = drawable->GetLodDistance();
  1958. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  1959. if (techniques.Empty())
  1960. return 0;
  1961. // Check for suitable technique. Techniques should be ordered like this:
  1962. // Most distant & highest quality
  1963. // Most distant & lowest quality
  1964. // Second most distant & highest quality
  1965. // ...
  1966. for (unsigned i = 0; i < techniques.Size(); ++i)
  1967. {
  1968. const TechniqueEntry& entry = techniques[i];
  1969. Technique* technique = entry.technique_;
  1970. if (!technique || (technique->IsSM3() && !graphics_->GetSM3Support()) || materialQuality_ < entry.qualityLevel_)
  1971. continue;
  1972. if (lodDistance >= entry.lodDistance_)
  1973. return technique;
  1974. }
  1975. // If no suitable technique found, fallback to the last
  1976. return techniques.Back().technique_;
  1977. }
  1978. void View::CheckMaterialForAuxView(Material* material)
  1979. {
  1980. const SharedPtr<Texture>* textures = material->GetTextures();
  1981. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  1982. {
  1983. // Have to check cube & 2D textures separately
  1984. Texture* texture = textures[i];
  1985. if (texture)
  1986. {
  1987. if (texture->GetType() == Texture2D::GetTypeStatic())
  1988. {
  1989. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1990. RenderSurface* target = tex2D->GetRenderSurface();
  1991. if (target)
  1992. {
  1993. Viewport* viewport = target->GetViewport();
  1994. if (viewport->GetScene() && viewport->GetCamera())
  1995. renderer_->AddView(target, viewport);
  1996. }
  1997. }
  1998. else if (texture->GetType() == TextureCube::GetTypeStatic())
  1999. {
  2000. TextureCube* texCube = static_cast<TextureCube*>(texture);
  2001. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  2002. {
  2003. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  2004. if (target)
  2005. {
  2006. Viewport* viewport = target->GetViewport();
  2007. if (viewport->GetScene() && viewport->GetCamera())
  2008. renderer_->AddView(target, viewport);
  2009. }
  2010. }
  2011. }
  2012. }
  2013. }
  2014. // Set frame number so that we can early-out next time we come across this material on the same frame
  2015. material->MarkForAuxView(frame_.frameNumber_);
  2016. }
  2017. void View::FinalizeBatch(Batch& batch, Technique* tech, Pass* pass, bool allowInstancing, bool allowShadows)
  2018. {
  2019. // Convert to instanced if possible
  2020. if (allowInstancing && batch.geometryType_ == GEOM_STATIC && !batch.shaderData_ && !batch.overrideView_)
  2021. batch.geometryType_ = GEOM_INSTANCED;
  2022. batch.pass_ = pass;
  2023. renderer_->SetBatchShaders(batch, tech, pass, allowShadows);
  2024. batch.CalculateSortKey();
  2025. }
  2026. void View::PrepareInstancingBuffer()
  2027. {
  2028. PROFILE(PrepareInstancingBuffer);
  2029. unsigned totalInstances = 0;
  2030. totalInstances += baseQueue_.GetNumInstances(renderer_);
  2031. totalInstances += preAlphaQueue_.GetNumInstances(renderer_);
  2032. if (renderMode_ != RENDER_FORWARD)
  2033. totalInstances += gbufferQueue_.GetNumInstances(renderer_);
  2034. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2035. {
  2036. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2037. totalInstances += i->shadowSplits_[j].shadowBatches_.GetNumInstances(renderer_);
  2038. totalInstances += i->litBatches_.GetNumInstances(renderer_);
  2039. }
  2040. // If fail to set buffer size, fall back to per-group locking
  2041. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  2042. {
  2043. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  2044. unsigned freeIndex = 0;
  2045. void* lockedData = instancingBuffer->Lock(0, totalInstances, LOCK_DISCARD);
  2046. if (lockedData)
  2047. {
  2048. baseQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  2049. preAlphaQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  2050. if (renderMode_ != RENDER_FORWARD)
  2051. gbufferQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  2052. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2053. {
  2054. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2055. i->shadowSplits_[j].shadowBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  2056. i->litBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  2057. }
  2058. instancingBuffer->Unlock();
  2059. }
  2060. }
  2061. }
  2062. void View::SetupLightVolumeBatch(Batch& batch)
  2063. {
  2064. Light* light = batch.lightQueue_->light_;
  2065. LightType type = light->GetLightType();
  2066. float lightDist;
  2067. // Use replace blend mode for the first pre-pass light volume, and additive for the rest
  2068. graphics_->SetAlphaTest(false);
  2069. graphics_->SetBlendMode(renderMode_ == RENDER_PREPASS && light == lightQueues_.Front().light_ ? BLEND_REPLACE : BLEND_ADD);
  2070. graphics_->SetDepthWrite(false);
  2071. if (type != LIGHT_DIRECTIONAL)
  2072. {
  2073. if (type == LIGHT_POINT)
  2074. lightDist = Sphere(light->GetWorldPosition(), light->GetRange() * 1.25f).Distance(camera_->GetWorldPosition());
  2075. else
  2076. lightDist = light->GetFrustum().Distance(camera_->GetWorldPosition());
  2077. // Draw front faces if not inside light volume
  2078. if (lightDist < camera_->GetNearClip() * 2.0f)
  2079. {
  2080. renderer_->SetCullMode(CULL_CW, camera_);
  2081. graphics_->SetDepthTest(CMP_GREATER);
  2082. }
  2083. else
  2084. {
  2085. renderer_->SetCullMode(CULL_CCW, camera_);
  2086. graphics_->SetDepthTest(CMP_LESSEQUAL);
  2087. }
  2088. }
  2089. else
  2090. {
  2091. // In case the same camera is used for multiple views with differing aspect ratios (not recommended)
  2092. // refresh the directional light's model transform before rendering
  2093. light->GetVolumeTransform(camera_);
  2094. graphics_->SetCullMode(CULL_NONE);
  2095. graphics_->SetDepthTest(CMP_ALWAYS);
  2096. }
  2097. graphics_->SetScissorTest(false);
  2098. graphics_->SetStencilTest(true, CMP_NOTEQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 0, light->GetLightMask());
  2099. }
  2100. void View::DrawFullscreenQuad(Camera* camera, bool nearQuad)
  2101. {
  2102. Light quadDirLight(context_);
  2103. quadDirLight.SetLightType(LIGHT_DIRECTIONAL);
  2104. Matrix3x4 model(quadDirLight.GetDirLightTransform(camera, nearQuad));
  2105. graphics_->SetCullMode(CULL_NONE);
  2106. graphics_->SetShaderParameter(VSP_MODEL, model);
  2107. graphics_->SetShaderParameter(VSP_VIEWPROJ, camera->GetProjection());
  2108. graphics_->ClearTransformSources();
  2109. renderer_->GetLightGeometry(&quadDirLight)->Draw(graphics_);
  2110. }
  2111. void View::RenderShadowMap(const LightBatchQueue& queue)
  2112. {
  2113. PROFILE(RenderShadowMap);
  2114. Texture2D* shadowMap = queue.shadowMap_;
  2115. graphics_->SetTexture(TU_SHADOWMAP, 0);
  2116. graphics_->SetColorWrite(false);
  2117. graphics_->SetStencilTest(false);
  2118. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  2119. graphics_->SetDepthStencil(shadowMap);
  2120. graphics_->SetViewport(IntRect(0, 0, shadowMap->GetWidth(), shadowMap->GetHeight()));
  2121. graphics_->Clear(CLEAR_DEPTH);
  2122. // Set shadow depth bias
  2123. BiasParameters parameters = queue.light_->GetShadowBias();
  2124. // Adjust the light's constant depth bias according to global shadow map resolution
  2125. /// \todo Should remove this adjustment and find a more flexible solution
  2126. unsigned shadowMapSize = renderer_->GetShadowMapSize();
  2127. if (shadowMapSize <= 512)
  2128. parameters.constantBias_ *= 2.0f;
  2129. else if (shadowMapSize >= 2048)
  2130. parameters.constantBias_ *= 0.5f;
  2131. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  2132. // Render each of the splits
  2133. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  2134. {
  2135. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  2136. if (!shadowQueue.shadowBatches_.IsEmpty())
  2137. {
  2138. graphics_->SetViewport(shadowQueue.shadowViewport_);
  2139. // Set a scissor rectangle to match possible shadow map size reduction by out-zooming
  2140. // However, do not do this for point lights, which need to render continuously across cube faces
  2141. float width = (float)(shadowQueue.shadowViewport_.right_ - shadowQueue.shadowViewport_.left_);
  2142. if (queue.light_->GetLightType() != LIGHT_POINT)
  2143. {
  2144. float zoom = Min(shadowQueue.shadowCamera_->GetZoom(), width - 2.0f / width);
  2145. Rect zoomRect(Vector2(-1.0f, -1.0f) * zoom, Vector2(1.0f, 1.0f) * zoom);
  2146. graphics_->SetScissorTest(true, zoomRect, false);
  2147. }
  2148. else
  2149. graphics_->SetScissorTest(false);
  2150. // Draw instanced and non-instanced shadow casters
  2151. shadowQueue.shadowBatches_.Draw(graphics_, renderer_);
  2152. }
  2153. }
  2154. graphics_->SetColorWrite(true);
  2155. graphics_->SetDepthBias(0.0f, 0.0f);
  2156. }
  2157. RenderSurface* View::GetDepthStencil(RenderSurface* renderTarget)
  2158. {
  2159. // If using the backbuffer, return the backbuffer depth-stencil
  2160. if (!renderTarget)
  2161. return 0;
  2162. // Then check for linked depth-stencil
  2163. RenderSurface* depthStencil = renderTarget->GetLinkedDepthStencil();
  2164. // Finally get one from Renderer
  2165. if (!depthStencil)
  2166. depthStencil = renderer_->GetDepthStencil(renderTarget->GetWidth(), renderTarget->GetHeight());
  2167. return depthStencil;
  2168. }