View.cpp 101 KB

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