View.cpp 101 KB

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