View.cpp 127 KB

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