View.cpp 123 KB

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