View.cpp 125 KB

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