View.cpp 96 KB

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