View.cpp 99 KB

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