View.cpp 100 KB

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