View.cpp 101 KB

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