View.cpp 119 KB

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