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