View.cpp 119 KB

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