View.cpp 119 KB

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