View.cpp 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "DebugRenderer.h"
  26. #include "Geometry.h"
  27. #include "Graphics.h"
  28. #include "GraphicsImpl.h"
  29. #include "Log.h"
  30. #include "Material.h"
  31. #include "OcclusionBuffer.h"
  32. #include "Octree.h"
  33. #include "Renderer.h"
  34. #include "ResourceCache.h"
  35. #include "PostProcess.h"
  36. #include "Profiler.h"
  37. #include "Scene.h"
  38. #include "ShaderVariation.h"
  39. #include "Skybox.h"
  40. #include "Sort.h"
  41. #include "Technique.h"
  42. #include "Texture2D.h"
  43. #include "TextureCube.h"
  44. #include "VertexBuffer.h"
  45. #include "View.h"
  46. #include "WorkQueue.h"
  47. #include "Zone.h"
  48. #include "DebugNew.h"
  49. static const Vector3 directions[] =
  50. {
  51. Vector3(1.0f, 0.0f, 0.0f),
  52. Vector3(-1.0f, 0.0f, 0.0f),
  53. Vector3(0.0f, 1.0f, 0.0f),
  54. Vector3(0.0f, -1.0f, 0.0f),
  55. Vector3(0.0f, 0.0f, 1.0f),
  56. Vector3(0.0f, 0.0f, -1.0f)
  57. };
  58. static const int CHECK_DRAWABLES_PER_WORK_ITEM = 64;
  59. static const float LIGHT_INTENSITY_THRESHOLD = 0.001f;
  60. /// %Frustum octree query for shadowcasters.
  61. class ShadowCasterOctreeQuery : public OctreeQuery
  62. {
  63. public:
  64. /// Construct with frustum and query parameters.
  65. ShadowCasterOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  66. unsigned viewMask = DEFAULT_VIEWMASK) :
  67. OctreeQuery(result, drawableFlags, viewMask),
  68. frustum_(frustum)
  69. {
  70. }
  71. /// Intersection test for an octant.
  72. virtual Intersection TestOctant(const BoundingBox& box, bool inside)
  73. {
  74. if (inside)
  75. return INSIDE;
  76. else
  77. return frustum_.IsInside(box);
  78. }
  79. /// Intersection test for drawables.
  80. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  81. {
  82. while (start != end)
  83. {
  84. Drawable* drawable = *start;
  85. if ((drawable->GetDrawableFlags() & drawableFlags_) && drawable->GetCastShadows() && drawable->IsVisible() &&
  86. (drawable->GetViewMask() & viewMask_))
  87. {
  88. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  89. result_.Push(drawable);
  90. }
  91. ++start;
  92. }
  93. }
  94. /// Frustum.
  95. Frustum frustum_;
  96. };
  97. /// %Frustum octree query for zones and occluders.
  98. class ZoneOccluderOctreeQuery : public OctreeQuery
  99. {
  100. public:
  101. /// Construct with frustum and query parameters.
  102. ZoneOccluderOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  103. unsigned viewMask = DEFAULT_VIEWMASK) :
  104. OctreeQuery(result, drawableFlags, viewMask),
  105. frustum_(frustum)
  106. {
  107. }
  108. /// Intersection test for an octant.
  109. virtual Intersection TestOctant(const BoundingBox& box, bool inside)
  110. {
  111. if (inside)
  112. return INSIDE;
  113. else
  114. return frustum_.IsInside(box);
  115. }
  116. /// Intersection test for drawables.
  117. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  118. {
  119. while (start != end)
  120. {
  121. Drawable* drawable = *start;
  122. unsigned char flags = drawable->GetDrawableFlags();
  123. if ((flags == DRAWABLE_ZONE || (flags == DRAWABLE_GEOMETRY && drawable->IsOccluder())) && drawable->IsVisible() &&
  124. (drawable->GetViewMask() & viewMask_))
  125. {
  126. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  127. result_.Push(drawable);
  128. }
  129. ++start;
  130. }
  131. }
  132. /// Frustum.
  133. Frustum frustum_;
  134. };
  135. /// %Frustum octree query with occlusion.
  136. class OccludedFrustumOctreeQuery : public OctreeQuery
  137. {
  138. public:
  139. /// Construct with frustum, occlusion buffer and query parameters.
  140. OccludedFrustumOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, OcclusionBuffer* buffer, unsigned char
  141. drawableFlags = DRAWABLE_ANY, unsigned viewMask = DEFAULT_VIEWMASK) :
  142. OctreeQuery(result, drawableFlags, viewMask),
  143. frustum_(frustum),
  144. buffer_(buffer)
  145. {
  146. }
  147. /// Intersection test for an octant.
  148. virtual Intersection TestOctant(const BoundingBox& box, bool inside)
  149. {
  150. if (inside)
  151. return buffer_->IsVisible(box) ? INSIDE : OUTSIDE;
  152. else
  153. {
  154. Intersection result = frustum_.IsInside(box);
  155. if (result != OUTSIDE && !buffer_->IsVisible(box))
  156. result = OUTSIDE;
  157. return result;
  158. }
  159. }
  160. /// Intersection test for drawables. Note: drawable occlusion is performed later in worker threads.
  161. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  162. {
  163. while (start != end)
  164. {
  165. Drawable* drawable = *start;
  166. if ((drawable->GetDrawableFlags() & drawableFlags_) && drawable->IsVisible() &&
  167. (drawable->GetViewMask() & viewMask_))
  168. {
  169. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  170. result_.Push(drawable);
  171. }
  172. ++start;
  173. }
  174. }
  175. /// Frustum.
  176. Frustum frustum_;
  177. /// Occlusion buffer.
  178. OcclusionBuffer* buffer_;
  179. };
  180. void CheckVisibilityWork(const WorkItem* item, unsigned threadIndex)
  181. {
  182. View* view = reinterpret_cast<View*>(item->aux_);
  183. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  184. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  185. OcclusionBuffer* buffer = view->occlusionBuffer_;
  186. const Matrix3x4& viewMatrix = view->camera_->GetInverseWorldTransform();
  187. while (start != end)
  188. {
  189. Drawable* drawable = *start++;
  190. drawable->UpdateBatches(view->frame_);
  191. // If draw distance non-zero, check it
  192. float maxDistance = drawable->GetDrawDistance();
  193. if ((maxDistance <= 0.0f || drawable->GetDistance() <= maxDistance) && (!buffer || !drawable->IsOccludee() ||
  194. buffer->IsVisible(drawable->GetWorldBoundingBox())))
  195. {
  196. drawable->MarkInView(view->frame_);
  197. // For geometries, clear lights and calculate view space Z range
  198. if (drawable->GetDrawableFlags() & DRAWABLE_GEOMETRY)
  199. {
  200. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  201. Vector3 center = geomBox.Center();
  202. float viewCenterZ = viewMatrix.m20_ * center.x_ + viewMatrix.m21_ * center.y_ + viewMatrix.m22_ * center.z_ +
  203. viewMatrix.m23_;
  204. Vector3 edge = geomBox.Size() * 0.5f;
  205. float viewEdgeZ = Abs(viewMatrix.m20_) * edge.x_ + Abs(viewMatrix.m21_) * edge.y_ + Abs(viewMatrix.m22_) *
  206. edge.z_;
  207. drawable->SetMinMaxZ(viewCenterZ - viewEdgeZ, viewCenterZ + viewEdgeZ);
  208. drawable->ClearLights();
  209. }
  210. }
  211. }
  212. }
  213. void ProcessLightWork(const WorkItem* item, unsigned threadIndex)
  214. {
  215. View* view = reinterpret_cast<View*>(item->aux_);
  216. LightQueryResult* query = reinterpret_cast<LightQueryResult*>(item->start_);
  217. view->ProcessLight(*query, threadIndex);
  218. }
  219. void UpdateDrawableGeometriesWork(const WorkItem* item, unsigned threadIndex)
  220. {
  221. const FrameInfo& frame = *(reinterpret_cast<FrameInfo*>(item->aux_));
  222. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  223. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  224. while (start != end)
  225. {
  226. Drawable* drawable = *start;
  227. drawable->UpdateGeometry(frame);
  228. ++start;
  229. }
  230. }
  231. void SortBatchQueueFrontToBackWork(const WorkItem* item, unsigned threadIndex)
  232. {
  233. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  234. queue->SortFrontToBack();
  235. }
  236. void SortBatchQueueBackToFrontWork(const WorkItem* item, unsigned threadIndex)
  237. {
  238. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  239. queue->SortBackToFront();
  240. }
  241. void SortLightQueueWork(const WorkItem* item, unsigned threadIndex)
  242. {
  243. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  244. start->litBatches_.SortFrontToBack();
  245. }
  246. void SortShadowQueueWork(const WorkItem* item, unsigned threadIndex)
  247. {
  248. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  249. for (unsigned i = 0; i < start->shadowSplits_.Size(); ++i)
  250. start->shadowSplits_[i].shadowBatches_.SortFrontToBack();
  251. }
  252. OBJECTTYPESTATIC(View);
  253. View::View(Context* context) :
  254. Object(context),
  255. graphics_(GetSubsystem<Graphics>()),
  256. renderer_(GetSubsystem<Renderer>()),
  257. octree_(0),
  258. camera_(0),
  259. cameraZone_(0),
  260. farClipZone_(0),
  261. renderTarget_(0)
  262. {
  263. frame_.camera_ = 0;
  264. // Create octree query vector for each thread
  265. tempDrawables_.Resize(GetSubsystem<WorkQueue>()->GetNumThreads() + 1);
  266. }
  267. View::~View()
  268. {
  269. }
  270. bool View::Define(RenderSurface* renderTarget, Viewport* viewport)
  271. {
  272. Scene* scene = viewport->GetScene();
  273. Camera* camera = viewport->GetCamera();
  274. if (!scene || !camera || !camera->GetNode())
  275. return false;
  276. // If scene is loading asynchronously, it is incomplete and should not be rendered
  277. if (scene->IsAsyncLoading())
  278. return false;
  279. Octree* octree = scene->GetComponent<Octree>();
  280. if (!octree)
  281. return false;
  282. renderMode_ = renderer_->GetRenderMode();
  283. octree_ = octree;
  284. camera_ = camera;
  285. cameraNode_ = camera->GetNode();
  286. renderTarget_ = renderTarget;
  287. // Get active post-processing effects on the viewport
  288. const Vector<SharedPtr<PostProcess> >& postProcesses = viewport->GetPostProcesses();
  289. postProcesses_.Clear();
  290. for (Vector<SharedPtr<PostProcess> >::ConstIterator i = postProcesses.Begin(); i != postProcesses.End(); ++i)
  291. {
  292. PostProcess* effect = i->Get();
  293. if (effect && effect->IsActive())
  294. postProcesses_.Push(*i);
  295. }
  296. // Validate the rect and calculate size. If zero rect, use whole rendertarget size
  297. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  298. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  299. const IntRect& rect = viewport->GetRect();
  300. if (rect != IntRect::ZERO)
  301. {
  302. viewRect_.left_ = Clamp(rect.left_, 0, rtWidth - 1);
  303. viewRect_.top_ = Clamp(rect.top_, 0, rtHeight - 1);
  304. viewRect_.right_ = Clamp(rect.right_, viewRect_.left_ + 1, rtWidth);
  305. viewRect_.bottom_ = Clamp(rect.bottom_, viewRect_.top_ + 1, rtHeight);
  306. }
  307. else
  308. viewRect_ = IntRect(0, 0, rtWidth, rtHeight);
  309. viewSize_ = IntVector2(viewRect_.right_ - viewRect_.left_, viewRect_.bottom_ - viewRect_.top_);
  310. rtSize_ = IntVector2(rtWidth, rtHeight);
  311. // On OpenGL flip the viewport if rendering to a texture for consistent UV addressing with Direct3D9
  312. #ifdef USE_OPENGL
  313. if (renderTarget_)
  314. {
  315. viewRect_.bottom_ = rtSize_.y_ - viewRect_.top_;
  316. viewRect_.top_ = viewRect_.bottom_ - viewSize_.y_;
  317. }
  318. #endif
  319. drawShadows_ = renderer_->GetDrawShadows();
  320. materialQuality_ = renderer_->GetMaterialQuality();
  321. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  322. // Set possible quality overrides from the camera
  323. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  324. if (viewOverrideFlags & VO_LOW_MATERIAL_QUALITY)
  325. materialQuality_ = QUALITY_LOW;
  326. if (viewOverrideFlags & VO_DISABLE_SHADOWS)
  327. drawShadows_ = false;
  328. if (viewOverrideFlags & VO_DISABLE_OCCLUSION)
  329. maxOccluderTriangles_ = 0;
  330. return true;
  331. }
  332. void View::Update(const FrameInfo& frame)
  333. {
  334. if (!camera_ || !octree_)
  335. return;
  336. frame_.camera_ = camera_;
  337. frame_.timeStep_ = frame.timeStep_;
  338. frame_.frameNumber_ = frame.frameNumber_;
  339. frame_.viewSize_ = viewSize_;
  340. int maxSortedInstances = renderer_->GetMaxSortedInstances();
  341. // Clear screen buffers, geometry, light, occluder & batch lists
  342. screenBuffers_.Clear();
  343. geometries_.Clear();
  344. shadowGeometries_.Clear();
  345. lights_.Clear();
  346. zones_.Clear();
  347. occluders_.Clear();
  348. baseQueue_.Clear(maxSortedInstances);
  349. preAlphaQueue_.Clear(maxSortedInstances);
  350. gbufferQueue_.Clear(maxSortedInstances);
  351. alphaQueue_.Clear(maxSortedInstances);
  352. postAlphaQueue_.Clear(maxSortedInstances);
  353. vertexLightQueues_.Clear();
  354. // Do not update if camera projection is illegal
  355. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  356. if (!camera_->IsProjectionValid())
  357. return;
  358. // Set automatic aspect ratio if required
  359. if (camera_->GetAutoAspectRatio())
  360. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  361. GetDrawables();
  362. GetBatches();
  363. UpdateGeometries();
  364. }
  365. void View::Render()
  366. {
  367. if (!octree_ || !camera_)
  368. return;
  369. // Allocate screen buffers for post-processing and blitting as necessary
  370. AllocateScreenBuffers();
  371. // Forget parameter sources from the previous view
  372. graphics_->ClearParameterSources();
  373. // If stream offset is supported, write all instance transforms to a single large buffer
  374. // Else we must lock the instance buffer for each batch group
  375. if (renderer_->GetDynamicInstancing() && graphics_->GetStreamOffsetSupport())
  376. PrepareInstancingBuffer();
  377. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  378. // again to ensure correct projection will be used
  379. if (camera_->GetAutoAspectRatio())
  380. camera_->SetAspectRatio((float)(viewSize_.x_) / (float)(viewSize_.y_));
  381. graphics_->SetColorWrite(true);
  382. // Bind the face selection and indirection cube maps for point light shadows
  383. if (renderer_->GetDrawShadows())
  384. {
  385. graphics_->SetTexture(TU_FACESELECT, renderer_->GetFaceSelectCubeMap());
  386. graphics_->SetTexture(TU_INDIRECTION, renderer_->GetIndirectionCubeMap());
  387. }
  388. // Set "view texture" to prevent destination texture sampling in case we do not render to the destination directly
  389. // ie. when using deferred rendering and/or doing post-processing
  390. if (renderTarget_)
  391. graphics_->SetViewTexture(renderTarget_->GetParentTexture());
  392. // On OpenGL, flip the projection if rendering to a texture so that the texture can be addressed in the same way
  393. // as a render texture produced on Direct3D9
  394. #ifdef USE_OPENGL
  395. if (renderTarget_)
  396. camera_->SetFlipVertical(true);
  397. #endif
  398. // Render
  399. if (renderMode_ == RENDER_FORWARD)
  400. RenderBatchesForward();
  401. else
  402. RenderBatchesDeferred();
  403. #ifdef USE_OPENGL
  404. camera_->SetFlipVertical(false);
  405. #endif
  406. graphics_->SetDepthBias(0.0f, 0.0f);
  407. graphics_->SetScissorTest(false);
  408. graphics_->SetStencilTest(false);
  409. graphics_->SetViewTexture(0);
  410. graphics_->ResetStreamFrequencies();
  411. // Run post-processes or framebuffer blitting now
  412. if (screenBuffers_.Size())
  413. {
  414. if (postProcesses_.Size())
  415. RunPostProcesses();
  416. else
  417. BlitFramebuffer();
  418. }
  419. // If this is a main view, draw the associated debug geometry now
  420. if (!renderTarget_)
  421. {
  422. DebugRenderer* debug = octree_->GetComponent<DebugRenderer>();
  423. if (debug)
  424. {
  425. debug->SetView(camera_);
  426. debug->Render();
  427. }
  428. }
  429. // "Forget" the camera, octree and zone after rendering
  430. camera_ = 0;
  431. octree_ = 0;
  432. cameraZone_ = 0;
  433. farClipZone_ = 0;
  434. occlusionBuffer_ = 0;
  435. frame_.camera_ = 0;
  436. }
  437. void View::GetDrawables()
  438. {
  439. PROFILE(GetDrawables);
  440. WorkQueue* queue = GetSubsystem<WorkQueue>();
  441. PODVector<Drawable*>& tempDrawables = tempDrawables_[0];
  442. // Get zones and occluders first
  443. {
  444. ZoneOccluderOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_ZONE);
  445. octree_->GetDrawables(query);
  446. }
  447. highestZonePriority_ = M_MIN_INT;
  448. int bestPriority = M_MIN_INT;
  449. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  450. // Get default zone first in case we do not have zones defined
  451. Zone* defaultZone = renderer_->GetDefaultZone();
  452. cameraZone_ = farClipZone_ = defaultZone;
  453. for (PODVector<Drawable*>::ConstIterator i = tempDrawables.Begin(); i != tempDrawables.End(); ++i)
  454. {
  455. Drawable* drawable = *i;
  456. unsigned char flags = drawable->GetDrawableFlags();
  457. if (flags & DRAWABLE_ZONE)
  458. {
  459. Zone* zone = static_cast<Zone*>(drawable);
  460. zones_.Push(zone);
  461. int priority = zone->GetPriority();
  462. if (priority > highestZonePriority_)
  463. highestZonePriority_ = priority;
  464. if (zone->IsInside(cameraPos) && priority > bestPriority)
  465. {
  466. cameraZone_ = zone;
  467. bestPriority = priority;
  468. }
  469. }
  470. else
  471. occluders_.Push(drawable);
  472. }
  473. // Determine the zone at far clip distance. If not found, or camera zone has override mode, use camera zone
  474. cameraZoneOverride_ = cameraZone_->GetOverride();
  475. if (!cameraZoneOverride_)
  476. {
  477. Vector3 farClipPos = cameraPos + cameraNode_->GetWorldDirection() * Vector3(0.0f, 0.0f, camera_->GetFarClip());
  478. bestPriority = M_MIN_INT;
  479. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  480. {
  481. int priority = (*i)->GetPriority();
  482. if ((*i)->IsInside(farClipPos) && priority > bestPriority)
  483. {
  484. farClipZone_ = *i;
  485. bestPriority = priority;
  486. }
  487. }
  488. }
  489. if (farClipZone_ == defaultZone)
  490. farClipZone_ = cameraZone_;
  491. // If occlusion in use, get & render the occluders
  492. occlusionBuffer_ = 0;
  493. if (maxOccluderTriangles_ > 0)
  494. {
  495. UpdateOccluders(occluders_, camera_);
  496. if (occluders_.Size())
  497. {
  498. PROFILE(DrawOcclusion);
  499. occlusionBuffer_ = renderer_->GetOcclusionBuffer(camera_);
  500. DrawOccluders(occlusionBuffer_, occluders_);
  501. }
  502. }
  503. // Get lights and geometries. Coarse occlusion for octants is used at this point
  504. if (occlusionBuffer_)
  505. {
  506. OccludedFrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), occlusionBuffer_, DRAWABLE_GEOMETRY |
  507. DRAWABLE_LIGHT);
  508. octree_->GetDrawables(query);
  509. }
  510. else
  511. {
  512. FrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  513. octree_->GetDrawables(query);
  514. }
  515. // Check drawable occlusion and find zones for moved drawables in worker threads
  516. {
  517. WorkItem item;
  518. item.workFunction_ = CheckVisibilityWork;
  519. item.aux_ = this;
  520. PODVector<Drawable*>::Iterator start = tempDrawables.Begin();
  521. while (start != tempDrawables.End())
  522. {
  523. PODVector<Drawable*>::Iterator end = tempDrawables.End();
  524. if (end - start > CHECK_DRAWABLES_PER_WORK_ITEM)
  525. end = start + CHECK_DRAWABLES_PER_WORK_ITEM;
  526. item.start_ = &(*start);
  527. item.end_ = &(*end);
  528. queue->AddWorkItem(item);
  529. start = end;
  530. }
  531. queue->Complete();
  532. }
  533. // Sort into geometries & lights, and build visible scene bounding boxes in world and view space
  534. sceneBox_.min_ = sceneBox_.max_ = Vector3::ZERO;
  535. sceneBox_.defined_ = false;
  536. minZ_ = M_INFINITY;
  537. maxZ_ = 0.0f;
  538. const Matrix3x4& view = camera_->GetInverseWorldTransform();
  539. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  540. {
  541. Drawable* drawable = tempDrawables[i];
  542. if (!drawable->IsInView(frame_))
  543. continue;
  544. if (drawable->GetDrawableFlags() & DRAWABLE_GEOMETRY)
  545. {
  546. // Find zone for the drawable if necessary
  547. if (!drawable->GetZone() && !cameraZoneOverride_)
  548. FindZone(drawable);
  549. // Expand the scene bounding box and Z range (skybox not included because of infinite size) and store the drawawble
  550. if (drawable->GetType() != Skybox::GetTypeStatic())
  551. {
  552. sceneBox_.Merge(drawable->GetWorldBoundingBox());
  553. minZ_ = Min(minZ_, drawable->GetMinZ());
  554. maxZ_ = Max(maxZ_, drawable->GetMaxZ());
  555. }
  556. geometries_.Push(drawable);
  557. }
  558. else
  559. {
  560. Light* light = static_cast<Light*>(drawable);
  561. // Skip lights which are so dim that they can not contribute to a rendertarget
  562. if (light->GetColor().Intensity() > LIGHT_INTENSITY_THRESHOLD)
  563. lights_.Push(light);
  564. }
  565. }
  566. if (minZ_ == M_INFINITY)
  567. minZ_ = 0.0f;
  568. // Sort the lights to brightest/closest first
  569. for (unsigned i = 0; i < lights_.Size(); ++i)
  570. {
  571. Light* light = lights_[i];
  572. light->SetIntensitySortValue(camera_->GetDistance(light->GetNode()->GetWorldPosition()));
  573. light->SetLightQueue(0);
  574. }
  575. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  576. }
  577. void View::GetBatches()
  578. {
  579. WorkQueue* queue = GetSubsystem<WorkQueue>();
  580. PODVector<Light*> vertexLights;
  581. // Process lit geometries and shadow casters for each light
  582. {
  583. PROFILE(ProcessLights);
  584. lightQueryResults_.Resize(lights_.Size());
  585. WorkItem item;
  586. item.workFunction_ = ProcessLightWork;
  587. item.aux_ = this;
  588. for (unsigned i = 0; i < lightQueryResults_.Size(); ++i)
  589. {
  590. LightQueryResult& query = lightQueryResults_[i];
  591. query.light_ = lights_[i];
  592. item.start_ = &query;
  593. queue->AddWorkItem(item);
  594. }
  595. // Ensure all lights have been processed before proceeding
  596. queue->Complete();
  597. }
  598. // Build light queues and lit batches
  599. {
  600. PROFILE(GetLightBatches);
  601. // Preallocate light queues: per-pixel lights which have lit geometries
  602. unsigned numLightQueues = 0;
  603. unsigned usedLightQueues = 0;
  604. for (Vector<LightQueryResult>::ConstIterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  605. {
  606. if (!i->light_->GetPerVertex() && i->litGeometries_.Size())
  607. ++numLightQueues;
  608. }
  609. lightQueues_.Resize(numLightQueues);
  610. maxLightsDrawables_.Clear();
  611. unsigned maxSortedInstances = renderer_->GetMaxSortedInstances();
  612. for (Vector<LightQueryResult>::Iterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  613. {
  614. LightQueryResult& query = *i;
  615. // If light has no affected geometries, no need to process further
  616. if (query.litGeometries_.Empty())
  617. continue;
  618. Light* light = query.light_;
  619. // Per-pixel light
  620. if (!light->GetPerVertex())
  621. {
  622. unsigned shadowSplits = query.numSplits_;
  623. // Initialize light queue and store it to the light so that it can be found later
  624. LightBatchQueue& lightQueue = lightQueues_[usedLightQueues++];
  625. light->SetLightQueue(&lightQueue);
  626. lightQueue.light_ = light;
  627. lightQueue.shadowMap_ = 0;
  628. lightQueue.litBatches_.Clear(maxSortedInstances);
  629. lightQueue.volumeBatches_.Clear();
  630. // Allocate shadow map now
  631. if (shadowSplits > 0)
  632. {
  633. lightQueue.shadowMap_ = renderer_->GetShadowMap(light, camera_, viewSize_.x_, viewSize_.y_);
  634. // If did not manage to get a shadow map, convert the light to unshadowed
  635. if (!lightQueue.shadowMap_)
  636. shadowSplits = 0;
  637. }
  638. // Setup shadow batch queues
  639. lightQueue.shadowSplits_.Resize(shadowSplits);
  640. for (unsigned j = 0; j < shadowSplits; ++j)
  641. {
  642. ShadowBatchQueue& shadowQueue = lightQueue.shadowSplits_[j];
  643. Camera* shadowCamera = query.shadowCameras_[j];
  644. shadowQueue.shadowCamera_ = shadowCamera;
  645. shadowQueue.nearSplit_ = query.shadowNearSplits_[j];
  646. shadowQueue.farSplit_ = query.shadowFarSplits_[j];
  647. shadowQueue.shadowBatches_.Clear(maxSortedInstances);
  648. // Setup the shadow split viewport and finalize shadow camera parameters
  649. shadowQueue.shadowViewport_ = GetShadowMapViewport(light, j, lightQueue.shadowMap_);
  650. FinalizeShadowCamera(shadowCamera, light, shadowQueue.shadowViewport_, query.shadowCasterBox_[j]);
  651. // Loop through shadow casters
  652. for (PODVector<Drawable*>::ConstIterator k = query.shadowCasters_.Begin() + query.shadowCasterBegin_[j];
  653. k < query.shadowCasters_.Begin() + query.shadowCasterEnd_[j]; ++k)
  654. {
  655. Drawable* drawable = *k;
  656. if (!drawable->IsInView(frame_, false))
  657. {
  658. drawable->MarkInView(frame_, false);
  659. shadowGeometries_.Push(drawable);
  660. }
  661. Zone* zone = GetZone(drawable);
  662. const Vector<SourceBatch>& batches = drawable->GetBatches();
  663. for (unsigned l = 0; l < batches.Size(); ++l)
  664. {
  665. const SourceBatch& srcBatch = batches[l];
  666. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  667. if (!srcBatch.geometry_ || !tech)
  668. continue;
  669. Pass* pass = tech->GetPass(PASS_SHADOW);
  670. // Skip if material has no shadow pass
  671. if (!pass)
  672. continue;
  673. Batch destBatch(srcBatch);
  674. destBatch.pass_ = pass;
  675. destBatch.camera_ = shadowCamera;
  676. destBatch.zone_ = zone;
  677. destBatch.lightQueue_ = &lightQueue;
  678. AddBatchToQueue(shadowQueue.shadowBatches_, destBatch, tech);
  679. }
  680. }
  681. }
  682. // Process lit geometries
  683. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  684. {
  685. Drawable* drawable = *j;
  686. drawable->AddLight(light);
  687. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  688. if (!drawable->GetMaxLights())
  689. GetLitBatches(drawable, lightQueue);
  690. else
  691. maxLightsDrawables_.Insert(drawable);
  692. }
  693. // In deferred modes, store the light volume batch now
  694. if (renderMode_ != RENDER_FORWARD)
  695. {
  696. Batch volumeBatch;
  697. volumeBatch.geometry_ = renderer_->GetLightGeometry(light);
  698. volumeBatch.worldTransform_ = &light->GetVolumeTransform(camera_);
  699. volumeBatch.overrideView_ = light->GetLightType() == LIGHT_DIRECTIONAL;
  700. volumeBatch.camera_ = camera_;
  701. volumeBatch.lightQueue_ = &lightQueue;
  702. volumeBatch.distance_ = light->GetDistance();
  703. volumeBatch.material_ = 0;
  704. volumeBatch.pass_ = 0;
  705. volumeBatch.zone_ = 0;
  706. renderer_->SetLightVolumeBatchShaders(volumeBatch);
  707. lightQueue.volumeBatches_.Push(volumeBatch);
  708. }
  709. }
  710. // Per-vertex light
  711. else
  712. {
  713. // Add the vertex light to lit drawables. It will be processed later during base pass batch generation
  714. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  715. {
  716. Drawable* drawable = *j;
  717. drawable->AddVertexLight(light);
  718. }
  719. }
  720. }
  721. }
  722. // Process drawables with limited per-pixel light count
  723. if (maxLightsDrawables_.Size())
  724. {
  725. PROFILE(GetMaxLightsBatches);
  726. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  727. {
  728. Drawable* drawable = *i;
  729. drawable->LimitLights();
  730. const PODVector<Light*>& lights = drawable->GetLights();
  731. for (unsigned i = 0; i < lights.Size(); ++i)
  732. {
  733. Light* light = lights[i];
  734. // Find the correct light queue again
  735. LightBatchQueue* queue = light->GetLightQueue();
  736. if (queue)
  737. GetLitBatches(drawable, *queue);
  738. }
  739. }
  740. }
  741. // Build base pass batches
  742. {
  743. PROFILE(GetBaseBatches);
  744. hasZeroLightMask_ = false;
  745. for (PODVector<Drawable*>::ConstIterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  746. {
  747. Drawable* drawable = *i;
  748. Zone* zone = GetZone(drawable);
  749. const Vector<SourceBatch>& batches = drawable->GetBatches();
  750. const PODVector<Light*>& drawableVertexLights = drawable->GetVertexLights();
  751. if (!drawableVertexLights.Empty())
  752. drawable->LimitVertexLights();
  753. for (unsigned j = 0; j < batches.Size(); ++j)
  754. {
  755. const SourceBatch& srcBatch = batches[j];
  756. // Check here if the material refers to a rendertarget texture with camera(s) attached
  757. // Only check this for the main view (null rendertarget)
  758. if (srcBatch.material_ && srcBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_ && !renderTarget_)
  759. CheckMaterialForAuxView(srcBatch.material_);
  760. // If already has a lit base pass, skip (forward rendering only)
  761. if (j < 32 && drawable->HasBasePass(j))
  762. continue;
  763. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  764. if (!srcBatch.geometry_ || !tech)
  765. continue;
  766. Batch destBatch(srcBatch);
  767. destBatch.camera_ = camera_;
  768. destBatch.zone_ = zone;
  769. destBatch.isBase_ = true;
  770. destBatch.pass_ = 0;
  771. destBatch.lightMask_ = GetLightMask(drawable);
  772. // In deferred modes check for G-buffer and material passes first
  773. if (renderMode_ == RENDER_PREPASS)
  774. {
  775. destBatch.pass_ = tech->GetPass(PASS_PREPASS);
  776. if (destBatch.pass_)
  777. {
  778. // If the opaque object has a zero lightmask, have to skip light buffer optimization
  779. if (!hasZeroLightMask_ && (!(GetLightMask(drawable) & 0xff)))
  780. hasZeroLightMask_ = true;
  781. // Allow G-buffer pass instancing only if lightmask matches zone lightmask
  782. AddBatchToQueue(gbufferQueue_, destBatch, tech, destBatch.lightMask_ == (zone->GetLightMask() & 0xff));
  783. destBatch.pass_ = tech->GetPass(PASS_MATERIAL);
  784. }
  785. }
  786. if (renderMode_ == RENDER_DEFERRED)
  787. destBatch.pass_ = tech->GetPass(PASS_DEFERRED);
  788. // Next check for forward unlit base pass
  789. if (!destBatch.pass_)
  790. destBatch.pass_ = tech->GetPass(PASS_BASE);
  791. if (destBatch.pass_)
  792. {
  793. // Check for vertex lights (both forward unlit, light pre-pass material pass, and deferred G-buffer)
  794. if (!drawableVertexLights.Empty())
  795. {
  796. // For a deferred opaque batch, check if the vertex lights include converted per-pixel lights, and remove
  797. // them to prevent double-lighting
  798. if (renderMode_ != RENDER_FORWARD && destBatch.pass_->GetBlendMode() == BLEND_REPLACE)
  799. {
  800. vertexLights.Clear();
  801. for (unsigned i = 0; i < drawableVertexLights.Size(); ++i)
  802. {
  803. if (drawableVertexLights[i]->GetPerVertex())
  804. vertexLights.Push(drawableVertexLights[i]);
  805. }
  806. }
  807. else
  808. vertexLights = drawableVertexLights;
  809. if (!vertexLights.Empty())
  810. {
  811. // Find a vertex light queue. If not found, create new
  812. unsigned long long hash = GetVertexLightQueueHash(vertexLights);
  813. HashMap<unsigned long long, LightBatchQueue>::Iterator i = vertexLightQueues_.Find(hash);
  814. if (i == vertexLightQueues_.End())
  815. {
  816. i = vertexLightQueues_.Insert(MakePair(hash, LightBatchQueue()));
  817. i->second_.light_ = 0;
  818. i->second_.shadowMap_ = 0;
  819. i->second_.vertexLights_ = vertexLights;
  820. }
  821. destBatch.lightQueue_ = &(i->second_);
  822. }
  823. }
  824. // Check whether batch is opaque or transparent
  825. if (destBatch.pass_->GetBlendMode() == BLEND_REPLACE)
  826. {
  827. if (destBatch.pass_->GetType() != PASS_DEFERRED)
  828. AddBatchToQueue(baseQueue_, destBatch, tech);
  829. else
  830. {
  831. // Allow G-buffer pass instancing only if lightmask matches zone lightmask
  832. AddBatchToQueue(gbufferQueue_, destBatch, tech, destBatch.lightMask_ == (destBatch.zone_->GetLightMask() & 0xff));
  833. }
  834. }
  835. else
  836. {
  837. // Transparent batches can not be instanced
  838. AddBatchToQueue(alphaQueue_, destBatch, tech, false);
  839. }
  840. continue;
  841. }
  842. // If no pass found so far, finally check for pre-alpha / post-alpha custom passes
  843. destBatch.pass_ = tech->GetPass(PASS_PREALPHA);
  844. if (destBatch.pass_)
  845. {
  846. AddBatchToQueue(preAlphaQueue_, destBatch, tech);
  847. continue;
  848. }
  849. destBatch.pass_ = tech->GetPass(PASS_POSTALPHA);
  850. if (destBatch.pass_)
  851. {
  852. // Post-alpha pass is treated similarly as alpha, and is not instanced
  853. AddBatchToQueue(postAlphaQueue_, destBatch, tech, false);
  854. continue;
  855. }
  856. }
  857. }
  858. }
  859. }
  860. void View::UpdateGeometries()
  861. {
  862. PROFILE(SortAndUpdateGeometry);
  863. WorkQueue* queue = GetSubsystem<WorkQueue>();
  864. // Sort batches
  865. {
  866. WorkItem item;
  867. item.workFunction_ = SortBatchQueueFrontToBackWork;
  868. item.start_ = &baseQueue_;
  869. queue->AddWorkItem(item);
  870. item.start_ = &preAlphaQueue_;
  871. queue->AddWorkItem(item);
  872. if (renderMode_ != RENDER_FORWARD)
  873. {
  874. item.start_ = &gbufferQueue_;
  875. queue->AddWorkItem(item);
  876. }
  877. item.workFunction_ = SortBatchQueueBackToFrontWork;
  878. item.start_ = &alphaQueue_;
  879. queue->AddWorkItem(item);
  880. item.start_ = &postAlphaQueue_;
  881. queue->AddWorkItem(item);
  882. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  883. {
  884. item.workFunction_ = SortLightQueueWork;
  885. item.start_ = &(*i);
  886. queue->AddWorkItem(item);
  887. if (i->shadowSplits_.Size())
  888. {
  889. item.workFunction_ = SortShadowQueueWork;
  890. queue->AddWorkItem(item);
  891. }
  892. }
  893. }
  894. // Update geometries. Split into threaded and non-threaded updates.
  895. {
  896. nonThreadedGeometries_.Clear();
  897. threadedGeometries_.Clear();
  898. for (PODVector<Drawable*>::Iterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  899. {
  900. UpdateGeometryType type = (*i)->GetUpdateGeometryType();
  901. if (type == UPDATE_MAIN_THREAD)
  902. nonThreadedGeometries_.Push(*i);
  903. else if (type == UPDATE_WORKER_THREAD)
  904. threadedGeometries_.Push(*i);
  905. }
  906. for (PODVector<Drawable*>::Iterator i = shadowGeometries_.Begin(); i != shadowGeometries_.End(); ++i)
  907. {
  908. UpdateGeometryType type = (*i)->GetUpdateGeometryType();
  909. if (type == UPDATE_MAIN_THREAD)
  910. nonThreadedGeometries_.Push(*i);
  911. else if (type == UPDATE_WORKER_THREAD)
  912. threadedGeometries_.Push(*i);
  913. }
  914. if (threadedGeometries_.Size())
  915. {
  916. WorkItem item;
  917. item.workFunction_ = UpdateDrawableGeometriesWork;
  918. item.aux_ = const_cast<FrameInfo*>(&frame_);
  919. PODVector<Drawable*>::Iterator start = threadedGeometries_.Begin();
  920. while (start != threadedGeometries_.End())
  921. {
  922. PODVector<Drawable*>::Iterator end = threadedGeometries_.End();
  923. if (end - start > DRAWABLES_PER_WORK_ITEM)
  924. end = start + DRAWABLES_PER_WORK_ITEM;
  925. item.start_ = &(*start);
  926. item.end_ = &(*end);
  927. queue->AddWorkItem(item);
  928. start = end;
  929. }
  930. }
  931. // While the work queue is processed, update non-threaded geometries
  932. for (PODVector<Drawable*>::ConstIterator i = nonThreadedGeometries_.Begin(); i != nonThreadedGeometries_.End(); ++i)
  933. (*i)->UpdateGeometry(frame_);
  934. }
  935. // Finally ensure all threaded work has completed
  936. queue->Complete();
  937. }
  938. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue)
  939. {
  940. Light* light = lightQueue.light_;
  941. Zone* zone = GetZone(drawable);
  942. const Vector<SourceBatch>& batches = drawable->GetBatches();
  943. bool hasAmbientGradient = zone->GetAmbientGradient() && zone->GetAmbientStartColor() != zone->GetAmbientEndColor();
  944. // Shadows on transparencies can only be rendered if shadow maps are not reused
  945. bool allowTransparentShadows = !renderer_->GetReuseShadowMaps();
  946. bool allowLitBase = light == drawable->GetFirstLight() && drawable->GetVertexLights().Empty() && !hasAmbientGradient;
  947. for (unsigned i = 0; i < batches.Size(); ++i)
  948. {
  949. const SourceBatch& srcBatch = batches[i];
  950. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  951. if (!srcBatch.geometry_ || !tech)
  952. continue;
  953. // Do not create pixel lit forward passes for materials that render into the G-buffer
  954. if ((renderMode_ == RENDER_PREPASS && tech->HasPass(PASS_PREPASS)) || (renderMode_ == RENDER_DEFERRED &&
  955. tech->HasPass(PASS_DEFERRED)))
  956. continue;
  957. Batch destBatch(srcBatch);
  958. // Check for lit base pass. Because it uses the replace blend mode, it must be ensured to be the first light
  959. // Also vertex lighting or ambient gradient require the non-lit base pass, so skip in those cases
  960. if (i < 32 && allowLitBase)
  961. {
  962. destBatch.pass_ = tech->GetPass(PASS_LITBASE);
  963. if (destBatch.pass_)
  964. {
  965. destBatch.isBase_ = true;
  966. drawable->SetBasePass(i);
  967. }
  968. else
  969. destBatch.pass_ = tech->GetPass(PASS_LIGHT);
  970. }
  971. else
  972. destBatch.pass_ = tech->GetPass(PASS_LIGHT);
  973. // Skip if material does not receive light at all
  974. if (!destBatch.pass_)
  975. continue;
  976. destBatch.camera_ = camera_;
  977. destBatch.lightQueue_ = &lightQueue;
  978. destBatch.zone_ = zone;
  979. // Check from the ambient pass whether the object is opaque or transparent
  980. Pass* ambientPass = tech->GetPass(PASS_BASE);
  981. if (!ambientPass || ambientPass->GetBlendMode() == BLEND_REPLACE)
  982. AddBatchToQueue(lightQueue.litBatches_, destBatch, tech);
  983. else
  984. {
  985. // Transparent batches can not be instanced
  986. AddBatchToQueue(alphaQueue_, destBatch, tech, false, allowTransparentShadows);
  987. }
  988. }
  989. }
  990. void View::RenderBatchesForward()
  991. {
  992. // If using hardware multisampling with post-processing, render to the backbuffer first and then resolve
  993. bool resolve = screenBuffers_.Size() && !renderTarget_ && graphics_->GetMultiSample() > 1;
  994. RenderSurface* renderTarget = (screenBuffers_.Size() && !resolve) ? screenBuffers_[0]->GetRenderSurface() : renderTarget_;
  995. RenderSurface* depthStencil = GetDepthStencil(renderTarget);
  996. // If not reusing shadowmaps, render all of them first
  997. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  998. {
  999. PROFILE(RenderShadowMaps);
  1000. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1001. {
  1002. if (i->shadowMap_)
  1003. RenderShadowMap(*i);
  1004. }
  1005. }
  1006. graphics_->SetRenderTarget(0, renderTarget);
  1007. graphics_->SetDepthStencil(depthStencil);
  1008. graphics_->SetViewport(viewRect_);
  1009. #ifndef GL_ES_VERSION_2_0
  1010. graphics_->Clear(CLEAR_DEPTH | CLEAR_STENCIL);
  1011. #else
  1012. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH, farClipZone_->GetFogColor());
  1013. #endif
  1014. // Render opaque object unlit base pass
  1015. if (!baseQueue_.IsEmpty())
  1016. {
  1017. PROFILE(RenderBase);
  1018. baseQueue_.Draw(graphics_, renderer_);
  1019. }
  1020. // Render shadow maps + opaque objects' additive lighting
  1021. if (!lightQueues_.Empty())
  1022. {
  1023. PROFILE(RenderLights);
  1024. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1025. {
  1026. // If reusing shadowmaps, render each of them before the lit batches
  1027. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1028. {
  1029. RenderShadowMap(*i);
  1030. graphics_->SetRenderTarget(0, renderTarget);
  1031. graphics_->SetDepthStencil(depthStencil);
  1032. graphics_->SetViewport(viewRect_);
  1033. }
  1034. i->litBatches_.Draw(i->light_, graphics_, renderer_);
  1035. }
  1036. }
  1037. graphics_->SetScissorTest(false);
  1038. graphics_->SetStencilTest(false);
  1039. #ifndef GL_ES_VERSION_2_0
  1040. // At this point clear the parts of viewport not occupied by opaque geometry with fog color.
  1041. // On OpenGL ES an ordinary color clear has been performed beforehand instead
  1042. graphics_->SetBlendMode(BLEND_REPLACE);
  1043. graphics_->SetColorWrite(true);
  1044. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1045. graphics_->SetDepthWrite(false);
  1046. graphics_->SetScissorTest(false);
  1047. graphics_->SetStencilTest(false);
  1048. graphics_->SetShaders(renderer_->GetVertexShader("Basic"), renderer_->GetPixelShader("Basic"));
  1049. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, farClipZone_->GetFogColor());
  1050. graphics_->ClearParameterSource(SP_MATERIAL);
  1051. DrawFullscreenQuad(camera_, false);
  1052. #endif
  1053. // Render pre-alpha custom pass
  1054. if (!preAlphaQueue_.IsEmpty())
  1055. {
  1056. PROFILE(RenderPreAlpha);
  1057. preAlphaQueue_.Draw(graphics_, renderer_);
  1058. }
  1059. // Render transparent objects (both base passes & additive lighting)
  1060. if (!alphaQueue_.IsEmpty())
  1061. {
  1062. PROFILE(RenderAlpha);
  1063. alphaQueue_.Draw(graphics_, renderer_, true);
  1064. }
  1065. // Render post-alpha custom pass
  1066. if (!postAlphaQueue_.IsEmpty())
  1067. {
  1068. PROFILE(RenderPostAlpha);
  1069. postAlphaQueue_.Draw(graphics_, renderer_);
  1070. }
  1071. // Resolve multisampled backbuffer now if necessary
  1072. if (resolve)
  1073. graphics_->ResolveToTexture(screenBuffers_[0], viewRect_);
  1074. }
  1075. void View::RenderBatchesDeferred()
  1076. {
  1077. // If not reusing shadowmaps, render all of them first
  1078. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  1079. {
  1080. PROFILE(RenderShadowMaps);
  1081. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1082. {
  1083. if (i->shadowMap_)
  1084. RenderShadowMap(*i);
  1085. }
  1086. }
  1087. bool hwDepth = graphics_->GetHardwareDepthSupport();
  1088. // In light prepass mode the albedo buffer is used for light accumulation instead
  1089. Texture2D* albedoBuffer = renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, Graphics::GetRGBAFormat());
  1090. Texture2D* normalBuffer = renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, Graphics::GetRGBAFormat());
  1091. Texture2D* depthBuffer = renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, hwDepth ? Graphics::GetDepthStencilFormat() :
  1092. Graphics::GetLinearDepthFormat());
  1093. RenderSurface* renderTarget = screenBuffers_.Size() ? screenBuffers_[0]->GetRenderSurface() : renderTarget_;
  1094. RenderSurface* depthStencil = hwDepth ? depthBuffer->GetRenderSurface() : renderer_->GetDepthStencil(rtSize_.x_, rtSize_.y_);
  1095. if (renderMode_ == RENDER_PREPASS)
  1096. {
  1097. graphics_->SetRenderTarget(0, normalBuffer);
  1098. if (!hwDepth)
  1099. graphics_->SetRenderTarget(1, depthBuffer);
  1100. }
  1101. else
  1102. {
  1103. graphics_->SetRenderTarget(0, renderTarget);
  1104. graphics_->SetRenderTarget(1, albedoBuffer);
  1105. graphics_->SetRenderTarget(2, normalBuffer);
  1106. if (!hwDepth)
  1107. graphics_->SetRenderTarget(3, depthBuffer);
  1108. }
  1109. graphics_->SetDepthStencil(depthStencil);
  1110. graphics_->SetViewport(viewRect_);
  1111. graphics_->Clear(CLEAR_DEPTH | CLEAR_STENCIL);
  1112. // Render G-buffer batches
  1113. if (!gbufferQueue_.IsEmpty())
  1114. {
  1115. PROFILE(RenderGBuffer);
  1116. gbufferQueue_.Draw(graphics_, renderer_, false, true);
  1117. }
  1118. // Clear the light accumulation buffer (light pre-pass only.) However, skip the clear if the first light is a directional
  1119. // light with full mask
  1120. RenderSurface* lightRenderTarget = renderMode_ == RENDER_PREPASS ? albedoBuffer->GetRenderSurface() : renderTarget;
  1121. if (renderMode_ == RENDER_PREPASS)
  1122. {
  1123. bool optimizeLightBuffer = !hasZeroLightMask_ && !lightQueues_.Empty() && lightQueues_.Front().light_->GetLightType() ==
  1124. LIGHT_DIRECTIONAL && (lightQueues_.Front().light_->GetLightMask() & 0xff) == 0xff;
  1125. graphics_->SetRenderTarget(0, lightRenderTarget);
  1126. graphics_->ResetRenderTarget(1);
  1127. graphics_->SetDepthStencil(depthStencil);
  1128. graphics_->SetViewport(viewRect_);
  1129. if (!optimizeLightBuffer)
  1130. graphics_->Clear(CLEAR_COLOR);
  1131. }
  1132. else
  1133. {
  1134. graphics_->ResetRenderTarget(1);
  1135. graphics_->ResetRenderTarget(2);
  1136. graphics_->ResetRenderTarget(3);
  1137. }
  1138. // Render shadow maps + light volumes
  1139. if (!lightQueues_.Empty())
  1140. {
  1141. PROFILE(RenderLights);
  1142. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1143. {
  1144. // If reusing shadowmaps, render each of them before the lit batches
  1145. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1146. {
  1147. RenderShadowMap(*i);
  1148. graphics_->SetRenderTarget(0, lightRenderTarget);
  1149. graphics_->SetDepthStencil(depthStencil);
  1150. graphics_->SetViewport(viewRect_);
  1151. }
  1152. if (renderMode_ == RENDER_DEFERRED)
  1153. graphics_->SetTexture(TU_ALBEDOBUFFER, albedoBuffer);
  1154. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  1155. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  1156. for (unsigned j = 0; j < i->volumeBatches_.Size(); ++j)
  1157. {
  1158. SetupLightVolumeBatch(i->volumeBatches_[j]);
  1159. i->volumeBatches_[j].Draw(graphics_, renderer_);
  1160. }
  1161. }
  1162. }
  1163. graphics_->SetTexture(TU_ALBEDOBUFFER, 0);
  1164. graphics_->SetTexture(TU_NORMALBUFFER, 0);
  1165. graphics_->SetTexture(TU_DEPTHBUFFER, 0);
  1166. if (renderMode_ == RENDER_PREPASS)
  1167. {
  1168. graphics_->SetRenderTarget(0, renderTarget);
  1169. graphics_->SetDepthStencil(depthStencil);
  1170. graphics_->SetViewport(viewRect_);
  1171. }
  1172. // At this point clear the parts of viewport not occupied by opaque geometry with fog color
  1173. graphics_->SetBlendMode(BLEND_REPLACE);
  1174. graphics_->SetColorWrite(true);
  1175. graphics_->SetDepthTest(CMP_ALWAYS);
  1176. graphics_->SetDepthWrite(false);
  1177. graphics_->SetScissorTest(false);
  1178. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 0);
  1179. graphics_->SetShaders(renderer_->GetVertexShader("Basic"), renderer_->GetPixelShader("Basic"));
  1180. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, farClipZone_->GetFogColor());
  1181. graphics_->ClearParameterSource(SP_MATERIAL);
  1182. DrawFullscreenQuad(camera_, false);
  1183. // Render opaque objects with deferred lighting result (light pre-pass only)
  1184. if (!baseQueue_.IsEmpty())
  1185. {
  1186. PROFILE(RenderBase);
  1187. graphics_->SetTexture(TU_LIGHTBUFFER, renderMode_ == RENDER_PREPASS ? albedoBuffer : 0);
  1188. baseQueue_.Draw(graphics_, renderer_);
  1189. graphics_->SetTexture(TU_LIGHTBUFFER, 0);
  1190. }
  1191. // Render pre-alpha custom pass
  1192. if (!preAlphaQueue_.IsEmpty())
  1193. {
  1194. PROFILE(RenderPreAlpha);
  1195. preAlphaQueue_.Draw(graphics_, renderer_);
  1196. }
  1197. // Render transparent objects (both base passes & additive lighting)
  1198. if (!alphaQueue_.IsEmpty())
  1199. {
  1200. PROFILE(RenderAlpha);
  1201. alphaQueue_.Draw(graphics_, renderer_, true);
  1202. }
  1203. // Render post-alpha custom pass
  1204. if (!postAlphaQueue_.IsEmpty())
  1205. {
  1206. PROFILE(RenderPostAlpha);
  1207. postAlphaQueue_.Draw(graphics_, renderer_);
  1208. }
  1209. }
  1210. void View::AllocateScreenBuffers()
  1211. {
  1212. unsigned neededBuffers = 0;
  1213. #ifdef USE_OPENGL
  1214. // Due to FBO limitations, in OpenGL deferred modes need to render to texture first and then blit to the backbuffer
  1215. // Also, if rendering to a texture with deferred rendering, it must be RGBA to comply with the rest of the buffers.
  1216. if (renderMode_ != RENDER_FORWARD && (!renderTarget_ || (renderMode_ == RENDER_DEFERRED &&
  1217. renderTarget_->GetParentTexture()->GetFormat() != Graphics::GetRGBAFormat())))
  1218. neededBuffers = 1;
  1219. #endif
  1220. unsigned postProcessPasses = 0;
  1221. for (unsigned i = 0; i < postProcesses_.Size(); ++i)
  1222. postProcessPasses += postProcesses_[i]->GetNumPasses();
  1223. // If more than one post-process pass, need 2 buffers for ping-pong rendering
  1224. if (postProcessPasses)
  1225. neededBuffers = Min((int)postProcessPasses, 2);
  1226. unsigned format = Graphics::GetRGBFormat();
  1227. #ifdef USE_OPENGL
  1228. if (renderMode_ == RENDER_DEFERRED)
  1229. format = Graphics::GetRGBAFormat();
  1230. #endif
  1231. // Allocate screen buffers with filtering active in case the post-processing effects need that
  1232. for (unsigned i = 0; i < neededBuffers; ++i)
  1233. screenBuffers_.Push(renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, format, true));
  1234. }
  1235. void View::BlitFramebuffer()
  1236. {
  1237. // Blit the final image to destination rendertarget
  1238. /// \todo Depth is reset to far plane, so geometry drawn after the view can not be depth tested
  1239. graphics_->SetBlendMode(BLEND_REPLACE);
  1240. graphics_->SetDepthTest(CMP_ALWAYS);
  1241. graphics_->SetDepthWrite(true);
  1242. graphics_->SetScissorTest(false);
  1243. graphics_->SetStencilTest(false);
  1244. graphics_->SetRenderTarget(0, renderTarget_);
  1245. graphics_->SetDepthStencil(GetDepthStencil(renderTarget_));
  1246. graphics_->SetViewport(viewRect_);
  1247. String shaderName = "CopyFramebuffer";
  1248. graphics_->SetShaders(renderer_->GetVertexShader(shaderName), renderer_->GetPixelShader(shaderName));
  1249. float rtWidth = (float)rtSize_.x_;
  1250. float rtHeight = (float)rtSize_.y_;
  1251. float widthRange = 0.5f * viewSize_.x_ / rtWidth;
  1252. float heightRange = 0.5f * viewSize_.y_ / rtHeight;
  1253. #ifdef USE_OPENGL
  1254. Vector4 bufferUVOffset(((float)viewRect_.left_) / rtWidth + widthRange,
  1255. 1.0f - (((float)viewRect_.top_) / rtHeight + heightRange), widthRange, heightRange);
  1256. #else
  1257. Vector4 bufferUVOffset((0.5f + (float)viewRect_.left_) / rtWidth + widthRange,
  1258. (0.5f + (float)viewRect_.top_) / rtHeight + heightRange, widthRange, heightRange);
  1259. #endif
  1260. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  1261. graphics_->SetTexture(TU_DIFFUSE, screenBuffers_[0]);
  1262. DrawFullscreenQuad(camera_, false);
  1263. }
  1264. void View::RunPostProcesses()
  1265. {
  1266. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1267. // Ping-pong buffer indices for read and write
  1268. unsigned readRtIndex = 0;
  1269. unsigned writeRtIndex = screenBuffers_.Size() - 1;
  1270. graphics_->SetBlendMode(BLEND_REPLACE);
  1271. graphics_->SetDepthTest(CMP_ALWAYS);
  1272. graphics_->SetScissorTest(false);
  1273. graphics_->SetStencilTest(false);
  1274. for (unsigned i = 0; i < postProcesses_.Size(); ++i)
  1275. {
  1276. PostProcess* effect = postProcesses_[i];
  1277. // For each effect, rendertargets can be re-used. Allocate them now
  1278. renderer_->SaveScreenBufferAllocations();
  1279. const HashMap<StringHash, PostProcessRenderTarget>& renderTargetInfos = effect->GetRenderTargets();
  1280. HashMap<StringHash, Texture2D*> renderTargets;
  1281. for (HashMap<StringHash, PostProcessRenderTarget>::ConstIterator j = renderTargetInfos.Begin(); j !=
  1282. renderTargetInfos.End(); ++j)
  1283. {
  1284. unsigned width = j->second_.size_.x_;
  1285. unsigned height = j->second_.size_.y_;
  1286. if (j->second_.sizeDivisor_)
  1287. {
  1288. width = viewSize_.x_ / width;
  1289. height = viewSize_.y_ / height;
  1290. }
  1291. renderTargets[j->first_] = renderer_->GetScreenBuffer(width, height, j->second_.format_, j->second_.filtered_);
  1292. }
  1293. // Run each effect pass
  1294. for (unsigned j = 0; j < effect->GetNumPasses(); ++j)
  1295. {
  1296. PostProcessPass* pass = effect->GetPass(j);
  1297. bool lastPass = (i == postProcesses_.Size() - 1) && (j == effect->GetNumPasses() - 1);
  1298. bool swapBuffers = false;
  1299. // Write depth on the last pass only
  1300. graphics_->SetDepthWrite(lastPass);
  1301. // Set output rendertarget
  1302. RenderSurface* rt = 0;
  1303. String output = pass->GetOutput().ToLower();
  1304. if (output == "viewport")
  1305. {
  1306. if (!lastPass)
  1307. {
  1308. rt = screenBuffers_[writeRtIndex]->GetRenderSurface();
  1309. swapBuffers = true;
  1310. }
  1311. else
  1312. rt = renderTarget_;
  1313. graphics_->SetRenderTarget(0, rt);
  1314. graphics_->SetDepthStencil(GetDepthStencil(rt));
  1315. graphics_->SetViewport(viewRect_);
  1316. }
  1317. else
  1318. {
  1319. HashMap<StringHash, Texture2D*>::ConstIterator k = renderTargets.Find(StringHash(output));
  1320. if (k != renderTargets.End())
  1321. rt = k->second_->GetRenderSurface();
  1322. else
  1323. continue; // Skip pass if rendertarget can not be found
  1324. graphics_->SetRenderTarget(0, rt);
  1325. graphics_->SetDepthStencil(GetDepthStencil(rt));
  1326. graphics_->SetViewport(IntRect(0, 0, rt->GetWidth(), rt->GetHeight()));
  1327. }
  1328. // Set shaders, shader parameters and textures
  1329. graphics_->SetShaders(renderer_->GetVertexShader(pass->GetVertexShader()),
  1330. renderer_->GetPixelShader(pass->GetPixelShader()));
  1331. const HashMap<StringHash, Vector4>& globalParameters = effect->GetShaderParameters();
  1332. for (HashMap<StringHash, Vector4>::ConstIterator k = globalParameters.Begin(); k != globalParameters.End(); ++k)
  1333. graphics_->SetShaderParameter(k->first_, k->second_);
  1334. const HashMap<StringHash, Vector4>& parameters = pass->GetShaderParameters();
  1335. for (HashMap<StringHash, Vector4>::ConstIterator k = parameters.Begin(); k != parameters.End(); ++k)
  1336. graphics_->SetShaderParameter(k->first_, k->second_);
  1337. float rtWidth = (float)rtSize_.x_;
  1338. float rtHeight = (float)rtSize_.y_;
  1339. float widthRange = 0.5f * viewSize_.x_ / rtWidth;
  1340. float heightRange = 0.5f * viewSize_.y_ / rtHeight;
  1341. #ifdef USE_OPENGL
  1342. Vector4 bufferUVOffset(((float)viewRect_.left_) / rtWidth + widthRange,
  1343. 1.0f - (((float)viewRect_.top_) / rtHeight + heightRange), widthRange, heightRange);
  1344. #else
  1345. Vector4 bufferUVOffset((0.5f + (float)viewRect_.left_) / rtWidth + widthRange,
  1346. (0.5f + (float)viewRect_.top_) / rtHeight + heightRange, widthRange, heightRange);
  1347. #endif
  1348. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  1349. graphics_->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector4(1.0f / rtWidth, 1.0f / rtHeight, 0.0f, 0.0f));
  1350. // Set per-rendertarget inverse size / offset shader parameters as necessary
  1351. for (HashMap<StringHash, PostProcessRenderTarget>::ConstIterator k = renderTargetInfos.Begin(); k !=
  1352. renderTargetInfos.End(); ++k)
  1353. {
  1354. String invSizeName = k->second_.name_ + "InvSize";
  1355. String offsetsName = k->second_.name_ + "Offsets";
  1356. float width = (float)renderTargets[k->first_]->GetWidth();
  1357. float height = (float)renderTargets[k->first_]->GetHeight();
  1358. graphics_->SetShaderParameter(StringHash(invSizeName), Vector4(1.0f / width, 1.0f / height, 0.0f, 0.0f));
  1359. #ifdef USE_OPENGL
  1360. graphics_->SetShaderParameter(StringHash(offsetsName), Vector4::ZERO);
  1361. #else
  1362. graphics_->SetShaderParameter(StringHash(offsetsName), Vector4(0.5f / width, 0.5f / height, 0.0f, 0.0f));
  1363. #endif
  1364. }
  1365. const String* textureNames = pass->GetTextures();
  1366. for (unsigned k = 0; k < MAX_MATERIAL_TEXTURE_UNITS; ++k)
  1367. {
  1368. if (!textureNames[k].Empty())
  1369. {
  1370. // Texture may either refer to a rendertarget or to a texture resource
  1371. if (!textureNames[k].Compare("viewport", false))
  1372. graphics_->SetTexture(k, screenBuffers_[readRtIndex]);
  1373. else
  1374. {
  1375. HashMap<StringHash, Texture2D*>::ConstIterator l = renderTargets.Find(StringHash(textureNames[k]));
  1376. if (l != renderTargets.End())
  1377. graphics_->SetTexture(k, l->second_);
  1378. else
  1379. {
  1380. // If requesting a texture fails, clear the texture name to prevent redundant attempts
  1381. Texture2D* texture = cache->GetResource<Texture2D>(textureNames[k]);
  1382. if (texture)
  1383. graphics_->SetTexture(k, texture);
  1384. else
  1385. pass->SetTexture((TextureUnit)k, String());
  1386. }
  1387. }
  1388. }
  1389. }
  1390. DrawFullscreenQuad(camera_, false);
  1391. // Swap the ping-pong buffer sides now if necessary
  1392. if (swapBuffers)
  1393. Swap(readRtIndex, writeRtIndex);
  1394. }
  1395. // Forget the rendertargets allocated during this effect
  1396. renderer_->RestoreScreenBufferAllocations();
  1397. }
  1398. }
  1399. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  1400. {
  1401. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  1402. float halfViewSize = camera->GetHalfViewSize();
  1403. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  1404. Vector3 cameraPos = camera->GetNode()->GetWorldPosition();
  1405. for (PODVector<Drawable*>::Iterator i = occluders.Begin(); i != occluders.End();)
  1406. {
  1407. Drawable* occluder = *i;
  1408. bool erase = false;
  1409. if (!occluder->IsInView(frame_, false))
  1410. occluder->UpdateBatches(frame_);
  1411. // Check occluder's draw distance (in main camera view)
  1412. float maxDistance = occluder->GetDrawDistance();
  1413. if (maxDistance <= 0.0f || occluder->GetDistance() <= maxDistance)
  1414. {
  1415. // Check that occluder is big enough on the screen
  1416. const BoundingBox& box = occluder->GetWorldBoundingBox();
  1417. float diagonal = box.Size().Length();
  1418. float compare;
  1419. if (!camera->IsOrthographic())
  1420. compare = diagonal * halfViewSize / occluder->GetDistance();
  1421. else
  1422. compare = diagonal * invOrthoSize;
  1423. if (compare < occluderSizeThreshold_)
  1424. erase = true;
  1425. else
  1426. {
  1427. // Store amount of triangles divided by screen size as a sorting key
  1428. // (best occluders are big and have few triangles)
  1429. occluder->SetSortValue((float)occluder->GetNumOccluderTriangles() / compare);
  1430. }
  1431. }
  1432. else
  1433. erase = true;
  1434. if (erase)
  1435. i = occluders.Erase(i);
  1436. else
  1437. ++i;
  1438. }
  1439. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  1440. if (occluders.Size())
  1441. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  1442. }
  1443. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  1444. {
  1445. buffer->SetMaxTriangles(maxOccluderTriangles_);
  1446. buffer->Clear();
  1447. for (unsigned i = 0; i < occluders.Size(); ++i)
  1448. {
  1449. Drawable* occluder = occluders[i];
  1450. if (i > 0)
  1451. {
  1452. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  1453. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  1454. continue;
  1455. }
  1456. // Check for running out of triangles
  1457. if (!occluder->DrawOcclusion(buffer))
  1458. break;
  1459. }
  1460. buffer->BuildDepthHierarchy();
  1461. }
  1462. void View::ProcessLight(LightQueryResult& query, unsigned threadIndex)
  1463. {
  1464. Light* light = query.light_;
  1465. LightType type = light->GetLightType();
  1466. const Frustum& frustum = camera_->GetFrustum();
  1467. // Check if light should be shadowed
  1468. bool isShadowed = drawShadows_ && light->GetCastShadows() && !light->GetPerVertex() && light->GetShadowIntensity() < 1.0f;
  1469. // If shadow distance non-zero, check it
  1470. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  1471. isShadowed = false;
  1472. // OpenGL ES can not support point light shadows
  1473. #ifdef GL_ES_VERSION_2_0
  1474. if (isShadowed && type == LIGHT_POINT)
  1475. isShadowed = false;
  1476. #endif
  1477. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  1478. PODVector<Drawable*>& tempDrawables = tempDrawables_[threadIndex];
  1479. query.litGeometries_.Clear();
  1480. switch (type)
  1481. {
  1482. case LIGHT_DIRECTIONAL:
  1483. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1484. {
  1485. if (GetLightMask(geometries_[i]) & light->GetLightMask())
  1486. query.litGeometries_.Push(geometries_[i]);
  1487. }
  1488. break;
  1489. case LIGHT_SPOT:
  1490. {
  1491. FrustumOctreeQuery octreeQuery(tempDrawables, light->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1492. octree_->GetDrawables(octreeQuery);
  1493. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1494. {
  1495. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1496. query.litGeometries_.Push(tempDrawables[i]);
  1497. }
  1498. }
  1499. break;
  1500. case LIGHT_POINT:
  1501. {
  1502. SphereOctreeQuery octreeQuery(tempDrawables, Sphere(light->GetNode()->GetWorldPosition(), light->GetRange()),
  1503. DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1504. octree_->GetDrawables(octreeQuery);
  1505. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1506. {
  1507. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1508. query.litGeometries_.Push(tempDrawables[i]);
  1509. }
  1510. }
  1511. break;
  1512. }
  1513. // If no lit geometries or not shadowed, no need to process shadow cameras
  1514. if (query.litGeometries_.Empty() || !isShadowed)
  1515. {
  1516. query.numSplits_ = 0;
  1517. return;
  1518. }
  1519. // Determine number of shadow cameras and setup their initial positions
  1520. SetupShadowCameras(query);
  1521. // Process each split for shadow casters
  1522. query.shadowCasters_.Clear();
  1523. for (unsigned i = 0; i < query.numSplits_; ++i)
  1524. {
  1525. Camera* shadowCamera = query.shadowCameras_[i];
  1526. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1527. query.shadowCasterBegin_[i] = query.shadowCasterEnd_[i] = query.shadowCasters_.Size();
  1528. // For point light check that the face is visible: if not, can skip the split
  1529. if (type == LIGHT_POINT && frustum.IsInsideFast(BoundingBox(shadowCameraFrustum)) == OUTSIDE)
  1530. continue;
  1531. // For directional light check that the split is inside the visible scene: if not, can skip the split
  1532. if (type == LIGHT_DIRECTIONAL)
  1533. {
  1534. if (minZ_ > query.shadowFarSplits_[i])
  1535. continue;
  1536. if (maxZ_ < query.shadowNearSplits_[i])
  1537. continue;
  1538. }
  1539. // Reuse lit geometry query for all except directional lights
  1540. if (type == LIGHT_DIRECTIONAL)
  1541. {
  1542. ShadowCasterOctreeQuery query(tempDrawables, shadowCameraFrustum, DRAWABLE_GEOMETRY,
  1543. camera_->GetViewMask());
  1544. octree_->GetDrawables(query);
  1545. }
  1546. // Check which shadow casters actually contribute to the shadowing
  1547. ProcessShadowCasters(query, tempDrawables, i);
  1548. }
  1549. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  1550. // only cost has been the shadow camera setup & queries
  1551. if (query.shadowCasters_.Empty())
  1552. query.numSplits_ = 0;
  1553. }
  1554. void View::ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex)
  1555. {
  1556. Light* light = query.light_;
  1557. Camera* shadowCamera = query.shadowCameras_[splitIndex];
  1558. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1559. const Matrix3x4& lightView = shadowCamera->GetInverseWorldTransform();
  1560. const Matrix4& lightProj = shadowCamera->GetProjection();
  1561. LightType type = light->GetLightType();
  1562. query.shadowCasterBox_[splitIndex].defined_ = false;
  1563. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  1564. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  1565. // frustum, so that shadow casters do not get rendered into unnecessary splits
  1566. Frustum lightViewFrustum;
  1567. if (type != LIGHT_DIRECTIONAL)
  1568. lightViewFrustum = camera_->GetSplitFrustum(minZ_, maxZ_).Transformed(lightView);
  1569. else
  1570. lightViewFrustum = camera_->GetSplitFrustum(Max(minZ_, query.shadowNearSplits_[splitIndex]),
  1571. Min(maxZ_, query.shadowFarSplits_[splitIndex])).Transformed(lightView);
  1572. BoundingBox lightViewFrustumBox(lightViewFrustum);
  1573. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1574. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1575. return;
  1576. BoundingBox lightViewBox;
  1577. BoundingBox lightProjBox;
  1578. for (PODVector<Drawable*>::ConstIterator i = drawables.Begin(); i != drawables.End(); ++i)
  1579. {
  1580. Drawable* drawable = *i;
  1581. // In case this is a point or spot light query result reused for optimization, we may have non-shadowcasters included.
  1582. // Check for that first
  1583. if (!drawable->GetCastShadows())
  1584. continue;
  1585. // For point light, check that this drawable is inside the split shadow camera frustum
  1586. if (type == LIGHT_POINT && shadowCameraFrustum.IsInsideFast(drawable->GetWorldBoundingBox()) == OUTSIDE)
  1587. continue;
  1588. // Note: as lights are processed threaded, it is possible a drawable's UpdateBatches() function is called several
  1589. // times. However, this should not cause problems as no scene modification happens at this point.
  1590. if (!drawable->IsInView(frame_, false))
  1591. drawable->UpdateBatches(frame_);
  1592. // Check shadow distance
  1593. float maxShadowDistance = drawable->GetShadowDistance();
  1594. if (maxShadowDistance > 0.0f && drawable->GetDistance() > maxShadowDistance)
  1595. continue;
  1596. // Check shadow mask
  1597. if (!(GetShadowMask(drawable) & light->GetLightMask()))
  1598. continue;
  1599. // Project shadow caster bounding box to light view space for visibility check
  1600. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1601. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1602. {
  1603. // Merge to shadow caster bounding box and add to the list
  1604. if (type == LIGHT_DIRECTIONAL)
  1605. query.shadowCasterBox_[splitIndex].Merge(lightViewBox);
  1606. else
  1607. {
  1608. lightProjBox = lightViewBox.Projected(lightProj);
  1609. query.shadowCasterBox_[splitIndex].Merge(lightProjBox);
  1610. }
  1611. query.shadowCasters_.Push(drawable);
  1612. }
  1613. }
  1614. query.shadowCasterEnd_[splitIndex] = query.shadowCasters_.Size();
  1615. }
  1616. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  1617. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  1618. {
  1619. if (shadowCamera->IsOrthographic())
  1620. {
  1621. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  1622. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  1623. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1624. }
  1625. else
  1626. {
  1627. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  1628. if (drawable->IsInView(frame_))
  1629. return true;
  1630. // For perspective lights, extrusion direction depends on the position of the shadow caster
  1631. Vector3 center = lightViewBox.Center();
  1632. Ray extrusionRay(center, center.Normalized());
  1633. float extrusionDistance = shadowCamera->GetFarClip();
  1634. float originalDistance = Clamp(center.Length(), M_EPSILON, extrusionDistance);
  1635. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  1636. float sizeFactor = extrusionDistance / originalDistance;
  1637. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  1638. // than necessary, so the test will be conservative
  1639. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  1640. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  1641. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  1642. lightViewBox.Merge(extrudedBox);
  1643. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1644. }
  1645. }
  1646. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  1647. {
  1648. unsigned width = shadowMap->GetWidth();
  1649. unsigned height = shadowMap->GetHeight();
  1650. int maxCascades = renderer_->GetMaxShadowCascades();
  1651. switch (light->GetLightType())
  1652. {
  1653. case LIGHT_DIRECTIONAL:
  1654. if (maxCascades == 1)
  1655. return IntRect(0, 0, width, height);
  1656. else if (maxCascades == 2)
  1657. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  1658. else
  1659. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  1660. (splitIndex / 2 + 1) * height / 2);
  1661. case LIGHT_SPOT:
  1662. return IntRect(0, 0, width, height);
  1663. case LIGHT_POINT:
  1664. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  1665. (splitIndex / 2 + 1) * height / 3);
  1666. }
  1667. return IntRect();
  1668. }
  1669. void View::SetupShadowCameras(LightQueryResult& query)
  1670. {
  1671. Light* light = query.light_;
  1672. LightType type = light->GetLightType();
  1673. int splits = 0;
  1674. if (type == LIGHT_DIRECTIONAL)
  1675. {
  1676. const CascadeParameters& cascade = light->GetShadowCascade();
  1677. float nearSplit = camera_->GetNearClip();
  1678. float farSplit;
  1679. while (splits < renderer_->GetMaxShadowCascades())
  1680. {
  1681. // If split is completely beyond camera far clip, we are done
  1682. if (nearSplit > camera_->GetFarClip())
  1683. break;
  1684. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  1685. if (farSplit <= nearSplit)
  1686. break;
  1687. // Setup the shadow camera for the split
  1688. Camera* shadowCamera = renderer_->GetShadowCamera();
  1689. query.shadowCameras_[splits] = shadowCamera;
  1690. query.shadowNearSplits_[splits] = nearSplit;
  1691. query.shadowFarSplits_[splits] = farSplit;
  1692. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit);
  1693. nearSplit = farSplit;
  1694. ++splits;
  1695. }
  1696. }
  1697. if (type == LIGHT_SPOT)
  1698. {
  1699. Camera* shadowCamera = renderer_->GetShadowCamera();
  1700. query.shadowCameras_[0] = shadowCamera;
  1701. Node* cameraNode = shadowCamera->GetNode();
  1702. Node* lightNode = light->GetNode();
  1703. cameraNode->SetTransform(lightNode->GetWorldPosition(), lightNode->GetWorldRotation());
  1704. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1705. shadowCamera->SetFarClip(light->GetRange());
  1706. shadowCamera->SetFov(light->GetFov());
  1707. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1708. splits = 1;
  1709. }
  1710. if (type == LIGHT_POINT)
  1711. {
  1712. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1713. {
  1714. Camera* shadowCamera = renderer_->GetShadowCamera();
  1715. query.shadowCameras_[i] = shadowCamera;
  1716. Node* cameraNode = shadowCamera->GetNode();
  1717. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1718. cameraNode->SetPosition(light->GetNode()->GetWorldPosition());
  1719. cameraNode->SetDirection(directions[i]);
  1720. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1721. shadowCamera->SetFarClip(light->GetRange());
  1722. shadowCamera->SetFov(90.0f);
  1723. shadowCamera->SetAspectRatio(1.0f);
  1724. }
  1725. splits = MAX_CUBEMAP_FACES;
  1726. }
  1727. query.numSplits_ = splits;
  1728. }
  1729. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit)
  1730. {
  1731. Node* shadowCameraNode = shadowCamera->GetNode();
  1732. Node* lightNode = light->GetNode();
  1733. float extrusionDistance = camera_->GetFarClip();
  1734. const FocusParameters& parameters = light->GetShadowFocus();
  1735. // Calculate initial position & rotation
  1736. Vector3 lightWorldDirection = lightNode->GetWorldRotation() * Vector3::FORWARD;
  1737. Vector3 pos = cameraNode_->GetWorldPosition() - extrusionDistance * lightWorldDirection;
  1738. shadowCameraNode->SetTransform(pos, lightNode->GetWorldRotation());
  1739. // Calculate main camera shadowed frustum in light's view space
  1740. farSplit = Min(farSplit, camera_->GetFarClip());
  1741. // Use the scene Z bounds to limit frustum size if applicable
  1742. if (parameters.focus_)
  1743. {
  1744. nearSplit = Max(minZ_, nearSplit);
  1745. farSplit = Min(maxZ_, farSplit);
  1746. }
  1747. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  1748. Polyhedron frustumVolume;
  1749. frustumVolume.Define(splitFrustum);
  1750. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  1751. if (parameters.focus_)
  1752. {
  1753. BoundingBox litGeometriesBox;
  1754. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1755. {
  1756. Drawable* drawable = geometries_[i];
  1757. // Skip skyboxes as they have undefinedly large bounding box size
  1758. if (drawable->GetType() == Skybox::GetTypeStatic())
  1759. continue;
  1760. if (drawable->GetMinZ() <= farSplit && drawable->GetMaxZ() >= nearSplit &&
  1761. (GetLightMask(drawable) & light->GetLightMask()))
  1762. litGeometriesBox.Merge(drawable->GetWorldBoundingBox());
  1763. }
  1764. if (litGeometriesBox.defined_)
  1765. {
  1766. frustumVolume.Clip(litGeometriesBox);
  1767. // If volume became empty, restore it to avoid zero size
  1768. if (frustumVolume.Empty())
  1769. frustumVolume.Define(splitFrustum);
  1770. }
  1771. }
  1772. // Transform frustum volume to light space
  1773. const Matrix3x4& lightView = shadowCamera->GetInverseWorldTransform();
  1774. frustumVolume.Transform(lightView);
  1775. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  1776. BoundingBox shadowBox;
  1777. if (!parameters.nonUniform_)
  1778. shadowBox.Define(Sphere(frustumVolume));
  1779. else
  1780. shadowBox.Define(frustumVolume);
  1781. shadowCamera->SetOrthographic(true);
  1782. shadowCamera->SetAspectRatio(1.0f);
  1783. shadowCamera->SetNearClip(0.0f);
  1784. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1785. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  1786. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  1787. }
  1788. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1789. const BoundingBox& shadowCasterBox)
  1790. {
  1791. const FocusParameters& parameters = light->GetShadowFocus();
  1792. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1793. LightType type = light->GetLightType();
  1794. if (type == LIGHT_DIRECTIONAL)
  1795. {
  1796. BoundingBox shadowBox;
  1797. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1798. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  1799. shadowBox.min_.y_ = -shadowBox.max_.y_;
  1800. shadowBox.min_.x_ = -shadowBox.max_.x_;
  1801. // Requantize and snap to shadow map texels
  1802. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  1803. }
  1804. if (type == LIGHT_SPOT)
  1805. {
  1806. if (parameters.focus_)
  1807. {
  1808. float viewSizeX = Max(Abs(shadowCasterBox.min_.x_), Abs(shadowCasterBox.max_.x_));
  1809. float viewSizeY = Max(Abs(shadowCasterBox.min_.y_), Abs(shadowCasterBox.max_.y_));
  1810. float viewSize = Max(viewSizeX, viewSizeY);
  1811. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  1812. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  1813. float quantize = parameters.quantize_ * invOrthoSize;
  1814. float minView = parameters.minView_ * invOrthoSize;
  1815. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  1816. if (viewSize < 1.0f)
  1817. shadowCamera->SetZoom(1.0f / viewSize);
  1818. }
  1819. }
  1820. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  1821. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  1822. if (shadowCamera->GetZoom() >= 1.0f)
  1823. {
  1824. if (light->GetLightType() != LIGHT_POINT)
  1825. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  1826. else
  1827. {
  1828. #ifdef USE_OPENGL
  1829. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  1830. #else
  1831. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  1832. #endif
  1833. }
  1834. }
  1835. }
  1836. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1837. const BoundingBox& viewBox)
  1838. {
  1839. Node* shadowCameraNode = shadowCamera->GetNode();
  1840. const FocusParameters& parameters = light->GetShadowFocus();
  1841. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1842. float minX = viewBox.min_.x_;
  1843. float minY = viewBox.min_.y_;
  1844. float maxX = viewBox.max_.x_;
  1845. float maxY = viewBox.max_.y_;
  1846. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  1847. Vector2 viewSize(maxX - minX, maxY - minY);
  1848. // Quantize size to reduce swimming
  1849. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  1850. if (parameters.nonUniform_)
  1851. {
  1852. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1853. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  1854. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1855. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  1856. }
  1857. else if (parameters.focus_)
  1858. {
  1859. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  1860. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1861. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1862. viewSize.y_ = viewSize.x_;
  1863. }
  1864. shadowCamera->SetOrthoSize(viewSize);
  1865. // Center shadow camera to the view space bounding box
  1866. Vector3 pos(shadowCameraNode->GetWorldPosition());
  1867. Quaternion rot(shadowCameraNode->GetWorldRotation());
  1868. Vector3 adjust(center.x_, center.y_, 0.0f);
  1869. shadowCameraNode->Translate(rot * adjust);
  1870. // If the shadow map viewport is known, snap to whole texels
  1871. if (shadowMapWidth > 0.0f)
  1872. {
  1873. Vector3 viewPos(rot.Inverse() * shadowCameraNode->GetWorldPosition());
  1874. // Take into account that shadow map border will not be used
  1875. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  1876. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  1877. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  1878. shadowCameraNode->Translate(rot * snap);
  1879. }
  1880. }
  1881. void View::FindZone(Drawable* drawable)
  1882. {
  1883. Vector3 center = drawable->GetWorldBoundingBox().Center();
  1884. int bestPriority = M_MIN_INT;
  1885. Zone* newZone = 0;
  1886. // If bounding box center is in view, the zone assignment is conclusive also for next frames. Otherwise it is temporary
  1887. // (possibly incorrect) and must be re-evaluated on the next frame
  1888. bool temporary = !camera_->GetFrustum().IsInside(center);
  1889. // First check if the last zone remains a conclusive result
  1890. Zone* lastZone = drawable->GetLastZone();
  1891. if (lastZone && lastZone->IsInside(center) && (drawable->GetZoneMask() & lastZone->GetZoneMask()) &&
  1892. lastZone->GetPriority() >= highestZonePriority_)
  1893. newZone = lastZone;
  1894. else
  1895. {
  1896. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  1897. {
  1898. Zone* zone = *i;
  1899. int priority = zone->GetPriority();
  1900. if (zone->IsInside(center) && (drawable->GetZoneMask() & zone->GetZoneMask()) && priority > bestPriority)
  1901. {
  1902. newZone = zone;
  1903. bestPriority = priority;
  1904. }
  1905. }
  1906. }
  1907. drawable->SetZone(newZone, temporary);
  1908. }
  1909. Zone* View::GetZone(Drawable* drawable)
  1910. {
  1911. if (cameraZoneOverride_)
  1912. return cameraZone_;
  1913. Zone* drawableZone = drawable->GetZone();
  1914. return drawableZone ? drawableZone : cameraZone_;
  1915. }
  1916. unsigned View::GetLightMask(Drawable* drawable)
  1917. {
  1918. return drawable->GetLightMask() & GetZone(drawable)->GetLightMask();
  1919. }
  1920. unsigned View::GetShadowMask(Drawable* drawable)
  1921. {
  1922. return drawable->GetShadowMask() & GetZone(drawable)->GetShadowMask();
  1923. }
  1924. unsigned long long View::GetVertexLightQueueHash(const PODVector<Light*>& vertexLights)
  1925. {
  1926. unsigned long long hash = 0;
  1927. for (PODVector<Light*>::ConstIterator i = vertexLights.Begin(); i != vertexLights.End(); ++i)
  1928. hash += (unsigned long long)(*i);
  1929. return hash;
  1930. }
  1931. Technique* View::GetTechnique(Drawable* drawable, Material* material)
  1932. {
  1933. if (!material)
  1934. {
  1935. const Vector<TechniqueEntry>& techniques = renderer_->GetDefaultMaterial()->GetTechniques();
  1936. return techniques.Size() ? techniques[0].technique_ : (Technique*)0;
  1937. }
  1938. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  1939. // If only one technique, no choice
  1940. if (techniques.Size() == 1)
  1941. return techniques[0].technique_;
  1942. else
  1943. {
  1944. float lodDistance = drawable->GetLodDistance();
  1945. // Check for suitable technique. Techniques should be ordered like this:
  1946. // Most distant & highest quality
  1947. // Most distant & lowest quality
  1948. // Second most distant & highest quality
  1949. // ...
  1950. for (unsigned i = 0; i < techniques.Size(); ++i)
  1951. {
  1952. const TechniqueEntry& entry = techniques[i];
  1953. Technique* tech = entry.technique_;
  1954. if (!tech || (tech->IsSM3() && !graphics_->GetSM3Support()) || materialQuality_ < entry.qualityLevel_)
  1955. continue;
  1956. if (lodDistance >= entry.lodDistance_)
  1957. return tech;
  1958. }
  1959. // If no suitable technique found, fallback to the last
  1960. return techniques.Size() ? techniques.Back().technique_ : (Technique*)0;
  1961. }
  1962. }
  1963. void View::CheckMaterialForAuxView(Material* material)
  1964. {
  1965. const SharedPtr<Texture>* textures = material->GetTextures();
  1966. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  1967. {
  1968. // Have to check cube & 2D textures separately
  1969. Texture* texture = textures[i];
  1970. if (texture)
  1971. {
  1972. if (texture->GetType() == Texture2D::GetTypeStatic())
  1973. {
  1974. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1975. RenderSurface* target = tex2D->GetRenderSurface();
  1976. if (target)
  1977. {
  1978. Viewport* viewport = target->GetViewport();
  1979. if (viewport->GetScene() && viewport->GetCamera())
  1980. renderer_->AddView(target, viewport);
  1981. }
  1982. }
  1983. else if (texture->GetType() == TextureCube::GetTypeStatic())
  1984. {
  1985. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1986. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1987. {
  1988. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  1989. if (target)
  1990. {
  1991. Viewport* viewport = target->GetViewport();
  1992. if (viewport->GetScene() && viewport->GetCamera())
  1993. renderer_->AddView(target, viewport);
  1994. }
  1995. }
  1996. }
  1997. }
  1998. }
  1999. // Set frame number so that we can early-out next time we come across this material on the same frame
  2000. material->MarkForAuxView(frame_.frameNumber_);
  2001. }
  2002. void View::AddBatchToQueue(BatchQueue& batchQueue, Batch& batch, Technique* tech, bool allowInstancing, bool allowShadows)
  2003. {
  2004. if (!batch.material_)
  2005. batch.material_ = renderer_->GetDefaultMaterial();
  2006. // Convert to instanced if possible
  2007. if (allowInstancing && batch.geometryType_ == GEOM_STATIC && batch.geometry_->GetIndexBuffer() && !batch.shaderData_ &&
  2008. !batch.overrideView_)
  2009. batch.geometryType_ = GEOM_INSTANCED;
  2010. if (batch.geometryType_ == GEOM_INSTANCED)
  2011. {
  2012. HashMap<BatchGroupKey, BatchGroup>* groups = batch.isBase_ ? &batchQueue.baseBatchGroups_ : &batchQueue.batchGroups_;
  2013. BatchGroupKey key(batch);
  2014. HashMap<BatchGroupKey, BatchGroup>::Iterator i = groups->Find(key);
  2015. if (i == groups->End())
  2016. {
  2017. // Create a new group based on the batch
  2018. renderer_->SetBatchShaders(batch, tech, allowShadows);
  2019. BatchGroup newGroup(batch);
  2020. newGroup.CalculateSortKey();
  2021. newGroup.instances_.Push(InstanceData(batch.worldTransform_, batch.distance_));
  2022. groups->Insert(MakePair(key, newGroup));
  2023. }
  2024. else
  2025. i->second_.instances_.Push(InstanceData(batch.worldTransform_, batch.distance_));
  2026. }
  2027. else
  2028. {
  2029. renderer_->SetBatchShaders(batch, tech, allowShadows);
  2030. batch.CalculateSortKey();
  2031. batchQueue.batches_.Push(batch);
  2032. }
  2033. }
  2034. void View::PrepareInstancingBuffer()
  2035. {
  2036. PROFILE(PrepareInstancingBuffer);
  2037. unsigned totalInstances = 0;
  2038. totalInstances += baseQueue_.GetNumInstances(renderer_);
  2039. totalInstances += preAlphaQueue_.GetNumInstances(renderer_);
  2040. if (renderMode_ != RENDER_FORWARD)
  2041. totalInstances += gbufferQueue_.GetNumInstances(renderer_);
  2042. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2043. {
  2044. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2045. totalInstances += i->shadowSplits_[j].shadowBatches_.GetNumInstances(renderer_);
  2046. totalInstances += i->litBatches_.GetNumInstances(renderer_);
  2047. }
  2048. // If fail to set buffer size, fall back to per-group locking
  2049. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  2050. {
  2051. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  2052. unsigned freeIndex = 0;
  2053. void* dest = instancingBuffer->Lock(0, totalInstances, true);
  2054. if (!dest)
  2055. return;
  2056. baseQueue_.SetTransforms(renderer_, dest, freeIndex);
  2057. preAlphaQueue_.SetTransforms(renderer_, dest, freeIndex);
  2058. if (renderMode_ != RENDER_FORWARD)
  2059. gbufferQueue_.SetTransforms(renderer_, dest, freeIndex);
  2060. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2061. {
  2062. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2063. i->shadowSplits_[j].shadowBatches_.SetTransforms(renderer_, dest, freeIndex);
  2064. i->litBatches_.SetTransforms(renderer_, dest, freeIndex);
  2065. }
  2066. instancingBuffer->Unlock();
  2067. }
  2068. }
  2069. void View::SetupLightVolumeBatch(Batch& batch)
  2070. {
  2071. Light* light = batch.lightQueue_->light_;
  2072. LightType type = light->GetLightType();
  2073. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  2074. float lightDist;
  2075. // Use replace blend mode for the first pre-pass light volume, and additive for the rest
  2076. graphics_->SetBlendMode(renderMode_ == RENDER_PREPASS && light == lightQueues_.Front().light_ ? BLEND_REPLACE : BLEND_ADD);
  2077. graphics_->SetDepthBias(0.0f, 0.0f);
  2078. graphics_->SetDepthWrite(false);
  2079. if (type != LIGHT_DIRECTIONAL)
  2080. {
  2081. if (type == LIGHT_POINT)
  2082. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  2083. else
  2084. lightDist = light->GetFrustum().Distance(cameraPos);
  2085. // Draw front faces if not inside light volume
  2086. if (lightDist < camera_->GetNearClip() * 2.0f)
  2087. {
  2088. renderer_->SetCullMode(CULL_CW, camera_);
  2089. graphics_->SetDepthTest(CMP_GREATER);
  2090. }
  2091. else
  2092. {
  2093. renderer_->SetCullMode(CULL_CCW, camera_);
  2094. graphics_->SetDepthTest(CMP_LESSEQUAL);
  2095. }
  2096. }
  2097. else
  2098. {
  2099. // In case the same camera is used for multiple views with differing aspect ratios (not recommended)
  2100. // refresh the directional light's model transform before rendering
  2101. light->GetVolumeTransform(camera_);
  2102. graphics_->SetCullMode(CULL_NONE);
  2103. graphics_->SetDepthTest(CMP_ALWAYS);
  2104. }
  2105. graphics_->SetScissorTest(false);
  2106. graphics_->SetStencilTest(true, CMP_NOTEQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 0, light->GetLightMask());
  2107. }
  2108. void View::DrawFullscreenQuad(Camera* camera, bool nearQuad)
  2109. {
  2110. Light* quadDirLight = renderer_->GetQuadDirLight();
  2111. Matrix3x4 model(quadDirLight->GetDirLightTransform(camera, nearQuad));
  2112. graphics_->SetCullMode(CULL_NONE);
  2113. graphics_->SetShaderParameter(VSP_MODEL, model);
  2114. graphics_->SetShaderParameter(VSP_VIEWPROJ, camera->GetProjection());
  2115. graphics_->ClearTransformSources();
  2116. renderer_->GetLightGeometry(quadDirLight)->Draw(graphics_);
  2117. }
  2118. void View::RenderShadowMap(const LightBatchQueue& queue)
  2119. {
  2120. PROFILE(RenderShadowMap);
  2121. Texture2D* shadowMap = queue.shadowMap_;
  2122. graphics_->SetTexture(TU_SHADOWMAP, 0);
  2123. graphics_->SetColorWrite(false);
  2124. graphics_->SetStencilTest(false);
  2125. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  2126. graphics_->SetDepthStencil(shadowMap);
  2127. graphics_->SetViewport(IntRect(0, 0, shadowMap->GetWidth(), shadowMap->GetHeight()));
  2128. graphics_->Clear(CLEAR_DEPTH);
  2129. // Set shadow depth bias
  2130. BiasParameters parameters = queue.light_->GetShadowBias();
  2131. // Adjust the light's constant depth bias according to global shadow map resolution
  2132. /// \todo Should remove this adjustment and find a more flexible solution
  2133. unsigned shadowMapSize = renderer_->GetShadowMapSize();
  2134. if (shadowMapSize <= 512)
  2135. parameters.constantBias_ *= 2.0f;
  2136. else if (shadowMapSize >= 2048)
  2137. parameters.constantBias_ *= 0.5f;
  2138. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  2139. // Render each of the splits
  2140. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  2141. {
  2142. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  2143. if (!shadowQueue.shadowBatches_.IsEmpty())
  2144. {
  2145. graphics_->SetViewport(shadowQueue.shadowViewport_);
  2146. shadowQueue.shadowBatches_.Draw(graphics_, renderer_);
  2147. }
  2148. }
  2149. graphics_->SetColorWrite(true);
  2150. graphics_->SetDepthBias(0.0f, 0.0f);
  2151. }
  2152. RenderSurface* View::GetDepthStencil(RenderSurface* renderTarget)
  2153. {
  2154. // If using the backbuffer, return the backbuffer depth-stencil
  2155. if (!renderTarget)
  2156. return 0;
  2157. // Then check for linked depth-stencil
  2158. RenderSurface* depthStencil = renderTarget->GetLinkedDepthStencil();
  2159. // Finally get one from Renderer
  2160. if (!depthStencil)
  2161. depthStencil = renderer_->GetDepthStencil(renderTarget->GetWidth(), renderTarget->GetHeight());
  2162. return depthStencil;
  2163. }