2
0

View.cpp 119 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Graphics/Camera.h"
  23. #include "../Graphics/DebugRenderer.h"
  24. #include "../IO/FileSystem.h"
  25. #include "../Graphics/Geometry.h"
  26. #include "../Graphics/Graphics.h"
  27. #include "../Graphics/GraphicsEvents.h"
  28. #include "../Graphics/GraphicsImpl.h"
  29. #include "../IO/Log.h"
  30. #include "../Graphics/Material.h"
  31. #include "../Graphics/OcclusionBuffer.h"
  32. #include "../Graphics/Octree.h"
  33. #include "../Graphics/Renderer.h"
  34. #include "../Graphics/RenderPath.h"
  35. #include "../Resource/ResourceCache.h"
  36. #include "../Core/Profiler.h"
  37. #include "../Scene/Scene.h"
  38. #include "../Graphics/ShaderVariation.h"
  39. #include "../Graphics/Skybox.h"
  40. #include "../Graphics/Technique.h"
  41. #include "../Graphics/Texture2D.h"
  42. #include "../Graphics/Texture3D.h"
  43. #include "../Graphics/TextureCube.h"
  44. #include "../Graphics/VertexBuffer.h"
  45. #include "../Graphics/View.h"
  46. #include "../UI/UI.h"
  47. #include "../Core/WorkQueue.h"
  48. #include "../DebugNew.h"
  49. namespace Urho3D
  50. {
  51. static const Vector3* directions[] =
  52. {
  53. &Vector3::RIGHT,
  54. &Vector3::LEFT,
  55. &Vector3::UP,
  56. &Vector3::DOWN,
  57. &Vector3::FORWARD,
  58. &Vector3::BACK
  59. };
  60. /// %Frustum octree query for shadowcasters.
  61. class ShadowCasterOctreeQuery : public FrustumOctreeQuery
  62. {
  63. public:
  64. /// Construct with frustum and query parameters.
  65. ShadowCasterOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  66. unsigned viewMask = DEFAULT_VIEWMASK) :
  67. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask)
  68. {
  69. }
  70. /// Intersection test for drawables.
  71. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  72. {
  73. while (start != end)
  74. {
  75. Drawable* drawable = *start++;
  76. if (drawable->GetCastShadows() && (drawable->GetDrawableFlags() & drawableFlags_) &&
  77. (drawable->GetViewMask() & viewMask_))
  78. {
  79. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  80. result_.Push(drawable);
  81. }
  82. }
  83. }
  84. };
  85. /// %Frustum octree query for zones and occluders.
  86. class ZoneOccluderOctreeQuery : public FrustumOctreeQuery
  87. {
  88. public:
  89. /// Construct with frustum and query parameters.
  90. ZoneOccluderOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  91. unsigned viewMask = DEFAULT_VIEWMASK) :
  92. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask)
  93. {
  94. }
  95. /// Intersection test for drawables.
  96. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  97. {
  98. while (start != end)
  99. {
  100. Drawable* drawable = *start++;
  101. unsigned char flags = drawable->GetDrawableFlags();
  102. if ((flags == DRAWABLE_ZONE || (flags == DRAWABLE_GEOMETRY &&
  103. drawable->IsOccluder())) && (drawable->GetViewMask() & viewMask_))
  104. {
  105. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  106. result_.Push(drawable);
  107. }
  108. }
  109. }
  110. };
  111. /// %Frustum octree query with occlusion.
  112. class OccludedFrustumOctreeQuery : public FrustumOctreeQuery
  113. {
  114. public:
  115. /// Construct with frustum, occlusion buffer and query parameters.
  116. OccludedFrustumOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, OcclusionBuffer* buffer, unsigned char
  117. drawableFlags = DRAWABLE_ANY, unsigned viewMask = DEFAULT_VIEWMASK) :
  118. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask),
  119. buffer_(buffer)
  120. {
  121. }
  122. /// Intersection test for an octant.
  123. virtual Intersection TestOctant(const BoundingBox& box, bool inside)
  124. {
  125. if (inside)
  126. return buffer_->IsVisible(box) ? INSIDE : OUTSIDE;
  127. else
  128. {
  129. Intersection result = frustum_.IsInside(box);
  130. if (result != OUTSIDE && !buffer_->IsVisible(box))
  131. result = OUTSIDE;
  132. return result;
  133. }
  134. }
  135. /// Intersection test for drawables. Note: drawable occlusion is performed later in worker threads.
  136. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  137. {
  138. while (start != end)
  139. {
  140. Drawable* drawable = *start++;
  141. if ((drawable->GetDrawableFlags() & drawableFlags_) && (drawable->GetViewMask() & viewMask_))
  142. {
  143. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  144. result_.Push(drawable);
  145. }
  146. }
  147. }
  148. /// Occlusion buffer.
  149. OcclusionBuffer* buffer_;
  150. };
  151. void CheckVisibilityWork(const WorkItem* item, unsigned threadIndex)
  152. {
  153. View* view = reinterpret_cast<View*>(item->aux_);
  154. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  155. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  156. OcclusionBuffer* buffer = view->occlusionBuffer_;
  157. const Matrix3x4& viewMatrix = view->camera_->GetView();
  158. Vector3 viewZ = Vector3(viewMatrix.m20_, viewMatrix.m21_, viewMatrix.m22_);
  159. Vector3 absViewZ = viewZ.Abs();
  160. unsigned cameraViewMask = view->camera_->GetViewMask();
  161. bool cameraZoneOverride = view->cameraZoneOverride_;
  162. PerThreadSceneResult& result = view->sceneResults_[threadIndex];
  163. while (start != end)
  164. {
  165. Drawable* drawable = *start++;
  166. if (!buffer || !drawable->IsOccludee() || buffer->IsVisible(drawable->GetWorldBoundingBox()))
  167. {
  168. drawable->UpdateBatches(view->frame_);
  169. // If draw distance non-zero, update and check it
  170. float maxDistance = drawable->GetDrawDistance();
  171. if (maxDistance > 0.0f)
  172. {
  173. if (drawable->GetDistance() > maxDistance)
  174. continue;
  175. }
  176. drawable->MarkInView(view->frame_);
  177. // For geometries, find zone, clear lights and calculate view space Z range
  178. if (drawable->GetDrawableFlags() & DRAWABLE_GEOMETRY)
  179. {
  180. Zone* drawableZone = drawable->GetZone();
  181. if (!cameraZoneOverride && (drawable->IsZoneDirty() || !drawableZone || (drawableZone->GetViewMask() &
  182. cameraViewMask) == 0))
  183. view->FindZone(drawable);
  184. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  185. Vector3 center = geomBox.Center();
  186. Vector3 edge = geomBox.Size() * 0.5f;
  187. // Do not add "infinite" objects like skybox to prevent shadow map focusing behaving erroneously
  188. if (edge.LengthSquared() < M_LARGE_VALUE * M_LARGE_VALUE)
  189. {
  190. float viewCenterZ = viewZ.DotProduct(center) + viewMatrix.m23_;
  191. float viewEdgeZ = absViewZ.DotProduct(edge);
  192. float minZ = viewCenterZ - viewEdgeZ;
  193. float maxZ = viewCenterZ + viewEdgeZ;
  194. drawable->SetMinMaxZ(viewCenterZ - viewEdgeZ, viewCenterZ + viewEdgeZ);
  195. result.minZ_ = Min(result.minZ_, minZ);
  196. result.maxZ_ = Max(result.maxZ_, maxZ);
  197. }
  198. else
  199. drawable->SetMinMaxZ(M_LARGE_VALUE, M_LARGE_VALUE);
  200. result.geometries_.Push(drawable);
  201. }
  202. else if (drawable->GetDrawableFlags() & DRAWABLE_LIGHT)
  203. {
  204. Light* light = static_cast<Light*>(drawable);
  205. // Skip lights with zero brightness or black color
  206. if (!light->GetEffectiveColor().Equals(Color::BLACK))
  207. result.lights_.Push(light);
  208. }
  209. }
  210. }
  211. }
  212. void ProcessLightWork(const WorkItem* item, unsigned threadIndex)
  213. {
  214. View* view = reinterpret_cast<View*>(item->aux_);
  215. LightQueryResult* query = reinterpret_cast<LightQueryResult*>(item->start_);
  216. view->ProcessLight(*query, threadIndex);
  217. }
  218. void UpdateDrawableGeometriesWork(const WorkItem* item, unsigned threadIndex)
  219. {
  220. const FrameInfo& frame = *(reinterpret_cast<FrameInfo*>(item->aux_));
  221. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  222. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  223. while (start != end)
  224. {
  225. Drawable* drawable = *start++;
  226. // We may leave null pointer holes in the queue if a drawable is found out to require a main thread update
  227. if (drawable)
  228. drawable->UpdateGeometry(frame);
  229. }
  230. }
  231. void SortBatchQueueFrontToBackWork(const WorkItem* item, unsigned threadIndex)
  232. {
  233. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  234. queue->SortFrontToBack();
  235. }
  236. void SortBatchQueueBackToFrontWork(const WorkItem* item, unsigned threadIndex)
  237. {
  238. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  239. queue->SortBackToFront();
  240. }
  241. void SortLightQueueWork(const WorkItem* item, unsigned threadIndex)
  242. {
  243. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  244. start->litBaseBatches_.SortFrontToBack();
  245. start->litBatches_.SortFrontToBack();
  246. }
  247. void SortShadowQueueWork(const WorkItem* item, unsigned threadIndex)
  248. {
  249. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  250. for (unsigned i = 0; i < start->shadowSplits_.Size(); ++i)
  251. start->shadowSplits_[i].shadowBatches_.SortFrontToBack();
  252. }
  253. View::View(Context* context) :
  254. Object(context),
  255. graphics_(GetSubsystem<Graphics>()),
  256. renderer_(GetSubsystem<Renderer>()),
  257. scene_(0),
  258. octree_(0),
  259. camera_(0),
  260. cameraZone_(0),
  261. farClipZone_(0),
  262. renderTarget_(0),
  263. substituteRenderTarget_(0)
  264. {
  265. // Create octree query and scene results vector for each thread
  266. unsigned numThreads = GetSubsystem<WorkQueue>()->GetNumThreads() + 1; // Worker threads + main thread
  267. tempDrawables_.Resize(numThreads);
  268. sceneResults_.Resize(numThreads);
  269. frame_.camera_ = 0;
  270. }
  271. View::~View()
  272. {
  273. }
  274. bool View::Define(RenderSurface* renderTarget, Viewport* viewport)
  275. {
  276. renderPath_ = viewport->GetRenderPath();
  277. if (!renderPath_)
  278. return false;
  279. // Set default passes
  280. gBufferPassIndex_ = M_MAX_UNSIGNED;
  281. basePassIndex_ = Technique::GetPassIndex("base");
  282. alphaPassIndex_ = Technique::GetPassIndex("alpha");
  283. lightPassIndex_ = Technique::GetPassIndex("light");
  284. litBasePassIndex_ = Technique::GetPassIndex("litbase");
  285. litAlphaPassIndex_ = Technique::GetPassIndex("litalpha");
  286. drawDebug_ = viewport->GetDrawDebug();
  287. hasScenePasses_ = false;
  288. lightVolumeCommand_ = 0;
  289. // Make sure that all necessary batch queues exist
  290. scenePasses_.Clear();
  291. noStencil_ = false;
  292. #ifdef URHO3D_OPENGL
  293. #ifdef GL_ES_VERSION_2_0
  294. // On OpenGL ES we assume a stencil is not available or would not give a good performance, and disable light stencil
  295. // optimizations in any case
  296. noStencil_ = true;
  297. #else
  298. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  299. {
  300. const RenderPathCommand& command = renderPath_->commands_[i];
  301. if (!command.enabled_)
  302. continue;
  303. if (command.depthStencilName_.Length())
  304. {
  305. // Using a readable depth texture will disable light stencil optimizations on OpenGL, as for compatibility reasons
  306. // we are using a depth format without stencil channel
  307. noStencil_ = true;
  308. break;
  309. }
  310. }
  311. #endif
  312. #endif
  313. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  314. {
  315. RenderPathCommand& command = renderPath_->commands_[i];
  316. if (!command.enabled_)
  317. continue;
  318. if (command.type_ == CMD_SCENEPASS)
  319. {
  320. hasScenePasses_ = true;
  321. ScenePassInfo info;
  322. info.passIndex_ = command.passIndex_ = Technique::GetPassIndex(command.pass_);
  323. info.allowInstancing_ = command.sortMode_ != SORT_BACKTOFRONT;
  324. info.markToStencil_ = !noStencil_ && command.markToStencil_;
  325. info.vertexLights_ = command.vertexLights_;
  326. // Check scenepass metadata for defining custom passes which interact with lighting
  327. if (!command.metadata_.Empty())
  328. {
  329. if (command.metadata_ == "gbuffer")
  330. gBufferPassIndex_ = command.passIndex_;
  331. else if (command.metadata_ == "base" && command.pass_ != "base")
  332. {
  333. basePassIndex_ = command.passIndex_;
  334. litBasePassIndex_ = Technique::GetPassIndex("lit" + command.pass_);
  335. }
  336. else if (command.metadata_ == "alpha" && command.pass_ != "alpha")
  337. {
  338. alphaPassIndex_ = command.passIndex_;
  339. litAlphaPassIndex_ = Technique::GetPassIndex("lit" + command.pass_);
  340. }
  341. }
  342. HashMap<unsigned, BatchQueue>::Iterator j = batchQueues_.Find(info.passIndex_);
  343. if (j == batchQueues_.End())
  344. j = batchQueues_.Insert(Pair<unsigned, BatchQueue>(info.passIndex_, BatchQueue()));
  345. info.batchQueue_ = &j->second_;
  346. scenePasses_.Push(info);
  347. }
  348. // Allow a custom forward light pass
  349. else if (command.type_ == CMD_FORWARDLIGHTS && !command.pass_.Empty())
  350. lightPassIndex_ = command.passIndex_ = Technique::GetPassIndex(command.pass_);
  351. }
  352. scene_ = viewport->GetScene();
  353. camera_ = viewport->GetCamera();
  354. octree_ = 0;
  355. // Get default zone first in case we do not have zones defined
  356. cameraZone_ = farClipZone_ = renderer_->GetDefaultZone();
  357. if (hasScenePasses_)
  358. {
  359. if (!scene_ || !camera_ || !camera_->IsEnabledEffective())
  360. return false;
  361. // If scene is loading scene content asynchronously, it is incomplete and should not be rendered
  362. if (scene_->IsAsyncLoading() && scene_->GetAsyncLoadMode() > LOAD_RESOURCES_ONLY)
  363. return false;
  364. octree_ = scene_->GetComponent<Octree>();
  365. if (!octree_)
  366. return false;
  367. // Do not accept view if camera projection is illegal
  368. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  369. if (!camera_->IsProjectionValid())
  370. return false;
  371. }
  372. cameraNode_ = camera_ ? camera_->GetNode() : (Node*)0;
  373. renderTarget_ = renderTarget;
  374. // Go through commands to check for deferred rendering and other flags
  375. deferred_ = false;
  376. deferredAmbient_ = false;
  377. useLitBase_ = false;
  378. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  379. {
  380. const RenderPathCommand& command = renderPath_->commands_[i];
  381. if (!command.enabled_)
  382. continue;
  383. // Check if ambient pass and G-buffer rendering happens at the same time
  384. if (command.type_ == CMD_SCENEPASS && command.outputNames_.Size() > 1)
  385. {
  386. if (CheckViewportWrite(command))
  387. deferredAmbient_ = true;
  388. }
  389. else if (command.type_ == CMD_LIGHTVOLUMES)
  390. {
  391. lightVolumeCommand_ = &command;
  392. deferred_ = true;
  393. }
  394. else if (command.type_ == CMD_FORWARDLIGHTS)
  395. useLitBase_ = command.useLitBase_;
  396. }
  397. // Validate the rect and calculate size. If zero rect, use whole rendertarget size
  398. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  399. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  400. const IntRect& rect = viewport->GetRect();
  401. if (rect != IntRect::ZERO)
  402. {
  403. viewRect_.left_ = Clamp(rect.left_, 0, rtWidth - 1);
  404. viewRect_.top_ = Clamp(rect.top_, 0, rtHeight - 1);
  405. viewRect_.right_ = Clamp(rect.right_, viewRect_.left_ + 1, rtWidth);
  406. viewRect_.bottom_ = Clamp(rect.bottom_, viewRect_.top_ + 1, rtHeight);
  407. }
  408. else
  409. viewRect_ = IntRect(0, 0, rtWidth, rtHeight);
  410. viewSize_ = viewRect_.Size();
  411. rtSize_ = IntVector2(rtWidth, rtHeight);
  412. // On OpenGL flip the viewport if rendering to a texture for consistent UV addressing with Direct3D9
  413. #ifdef URHO3D_OPENGL
  414. if (renderTarget_)
  415. {
  416. viewRect_.bottom_ = rtHeight - viewRect_.top_;
  417. viewRect_.top_ = viewRect_.bottom_ - viewSize_.y_;
  418. }
  419. #endif
  420. drawShadows_ = renderer_->GetDrawShadows();
  421. materialQuality_ = renderer_->GetMaterialQuality();
  422. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  423. minInstances_ = renderer_->GetMinInstances();
  424. // Set possible quality overrides from the camera
  425. unsigned viewOverrideFlags = camera_ ? camera_->GetViewOverrideFlags() : VO_NONE;
  426. if (viewOverrideFlags & VO_LOW_MATERIAL_QUALITY)
  427. materialQuality_ = QUALITY_LOW;
  428. if (viewOverrideFlags & VO_DISABLE_SHADOWS)
  429. drawShadows_ = false;
  430. if (viewOverrideFlags & VO_DISABLE_OCCLUSION)
  431. maxOccluderTriangles_ = 0;
  432. // Occlusion buffer has constant width. If resulting height would be too large due to aspect ratio, disable occlusion
  433. if (viewSize_.y_ > viewSize_.x_ * 4)
  434. maxOccluderTriangles_ = 0;
  435. return true;
  436. }
  437. void View::Update(const FrameInfo& frame)
  438. {
  439. frame_.camera_ = camera_;
  440. frame_.timeStep_ = frame.timeStep_;
  441. frame_.frameNumber_ = frame.frameNumber_;
  442. frame_.viewSize_ = viewSize_;
  443. using namespace BeginViewUpdate;
  444. VariantMap& eventData = GetEventDataMap();
  445. eventData[P_VIEW] = this;
  446. eventData[P_SURFACE] = renderTarget_;
  447. eventData[P_TEXTURE] = (renderTarget_ ? renderTarget_->GetParentTexture() : 0);
  448. eventData[P_SCENE] = scene_;
  449. eventData[P_CAMERA] = camera_;
  450. renderer_->SendEvent(E_BEGINVIEWUPDATE, eventData);
  451. int maxSortedInstances = renderer_->GetMaxSortedInstances();
  452. // Clear buffers, geometry, light, occluder & batch list
  453. renderTargets_.Clear();
  454. geometries_.Clear();
  455. lights_.Clear();
  456. zones_.Clear();
  457. occluders_.Clear();
  458. vertexLightQueues_.Clear();
  459. for (HashMap<unsigned, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  460. i->second_.Clear(maxSortedInstances);
  461. if (hasScenePasses_ && (!camera_ || !octree_))
  462. {
  463. renderer_->SendEvent(E_ENDVIEWUPDATE, eventData);
  464. return;
  465. }
  466. // Set automatic aspect ratio if required
  467. if (camera_ && camera_->GetAutoAspectRatio())
  468. camera_->SetAspectRatioInternal((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  469. GetDrawables();
  470. GetBatches();
  471. renderer_->SendEvent(E_ENDVIEWUPDATE, eventData);
  472. }
  473. void View::Render()
  474. {
  475. if (hasScenePasses_ && (!octree_ || !camera_))
  476. return;
  477. // Actually update geometry data now
  478. UpdateGeometries();
  479. // Allocate screen buffers as necessary
  480. AllocateScreenBuffers();
  481. // Forget parameter sources from the previous view
  482. graphics_->ClearParameterSources();
  483. if (renderer_->GetDynamicInstancing() && graphics_->GetInstancingSupport())
  484. PrepareInstancingBuffer();
  485. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  486. // again to ensure correct projection will be used
  487. if (camera_)
  488. {
  489. if (camera_->GetAutoAspectRatio())
  490. camera_->SetAspectRatioInternal((float)(viewSize_.x_) / (float)(viewSize_.y_));
  491. }
  492. // Bind the face selection and indirection cube maps for point light shadows
  493. #ifndef GL_ES_VERSION_2_0
  494. if (renderer_->GetDrawShadows())
  495. {
  496. graphics_->SetTexture(TU_FACESELECT, renderer_->GetFaceSelectCubeMap());
  497. graphics_->SetTexture(TU_INDIRECTION, renderer_->GetIndirectionCubeMap());
  498. }
  499. #endif
  500. if (renderTarget_)
  501. {
  502. // On OpenGL, flip the projection if rendering to a texture so that the texture can be addressed in the same way
  503. // as a render texture produced on Direct3D9
  504. #ifdef URHO3D_OPENGL
  505. if (camera_)
  506. camera_->SetFlipVertical(true);
  507. #endif
  508. }
  509. // Render
  510. ExecuteRenderPathCommands();
  511. // After executing all commands, reset rendertarget & state for debug geometry rendering
  512. // Use the last rendertarget (before blitting) so that OpenGL deferred rendering can have benefit of proper depth buffer
  513. // values; after a blit to backbuffer the same depth buffer would not be available any longer
  514. graphics_->SetRenderTarget(0, currentRenderTarget_);
  515. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  516. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  517. graphics_->SetDepthStencil(GetDepthStencil(currentRenderTarget_));
  518. IntVector2 rtSizeNow = graphics_->GetRenderTargetDimensions();
  519. IntRect viewport = (currentRenderTarget_ == renderTarget_) ? viewRect_ : IntRect(0, 0, rtSizeNow.x_,
  520. rtSizeNow.y_);
  521. graphics_->SetViewport(viewport);
  522. graphics_->SetFillMode(FILL_SOLID);
  523. graphics_->SetClipPlane(false);
  524. graphics_->SetColorWrite(true);
  525. graphics_->SetDepthBias(0.0f, 0.0f);
  526. graphics_->SetScissorTest(false);
  527. graphics_->SetStencilTest(false);
  528. // Draw the associated debug geometry now if enabled
  529. if (drawDebug_ && octree_ && camera_)
  530. {
  531. DebugRenderer* debug = octree_->GetComponent<DebugRenderer>();
  532. if (debug && debug->IsEnabledEffective())
  533. {
  534. debug->SetView(camera_);
  535. debug->Render();
  536. }
  537. }
  538. #ifdef URHO3D_OPENGL
  539. if (camera_)
  540. camera_->SetFlipVertical(false);
  541. #endif
  542. // Run framebuffer blitting if necessary
  543. if (currentRenderTarget_ != renderTarget_)
  544. BlitFramebuffer(static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture()), renderTarget_, true);
  545. // "Forget" the scene, camera, octree and zone after rendering
  546. scene_ = 0;
  547. camera_ = 0;
  548. octree_ = 0;
  549. cameraZone_ = 0;
  550. farClipZone_ = 0;
  551. occlusionBuffer_ = 0;
  552. frame_.camera_ = 0;
  553. }
  554. Graphics* View::GetGraphics() const
  555. {
  556. return graphics_;
  557. }
  558. Renderer* View::GetRenderer() const
  559. {
  560. return renderer_;
  561. }
  562. void View::SetGlobalShaderParameters()
  563. {
  564. graphics_->SetShaderParameter(VSP_DELTATIME, frame_.timeStep_);
  565. graphics_->SetShaderParameter(PSP_DELTATIME, frame_.timeStep_);
  566. if (scene_)
  567. {
  568. float elapsedTime = scene_->GetElapsedTime();
  569. graphics_->SetShaderParameter(VSP_ELAPSEDTIME, elapsedTime);
  570. graphics_->SetShaderParameter(PSP_ELAPSEDTIME, elapsedTime);
  571. }
  572. }
  573. void View::SetCameraShaderParameters(Camera* camera, bool setProjection)
  574. {
  575. if (!camera)
  576. return;
  577. Matrix3x4 cameraEffectiveTransform = camera->GetEffectiveWorldTransform();
  578. graphics_->SetShaderParameter(VSP_CAMERAPOS, cameraEffectiveTransform.Translation());
  579. graphics_->SetShaderParameter(VSP_CAMERAROT, cameraEffectiveTransform.RotationMatrix());
  580. graphics_->SetShaderParameter(PSP_CAMERAPOS, cameraEffectiveTransform.Translation());
  581. float nearClip = camera->GetNearClip();
  582. float farClip = camera->GetFarClip();
  583. graphics_->SetShaderParameter(VSP_NEARCLIP, nearClip);
  584. graphics_->SetShaderParameter(VSP_FARCLIP, farClip);
  585. graphics_->SetShaderParameter(PSP_NEARCLIP, nearClip);
  586. graphics_->SetShaderParameter(PSP_FARCLIP, farClip);
  587. Vector4 depthMode = Vector4::ZERO;
  588. if (camera->IsOrthographic())
  589. {
  590. depthMode.x_ = 1.0f;
  591. #ifdef URHO3D_OPENGL
  592. depthMode.z_ = 0.5f;
  593. depthMode.w_ = 0.5f;
  594. #else
  595. depthMode.z_ = 1.0f;
  596. #endif
  597. }
  598. else
  599. depthMode.w_ = 1.0f / camera->GetFarClip();
  600. graphics_->SetShaderParameter(VSP_DEPTHMODE, depthMode);
  601. Vector4 depthReconstruct(farClip / (farClip - nearClip), -nearClip / (farClip - nearClip), camera->IsOrthographic() ? 1.0f :
  602. 0.0f, camera->IsOrthographic() ? 0.0f : 1.0f);
  603. graphics_->SetShaderParameter(PSP_DEPTHRECONSTRUCT, depthReconstruct);
  604. Vector3 nearVector, farVector;
  605. camera->GetFrustumSize(nearVector, farVector);
  606. graphics_->SetShaderParameter(VSP_FRUSTUMSIZE, farVector);
  607. if (setProjection)
  608. {
  609. Matrix4 projection = camera->GetProjection();
  610. #ifdef URHO3D_OPENGL
  611. // Add constant depth bias manually to the projection matrix due to glPolygonOffset() inconsistency
  612. float constantBias = 2.0f * graphics_->GetDepthConstantBias();
  613. projection.m22_ += projection.m32_ * constantBias;
  614. projection.m23_ += projection.m33_ * constantBias;
  615. #endif
  616. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * camera->GetView());
  617. }
  618. }
  619. void View::SetGBufferShaderParameters(const IntVector2& texSize, const IntRect& viewRect)
  620. {
  621. float texWidth = (float)texSize.x_;
  622. float texHeight = (float)texSize.y_;
  623. float widthRange = 0.5f * viewRect.Width() / texWidth;
  624. float heightRange = 0.5f * viewRect.Height() / texHeight;
  625. #ifdef URHO3D_OPENGL
  626. Vector4 bufferUVOffset(((float)viewRect.left_) / texWidth + widthRange,
  627. 1.0f - (((float)viewRect.top_) / texHeight + heightRange), widthRange, heightRange);
  628. #else
  629. const Vector2& pixelUVOffset = Graphics::GetPixelUVOffset();
  630. Vector4 bufferUVOffset((pixelUVOffset.x_ + (float)viewRect.left_) / texWidth + widthRange,
  631. (pixelUVOffset.y_ + (float)viewRect.top_) / texHeight + heightRange, widthRange, heightRange);
  632. #endif
  633. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  634. float invSizeX = 1.0f / texWidth;
  635. float invSizeY = 1.0f / texHeight;
  636. graphics_->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector4(invSizeX, invSizeY, 0.0f, 0.0f));
  637. }
  638. void View::GetDrawables()
  639. {
  640. if (!octree_ || !camera_)
  641. return;
  642. PROFILE(GetDrawables);
  643. WorkQueue* queue = GetSubsystem<WorkQueue>();
  644. PODVector<Drawable*>& tempDrawables = tempDrawables_[0];
  645. // Get zones and occluders first
  646. {
  647. ZoneOccluderOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_ZONE, camera_->GetViewMask());
  648. octree_->GetDrawables(query);
  649. }
  650. highestZonePriority_ = M_MIN_INT;
  651. int bestPriority = M_MIN_INT;
  652. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  653. for (PODVector<Drawable*>::ConstIterator i = tempDrawables.Begin(); i != tempDrawables.End(); ++i)
  654. {
  655. Drawable* drawable = *i;
  656. unsigned char flags = drawable->GetDrawableFlags();
  657. if (flags & DRAWABLE_ZONE)
  658. {
  659. Zone* zone = static_cast<Zone*>(drawable);
  660. zones_.Push(zone);
  661. int priority = zone->GetPriority();
  662. if (priority > highestZonePriority_)
  663. highestZonePriority_ = priority;
  664. if (priority > bestPriority && zone->IsInside(cameraPos))
  665. {
  666. cameraZone_ = zone;
  667. bestPriority = priority;
  668. }
  669. }
  670. else
  671. occluders_.Push(drawable);
  672. }
  673. // Determine the zone at far clip distance. If not found, or camera zone has override mode, use camera zone
  674. cameraZoneOverride_ = cameraZone_->GetOverride();
  675. if (!cameraZoneOverride_)
  676. {
  677. Vector3 farClipPos = cameraPos + cameraNode_->GetWorldDirection() * Vector3(0.0f, 0.0f, camera_->GetFarClip());
  678. bestPriority = M_MIN_INT;
  679. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  680. {
  681. int priority = (*i)->GetPriority();
  682. if (priority > bestPriority && (*i)->IsInside(farClipPos))
  683. {
  684. farClipZone_ = *i;
  685. bestPriority = priority;
  686. }
  687. }
  688. }
  689. if (farClipZone_ == renderer_->GetDefaultZone())
  690. farClipZone_ = cameraZone_;
  691. // If occlusion in use, get & render the occluders
  692. occlusionBuffer_ = 0;
  693. if (maxOccluderTriangles_ > 0)
  694. {
  695. UpdateOccluders(occluders_, camera_);
  696. if (occluders_.Size())
  697. {
  698. PROFILE(DrawOcclusion);
  699. occlusionBuffer_ = renderer_->GetOcclusionBuffer(camera_);
  700. DrawOccluders(occlusionBuffer_, occluders_);
  701. }
  702. }
  703. // Get lights and geometries. Coarse occlusion for octants is used at this point
  704. if (occlusionBuffer_)
  705. {
  706. OccludedFrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), occlusionBuffer_, DRAWABLE_GEOMETRY |
  707. DRAWABLE_LIGHT, camera_->GetViewMask());
  708. octree_->GetDrawables(query);
  709. }
  710. else
  711. {
  712. FrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY |
  713. DRAWABLE_LIGHT, camera_->GetViewMask());
  714. octree_->GetDrawables(query);
  715. }
  716. // Check drawable occlusion, find zones for moved drawables and collect geometries & lights in worker threads
  717. {
  718. for (unsigned i = 0; i < sceneResults_.Size(); ++i)
  719. {
  720. PerThreadSceneResult& result = sceneResults_[i];
  721. result.geometries_.Clear();
  722. result.lights_.Clear();
  723. result.minZ_ = M_INFINITY;
  724. result.maxZ_ = 0.0f;
  725. }
  726. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  727. int drawablesPerItem = tempDrawables.Size() / numWorkItems;
  728. PODVector<Drawable*>::Iterator start = tempDrawables.Begin();
  729. // Create a work item for each thread
  730. for (int i = 0; i < numWorkItems; ++i)
  731. {
  732. SharedPtr<WorkItem> item = queue->GetFreeItem();
  733. item->priority_ = M_MAX_UNSIGNED;
  734. item->workFunction_ = CheckVisibilityWork;
  735. item->aux_ = this;
  736. PODVector<Drawable*>::Iterator end = tempDrawables.End();
  737. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  738. end = start + drawablesPerItem;
  739. item->start_ = &(*start);
  740. item->end_ = &(*end);
  741. queue->AddWorkItem(item);
  742. start = end;
  743. }
  744. queue->Complete(M_MAX_UNSIGNED);
  745. }
  746. // Combine lights, geometries & scene Z range from the threads
  747. geometries_.Clear();
  748. lights_.Clear();
  749. minZ_ = M_INFINITY;
  750. maxZ_ = 0.0f;
  751. if (sceneResults_.Size() > 1)
  752. {
  753. for (unsigned i = 0; i < sceneResults_.Size(); ++i)
  754. {
  755. PerThreadSceneResult& result = sceneResults_[i];
  756. geometries_.Push(result.geometries_);
  757. lights_.Push(result.lights_);
  758. minZ_ = Min(minZ_, result.minZ_);
  759. maxZ_ = Max(maxZ_, result.maxZ_);
  760. }
  761. }
  762. else
  763. {
  764. // If just 1 thread, copy the results directly
  765. PerThreadSceneResult& result = sceneResults_[0];
  766. minZ_ = result.minZ_;
  767. maxZ_ = result.maxZ_;
  768. Swap(geometries_, result.geometries_);
  769. Swap(lights_, result.lights_);
  770. }
  771. if (minZ_ == M_INFINITY)
  772. minZ_ = 0.0f;
  773. // Sort the lights to brightest/closest first, and per-vertex lights first so that per-vertex base pass can be evaluated first
  774. for (unsigned i = 0; i < lights_.Size(); ++i)
  775. {
  776. Light* light = lights_[i];
  777. light->SetIntensitySortValue(camera_->GetDistance(light->GetNode()->GetWorldPosition()));
  778. light->SetLightQueue(0);
  779. }
  780. Sort(lights_.Begin(), lights_.End(), CompareLights);
  781. }
  782. void View::GetBatches()
  783. {
  784. if (!octree_ || !camera_)
  785. return;
  786. nonThreadedGeometries_.Clear();
  787. threadedGeometries_.Clear();
  788. WorkQueue* queue = GetSubsystem<WorkQueue>();
  789. BatchQueue* alphaQueue = batchQueues_.Contains(alphaPassIndex_) ? &batchQueues_[alphaPassIndex_] : (BatchQueue*)0;
  790. // Process lit geometries and shadow casters for each light
  791. {
  792. PROFILE(ProcessLights);
  793. lightQueryResults_.Resize(lights_.Size());
  794. for (unsigned i = 0; i < lightQueryResults_.Size(); ++i)
  795. {
  796. SharedPtr<WorkItem> item = queue->GetFreeItem();
  797. item->priority_ = M_MAX_UNSIGNED;
  798. item->workFunction_ = ProcessLightWork;
  799. item->aux_ = this;
  800. LightQueryResult& query = lightQueryResults_[i];
  801. query.light_ = lights_[i];
  802. item->start_ = &query;
  803. queue->AddWorkItem(item);
  804. }
  805. // Ensure all lights have been processed before proceeding
  806. queue->Complete(M_MAX_UNSIGNED);
  807. }
  808. // Build light queues and lit batches
  809. {
  810. PROFILE(GetLightBatches);
  811. // Preallocate light queues: per-pixel lights which have lit geometries
  812. unsigned numLightQueues = 0;
  813. unsigned usedLightQueues = 0;
  814. for (Vector<LightQueryResult>::ConstIterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  815. {
  816. if (!i->light_->GetPerVertex() && i->litGeometries_.Size())
  817. ++numLightQueues;
  818. }
  819. lightQueues_.Resize(numLightQueues);
  820. maxLightsDrawables_.Clear();
  821. unsigned maxSortedInstances = renderer_->GetMaxSortedInstances();
  822. for (Vector<LightQueryResult>::Iterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  823. {
  824. LightQueryResult& query = *i;
  825. // If light has no affected geometries, no need to process further
  826. if (query.litGeometries_.Empty())
  827. continue;
  828. Light* light = query.light_;
  829. // Per-pixel light
  830. if (!light->GetPerVertex())
  831. {
  832. unsigned shadowSplits = query.numSplits_;
  833. // Initialize light queue and store it to the light so that it can be found later
  834. LightBatchQueue& lightQueue = lightQueues_[usedLightQueues++];
  835. light->SetLightQueue(&lightQueue);
  836. lightQueue.light_ = light;
  837. lightQueue.negative_ = light->IsNegative();
  838. lightQueue.shadowMap_ = 0;
  839. lightQueue.litBaseBatches_.Clear(maxSortedInstances);
  840. lightQueue.litBatches_.Clear(maxSortedInstances);
  841. lightQueue.volumeBatches_.Clear();
  842. // Allocate shadow map now
  843. if (shadowSplits > 0)
  844. {
  845. lightQueue.shadowMap_ = renderer_->GetShadowMap(light, camera_, viewSize_.x_, viewSize_.y_);
  846. // If did not manage to get a shadow map, convert the light to unshadowed
  847. if (!lightQueue.shadowMap_)
  848. shadowSplits = 0;
  849. }
  850. // Setup shadow batch queues
  851. lightQueue.shadowSplits_.Resize(shadowSplits);
  852. for (unsigned j = 0; j < shadowSplits; ++j)
  853. {
  854. ShadowBatchQueue& shadowQueue = lightQueue.shadowSplits_[j];
  855. Camera* shadowCamera = query.shadowCameras_[j];
  856. shadowQueue.shadowCamera_ = shadowCamera;
  857. shadowQueue.nearSplit_ = query.shadowNearSplits_[j];
  858. shadowQueue.farSplit_ = query.shadowFarSplits_[j];
  859. shadowQueue.shadowBatches_.Clear(maxSortedInstances);
  860. // Setup the shadow split viewport and finalize shadow camera parameters
  861. shadowQueue.shadowViewport_ = GetShadowMapViewport(light, j, lightQueue.shadowMap_);
  862. FinalizeShadowCamera(shadowCamera, light, shadowQueue.shadowViewport_, query.shadowCasterBox_[j]);
  863. // Loop through shadow casters
  864. for (PODVector<Drawable*>::ConstIterator k = query.shadowCasters_.Begin() + query.shadowCasterBegin_[j];
  865. k < query.shadowCasters_.Begin() + query.shadowCasterEnd_[j]; ++k)
  866. {
  867. Drawable* drawable = *k;
  868. // If drawable is not in actual view frustum, mark it in view here and check its geometry update type
  869. if (!drawable->IsInView(frame_, true))
  870. {
  871. drawable->MarkInView(frame_.frameNumber_, 0);
  872. UpdateGeometryType type = drawable->GetUpdateGeometryType();
  873. if (type == UPDATE_MAIN_THREAD)
  874. nonThreadedGeometries_.Push(drawable);
  875. else if (type == UPDATE_WORKER_THREAD)
  876. threadedGeometries_.Push(drawable);
  877. }
  878. Zone* zone = GetZone(drawable);
  879. const Vector<SourceBatch>& batches = drawable->GetBatches();
  880. for (unsigned l = 0; l < batches.Size(); ++l)
  881. {
  882. const SourceBatch& srcBatch = batches[l];
  883. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  884. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  885. continue;
  886. Pass* pass = tech->GetSupportedPass(Technique::shadowPassIndex);
  887. // Skip if material has no shadow pass
  888. if (!pass)
  889. continue;
  890. Batch destBatch(srcBatch);
  891. destBatch.pass_ = pass;
  892. destBatch.camera_ = shadowCamera;
  893. destBatch.zone_ = zone;
  894. destBatch.lightQueue_ = &lightQueue;
  895. AddBatchToQueue(shadowQueue.shadowBatches_, destBatch, tech);
  896. }
  897. }
  898. }
  899. // Process lit geometries
  900. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  901. {
  902. Drawable* drawable = *j;
  903. drawable->AddLight(light);
  904. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  905. if (!drawable->GetMaxLights())
  906. GetLitBatches(drawable, lightQueue, alphaQueue);
  907. else
  908. maxLightsDrawables_.Insert(drawable);
  909. }
  910. // In deferred modes, store the light volume batch now
  911. if (deferred_)
  912. {
  913. Batch volumeBatch;
  914. volumeBatch.geometry_ = renderer_->GetLightGeometry(light);
  915. volumeBatch.geometryType_ = GEOM_STATIC;
  916. volumeBatch.worldTransform_ = &light->GetVolumeTransform(camera_);
  917. volumeBatch.numWorldTransforms_ = 1;
  918. volumeBatch.camera_ = camera_;
  919. volumeBatch.lightQueue_ = &lightQueue;
  920. volumeBatch.distance_ = light->GetDistance();
  921. volumeBatch.material_ = 0;
  922. volumeBatch.pass_ = 0;
  923. volumeBatch.zone_ = 0;
  924. renderer_->SetLightVolumeBatchShaders(volumeBatch, lightVolumeCommand_->vertexShaderName_,
  925. lightVolumeCommand_->pixelShaderName_, lightVolumeCommand_->vertexShaderDefines_,
  926. lightVolumeCommand_->pixelShaderDefines_);
  927. lightQueue.volumeBatches_.Push(volumeBatch);
  928. }
  929. }
  930. // Per-vertex light
  931. else
  932. {
  933. // Add the vertex light to lit drawables. It will be processed later during base pass batch generation
  934. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  935. {
  936. Drawable* drawable = *j;
  937. drawable->AddVertexLight(light);
  938. }
  939. }
  940. }
  941. }
  942. // Process drawables with limited per-pixel light count
  943. if (maxLightsDrawables_.Size())
  944. {
  945. PROFILE(GetMaxLightsBatches);
  946. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  947. {
  948. Drawable* drawable = *i;
  949. drawable->LimitLights();
  950. const PODVector<Light*>& lights = drawable->GetLights();
  951. for (unsigned i = 0; i < lights.Size(); ++i)
  952. {
  953. Light* light = lights[i];
  954. // Find the correct light queue again
  955. LightBatchQueue* queue = light->GetLightQueue();
  956. if (queue)
  957. GetLitBatches(drawable, *queue, alphaQueue);
  958. }
  959. }
  960. }
  961. // Build base pass batches and find out the geometry update queue (threaded or nonthreaded) drawables should end up to
  962. {
  963. PROFILE(GetBaseBatches);
  964. for (PODVector<Drawable*>::ConstIterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  965. {
  966. Drawable* drawable = *i;
  967. UpdateGeometryType type = drawable->GetUpdateGeometryType();
  968. if (type == UPDATE_MAIN_THREAD)
  969. nonThreadedGeometries_.Push(drawable);
  970. else if (type == UPDATE_WORKER_THREAD)
  971. threadedGeometries_.Push(drawable);
  972. const Vector<SourceBatch>& batches = drawable->GetBatches();
  973. bool vertexLightsProcessed = false;
  974. for (unsigned j = 0; j < batches.Size(); ++j)
  975. {
  976. const SourceBatch& srcBatch = batches[j];
  977. // Check here if the material refers to a rendertarget texture with camera(s) attached
  978. // Only check this for backbuffer views (null rendertarget)
  979. if (srcBatch.material_ && srcBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_ && !renderTarget_)
  980. CheckMaterialForAuxView(srcBatch.material_);
  981. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  982. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  983. continue;
  984. // Check each of the scene passes
  985. for (unsigned k = 0; k < scenePasses_.Size(); ++k)
  986. {
  987. ScenePassInfo& info = scenePasses_[k];
  988. // Skip forward base pass if the corresponding litbase pass already exists
  989. if (info.passIndex_ == basePassIndex_ && j < 32 && drawable->HasBasePass(j))
  990. continue;
  991. Pass* pass = tech->GetSupportedPass(info.passIndex_);
  992. if (!pass)
  993. continue;
  994. Batch destBatch(srcBatch);
  995. destBatch.pass_ = pass;
  996. destBatch.camera_ = camera_;
  997. destBatch.zone_ = GetZone(drawable);
  998. destBatch.isBase_ = true;
  999. destBatch.lightMask_ = GetLightMask(drawable);
  1000. if (info.vertexLights_)
  1001. {
  1002. const PODVector<Light*>& drawableVertexLights = drawable->GetVertexLights();
  1003. if (drawableVertexLights.Size() && !vertexLightsProcessed)
  1004. {
  1005. // Limit vertex lights. If this is a deferred opaque batch, remove converted per-pixel lights,
  1006. // as they will be rendered as light volumes in any case, and drawing them also as vertex lights
  1007. // would result in double lighting
  1008. drawable->LimitVertexLights(deferred_ && destBatch.pass_->GetBlendMode() == BLEND_REPLACE);
  1009. vertexLightsProcessed = true;
  1010. }
  1011. if (drawableVertexLights.Size())
  1012. {
  1013. // Find a vertex light queue. If not found, create new
  1014. unsigned long long hash = GetVertexLightQueueHash(drawableVertexLights);
  1015. HashMap<unsigned long long, LightBatchQueue>::Iterator i = vertexLightQueues_.Find(hash);
  1016. if (i == vertexLightQueues_.End())
  1017. {
  1018. i = vertexLightQueues_.Insert(MakePair(hash, LightBatchQueue()));
  1019. i->second_.light_ = 0;
  1020. i->second_.shadowMap_ = 0;
  1021. i->second_.vertexLights_ = drawableVertexLights;
  1022. }
  1023. destBatch.lightQueue_ = &(i->second_);
  1024. }
  1025. }
  1026. else
  1027. destBatch.lightQueue_ = 0;
  1028. bool allowInstancing = info.allowInstancing_;
  1029. if (allowInstancing && info.markToStencil_ && destBatch.lightMask_ != (destBatch.zone_->GetLightMask() & 0xff))
  1030. allowInstancing = false;
  1031. AddBatchToQueue(*info.batchQueue_, destBatch, tech, allowInstancing);
  1032. }
  1033. }
  1034. }
  1035. }
  1036. }
  1037. void View::UpdateGeometries()
  1038. {
  1039. PROFILE(SortAndUpdateGeometry);
  1040. WorkQueue* queue = GetSubsystem<WorkQueue>();
  1041. // Sort batches
  1042. {
  1043. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1044. {
  1045. const RenderPathCommand& command = renderPath_->commands_[i];
  1046. if (!IsNecessary(command))
  1047. continue;
  1048. if (command.type_ == CMD_SCENEPASS)
  1049. {
  1050. SharedPtr<WorkItem> item = queue->GetFreeItem();
  1051. item->priority_ = M_MAX_UNSIGNED;
  1052. item->workFunction_ = command.sortMode_ == SORT_FRONTTOBACK ? SortBatchQueueFrontToBackWork : SortBatchQueueBackToFrontWork;
  1053. item->start_ = &batchQueues_[command.passIndex_];
  1054. queue->AddWorkItem(item);
  1055. }
  1056. }
  1057. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1058. {
  1059. SharedPtr<WorkItem> lightItem = queue->GetFreeItem();
  1060. lightItem->priority_ = M_MAX_UNSIGNED;
  1061. lightItem->workFunction_ = SortLightQueueWork;
  1062. lightItem->start_ = &(*i);
  1063. queue->AddWorkItem(lightItem);
  1064. if (i->shadowSplits_.Size())
  1065. {
  1066. SharedPtr<WorkItem> shadowItem = queue->GetFreeItem();
  1067. shadowItem->priority_ = M_MAX_UNSIGNED;
  1068. shadowItem->workFunction_ = SortShadowQueueWork;
  1069. shadowItem->start_ = &(*i);
  1070. queue->AddWorkItem(shadowItem);
  1071. }
  1072. }
  1073. }
  1074. // Update geometries. Split into threaded and non-threaded updates.
  1075. {
  1076. if (threadedGeometries_.Size())
  1077. {
  1078. // In special cases (context loss, multi-view) a drawable may theoretically first have reported a threaded update, but will actually
  1079. // require a main thread update. Check these cases first and move as applicable. The threaded work routine will tolerate the null
  1080. // pointer holes that we leave to the threaded update queue.
  1081. for (PODVector<Drawable*>::Iterator i = threadedGeometries_.Begin(); i != threadedGeometries_.End(); ++i)
  1082. {
  1083. if ((*i)->GetUpdateGeometryType() == UPDATE_MAIN_THREAD)
  1084. {
  1085. nonThreadedGeometries_.Push(*i);
  1086. *i = 0;
  1087. }
  1088. }
  1089. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  1090. int drawablesPerItem = threadedGeometries_.Size() / numWorkItems;
  1091. PODVector<Drawable*>::Iterator start = threadedGeometries_.Begin();
  1092. for (int i = 0; i < numWorkItems; ++i)
  1093. {
  1094. PODVector<Drawable*>::Iterator end = threadedGeometries_.End();
  1095. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  1096. end = start + drawablesPerItem;
  1097. SharedPtr<WorkItem> item = queue->GetFreeItem();
  1098. item->priority_ = M_MAX_UNSIGNED;
  1099. item->workFunction_ = UpdateDrawableGeometriesWork;
  1100. item->aux_ = const_cast<FrameInfo*>(&frame_);
  1101. item->start_ = &(*start);
  1102. item->end_ = &(*end);
  1103. queue->AddWorkItem(item);
  1104. start = end;
  1105. }
  1106. }
  1107. // While the work queue is processed, update non-threaded geometries
  1108. for (PODVector<Drawable*>::ConstIterator i = nonThreadedGeometries_.Begin(); i != nonThreadedGeometries_.End(); ++i)
  1109. (*i)->UpdateGeometry(frame_);
  1110. }
  1111. // Finally ensure all threaded work has completed
  1112. queue->Complete(M_MAX_UNSIGNED);
  1113. }
  1114. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue, BatchQueue* alphaQueue)
  1115. {
  1116. Light* light = lightQueue.light_;
  1117. Zone* zone = GetZone(drawable);
  1118. const Vector<SourceBatch>& batches = drawable->GetBatches();
  1119. bool allowLitBase = useLitBase_ && !lightQueue.negative_ && light == drawable->GetFirstLight() &&
  1120. drawable->GetVertexLights().Empty() && !zone->GetAmbientGradient();
  1121. for (unsigned i = 0; i < batches.Size(); ++i)
  1122. {
  1123. const SourceBatch& srcBatch = batches[i];
  1124. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  1125. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  1126. continue;
  1127. // Do not create pixel lit forward passes for materials that render into the G-buffer
  1128. if (gBufferPassIndex_ != M_MAX_UNSIGNED && tech->HasPass(gBufferPassIndex_))
  1129. continue;
  1130. Batch destBatch(srcBatch);
  1131. bool isLitAlpha = false;
  1132. // Check for lit base pass. Because it uses the replace blend mode, it must be ensured to be the first light
  1133. // Also vertex lighting or ambient gradient require the non-lit base pass, so skip in those cases
  1134. if (i < 32 && allowLitBase)
  1135. {
  1136. destBatch.pass_ = tech->GetSupportedPass(litBasePassIndex_);
  1137. if (destBatch.pass_)
  1138. {
  1139. destBatch.isBase_ = true;
  1140. drawable->SetBasePass(i);
  1141. }
  1142. else
  1143. destBatch.pass_ = tech->GetSupportedPass(lightPassIndex_);
  1144. }
  1145. else
  1146. destBatch.pass_ = tech->GetSupportedPass(lightPassIndex_);
  1147. // If no lit pass, check for lit alpha
  1148. if (!destBatch.pass_)
  1149. {
  1150. destBatch.pass_ = tech->GetSupportedPass(litAlphaPassIndex_);
  1151. isLitAlpha = true;
  1152. }
  1153. // Skip if material does not receive light at all
  1154. if (!destBatch.pass_)
  1155. continue;
  1156. destBatch.camera_ = camera_;
  1157. destBatch.lightQueue_ = &lightQueue;
  1158. destBatch.zone_ = zone;
  1159. if (!isLitAlpha)
  1160. {
  1161. if (destBatch.isBase_)
  1162. AddBatchToQueue(lightQueue.litBaseBatches_, destBatch, tech);
  1163. else
  1164. AddBatchToQueue(lightQueue.litBatches_, destBatch, tech);
  1165. }
  1166. else if (alphaQueue)
  1167. {
  1168. // Transparent batches can not be instanced, and shadows on transparencies can only be rendered if shadow maps are
  1169. // not reused
  1170. AddBatchToQueue(*alphaQueue, destBatch, tech, false, !renderer_->GetReuseShadowMaps());
  1171. }
  1172. }
  1173. }
  1174. void View::ExecuteRenderPathCommands()
  1175. {
  1176. // If not reusing shadowmaps, render all of them first
  1177. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  1178. {
  1179. PROFILE(RenderShadowMaps);
  1180. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1181. {
  1182. if (i->shadowMap_)
  1183. RenderShadowMap(*i);
  1184. }
  1185. }
  1186. {
  1187. PROFILE(ExecuteRenderPath);
  1188. // Set for safety in case of empty renderpath
  1189. currentRenderTarget_ = substituteRenderTarget_ ? substituteRenderTarget_ : renderTarget_;
  1190. currentViewportTexture_ = 0;
  1191. bool viewportModified = false;
  1192. bool isPingponging = false;
  1193. unsigned lastCommandIndex = 0;
  1194. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1195. {
  1196. RenderPathCommand& command = renderPath_->commands_[i];
  1197. if (IsNecessary(command))
  1198. lastCommandIndex = i;
  1199. }
  1200. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1201. {
  1202. RenderPathCommand& command = renderPath_->commands_[i];
  1203. if (!IsNecessary(command))
  1204. continue;
  1205. bool viewportRead = CheckViewportRead(command);
  1206. bool viewportWrite = CheckViewportWrite(command);
  1207. bool beginPingpong = CheckPingpong(i);
  1208. // Has the viewport been modified and will be read as a texture by the current command?
  1209. if (viewportRead && viewportModified)
  1210. {
  1211. // Start pingponging without a blit if already rendering to the substitute render target
  1212. if (currentRenderTarget_ && currentRenderTarget_ == substituteRenderTarget_ && beginPingpong)
  1213. isPingponging = true;
  1214. // If not using pingponging, simply resolve/copy to the first viewport texture
  1215. if (!isPingponging)
  1216. {
  1217. if (!currentRenderTarget_)
  1218. {
  1219. graphics_->ResolveToTexture(viewportTextures_[0], viewRect_);
  1220. currentViewportTexture_ = viewportTextures_[0];
  1221. viewportModified = false;
  1222. }
  1223. else
  1224. {
  1225. if (viewportWrite)
  1226. {
  1227. BlitFramebuffer(static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture()),
  1228. viewportTextures_[0]->GetRenderSurface(), false);
  1229. currentViewportTexture_ = viewportTextures_[0];
  1230. viewportModified = false;
  1231. }
  1232. else
  1233. {
  1234. // If the current render target is already a texture, and we are not writing to it, can read that
  1235. // texture directly instead of blitting. However keep the viewport dirty flag in case a later command
  1236. // will do both read and write, and then we need to blit / resolve
  1237. currentViewportTexture_ = static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture());
  1238. }
  1239. }
  1240. }
  1241. else
  1242. {
  1243. // Swap the pingpong double buffer sides. Texture 0 will be read next
  1244. viewportTextures_[1] = viewportTextures_[0];
  1245. viewportTextures_[0] = static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture());
  1246. currentViewportTexture_ = viewportTextures_[0];
  1247. viewportModified = false;
  1248. }
  1249. }
  1250. if (beginPingpong)
  1251. isPingponging = true;
  1252. // Determine viewport write target
  1253. if (viewportWrite)
  1254. {
  1255. if (isPingponging)
  1256. {
  1257. currentRenderTarget_ = viewportTextures_[1]->GetRenderSurface();
  1258. // If the render path ends into a quad, it can be redirected to the final render target
  1259. // However, on OpenGL we can not reliably do this in case the final target is the backbuffer, and we want to
  1260. // render depth buffer sensitive debug geometry afterward (backbuffer and textures can not share depth)
  1261. #ifndef URHO3D_OPENGL
  1262. if (i == lastCommandIndex && command.type_ == CMD_QUAD)
  1263. #else
  1264. if (i == lastCommandIndex && command.type_ == CMD_QUAD && renderTarget_)
  1265. #endif
  1266. currentRenderTarget_ = renderTarget_;
  1267. }
  1268. else
  1269. currentRenderTarget_ = substituteRenderTarget_ ? substituteRenderTarget_ : renderTarget_;
  1270. }
  1271. switch (command.type_)
  1272. {
  1273. case CMD_CLEAR:
  1274. {
  1275. PROFILE(ClearRenderTarget);
  1276. Color clearColor = command.clearColor_;
  1277. if (command.useFogColor_)
  1278. clearColor = farClipZone_->GetFogColor();
  1279. SetRenderTargets(command);
  1280. graphics_->Clear(command.clearFlags_, clearColor, command.clearDepth_, command.clearStencil_);
  1281. }
  1282. break;
  1283. case CMD_SCENEPASS:
  1284. {
  1285. if (!batchQueues_[command.passIndex_].IsEmpty())
  1286. {
  1287. PROFILE(RenderScenePass);
  1288. SetRenderTargets(command);
  1289. bool allowDepthWrite = SetTextures(command);
  1290. graphics_->SetFillMode(camera_->GetFillMode());
  1291. graphics_->SetClipPlane(camera_->GetUseClipping(), camera_->GetClipPlane(), camera_->GetView(), camera_->GetProjection());
  1292. batchQueues_[command.passIndex_].Draw(this, command.markToStencil_, false, allowDepthWrite);
  1293. }
  1294. }
  1295. break;
  1296. case CMD_QUAD:
  1297. {
  1298. PROFILE(RenderQuad);
  1299. SetRenderTargets(command);
  1300. SetTextures(command);
  1301. RenderQuad(command);
  1302. }
  1303. break;
  1304. case CMD_FORWARDLIGHTS:
  1305. // Render shadow maps + opaque objects' additive lighting
  1306. if (!lightQueues_.Empty())
  1307. {
  1308. PROFILE(RenderLights);
  1309. SetRenderTargets(command);
  1310. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1311. {
  1312. // If reusing shadowmaps, render each of them before the lit batches
  1313. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1314. {
  1315. RenderShadowMap(*i);
  1316. SetRenderTargets(command);
  1317. }
  1318. bool allowDepthWrite = SetTextures(command);
  1319. graphics_->SetFillMode(camera_->GetFillMode());
  1320. graphics_->SetClipPlane(camera_->GetUseClipping(), camera_->GetClipPlane(), camera_->GetView(), camera_->GetProjection());
  1321. // Draw base (replace blend) batches first
  1322. i->litBaseBatches_.Draw(this, false, false, allowDepthWrite);
  1323. // Then, if there are additive passes, optimize the light and draw them
  1324. if (!i->litBatches_.IsEmpty())
  1325. {
  1326. renderer_->OptimizeLightByScissor(i->light_, camera_);
  1327. if (!noStencil_)
  1328. renderer_->OptimizeLightByStencil(i->light_, camera_);
  1329. i->litBatches_.Draw(this, false, true, allowDepthWrite);
  1330. }
  1331. }
  1332. graphics_->SetScissorTest(false);
  1333. graphics_->SetStencilTest(false);
  1334. }
  1335. break;
  1336. case CMD_LIGHTVOLUMES:
  1337. // Render shadow maps + light volumes
  1338. if (!lightQueues_.Empty())
  1339. {
  1340. PROFILE(RenderLightVolumes);
  1341. SetRenderTargets(command);
  1342. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1343. {
  1344. // If reusing shadowmaps, render each of them before the lit batches
  1345. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1346. {
  1347. RenderShadowMap(*i);
  1348. SetRenderTargets(command);
  1349. }
  1350. SetTextures(command);
  1351. for (unsigned j = 0; j < i->volumeBatches_.Size(); ++j)
  1352. {
  1353. SetupLightVolumeBatch(i->volumeBatches_[j]);
  1354. i->volumeBatches_[j].Draw(this, false);
  1355. }
  1356. }
  1357. graphics_->SetScissorTest(false);
  1358. graphics_->SetStencilTest(false);
  1359. }
  1360. break;
  1361. case CMD_RENDERUI:
  1362. {
  1363. SetRenderTargets(command);
  1364. GetSubsystem<UI>()->Render(false);
  1365. }
  1366. break;
  1367. default:
  1368. break;
  1369. }
  1370. // If current command output to the viewport, mark it modified
  1371. if (viewportWrite)
  1372. viewportModified = true;
  1373. }
  1374. }
  1375. }
  1376. void View::SetRenderTargets(RenderPathCommand& command)
  1377. {
  1378. unsigned index = 0;
  1379. bool useColorWrite = true;
  1380. bool useCustomDepth = false;
  1381. while (index < command.outputNames_.Size())
  1382. {
  1383. if (!command.outputNames_[index].Compare("viewport", false))
  1384. graphics_->SetRenderTarget(index, currentRenderTarget_);
  1385. else
  1386. {
  1387. StringHash nameHash(command.outputNames_[index]);
  1388. if (renderTargets_.Contains(nameHash))
  1389. {
  1390. Texture2D* texture = renderTargets_[nameHash];
  1391. // Check for depth only rendering (by specifying a depth texture as the sole output)
  1392. if (!index && command.outputNames_.Size() == 1 && texture && (texture->GetFormat() ==
  1393. Graphics::GetReadableDepthFormat() || texture->GetFormat() == Graphics::GetDepthStencilFormat()))
  1394. {
  1395. useColorWrite = false;
  1396. useCustomDepth = true;
  1397. #ifndef URHO3D_OPENGL
  1398. // On D3D actual depth-only rendering is illegal, we need a color rendertarget
  1399. if (!depthOnlyDummyTexture_)
  1400. {
  1401. depthOnlyDummyTexture_ = renderer_->GetScreenBuffer(texture->GetWidth(), texture->GetHeight(),
  1402. graphics_->GetDummyColorFormat(), false, false);
  1403. }
  1404. #endif
  1405. graphics_->SetRenderTarget(0, depthOnlyDummyTexture_);
  1406. graphics_->SetDepthStencil(texture);
  1407. }
  1408. else
  1409. graphics_->SetRenderTarget(index, texture);
  1410. }
  1411. else
  1412. graphics_->SetRenderTarget(0, (RenderSurface*)0);
  1413. }
  1414. ++index;
  1415. }
  1416. while (index < MAX_RENDERTARGETS)
  1417. {
  1418. graphics_->SetRenderTarget(index, (RenderSurface*)0);
  1419. ++index;
  1420. }
  1421. if (command.depthStencilName_.Length())
  1422. {
  1423. Texture2D* depthTexture = renderTargets_[StringHash(command.depthStencilName_)];
  1424. if (depthTexture)
  1425. {
  1426. useCustomDepth = true;
  1427. graphics_->SetDepthStencil(depthTexture);
  1428. }
  1429. }
  1430. // When rendering to the final destination rendertarget, use the actual viewport. Otherwise texture rendertargets will be
  1431. // viewport-sized, so they should use their full size as the viewport
  1432. IntVector2 rtSizeNow = graphics_->GetRenderTargetDimensions();
  1433. IntRect viewport = (graphics_->GetRenderTarget(0) == renderTarget_) ? viewRect_ : IntRect(0, 0, rtSizeNow.x_,
  1434. rtSizeNow.y_);
  1435. if (!useCustomDepth)
  1436. graphics_->SetDepthStencil(GetDepthStencil(graphics_->GetRenderTarget(0)));
  1437. graphics_->SetViewport(viewport);
  1438. graphics_->SetColorWrite(useColorWrite);
  1439. }
  1440. bool View::SetTextures(RenderPathCommand& command)
  1441. {
  1442. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1443. bool allowDepthWrite = true;
  1444. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1445. {
  1446. if (command.textureNames_[i].Empty())
  1447. continue;
  1448. // Bind the rendered output
  1449. if (!command.textureNames_[i].Compare("viewport", false))
  1450. {
  1451. graphics_->SetTexture(i, currentViewportTexture_);
  1452. continue;
  1453. }
  1454. // Bind a rendertarget
  1455. HashMap<StringHash, Texture2D*>::ConstIterator j = renderTargets_.Find(command.textureNames_[i]);
  1456. if (j != renderTargets_.End())
  1457. {
  1458. graphics_->SetTexture(i, j->second_);
  1459. // Check if the current depth stencil is being sampled
  1460. if (graphics_->GetDepthStencil() && j->second_ == graphics_->GetDepthStencil()->GetParentTexture())
  1461. allowDepthWrite = false;
  1462. continue;
  1463. }
  1464. // Bind a texture from the resource system
  1465. Texture* texture;
  1466. // Detect cube/3D textures by file extension: they are defined by an XML file
  1467. if (GetExtension(command.textureNames_[i]) == ".xml")
  1468. {
  1469. // Assume 3D textures are only bound to the volume map unit, otherwise it's a cube texture
  1470. #ifdef DESKTOP_GRAPHICS
  1471. if (i == TU_VOLUMEMAP)
  1472. texture = cache->GetResource<Texture3D>(command.textureNames_[i]);
  1473. else
  1474. #endif
  1475. texture = cache->GetResource<TextureCube>(command.textureNames_[i]);
  1476. }
  1477. else
  1478. texture = cache->GetResource<Texture2D>(command.textureNames_[i]);
  1479. if (texture)
  1480. graphics_->SetTexture(i, texture);
  1481. else
  1482. {
  1483. // If requesting a texture fails, clear the texture name to prevent redundant attempts
  1484. command.textureNames_[i] = String::EMPTY;
  1485. }
  1486. }
  1487. return allowDepthWrite;
  1488. }
  1489. void View::RenderQuad(RenderPathCommand& command)
  1490. {
  1491. if (command.vertexShaderName_.Empty() || command.pixelShaderName_.Empty())
  1492. return;
  1493. // If shader can not be found, clear it from the command to prevent redundant attempts
  1494. ShaderVariation* vs = graphics_->GetShader(VS, command.vertexShaderName_, command.vertexShaderDefines_);
  1495. if (!vs)
  1496. command.vertexShaderName_ = String::EMPTY;
  1497. ShaderVariation* ps = graphics_->GetShader(PS, command.pixelShaderName_, command.pixelShaderDefines_);
  1498. if (!ps)
  1499. command.pixelShaderName_ = String::EMPTY;
  1500. // Set shaders & shader parameters and textures
  1501. graphics_->SetShaders(vs, ps);
  1502. const HashMap<StringHash, Variant>& parameters = command.shaderParameters_;
  1503. for (HashMap<StringHash, Variant>::ConstIterator k = parameters.Begin(); k != parameters.End(); ++k)
  1504. graphics_->SetShaderParameter(k->first_, k->second_);
  1505. SetGlobalShaderParameters();
  1506. SetCameraShaderParameters(camera_, false);
  1507. // During renderpath commands the G-Buffer or viewport texture is assumed to always be viewport-sized
  1508. IntRect viewport = graphics_->GetViewport();
  1509. IntVector2 viewSize = IntVector2(viewport.Width(), viewport.Height());
  1510. SetGBufferShaderParameters(viewSize, IntRect(0, 0, viewSize.x_, viewSize.y_));
  1511. // Set per-rendertarget inverse size / offset shader parameters as necessary
  1512. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1513. {
  1514. const RenderTargetInfo& rtInfo = renderPath_->renderTargets_[i];
  1515. if (!rtInfo.enabled_)
  1516. continue;
  1517. StringHash nameHash(rtInfo.name_);
  1518. if (!renderTargets_.Contains(nameHash))
  1519. continue;
  1520. String invSizeName = rtInfo.name_ + "InvSize";
  1521. String offsetsName = rtInfo.name_ + "Offsets";
  1522. float width = (float)renderTargets_[nameHash]->GetWidth();
  1523. float height = (float)renderTargets_[nameHash]->GetHeight();
  1524. const Vector2& pixelUVOffset = Graphics::GetPixelUVOffset();
  1525. graphics_->SetShaderParameter(invSizeName, Vector2(1.0f / width, 1.0f / height));
  1526. graphics_->SetShaderParameter(offsetsName, Vector2(pixelUVOffset.x_ / width, pixelUVOffset.y_ / height));
  1527. }
  1528. graphics_->SetBlendMode(BLEND_REPLACE);
  1529. graphics_->SetDepthTest(CMP_ALWAYS);
  1530. graphics_->SetDepthWrite(false);
  1531. graphics_->SetFillMode(FILL_SOLID);
  1532. graphics_->SetClipPlane(false);
  1533. graphics_->SetScissorTest(false);
  1534. graphics_->SetStencilTest(false);
  1535. DrawFullscreenQuad(false);
  1536. }
  1537. bool View::IsNecessary(const RenderPathCommand& command)
  1538. {
  1539. return command.enabled_ && command.outputNames_.Size() && (command.type_ != CMD_SCENEPASS ||
  1540. !batchQueues_[command.passIndex_].IsEmpty());
  1541. }
  1542. bool View::CheckViewportRead(const RenderPathCommand& command)
  1543. {
  1544. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1545. {
  1546. if (!command.textureNames_[i].Empty() && !command.textureNames_[i].Compare("viewport", false))
  1547. return true;
  1548. }
  1549. return false;
  1550. }
  1551. bool View::CheckViewportWrite(const RenderPathCommand& command)
  1552. {
  1553. for (unsigned i = 0; i < command.outputNames_.Size(); ++i)
  1554. {
  1555. if (!command.outputNames_[i].Compare("viewport", false))
  1556. return true;
  1557. }
  1558. return false;
  1559. }
  1560. bool View::CheckPingpong(unsigned index)
  1561. {
  1562. // Current command must be a viewport-reading & writing quad to begin the pingpong chain
  1563. RenderPathCommand& current = renderPath_->commands_[index];
  1564. if (current.type_ != CMD_QUAD || !CheckViewportRead(current) || !CheckViewportWrite(current))
  1565. return false;
  1566. // If there are commands other than quads that target the viewport, we must keep rendering to the final target and resolving
  1567. // to a viewport texture when necessary instead of pingponging, as a scene pass is not guaranteed to fill the entire viewport
  1568. for (unsigned i = index + 1; i < renderPath_->commands_.Size(); ++i)
  1569. {
  1570. RenderPathCommand& command = renderPath_->commands_[i];
  1571. if (!IsNecessary(command))
  1572. continue;
  1573. if (CheckViewportWrite(command))
  1574. {
  1575. if (command.type_ != CMD_QUAD)
  1576. return false;
  1577. }
  1578. }
  1579. return true;
  1580. }
  1581. void View::AllocateScreenBuffers()
  1582. {
  1583. bool needSubstitute = false;
  1584. unsigned numViewportTextures = 0;
  1585. depthOnlyDummyTexture_ = 0;
  1586. #ifdef URHO3D_OPENGL
  1587. // Due to FBO limitations, in OpenGL deferred modes need to render to texture first and then blit to the backbuffer
  1588. // Also, if rendering to a texture with full deferred rendering, it must be RGBA to comply with the rest of the buffers.
  1589. if ((deferred_ && !renderTarget_) || (deferredAmbient_ && renderTarget_ && renderTarget_->GetParentTexture()->GetFormat() !=
  1590. Graphics::GetRGBAFormat()))
  1591. needSubstitute = true;
  1592. // Also need substitute if rendering to backbuffer using a custom (readable) depth buffer
  1593. if (!renderTarget_ && !needSubstitute)
  1594. {
  1595. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1596. {
  1597. const RenderPathCommand& command = renderPath_->commands_[i];
  1598. if (!IsNecessary(command))
  1599. continue;
  1600. if (command.depthStencilName_.Length() && command.outputNames_.Size() && !command.outputNames_[0].Compare("viewport",
  1601. false))
  1602. {
  1603. needSubstitute = true;
  1604. break;
  1605. }
  1606. }
  1607. }
  1608. #endif
  1609. // If backbuffer is antialiased when using deferred rendering, need to reserve a buffer
  1610. if (deferred_ && !renderTarget_ && graphics_->GetMultiSample() > 1)
  1611. needSubstitute = true;
  1612. // If viewport is smaller than whole texture/backbuffer in deferred rendering, need to reserve a buffer, as the G-buffer
  1613. // textures will be sized equal to the viewport
  1614. if (viewSize_.x_ < rtSize_.x_ || viewSize_.y_ < rtSize_.y_)
  1615. {
  1616. if (deferred_)
  1617. needSubstitute = true;
  1618. else if (!needSubstitute)
  1619. {
  1620. // Check also if using MRT without deferred rendering and rendering to the viewport and another texture,
  1621. // or using custom depth
  1622. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1623. {
  1624. const RenderPathCommand& command = renderPath_->commands_[i];
  1625. if (!IsNecessary(command))
  1626. continue;
  1627. if (command.depthStencilName_.Length())
  1628. needSubstitute = true;
  1629. if (!needSubstitute && command.outputNames_.Size() > 1)
  1630. {
  1631. for (unsigned j = 0; j < command.outputNames_.Size(); ++j)
  1632. {
  1633. if (!command.outputNames_[j].Compare("viewport", false))
  1634. {
  1635. needSubstitute = true;
  1636. break;
  1637. }
  1638. }
  1639. }
  1640. if (needSubstitute)
  1641. break;
  1642. }
  1643. }
  1644. }
  1645. // Follow final rendertarget format, or use RGB to match the backbuffer format
  1646. unsigned format = renderTarget_ ? renderTarget_->GetParentTexture()->GetFormat() : Graphics::GetRGBFormat();
  1647. // If HDR rendering is enabled use RGBA16f and reserve a buffer
  1648. if (renderer_->GetHDRRendering())
  1649. {
  1650. format = Graphics::GetRGBAFloat16Format();
  1651. needSubstitute = true;
  1652. }
  1653. #ifdef URHO3D_OPENGL
  1654. if (deferred_ && !renderer_->GetHDRRendering())
  1655. format = Graphics::GetRGBAFormat();
  1656. #endif
  1657. // Check for commands which read the viewport, or pingpong between viewport textures
  1658. bool hasViewportRead = false;
  1659. bool hasPingpong = false;
  1660. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1661. {
  1662. const RenderPathCommand& command = renderPath_->commands_[i];
  1663. if (!IsNecessary(command))
  1664. continue;
  1665. if (CheckViewportRead(command))
  1666. hasViewportRead = true;
  1667. if (!hasPingpong && CheckPingpong(i))
  1668. hasPingpong = true;
  1669. }
  1670. if (hasViewportRead)
  1671. {
  1672. ++numViewportTextures;
  1673. // If OpenGL ES, use substitute target to avoid resolve from the backbuffer, which may be slow. However if multisampling
  1674. // is specified, there is no choice
  1675. #ifdef GL_ES_VERSION_2_0
  1676. if (!renderTarget_ && graphics_->GetMultiSample() < 2)
  1677. needSubstitute = true;
  1678. #endif
  1679. // If we have viewport read and target is a cube map, must allocate a substitute target instead as BlitFramebuffer()
  1680. // does not support reading a cube map
  1681. if (renderTarget_ && renderTarget_->GetParentTexture()->GetType() == TextureCube::GetTypeStatic())
  1682. needSubstitute = true;
  1683. // If rendering to a texture, but the viewport is less than the whole texture, use a substitute to ensure
  1684. // postprocessing shaders will never read outside the viewport
  1685. if (renderTarget_ && (viewSize_.x_ < renderTarget_->GetWidth() || viewSize_.y_ < renderTarget_->GetHeight()))
  1686. needSubstitute = true;
  1687. if (hasPingpong && !needSubstitute)
  1688. ++numViewportTextures;
  1689. }
  1690. // Allocate screen buffers with filtering active in case the quad commands need that
  1691. // Follow the sRGB mode of the destination render target
  1692. bool sRGB = renderTarget_ ? renderTarget_->GetParentTexture()->GetSRGB() : graphics_->GetSRGB();
  1693. substituteRenderTarget_ = needSubstitute ? renderer_->GetScreenBuffer(viewSize_.x_, viewSize_.y_, format, true,
  1694. sRGB)->GetRenderSurface() : (RenderSurface*)0;
  1695. for (unsigned i = 0; i < MAX_VIEWPORT_TEXTURES; ++i)
  1696. {
  1697. viewportTextures_[i] = i < numViewportTextures ? renderer_->GetScreenBuffer(viewSize_.x_, viewSize_.y_, format, true, sRGB) :
  1698. (Texture2D*)0;
  1699. }
  1700. // If using a substitute render target and pingponging, the substitute can act as the second viewport texture
  1701. if (numViewportTextures == 1 && substituteRenderTarget_)
  1702. viewportTextures_[1] = static_cast<Texture2D*>(substituteRenderTarget_->GetParentTexture());
  1703. // Allocate extra render targets defined by the rendering path
  1704. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1705. {
  1706. const RenderTargetInfo& rtInfo = renderPath_->renderTargets_[i];
  1707. if (!rtInfo.enabled_)
  1708. continue;
  1709. float width = rtInfo.size_.x_;
  1710. float height = rtInfo.size_.y_;
  1711. if (rtInfo.sizeMode_ == SIZE_VIEWPORTDIVISOR)
  1712. {
  1713. width = (float)viewSize_.x_ / Max(width, M_EPSILON);
  1714. height = (float)viewSize_.y_ / Max(height, M_EPSILON);
  1715. }
  1716. else if (rtInfo.sizeMode_ == SIZE_VIEWPORTMULTIPLIER)
  1717. {
  1718. width = (float)viewSize_.x_ * width;
  1719. height = (float)viewSize_.y_ * height;
  1720. }
  1721. int intWidth = (int)(width + 0.5f);
  1722. int intHeight = (int)(height + 0.5f);
  1723. // If the rendertarget is persistent, key it with a hash derived from the RT name and the view's pointer
  1724. renderTargets_[rtInfo.name_] = renderer_->GetScreenBuffer(intWidth, intHeight, rtInfo.format_, rtInfo.filtered_,
  1725. rtInfo.sRGB_, rtInfo.persistent_ ? StringHash(rtInfo.name_).Value() + (unsigned)(size_t)this : 0);
  1726. }
  1727. }
  1728. void View::BlitFramebuffer(Texture2D* source, RenderSurface* destination, bool depthWrite)
  1729. {
  1730. if (!source)
  1731. return;
  1732. PROFILE(BlitFramebuffer);
  1733. // If blitting to the destination rendertarget, use the actual viewport. Intermediate textures on the other hand
  1734. // are always viewport-sized
  1735. IntVector2 srcSize(source->GetWidth(), source->GetHeight());
  1736. IntVector2 destSize = destination ? IntVector2(destination->GetWidth(), destination->GetHeight()) : IntVector2(
  1737. graphics_->GetWidth(), graphics_->GetHeight());
  1738. IntRect srcRect = (source->GetRenderSurface() == renderTarget_) ? viewRect_ : IntRect(0, 0, srcSize.x_, srcSize.y_);
  1739. IntRect destRect = (destination == renderTarget_) ? viewRect_ : IntRect(0, 0, destSize.x_, destSize.y_);
  1740. graphics_->SetBlendMode(BLEND_REPLACE);
  1741. graphics_->SetDepthTest(CMP_ALWAYS);
  1742. graphics_->SetDepthWrite(depthWrite);
  1743. graphics_->SetFillMode(FILL_SOLID);
  1744. graphics_->SetClipPlane(false);
  1745. graphics_->SetScissorTest(false);
  1746. graphics_->SetStencilTest(false);
  1747. graphics_->SetRenderTarget(0, destination);
  1748. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  1749. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  1750. graphics_->SetDepthStencil(GetDepthStencil(destination));
  1751. graphics_->SetViewport(destRect);
  1752. static const String shaderName("CopyFramebuffer");
  1753. graphics_->SetShaders(graphics_->GetShader(VS, shaderName), graphics_->GetShader(PS, shaderName));
  1754. SetGBufferShaderParameters(srcSize, srcRect);
  1755. graphics_->SetTexture(TU_DIFFUSE, source);
  1756. DrawFullscreenQuad(false);
  1757. }
  1758. void View::DrawFullscreenQuad(bool nearQuad)
  1759. {
  1760. Geometry* geometry = renderer_->GetQuadGeometry();
  1761. Matrix3x4 model = Matrix3x4::IDENTITY;
  1762. Matrix4 projection = Matrix4::IDENTITY;
  1763. #ifdef URHO3D_OPENGL
  1764. if (camera_ && camera_->GetFlipVertical())
  1765. projection.m11_ = -1.0f;
  1766. model.m23_ = nearQuad ? -1.0f : 1.0f;
  1767. #else
  1768. model.m23_ = nearQuad ? 0.0f : 1.0f;
  1769. #endif
  1770. graphics_->SetCullMode(CULL_NONE);
  1771. graphics_->SetShaderParameter(VSP_MODEL, model);
  1772. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1773. graphics_->ClearTransformSources();
  1774. geometry->Draw(graphics_);
  1775. }
  1776. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  1777. {
  1778. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  1779. float halfViewSize = camera->GetHalfViewSize();
  1780. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  1781. for (PODVector<Drawable*>::Iterator i = occluders.Begin(); i != occluders.End();)
  1782. {
  1783. Drawable* occluder = *i;
  1784. bool erase = false;
  1785. if (!occluder->IsInView(frame_, true))
  1786. occluder->UpdateBatches(frame_);
  1787. // Check occluder's draw distance (in main camera view)
  1788. float maxDistance = occluder->GetDrawDistance();
  1789. if (maxDistance <= 0.0f || occluder->GetDistance() <= maxDistance)
  1790. {
  1791. // Check that occluder is big enough on the screen
  1792. const BoundingBox& box = occluder->GetWorldBoundingBox();
  1793. float diagonal = box.Size().Length();
  1794. float compare;
  1795. if (!camera->IsOrthographic())
  1796. compare = diagonal * halfViewSize / occluder->GetDistance();
  1797. else
  1798. compare = diagonal * invOrthoSize;
  1799. if (compare < occluderSizeThreshold_)
  1800. erase = true;
  1801. else
  1802. {
  1803. // Store amount of triangles divided by screen size as a sorting key
  1804. // (best occluders are big and have few triangles)
  1805. occluder->SetSortValue((float)occluder->GetNumOccluderTriangles() / compare);
  1806. }
  1807. }
  1808. else
  1809. erase = true;
  1810. if (erase)
  1811. i = occluders.Erase(i);
  1812. else
  1813. ++i;
  1814. }
  1815. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  1816. if (occluders.Size())
  1817. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  1818. }
  1819. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  1820. {
  1821. buffer->SetMaxTriangles(maxOccluderTriangles_);
  1822. buffer->Clear();
  1823. for (unsigned i = 0; i < occluders.Size(); ++i)
  1824. {
  1825. Drawable* occluder = occluders[i];
  1826. if (i > 0)
  1827. {
  1828. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  1829. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  1830. continue;
  1831. }
  1832. // Check for running out of triangles
  1833. if (!occluder->DrawOcclusion(buffer))
  1834. break;
  1835. }
  1836. buffer->BuildDepthHierarchy();
  1837. }
  1838. void View::ProcessLight(LightQueryResult& query, unsigned threadIndex)
  1839. {
  1840. Light* light = query.light_;
  1841. LightType type = light->GetLightType();
  1842. const Frustum& frustum = camera_->GetFrustum();
  1843. // Check if light should be shadowed
  1844. bool isShadowed = drawShadows_ && light->GetCastShadows() && !light->GetPerVertex() && light->GetShadowIntensity() < 1.0f;
  1845. // If shadow distance non-zero, check it
  1846. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  1847. isShadowed = false;
  1848. // OpenGL ES can not support point light shadows
  1849. #ifdef GL_ES_VERSION_2_0
  1850. if (isShadowed && type == LIGHT_POINT)
  1851. isShadowed = false;
  1852. #endif
  1853. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  1854. PODVector<Drawable*>& tempDrawables = tempDrawables_[threadIndex];
  1855. query.litGeometries_.Clear();
  1856. switch (type)
  1857. {
  1858. case LIGHT_DIRECTIONAL:
  1859. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1860. {
  1861. if (GetLightMask(geometries_[i]) & light->GetLightMask())
  1862. query.litGeometries_.Push(geometries_[i]);
  1863. }
  1864. break;
  1865. case LIGHT_SPOT:
  1866. {
  1867. FrustumOctreeQuery octreeQuery(tempDrawables, light->GetFrustum(), DRAWABLE_GEOMETRY,
  1868. camera_->GetViewMask());
  1869. octree_->GetDrawables(octreeQuery);
  1870. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1871. {
  1872. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1873. query.litGeometries_.Push(tempDrawables[i]);
  1874. }
  1875. }
  1876. break;
  1877. case LIGHT_POINT:
  1878. {
  1879. SphereOctreeQuery octreeQuery(tempDrawables, Sphere(light->GetNode()->GetWorldPosition(), light->GetRange()),
  1880. DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1881. octree_->GetDrawables(octreeQuery);
  1882. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1883. {
  1884. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1885. query.litGeometries_.Push(tempDrawables[i]);
  1886. }
  1887. }
  1888. break;
  1889. }
  1890. // If no lit geometries or not shadowed, no need to process shadow cameras
  1891. if (query.litGeometries_.Empty() || !isShadowed)
  1892. {
  1893. query.numSplits_ = 0;
  1894. return;
  1895. }
  1896. // Determine number of shadow cameras and setup their initial positions
  1897. SetupShadowCameras(query);
  1898. // Process each split for shadow casters
  1899. query.shadowCasters_.Clear();
  1900. for (unsigned i = 0; i < query.numSplits_; ++i)
  1901. {
  1902. Camera* shadowCamera = query.shadowCameras_[i];
  1903. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1904. query.shadowCasterBegin_[i] = query.shadowCasterEnd_[i] = query.shadowCasters_.Size();
  1905. // For point light check that the face is visible: if not, can skip the split
  1906. if (type == LIGHT_POINT && frustum.IsInsideFast(BoundingBox(shadowCameraFrustum)) == OUTSIDE)
  1907. continue;
  1908. // For directional light check that the split is inside the visible scene: if not, can skip the split
  1909. if (type == LIGHT_DIRECTIONAL)
  1910. {
  1911. if (minZ_ > query.shadowFarSplits_[i])
  1912. continue;
  1913. if (maxZ_ < query.shadowNearSplits_[i])
  1914. continue;
  1915. // Reuse lit geometry query for all except directional lights
  1916. ShadowCasterOctreeQuery query(tempDrawables, shadowCameraFrustum, DRAWABLE_GEOMETRY,
  1917. camera_->GetViewMask());
  1918. octree_->GetDrawables(query);
  1919. }
  1920. // Check which shadow casters actually contribute to the shadowing
  1921. ProcessShadowCasters(query, tempDrawables, i);
  1922. }
  1923. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  1924. // only cost has been the shadow camera setup & queries
  1925. if (query.shadowCasters_.Empty())
  1926. query.numSplits_ = 0;
  1927. }
  1928. void View::ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex)
  1929. {
  1930. Light* light = query.light_;
  1931. Camera* shadowCamera = query.shadowCameras_[splitIndex];
  1932. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1933. const Matrix3x4& lightView = shadowCamera->GetView();
  1934. const Matrix4& lightProj = shadowCamera->GetProjection();
  1935. LightType type = light->GetLightType();
  1936. query.shadowCasterBox_[splitIndex].defined_ = false;
  1937. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  1938. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  1939. // frustum, so that shadow casters do not get rendered into unnecessary splits
  1940. Frustum lightViewFrustum;
  1941. if (type != LIGHT_DIRECTIONAL)
  1942. lightViewFrustum = camera_->GetSplitFrustum(minZ_, maxZ_).Transformed(lightView);
  1943. else
  1944. lightViewFrustum = camera_->GetSplitFrustum(Max(minZ_, query.shadowNearSplits_[splitIndex]),
  1945. Min(maxZ_, query.shadowFarSplits_[splitIndex])).Transformed(lightView);
  1946. BoundingBox lightViewFrustumBox(lightViewFrustum);
  1947. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1948. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1949. return;
  1950. BoundingBox lightViewBox;
  1951. BoundingBox lightProjBox;
  1952. for (PODVector<Drawable*>::ConstIterator i = drawables.Begin(); i != drawables.End(); ++i)
  1953. {
  1954. Drawable* drawable = *i;
  1955. // In case this is a point or spot light query result reused for optimization, we may have non-shadowcasters included.
  1956. // Check for that first
  1957. if (!drawable->GetCastShadows())
  1958. continue;
  1959. // Check shadow mask
  1960. if (!(GetShadowMask(drawable) & light->GetLightMask()))
  1961. continue;
  1962. // For point light, check that this drawable is inside the split shadow camera frustum
  1963. if (type == LIGHT_POINT && shadowCameraFrustum.IsInsideFast(drawable->GetWorldBoundingBox()) == OUTSIDE)
  1964. continue;
  1965. // Check shadow distance
  1966. // Note: as lights are processed threaded, it is possible a drawable's UpdateBatches() function is called several
  1967. // times. However, this should not cause problems as no scene modification happens at this point.
  1968. if (!drawable->IsInView(frame_, true))
  1969. drawable->UpdateBatches(frame_);
  1970. float maxShadowDistance = drawable->GetShadowDistance();
  1971. float drawDistance = drawable->GetDrawDistance();
  1972. if (drawDistance > 0.0f && (maxShadowDistance <= 0.0f || drawDistance < maxShadowDistance))
  1973. maxShadowDistance = drawDistance;
  1974. if (maxShadowDistance > 0.0f && drawable->GetDistance() > maxShadowDistance)
  1975. continue;
  1976. // Project shadow caster bounding box to light view space for visibility check
  1977. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1978. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1979. {
  1980. // Merge to shadow caster bounding box (only needed for focused spot lights) and add to the list
  1981. if (type == LIGHT_SPOT && light->GetShadowFocus().focus_)
  1982. {
  1983. lightProjBox = lightViewBox.Projected(lightProj);
  1984. query.shadowCasterBox_[splitIndex].Merge(lightProjBox);
  1985. }
  1986. query.shadowCasters_.Push(drawable);
  1987. }
  1988. }
  1989. query.shadowCasterEnd_[splitIndex] = query.shadowCasters_.Size();
  1990. }
  1991. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  1992. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  1993. {
  1994. if (shadowCamera->IsOrthographic())
  1995. {
  1996. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  1997. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  1998. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1999. }
  2000. else
  2001. {
  2002. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  2003. if (drawable->IsInView(frame_))
  2004. return true;
  2005. // For perspective lights, extrusion direction depends on the position of the shadow caster
  2006. Vector3 center = lightViewBox.Center();
  2007. Ray extrusionRay(center, center);
  2008. float extrusionDistance = shadowCamera->GetFarClip();
  2009. float originalDistance = Clamp(center.Length(), M_EPSILON, extrusionDistance);
  2010. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  2011. float sizeFactor = extrusionDistance / originalDistance;
  2012. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  2013. // than necessary, so the test will be conservative
  2014. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  2015. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  2016. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  2017. lightViewBox.Merge(extrudedBox);
  2018. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  2019. }
  2020. }
  2021. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  2022. {
  2023. unsigned width = shadowMap->GetWidth();
  2024. unsigned height = shadowMap->GetHeight();
  2025. switch (light->GetLightType())
  2026. {
  2027. case LIGHT_DIRECTIONAL:
  2028. {
  2029. int numSplits = light->GetNumShadowSplits();
  2030. if (numSplits == 1)
  2031. return IntRect(0, 0, width, height);
  2032. else if (numSplits == 2)
  2033. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  2034. else
  2035. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  2036. (splitIndex / 2 + 1) * height / 2);
  2037. }
  2038. case LIGHT_SPOT:
  2039. return IntRect(0, 0, width, height);
  2040. case LIGHT_POINT:
  2041. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  2042. (splitIndex / 2 + 1) * height / 3);
  2043. }
  2044. return IntRect();
  2045. }
  2046. void View::SetupShadowCameras(LightQueryResult& query)
  2047. {
  2048. Light* light = query.light_;
  2049. int splits = 0;
  2050. switch (light->GetLightType())
  2051. {
  2052. case LIGHT_DIRECTIONAL:
  2053. {
  2054. const CascadeParameters& cascade = light->GetShadowCascade();
  2055. float nearSplit = camera_->GetNearClip();
  2056. float farSplit;
  2057. int numSplits = light->GetNumShadowSplits();
  2058. while (splits < numSplits)
  2059. {
  2060. // If split is completely beyond camera far clip, we are done
  2061. if (nearSplit > camera_->GetFarClip())
  2062. break;
  2063. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  2064. if (farSplit <= nearSplit)
  2065. break;
  2066. // Setup the shadow camera for the split
  2067. Camera* shadowCamera = renderer_->GetShadowCamera();
  2068. query.shadowCameras_[splits] = shadowCamera;
  2069. query.shadowNearSplits_[splits] = nearSplit;
  2070. query.shadowFarSplits_[splits] = farSplit;
  2071. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit);
  2072. nearSplit = farSplit;
  2073. ++splits;
  2074. }
  2075. }
  2076. break;
  2077. case LIGHT_SPOT:
  2078. {
  2079. Camera* shadowCamera = renderer_->GetShadowCamera();
  2080. query.shadowCameras_[0] = shadowCamera;
  2081. Node* cameraNode = shadowCamera->GetNode();
  2082. Node* lightNode = light->GetNode();
  2083. cameraNode->SetTransform(lightNode->GetWorldPosition(), lightNode->GetWorldRotation());
  2084. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  2085. shadowCamera->SetFarClip(light->GetRange());
  2086. shadowCamera->SetFov(light->GetFov());
  2087. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  2088. splits = 1;
  2089. }
  2090. break;
  2091. case LIGHT_POINT:
  2092. {
  2093. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  2094. {
  2095. Camera* shadowCamera = renderer_->GetShadowCamera();
  2096. query.shadowCameras_[i] = shadowCamera;
  2097. Node* cameraNode = shadowCamera->GetNode();
  2098. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  2099. cameraNode->SetPosition(light->GetNode()->GetWorldPosition());
  2100. cameraNode->SetDirection(*directions[i]);
  2101. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  2102. shadowCamera->SetFarClip(light->GetRange());
  2103. shadowCamera->SetFov(90.0f);
  2104. shadowCamera->SetAspectRatio(1.0f);
  2105. }
  2106. splits = MAX_CUBEMAP_FACES;
  2107. }
  2108. break;
  2109. }
  2110. query.numSplits_ = splits;
  2111. }
  2112. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit)
  2113. {
  2114. Node* shadowCameraNode = shadowCamera->GetNode();
  2115. Node* lightNode = light->GetNode();
  2116. float extrusionDistance = camera_->GetFarClip();
  2117. const FocusParameters& parameters = light->GetShadowFocus();
  2118. // Calculate initial position & rotation
  2119. Vector3 pos = cameraNode_->GetWorldPosition() - extrusionDistance * lightNode->GetWorldDirection();
  2120. shadowCameraNode->SetTransform(pos, lightNode->GetWorldRotation());
  2121. // Calculate main camera shadowed frustum in light's view space
  2122. farSplit = Min(farSplit, camera_->GetFarClip());
  2123. // Use the scene Z bounds to limit frustum size if applicable
  2124. if (parameters.focus_)
  2125. {
  2126. nearSplit = Max(minZ_, nearSplit);
  2127. farSplit = Min(maxZ_, farSplit);
  2128. }
  2129. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  2130. Polyhedron frustumVolume;
  2131. frustumVolume.Define(splitFrustum);
  2132. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  2133. if (parameters.focus_)
  2134. {
  2135. BoundingBox litGeometriesBox;
  2136. for (unsigned i = 0; i < geometries_.Size(); ++i)
  2137. {
  2138. Drawable* drawable = geometries_[i];
  2139. if (drawable->GetMinZ() <= farSplit && drawable->GetMaxZ() >= nearSplit &&
  2140. (GetLightMask(drawable) & light->GetLightMask()))
  2141. litGeometriesBox.Merge(drawable->GetWorldBoundingBox());
  2142. }
  2143. if (litGeometriesBox.defined_)
  2144. {
  2145. frustumVolume.Clip(litGeometriesBox);
  2146. // If volume became empty, restore it to avoid zero size
  2147. if (frustumVolume.Empty())
  2148. frustumVolume.Define(splitFrustum);
  2149. }
  2150. }
  2151. // Transform frustum volume to light space
  2152. const Matrix3x4& lightView = shadowCamera->GetView();
  2153. frustumVolume.Transform(lightView);
  2154. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  2155. BoundingBox shadowBox;
  2156. if (!parameters.nonUniform_)
  2157. shadowBox.Define(Sphere(frustumVolume));
  2158. else
  2159. shadowBox.Define(frustumVolume);
  2160. shadowCamera->SetOrthographic(true);
  2161. shadowCamera->SetAspectRatio(1.0f);
  2162. shadowCamera->SetNearClip(0.0f);
  2163. shadowCamera->SetFarClip(shadowBox.max_.z_);
  2164. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  2165. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  2166. }
  2167. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  2168. const BoundingBox& shadowCasterBox)
  2169. {
  2170. const FocusParameters& parameters = light->GetShadowFocus();
  2171. float shadowMapWidth = (float)(shadowViewport.Width());
  2172. LightType type = light->GetLightType();
  2173. if (type == LIGHT_DIRECTIONAL)
  2174. {
  2175. BoundingBox shadowBox;
  2176. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  2177. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  2178. shadowBox.min_.y_ = -shadowBox.max_.y_;
  2179. shadowBox.min_.x_ = -shadowBox.max_.x_;
  2180. // Requantize and snap to shadow map texels
  2181. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  2182. }
  2183. if (type == LIGHT_SPOT && parameters.focus_)
  2184. {
  2185. float viewSizeX = Max(Abs(shadowCasterBox.min_.x_), Abs(shadowCasterBox.max_.x_));
  2186. float viewSizeY = Max(Abs(shadowCasterBox.min_.y_), Abs(shadowCasterBox.max_.y_));
  2187. float viewSize = Max(viewSizeX, viewSizeY);
  2188. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  2189. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  2190. float quantize = parameters.quantize_ * invOrthoSize;
  2191. float minView = parameters.minView_ * invOrthoSize;
  2192. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  2193. if (viewSize < 1.0f)
  2194. shadowCamera->SetZoom(1.0f / viewSize);
  2195. }
  2196. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  2197. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  2198. if (shadowCamera->GetZoom() >= 1.0f)
  2199. {
  2200. if (light->GetLightType() != LIGHT_POINT)
  2201. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  2202. else
  2203. {
  2204. #ifdef URHO3D_OPENGL
  2205. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  2206. #else
  2207. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  2208. #endif
  2209. }
  2210. }
  2211. }
  2212. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  2213. const BoundingBox& viewBox)
  2214. {
  2215. Node* shadowCameraNode = shadowCamera->GetNode();
  2216. const FocusParameters& parameters = light->GetShadowFocus();
  2217. float shadowMapWidth = (float)(shadowViewport.Width());
  2218. float minX = viewBox.min_.x_;
  2219. float minY = viewBox.min_.y_;
  2220. float maxX = viewBox.max_.x_;
  2221. float maxY = viewBox.max_.y_;
  2222. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  2223. Vector2 viewSize(maxX - minX, maxY - minY);
  2224. // Quantize size to reduce swimming
  2225. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  2226. if (parameters.nonUniform_)
  2227. {
  2228. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  2229. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  2230. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  2231. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  2232. }
  2233. else if (parameters.focus_)
  2234. {
  2235. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  2236. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  2237. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  2238. viewSize.y_ = viewSize.x_;
  2239. }
  2240. shadowCamera->SetOrthoSize(viewSize);
  2241. // Center shadow camera to the view space bounding box
  2242. Quaternion rot(shadowCameraNode->GetWorldRotation());
  2243. Vector3 adjust(center.x_, center.y_, 0.0f);
  2244. shadowCameraNode->Translate(rot * adjust, TS_WORLD);
  2245. // If the shadow map viewport is known, snap to whole texels
  2246. if (shadowMapWidth > 0.0f)
  2247. {
  2248. Vector3 viewPos(rot.Inverse() * shadowCameraNode->GetWorldPosition());
  2249. // Take into account that shadow map border will not be used
  2250. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  2251. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  2252. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  2253. shadowCameraNode->Translate(rot * snap, TS_WORLD);
  2254. }
  2255. }
  2256. void View::FindZone(Drawable* drawable)
  2257. {
  2258. Vector3 center = drawable->GetWorldBoundingBox().Center();
  2259. int bestPriority = M_MIN_INT;
  2260. Zone* newZone = 0;
  2261. // If bounding box center is in view, the zone assignment is conclusive also for next frames. Otherwise it is temporary
  2262. // (possibly incorrect) and must be re-evaluated on the next frame
  2263. bool temporary = !camera_->GetFrustum().IsInside(center);
  2264. // First check if the current zone remains a conclusive result
  2265. Zone* lastZone = drawable->GetZone();
  2266. if (lastZone && (lastZone->GetViewMask() & camera_->GetViewMask()) && lastZone->GetPriority() >= highestZonePriority_ &&
  2267. (drawable->GetZoneMask() & lastZone->GetZoneMask()) && lastZone->IsInside(center))
  2268. newZone = lastZone;
  2269. else
  2270. {
  2271. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  2272. {
  2273. Zone* zone = *i;
  2274. int priority = zone->GetPriority();
  2275. if (priority > bestPriority && (drawable->GetZoneMask() & zone->GetZoneMask()) && zone->IsInside(center))
  2276. {
  2277. newZone = zone;
  2278. bestPriority = priority;
  2279. }
  2280. }
  2281. }
  2282. drawable->SetZone(newZone, temporary);
  2283. }
  2284. Technique* View::GetTechnique(Drawable* drawable, Material* material)
  2285. {
  2286. if (!material)
  2287. {
  2288. const Vector<TechniqueEntry>& techniques = renderer_->GetDefaultMaterial()->GetTechniques();
  2289. return techniques.Size() ? techniques[0].technique_ : (Technique*)0;
  2290. }
  2291. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  2292. // If only one technique, no choice
  2293. if (techniques.Size() == 1)
  2294. return techniques[0].technique_;
  2295. else
  2296. {
  2297. float lodDistance = drawable->GetLodDistance();
  2298. // Check for suitable technique. Techniques should be ordered like this:
  2299. // Most distant & highest quality
  2300. // Most distant & lowest quality
  2301. // Second most distant & highest quality
  2302. // ...
  2303. for (unsigned i = 0; i < techniques.Size(); ++i)
  2304. {
  2305. const TechniqueEntry& entry = techniques[i];
  2306. Technique* tech = entry.technique_;
  2307. if (!tech || (!tech->IsSupported()) || materialQuality_ < entry.qualityLevel_)
  2308. continue;
  2309. if (lodDistance >= entry.lodDistance_)
  2310. return tech;
  2311. }
  2312. // If no suitable technique found, fallback to the last
  2313. return techniques.Size() ? techniques.Back().technique_ : (Technique*)0;
  2314. }
  2315. }
  2316. void View::CheckMaterialForAuxView(Material* material)
  2317. {
  2318. const HashMap<TextureUnit, SharedPtr<Texture> >& textures = material->GetTextures();
  2319. for (HashMap<TextureUnit, SharedPtr<Texture> >::ConstIterator i = textures.Begin(); i != textures.End(); ++i)
  2320. {
  2321. Texture* texture = i->second_.Get();
  2322. if (texture && texture->GetUsage() == TEXTURE_RENDERTARGET)
  2323. {
  2324. // Have to check cube & 2D textures separately
  2325. if (texture->GetType() == Texture2D::GetTypeStatic())
  2326. {
  2327. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  2328. RenderSurface* target = tex2D->GetRenderSurface();
  2329. if (target && target->GetUpdateMode() == SURFACE_UPDATEVISIBLE)
  2330. target->QueueUpdate();
  2331. }
  2332. else if (texture->GetType() == TextureCube::GetTypeStatic())
  2333. {
  2334. TextureCube* texCube = static_cast<TextureCube*>(texture);
  2335. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  2336. {
  2337. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  2338. if (target && target->GetUpdateMode() == SURFACE_UPDATEVISIBLE)
  2339. target->QueueUpdate();
  2340. }
  2341. }
  2342. }
  2343. }
  2344. // Flag as processed so we can early-out next time we come across this material on the same frame
  2345. material->MarkForAuxView(frame_.frameNumber_);
  2346. }
  2347. void View::AddBatchToQueue(BatchQueue& batchQueue, Batch& batch, Technique* tech, bool allowInstancing, bool allowShadows)
  2348. {
  2349. if (!batch.material_)
  2350. batch.material_ = renderer_->GetDefaultMaterial();
  2351. // Convert to instanced if possible
  2352. if (allowInstancing && batch.geometryType_ == GEOM_STATIC && batch.geometry_->GetIndexBuffer())
  2353. batch.geometryType_ = GEOM_INSTANCED;
  2354. if (batch.geometryType_ == GEOM_INSTANCED)
  2355. {
  2356. BatchGroupKey key(batch);
  2357. HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchQueue.batchGroups_.Find(key);
  2358. if (i == batchQueue.batchGroups_.End())
  2359. {
  2360. // Create a new group based on the batch
  2361. // In case the group remains below the instancing limit, do not enable instancing shaders yet
  2362. BatchGroup newGroup(batch);
  2363. newGroup.geometryType_ = GEOM_STATIC;
  2364. renderer_->SetBatchShaders(newGroup, tech, allowShadows);
  2365. newGroup.CalculateSortKey();
  2366. i = batchQueue.batchGroups_.Insert(MakePair(key, newGroup));
  2367. }
  2368. int oldSize = i->second_.instances_.Size();
  2369. i->second_.AddTransforms(batch);
  2370. // Convert to using instancing shaders when the instancing limit is reached
  2371. if (oldSize < minInstances_ && (int)i->second_.instances_.Size() >= minInstances_)
  2372. {
  2373. i->second_.geometryType_ = GEOM_INSTANCED;
  2374. renderer_->SetBatchShaders(i->second_, tech, allowShadows);
  2375. i->second_.CalculateSortKey();
  2376. }
  2377. }
  2378. else
  2379. {
  2380. renderer_->SetBatchShaders(batch, tech, allowShadows);
  2381. batch.CalculateSortKey();
  2382. // If batch is static with multiple world transforms and cannot instance, we must push copies of the batch individually
  2383. if (batch.geometryType_ == GEOM_STATIC && batch.numWorldTransforms_ > 1)
  2384. {
  2385. unsigned numTransforms = batch.numWorldTransforms_;
  2386. batch.numWorldTransforms_ = 1;
  2387. for (unsigned i = 0; i < numTransforms; ++i)
  2388. {
  2389. // Move the transform pointer to generate copies of the batch which only refer to 1 world transform
  2390. batchQueue.batches_.Push(batch);
  2391. ++batch.worldTransform_;
  2392. }
  2393. }
  2394. else
  2395. batchQueue.batches_.Push(batch);
  2396. }
  2397. }
  2398. void View::PrepareInstancingBuffer()
  2399. {
  2400. PROFILE(PrepareInstancingBuffer);
  2401. unsigned totalInstances = 0;
  2402. for (HashMap<unsigned, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  2403. totalInstances += i->second_.GetNumInstances();
  2404. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2405. {
  2406. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2407. totalInstances += i->shadowSplits_[j].shadowBatches_.GetNumInstances();
  2408. totalInstances += i->litBaseBatches_.GetNumInstances();
  2409. totalInstances += i->litBatches_.GetNumInstances();
  2410. }
  2411. if (!totalInstances || !renderer_->ResizeInstancingBuffer(totalInstances))
  2412. return;
  2413. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  2414. unsigned freeIndex = 0;
  2415. void* dest = instancingBuffer->Lock(0, totalInstances, true);
  2416. if (!dest)
  2417. return;
  2418. for (HashMap<unsigned, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  2419. i->second_.SetTransforms(dest, freeIndex);
  2420. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2421. {
  2422. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2423. i->shadowSplits_[j].shadowBatches_.SetTransforms(dest, freeIndex);
  2424. i->litBaseBatches_.SetTransforms(dest, freeIndex);
  2425. i->litBatches_.SetTransforms(dest, freeIndex);
  2426. }
  2427. instancingBuffer->Unlock();
  2428. }
  2429. void View::SetupLightVolumeBatch(Batch& batch)
  2430. {
  2431. Light* light = batch.lightQueue_->light_;
  2432. LightType type = light->GetLightType();
  2433. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  2434. float lightDist;
  2435. graphics_->SetBlendMode(light->IsNegative() ? BLEND_SUBTRACT : BLEND_ADD);
  2436. graphics_->SetDepthBias(0.0f, 0.0f);
  2437. graphics_->SetDepthWrite(false);
  2438. graphics_->SetFillMode(FILL_SOLID);
  2439. graphics_->SetClipPlane(false);
  2440. if (type != LIGHT_DIRECTIONAL)
  2441. {
  2442. if (type == LIGHT_POINT)
  2443. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  2444. else
  2445. lightDist = light->GetFrustum().Distance(cameraPos);
  2446. // Draw front faces if not inside light volume
  2447. if (lightDist < camera_->GetNearClip() * 2.0f)
  2448. {
  2449. renderer_->SetCullMode(CULL_CW, camera_);
  2450. graphics_->SetDepthTest(CMP_GREATER);
  2451. }
  2452. else
  2453. {
  2454. renderer_->SetCullMode(CULL_CCW, camera_);
  2455. graphics_->SetDepthTest(CMP_LESSEQUAL);
  2456. }
  2457. }
  2458. else
  2459. {
  2460. // In case the same camera is used for multiple views with differing aspect ratios (not recommended)
  2461. // refresh the directional light's model transform before rendering
  2462. light->GetVolumeTransform(camera_);
  2463. graphics_->SetCullMode(CULL_NONE);
  2464. graphics_->SetDepthTest(CMP_ALWAYS);
  2465. }
  2466. graphics_->SetScissorTest(false);
  2467. if (!noStencil_)
  2468. graphics_->SetStencilTest(true, CMP_NOTEQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 0, light->GetLightMask());
  2469. else
  2470. graphics_->SetStencilTest(false);
  2471. }
  2472. void View::RenderShadowMap(const LightBatchQueue& queue)
  2473. {
  2474. PROFILE(RenderShadowMap);
  2475. Texture2D* shadowMap = queue.shadowMap_;
  2476. graphics_->SetTexture(TU_SHADOWMAP, 0);
  2477. graphics_->SetColorWrite(false);
  2478. graphics_->SetFillMode(FILL_SOLID);
  2479. graphics_->SetClipPlane(false);
  2480. graphics_->SetStencilTest(false);
  2481. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  2482. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  2483. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  2484. graphics_->SetDepthStencil(shadowMap);
  2485. graphics_->SetViewport(IntRect(0, 0, shadowMap->GetWidth(), shadowMap->GetHeight()));
  2486. graphics_->Clear(CLEAR_DEPTH);
  2487. // Set shadow depth bias
  2488. const BiasParameters& parameters = queue.light_->GetShadowBias();
  2489. // Render each of the splits
  2490. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  2491. {
  2492. float multiplier = 1.0f;
  2493. // For directional light cascade splits, adjust depth bias according to the far clip ratio of the splits
  2494. if (i > 0 && queue.light_->GetLightType() == LIGHT_DIRECTIONAL)
  2495. {
  2496. multiplier = Max(queue.shadowSplits_[i].shadowCamera_->GetFarClip() / queue.shadowSplits_[0].shadowCamera_->GetFarClip(), 1.0f);
  2497. multiplier = 1.0f + (multiplier - 1.0f) * queue.light_->GetShadowCascade().biasAutoAdjust_;
  2498. // Quantize multiplier to prevent creation of too many rasterizer states on D3D11
  2499. multiplier = (int)(multiplier * 10.0f) / 10.0f;
  2500. }
  2501. // Perform further modification of depth bias on OpenGL ES, as shadow calculations' precision is limited
  2502. float addition = 0.0f;
  2503. #ifdef GL_ES_VERSION_2_0
  2504. multiplier *= renderer_->GetMobileShadowBiasMul();
  2505. addition = renderer_->GetMobileShadowBiasAdd();
  2506. #endif
  2507. graphics_->SetDepthBias(multiplier * parameters.constantBias_ + addition, multiplier * parameters.slopeScaledBias_);
  2508. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  2509. if (!shadowQueue.shadowBatches_.IsEmpty())
  2510. {
  2511. graphics_->SetViewport(shadowQueue.shadowViewport_);
  2512. shadowQueue.shadowBatches_.Draw(this, false, false, true);
  2513. }
  2514. }
  2515. graphics_->SetColorWrite(true);
  2516. graphics_->SetDepthBias(0.0f, 0.0f);
  2517. }
  2518. RenderSurface* View::GetDepthStencil(RenderSurface* renderTarget)
  2519. {
  2520. // If using the backbuffer, return the backbuffer depth-stencil
  2521. if (!renderTarget)
  2522. return 0;
  2523. // Then check for linked depth-stencil
  2524. RenderSurface* depthStencil = renderTarget->GetLinkedDepthStencil();
  2525. // Finally get one from Renderer
  2526. if (!depthStencil)
  2527. depthStencil = renderer_->GetDepthStencil(renderTarget->GetWidth(), renderTarget->GetHeight());
  2528. return depthStencil;
  2529. }
  2530. }