View.cpp 127 KB

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