View.cpp 101 KB

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