View.cpp 113 KB

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