View.cpp 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "DebugRenderer.h"
  26. #include "Geometry.h"
  27. #include "Graphics.h"
  28. #include "Light.h"
  29. #include "Log.h"
  30. #include "Material.h"
  31. #include "OcclusionBuffer.h"
  32. #include "Octree.h"
  33. #include "OctreeQuery.h"
  34. #include "Renderer.h"
  35. #include "Profiler.h"
  36. #include "Scene.h"
  37. #include "ShaderVariation.h"
  38. #include "Sort.h"
  39. #include "Technique.h"
  40. #include "Texture2D.h"
  41. #include "TextureCube.h"
  42. #include "VertexBuffer.h"
  43. #include "View.h"
  44. #include "Zone.h"
  45. #include "DebugNew.h"
  46. static const Vector3 directions[] =
  47. {
  48. Vector3(1.0f, 0.0f, 0.0f),
  49. Vector3(-1.0f, 0.0f, 0.0f),
  50. Vector3(0.0f, 1.0f, 0.0f),
  51. Vector3(0.0f, -1.0f, 0.0f),
  52. Vector3(0.0f, 0.0f, 1.0f),
  53. Vector3(0.0f, 0.0f, -1.0f)
  54. };
  55. OBJECTTYPESTATIC(View);
  56. View::View(Context* context) :
  57. Object(context),
  58. graphics_(GetSubsystem<Graphics>()),
  59. renderer_(GetSubsystem<Renderer>()),
  60. octree_(0),
  61. camera_(0),
  62. zone_(0),
  63. renderTarget_(0),
  64. depthStencil_(0),
  65. jitterCounter_(0)
  66. {
  67. frame_.camera_ = 0;
  68. }
  69. View::~View()
  70. {
  71. }
  72. bool View::Define(RenderSurface* renderTarget, const Viewport& viewport)
  73. {
  74. if (!viewport.scene_ || !viewport.camera_)
  75. return false;
  76. // If scene is loading asynchronously, it is incomplete and should not be rendered
  77. if (viewport.scene_->IsAsyncLoading())
  78. return false;
  79. Octree* octree = viewport.scene_->GetComponent<Octree>();
  80. if (!octree)
  81. return false;
  82. mode_ = graphics_->GetRenderMode();
  83. // In deferred mode, check for the render texture being too large
  84. if (mode_ != RENDER_FORWARD && renderTarget)
  85. {
  86. if (renderTarget->GetWidth() > graphics_->GetWidth() || renderTarget->GetHeight() > graphics_->GetHeight())
  87. {
  88. // Display message only once per rendertarget, do not spam each frame
  89. if (!gBufferErrorDisplayed_.Contains(renderTarget))
  90. {
  91. gBufferErrorDisplayed_.Insert(renderTarget);
  92. LOGERROR("Render texture is larger than the G-buffer, can not render");
  93. }
  94. return false;
  95. }
  96. }
  97. octree_ = octree;
  98. camera_ = viewport.camera_;
  99. renderTarget_ = renderTarget;
  100. if (!renderTarget)
  101. depthStencil_ = 0;
  102. else
  103. {
  104. // In Direct3D9 deferred rendering, always use the system depth stencil for the whole time
  105. // to ensure it is as large as the G-buffer
  106. #ifdef USE_OPENGL
  107. depthStencil_ = renderTarget->GetLinkedDepthBuffer();
  108. #else
  109. if (mode_ == RENDER_FORWARD)
  110. depthStencil_ = renderTarget->GetLinkedDepthBuffer();
  111. else
  112. depthStencil_ = 0;
  113. #endif
  114. }
  115. zone_ = renderer_->GetDefaultZone();
  116. // Validate the rect and calculate size. If zero rect, use whole render target size
  117. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  118. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  119. if (viewport.rect_ != IntRect::ZERO)
  120. {
  121. screenRect_.left_ = Clamp(viewport.rect_.left_, 0, rtWidth - 1);
  122. screenRect_.top_ = Clamp(viewport.rect_.top_, 0, rtHeight - 1);
  123. screenRect_.right_ = Clamp(viewport.rect_.right_, screenRect_.left_ + 1, rtWidth);
  124. screenRect_.bottom_ = Clamp(viewport.rect_.bottom_, screenRect_.top_ + 1, rtHeight);
  125. }
  126. else
  127. screenRect_ = IntRect(0, 0, rtWidth, rtHeight);
  128. width_ = screenRect_.right_ - screenRect_.left_;
  129. height_ = screenRect_.bottom_ - screenRect_.top_;
  130. // Set possible quality overrides from the camera
  131. drawShadows_ = renderer_->GetDrawShadows();
  132. materialQuality_ = renderer_->GetMaterialQuality();
  133. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  134. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  135. if (viewOverrideFlags & VOF_LOW_MATERIAL_QUALITY)
  136. materialQuality_ = QUALITY_LOW;
  137. if (viewOverrideFlags & VOF_DISABLE_SHADOWS)
  138. drawShadows_ = false;
  139. if (viewOverrideFlags & VOF_DISABLE_OCCLUSION)
  140. maxOccluderTriangles_ = 0;
  141. return true;
  142. }
  143. void View::Update(const FrameInfo& frame)
  144. {
  145. if (!camera_ || !octree_)
  146. return;
  147. frame_.camera_ = camera_;
  148. frame_.timeStep_ = frame.timeStep_;
  149. frame_.frameNumber_ = frame.frameNumber_;
  150. frame_.viewSize_ = IntVector2(width_, height_);
  151. // Clear old light scissor cache, geometry, light, occluder & batch lists
  152. lightScissorCache_.Clear();
  153. geometries_.Clear();
  154. geometryDepthBounds_.Clear();
  155. lights_.Clear();
  156. occluders_.Clear();
  157. shadowOccluders_.Clear();
  158. gBufferQueue_.Clear();
  159. baseQueue_.Clear();
  160. extraQueue_.Clear();
  161. transparentQueue_.Clear();
  162. noShadowLightQueue_.Clear();
  163. lightQueues_.Clear();
  164. // Do not update if camera projection is illegal
  165. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  166. if (!camera_->IsProjectionValid())
  167. return;
  168. // Set automatic aspect ratio if required
  169. if (camera_->GetAutoAspectRatio())
  170. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  171. // Reset projection jitter if was used last frame
  172. camera_->SetProjectionOffset(Vector2::ZERO);
  173. // Reset shadow map use count; they can be reused between views as each is rendered completely at a time
  174. renderer_->ResetShadowMapUseCount();
  175. GetDrawables();
  176. GetBatches();
  177. }
  178. void View::Render()
  179. {
  180. if (!octree_ || !camera_)
  181. return;
  182. // Forget parameter sources from the previous view
  183. graphics_->ClearParameterSources();
  184. // If stream offset is supported, write all instance transforms to a single large buffer
  185. // Else we must lock the instance buffer for each batch group
  186. if (renderer_->GetDynamicInstancing() && graphics_->GetStreamOffsetSupport())
  187. PrepareInstancingBuffer();
  188. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  189. // again to ensure correct projection will be used
  190. if (camera_->GetAutoAspectRatio())
  191. camera_->SetAspectRatio((float)(screenRect_.right_ - screenRect_.left_) / (float)(screenRect_.bottom_ - screenRect_.top_));
  192. // Set the "view texture" to ensure the rendertarget will not be bound as a texture during rendering
  193. if (renderTarget_)
  194. graphics_->SetViewTexture(renderTarget_->GetParentTexture());
  195. else
  196. graphics_->SetViewTexture(0);
  197. graphics_->SetColorWrite(true);
  198. graphics_->SetFillMode(FILL_SOLID);
  199. graphics_->SetScissorTest(false);
  200. graphics_->SetStencilTest(false);
  201. // Calculate view-global shader parameters
  202. CalculateShaderParameters();
  203. // If not reusing shadowmaps, render all of them first
  204. if (!renderer_->reuseShadowMaps_)
  205. {
  206. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  207. {
  208. LightBatchQueue& queue = lightQueues_[i];
  209. if (queue.light_->GetShadowMap())
  210. RenderShadowMap(queue);
  211. }
  212. }
  213. if (mode_ == RENDER_FORWARD)
  214. RenderBatchesForward();
  215. else
  216. RenderBatchesDeferred();
  217. graphics_->SetViewTexture(0);
  218. graphics_->SetScissorTest(false);
  219. graphics_->SetStencilTest(false);
  220. graphics_->ResetStreamFrequencies();
  221. // If this is a main view, draw the associated debug geometry now
  222. if (!renderTarget_)
  223. {
  224. Scene* scene = static_cast<Scene*>(octree_->GetNode());
  225. if (scene)
  226. {
  227. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  228. if (debug)
  229. {
  230. debug->SetView(camera_);
  231. debug->Render();
  232. }
  233. }
  234. }
  235. // "Forget" the camera, octree and zone after rendering
  236. camera_ = 0;
  237. octree_ = 0;
  238. zone_ = 0;
  239. frame_.camera_ = 0;
  240. }
  241. void View::GetDrawables()
  242. {
  243. PROFILE(GetDrawables);
  244. Vector3 cameraPos = camera_->GetWorldPosition();
  245. // Get zones & find the zone camera is in
  246. PointOctreeQuery query(tempDrawables_, cameraPos, DRAWABLE_ZONE, camera_->GetViewMask());
  247. octree_->GetDrawables(query);
  248. int highestZonePriority = M_MIN_INT;
  249. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  250. {
  251. Zone* zone = static_cast<Zone*>(tempDrawables_[i]);
  252. if (zone->IsInside(cameraPos) && zone->GetPriority() > highestZonePriority)
  253. {
  254. zone_ = zone;
  255. highestZonePriority = zone->GetPriority();
  256. }
  257. }
  258. // If occlusion in use, get & render the occluders, then build the depth buffer hierarchy
  259. OcclusionBuffer* buffer = 0;
  260. if (maxOccluderTriangles_ > 0)
  261. {
  262. FrustumOctreeQuery query(occluders_, camera_->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask(), true, false);
  263. octree_->GetDrawables(query);
  264. UpdateOccluders(occluders_, camera_);
  265. if (occluders_.Size())
  266. {
  267. buffer = renderer_->GetOrCreateOcclusionBuffer(camera_, maxOccluderTriangles_);
  268. DrawOccluders(buffer, occluders_);
  269. buffer->BuildDepthHierarchy();
  270. }
  271. }
  272. if (!buffer)
  273. {
  274. // Get geometries & lights without occlusion
  275. FrustumOctreeQuery query(tempDrawables_, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  276. octree_->GetDrawables(query);
  277. }
  278. else
  279. {
  280. // Get geometries & lights using occlusion
  281. OccludedFrustumOctreeQuery query(tempDrawables_, camera_->GetFrustum(), buffer, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT,
  282. camera_->GetViewMask());
  283. octree_->GetDrawables(query);
  284. }
  285. // Sort into geometries & lights, and build visible scene bounding boxes in world and view space
  286. sceneBox_.min_ = sceneBox_.max_ = Vector3::ZERO;
  287. sceneBox_.defined_ = false;
  288. sceneViewBox_.min_ = sceneViewBox_.max_ = Vector3::ZERO;
  289. sceneViewBox_.defined_ = false;
  290. Matrix3x4 view(camera_->GetInverseWorldTransform());
  291. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  292. {
  293. Drawable* drawable = tempDrawables_[i];
  294. drawable->UpdateDistance(frame_);
  295. // If draw distance non-zero, check it
  296. float maxDistance = drawable->GetDrawDistance();
  297. if (maxDistance > 0.0f && drawable->GetDistance() > maxDistance)
  298. continue;
  299. unsigned flags = drawable->GetDrawableFlags();
  300. if (flags & DRAWABLE_GEOMETRY)
  301. {
  302. drawable->ClearBasePass();
  303. drawable->MarkInView(frame_);
  304. drawable->UpdateGeometry(frame_);
  305. // Expand the scene bounding boxes
  306. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  307. BoundingBox geomViewBox = geomBox.Transformed(view);
  308. sceneBox_.Merge(geomBox);
  309. sceneViewBox_.Merge(geomViewBox);
  310. // Store depth info to speed up split directional light queries
  311. GeometryDepthBounds bounds;
  312. bounds.min_ = geomViewBox.min_.z_;
  313. bounds.max_ = geomViewBox.max_.z_;
  314. geometryDepthBounds_.Push(bounds);
  315. geometries_.Push(drawable);
  316. }
  317. else if (flags & DRAWABLE_LIGHT)
  318. {
  319. Light* light = static_cast<Light*>(drawable);
  320. // Skip if light is culled by the zone
  321. if (!(light->GetViewMask() & zone_->GetViewMask()))
  322. continue;
  323. light->MarkInView(frame_);
  324. lights_.Push(light);
  325. }
  326. }
  327. // Sort the lights to brightest/closest first
  328. for (unsigned i = 0; i < lights_.Size(); ++i)
  329. lights_[i]->SetIntensitySortValue(cameraPos);
  330. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  331. }
  332. void View::GetBatches()
  333. {
  334. litTransparencies_.Clear();
  335. maxLightsDrawables_.Clear();
  336. lightQueueIndex_.Clear();
  337. // Go through lights
  338. {
  339. PROFILE_MULTIPLE(GetLightBatches, lights_.Size());
  340. unsigned lightQueueCount = 0;
  341. for (unsigned i = 0; i < lights_.Size(); ++i)
  342. {
  343. Light* light = lights_[i];
  344. unsigned splits = ProcessLight(light);
  345. if (!splits)
  346. continue;
  347. // Prepare lit object + shadow caster queues for each split
  348. if (lightQueues_.Size() < lightQueueCount + splits)
  349. lightQueues_.Resize(lightQueueCount + splits);
  350. bool firstSplitStored = false;
  351. for (unsigned j = 0; j < splits; ++j)
  352. {
  353. Light* splitLight = splitLights_[j];
  354. LightBatchQueue& lightQueue = lightQueues_[lightQueueCount];
  355. lightQueue.light_ = splitLight;
  356. lightQueue.shadowBatches_.Clear();
  357. lightQueue.litBatches_.Clear();
  358. lightQueue.volumeBatches_.Clear();
  359. lightQueue.firstSplit_ = !firstSplitStored;
  360. // Loop through shadow casters
  361. Camera* shadowCamera = splitLight->GetShadowCamera();
  362. for (unsigned k = 0; k < shadowCasters_[j].Size(); ++k)
  363. {
  364. Drawable* drawable = shadowCasters_[j][k];
  365. unsigned numBatches = drawable->GetNumBatches();
  366. for (unsigned l = 0; l < numBatches; ++l)
  367. {
  368. Batch shadowBatch;
  369. drawable->GetBatch(frame_, l, shadowBatch);
  370. Technique* tech = GetTechnique(drawable, shadowBatch.material_);
  371. if (!shadowBatch.geometry_ || !tech)
  372. continue;
  373. Pass* pass = tech->GetPass(PASS_SHADOW);
  374. // Skip if material has no shadow pass
  375. if (!pass)
  376. continue;
  377. // Fill the rest of the batch
  378. shadowBatch.camera_ = shadowCamera;
  379. shadowBatch.distance_ = shadowCamera->GetDistance(drawable->GetWorldPosition());
  380. shadowBatch.light_ = splitLight;
  381. shadowBatch.hasPriority_ = !pass->GetAlphaTest() && !pass->GetAlphaMask();
  382. renderer_->SetBatchShaders(shadowBatch, tech, pass);
  383. lightQueue.shadowBatches_.AddBatch(shadowBatch);
  384. }
  385. }
  386. // Loop through lit geometries
  387. if (litGeometries_[j].Size())
  388. {
  389. bool storeLightQueue = true;
  390. for (unsigned k = 0; k < litGeometries_[j].Size(); ++k)
  391. {
  392. Drawable* drawable = litGeometries_[j][k];
  393. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  394. if (!drawable->GetMaxLights())
  395. GetLitBatches(drawable, light, splitLight, lightQueue);
  396. else
  397. {
  398. drawable->AddLight(splitLight);
  399. maxLightsDrawables_.Insert(drawable);
  400. }
  401. }
  402. // Store the light queue, and light volume batch in deferred mode
  403. if (mode_ != RENDER_FORWARD)
  404. {
  405. Batch volumeBatch;
  406. volumeBatch.geometry_ = renderer_->GetLightGeometry(splitLight);
  407. volumeBatch.worldTransform_ = &splitLight->GetVolumeTransform(*camera_);
  408. volumeBatch.overrideView_ = splitLight->GetLightType() == LIGHT_DIRECTIONAL;
  409. volumeBatch.camera_ = camera_;
  410. volumeBatch.light_ = splitLight;
  411. volumeBatch.distance_ = splitLight->GetDistance();
  412. renderer_->SetLightVolumeShaders(volumeBatch);
  413. // If light is a split point light, it must be treated as shadowed in any case for correct stencil clearing
  414. if (splitLight->GetShadowMap() || splitLight->GetLightType() == LIGHT_SPLITPOINT)
  415. lightQueue.volumeBatches_.Push(volumeBatch);
  416. else
  417. {
  418. storeLightQueue = false;
  419. noShadowLightQueue_.AddBatch(volumeBatch, true);
  420. }
  421. }
  422. if (storeLightQueue)
  423. {
  424. lightQueueIndex_[splitLight] = lightQueueCount;
  425. firstSplitStored = true;
  426. ++lightQueueCount;
  427. }
  428. }
  429. }
  430. }
  431. // Resize the light queue vector now that final size is known
  432. lightQueues_.Resize(lightQueueCount);
  433. }
  434. // Process drawables with limited light count
  435. if (maxLightsDrawables_.Size())
  436. {
  437. PROFILE(GetMaxLightsBatches);
  438. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  439. {
  440. Drawable* drawable = *i;
  441. drawable->LimitLights();
  442. const PODVector<Light*>& lights = drawable->GetLights();
  443. for (unsigned i = 0; i < lights.Size(); ++i)
  444. {
  445. Light* splitLight = lights[i];
  446. Light* light = splitLight->GetOriginalLight();
  447. if (!light)
  448. light = splitLight;
  449. // Find the correct light queue again
  450. LightBatchQueue* queue = 0;
  451. Map<Light*, unsigned>::Iterator j = lightQueueIndex_.Find(splitLight);
  452. if (j != lightQueueIndex_.End())
  453. GetLitBatches(drawable, light, splitLight, lightQueues_[j->second_]);
  454. }
  455. }
  456. }
  457. // Go through geometries for base pass batches
  458. {
  459. PROFILE(GetBaseBatches);
  460. for (unsigned i = 0; i < geometries_.Size(); ++i)
  461. {
  462. Drawable* drawable = geometries_[i];
  463. unsigned numBatches = drawable->GetNumBatches();
  464. for (unsigned j = 0; j < numBatches; ++j)
  465. {
  466. Batch baseBatch;
  467. drawable->GetBatch(frame_, j, baseBatch);
  468. Technique* tech = GetTechnique(drawable, baseBatch.material_);
  469. if (!baseBatch.geometry_ || !tech)
  470. continue;
  471. // Check here if the material technique refers to a render target texture with camera(s) attached
  472. // Only check this for the main view (null rendertarget)
  473. if (!renderTarget_ && baseBatch.material_ && baseBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_)
  474. CheckMaterialForAuxView(baseBatch.material_);
  475. // If object already has a lit base pass, can skip the unlit base pass
  476. if (drawable->HasBasePass(j))
  477. continue;
  478. // Fill the rest of the batch
  479. baseBatch.camera_ = camera_;
  480. baseBatch.distance_ = drawable->GetDistance();
  481. Pass* pass = 0;
  482. // In deferred mode, check for a G-buffer batch first
  483. if (mode_ != RENDER_FORWARD)
  484. {
  485. pass = tech->GetPass(PASS_GBUFFER);
  486. if (pass)
  487. {
  488. renderer_->SetBatchShaders(baseBatch, tech, pass);
  489. baseBatch.hasPriority_ = !pass->GetAlphaTest() && !pass->GetAlphaMask();
  490. gBufferQueue_.AddBatch(baseBatch);
  491. // Check also for an additional pass (possibly for emissive)
  492. pass = tech->GetPass(PASS_EXTRA);
  493. if (pass)
  494. {
  495. renderer_->SetBatchShaders(baseBatch, tech, pass);
  496. baseQueue_.AddBatch(baseBatch);
  497. }
  498. continue;
  499. }
  500. }
  501. // Then check for forward rendering base pass
  502. pass = tech->GetPass(PASS_BASE);
  503. if (pass)
  504. {
  505. renderer_->SetBatchShaders(baseBatch, tech, pass);
  506. if (pass->GetBlendMode() == BLEND_REPLACE)
  507. {
  508. baseBatch.hasPriority_ = !pass->GetAlphaTest() && !pass->GetAlphaMask();
  509. baseQueue_.AddBatch(baseBatch);
  510. }
  511. else
  512. {
  513. baseBatch.hasPriority_ = true;
  514. transparentQueue_.AddBatch(baseBatch, true);
  515. }
  516. continue;
  517. }
  518. else
  519. {
  520. // If no base pass, finally check for extra / custom pass
  521. pass = tech->GetPass(PASS_EXTRA);
  522. if (pass)
  523. {
  524. baseBatch.hasPriority_ = false;
  525. renderer_->SetBatchShaders(baseBatch, tech, pass);
  526. extraQueue_.AddBatch(baseBatch);
  527. }
  528. }
  529. }
  530. }
  531. }
  532. // All batches have been collected. Sort them now
  533. SortBatches();
  534. }
  535. void View::GetLitBatches(Drawable* drawable, Light* light, Light* splitLight, LightBatchQueue& lightQueue)
  536. {
  537. bool splitPointLight = splitLight->GetLightType() == LIGHT_SPLITPOINT;
  538. // Whether to allow shadows for transparencies, or for forward lit objects in deferred mode
  539. bool allowShadows = !renderer_->reuseShadowMaps_ && !splitPointLight;
  540. unsigned numBatches = drawable->GetNumBatches();
  541. for (unsigned i = 0; i < numBatches; ++i)
  542. {
  543. Batch litBatch;
  544. drawable->GetBatch(frame_, i, litBatch);
  545. Technique* tech = GetTechnique(drawable, litBatch.material_);
  546. if (!litBatch.geometry_ || !tech)
  547. continue;
  548. // If material uses opaque G-buffer rendering, skip
  549. if (mode_ != RENDER_FORWARD && tech->HasPass(PASS_GBUFFER))
  550. continue;
  551. Pass* pass = 0;
  552. bool priority = false;
  553. // For the (first) directional light, check for lit base pass
  554. if (light == lights_[0] && splitLight->GetLightType() == LIGHT_DIRECTIONAL)
  555. {
  556. if (!drawable->HasBasePass(i))
  557. {
  558. pass = tech->GetPass(PASS_LITBASE);
  559. if (pass)
  560. {
  561. priority = true;
  562. drawable->SetBasePass(i);
  563. }
  564. }
  565. }
  566. // If no lit base pass, get ordinary light pass
  567. if (!pass)
  568. pass = tech->GetPass(PASS_LIGHT);
  569. // Skip if material does not receive light at all
  570. if (!pass)
  571. continue;
  572. // Fill the rest of the batch
  573. litBatch.camera_ = camera_;
  574. litBatch.distance_ = drawable->GetDistance();
  575. litBatch.light_ = splitLight;
  576. litBatch.hasPriority_ = priority;
  577. // Check from the ambient pass whether the object is opaque
  578. Pass* ambientPass = tech->GetPass(PASS_BASE);
  579. if (!ambientPass || ambientPass->GetBlendMode() == BLEND_REPLACE)
  580. {
  581. if (mode_ == RENDER_FORWARD)
  582. {
  583. renderer_->SetBatchShaders(litBatch, tech, pass);
  584. lightQueue.litBatches_.AddBatch(litBatch);
  585. }
  586. else
  587. {
  588. renderer_->SetBatchShaders(litBatch, tech, pass, allowShadows);
  589. baseQueue_.AddBatch(litBatch);
  590. }
  591. }
  592. else
  593. {
  594. if (splitPointLight)
  595. {
  596. // Check if already lit
  597. LitTransparencyCheck check(light, drawable, i);
  598. if (!litTransparencies_.Contains(check))
  599. {
  600. // Use the original light instead of the split one, to choose correct scissor
  601. litBatch.light_ = light;
  602. litTransparencies_.Insert(check);
  603. }
  604. else
  605. continue;
  606. }
  607. renderer_->SetBatchShaders(litBatch, tech, pass, allowShadows);
  608. transparentQueue_.AddBatch(litBatch, true);
  609. }
  610. }
  611. }
  612. void View::RenderBatchesForward()
  613. {
  614. {
  615. // Render opaque objects' base passes
  616. PROFILE(RenderBasePass);
  617. graphics_->SetRenderTarget(0, renderTarget_);
  618. graphics_->SetDepthStencil(depthStencil_);
  619. graphics_->SetViewport(screenRect_);
  620. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, zone_->GetFogColor());
  621. RenderBatchQueue(baseQueue_);
  622. }
  623. {
  624. // Render shadow maps + opaque objects' shadowed additive lighting
  625. PROFILE(RenderLights);
  626. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  627. {
  628. LightBatchQueue& queue = lightQueues_[i];
  629. // If reusing shadowmaps, render each of them before the lit batches
  630. if (renderer_->reuseShadowMaps_ && queue.light_->GetShadowMap())
  631. RenderShadowMap(queue);
  632. graphics_->SetRenderTarget(0, renderTarget_);
  633. graphics_->SetDepthStencil(depthStencil_);
  634. graphics_->SetViewport(screenRect_);
  635. RenderForwardLightBatchQueue(queue.litBatches_, queue.light_, queue.firstSplit_);
  636. }
  637. }
  638. graphics_->SetScissorTest(false);
  639. graphics_->SetStencilTest(false);
  640. graphics_->SetRenderTarget(0, renderTarget_);
  641. graphics_->SetDepthStencil(depthStencil_);
  642. graphics_->SetViewport(screenRect_);
  643. if (!extraQueue_.IsEmpty())
  644. {
  645. // Render extra / custom passes
  646. PROFILE(RenderExtraPass);
  647. RenderBatchQueue(extraQueue_);
  648. }
  649. if (!transparentQueue_.IsEmpty())
  650. {
  651. // Render transparent objects last (both base passes & additive lighting)
  652. PROFILE(RenderTransparent);
  653. RenderBatchQueue(transparentQueue_, true);
  654. }
  655. }
  656. void View::RenderBatchesDeferred()
  657. {
  658. Texture2D* diffBuffer = graphics_->GetDiffBuffer();
  659. Texture2D* normalBuffer = graphics_->GetNormalBuffer();
  660. Texture2D* depthBuffer = graphics_->GetDepthBuffer();
  661. // Check for temporal antialiasing in deferred mode. Only use it on the main view (null rendertarget)
  662. bool temporalAA = (!renderTarget_) && (graphics_->GetMultiSample() > 1);
  663. if (temporalAA)
  664. {
  665. ++jitterCounter_;
  666. if (jitterCounter_ > 3)
  667. jitterCounter_ = 2;
  668. Vector2 jitter(-0.25f, -0.25f);
  669. if (jitterCounter_ & 1)
  670. jitter = -jitter;
  671. jitter.x_ /= width_;
  672. jitter.y_ /= height_;
  673. camera_->SetProjectionOffset(jitter);
  674. }
  675. RenderSurface* renderBuffer = temporalAA ? graphics_->GetScreenBuffer(jitterCounter_ & 1)->GetRenderSurface() : renderTarget_;
  676. {
  677. // Clear and render the G-buffer
  678. PROFILE(RenderGBuffer);
  679. graphics_->SetRenderTarget(0, diffBuffer);
  680. graphics_->SetDepthStencil(depthBuffer);
  681. if (graphics_->GetHardwareDepthSupport())
  682. {
  683. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL);
  684. graphics_->SetRenderTarget(1, normalBuffer);
  685. }
  686. else
  687. {
  688. graphics_->Clear(CLEAR_DEPTH | CLEAR_STENCIL);
  689. graphics_->SetRenderTarget(1, normalBuffer);
  690. graphics_->SetRenderTarget(2, depthBuffer);
  691. }
  692. RenderBatchQueue(gBufferQueue_);
  693. graphics_->SetAlphaTest(false);
  694. graphics_->SetBlendMode(BLEND_REPLACE);
  695. // If hardware depth is not available, perform a post-step to initialize the parts of the G-buffer that were not rendered into
  696. // (it is less expensive than clearing all the buffers in the first place)
  697. if (!graphics_->GetHardwareDepthSupport())
  698. {
  699. graphics_->SetDepthTest(CMP_LESSEQUAL);
  700. graphics_->SetDepthWrite(false);
  701. graphics_->ResetRenderTarget(2);
  702. graphics_->SetRenderTarget(1, depthBuffer);
  703. DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("GBufferFill"), renderer_->GetPixelShader("GBufferFill"),
  704. false, shaderParameters_);
  705. }
  706. graphics_->ResetRenderTarget(1);
  707. }
  708. {
  709. PROFILE(RenderAmbientQuad);
  710. // Render ambient color & fog. On OpenGL the depth buffer will be copied now
  711. graphics_->SetDepthTest(CMP_ALWAYS);
  712. #ifdef USE_OPENGL
  713. graphics_->SetDepthWrite(true);
  714. #else
  715. graphics_->SetDepthWrite(false);
  716. #endif
  717. graphics_->SetRenderTarget(0, renderBuffer);
  718. graphics_->SetDepthStencil(depthStencil_);
  719. graphics_->SetViewport(screenRect_);
  720. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  721. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  722. String pixelShaderName = "Ambient";
  723. #ifdef USE_OPENGL
  724. if (camera_->IsOrthographic())
  725. pixelShaderName += "_Ortho";
  726. // On OpenGL, set up a stencil operation to reset the stencil during ambient quad rendering
  727. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_ZERO, OP_KEEP, OP_KEEP);
  728. #else
  729. if (camera_->IsOrthographic() || !graphics_->GetHardwareDepthSupport())
  730. pixelShaderName += "_Linear";
  731. #endif
  732. DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("Ambient"), renderer_->GetPixelShader(pixelShaderName),
  733. false, shaderParameters_);
  734. #ifdef USE_OPENGL
  735. graphics_->SetStencilTest(false);
  736. #endif
  737. }
  738. {
  739. // Render lights
  740. PROFILE(RenderLights);
  741. // Shadowed lights
  742. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  743. {
  744. LightBatchQueue& queue = lightQueues_[i];
  745. // If reusing shadowmaps, render each of them before the lit batches
  746. if (renderer_->reuseShadowMaps_ && queue.light_->GetShadowMap())
  747. RenderShadowMap(queue);
  748. // Light volume batches are not sorted as there should be only one of them
  749. if (queue.volumeBatches_.Size())
  750. {
  751. graphics_->SetRenderTarget(0, renderBuffer);
  752. graphics_->SetDepthStencil(depthStencil_);
  753. graphics_->SetViewport(screenRect_);
  754. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  755. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  756. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  757. for (unsigned j = 0; j < queue.volumeBatches_.Size(); ++j)
  758. {
  759. SetupLightBatch(queue.volumeBatches_[j], queue.firstSplit_);
  760. queue.volumeBatches_[j].Draw(graphics_, shaderParameters_);
  761. }
  762. }
  763. }
  764. // Non-shadowed lights
  765. if (noShadowLightQueue_.sortedBatches_.Size())
  766. {
  767. graphics_->SetRenderTarget(0, renderBuffer);
  768. graphics_->SetDepthStencil(depthStencil_);
  769. graphics_->SetViewport(screenRect_);
  770. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  771. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  772. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  773. for (unsigned i = 0; i < noShadowLightQueue_.sortedBatches_.Size(); ++i)
  774. {
  775. SetupLightBatch(*noShadowLightQueue_.sortedBatches_[i], false);
  776. noShadowLightQueue_.sortedBatches_[i]->Draw(graphics_, shaderParameters_);
  777. }
  778. }
  779. }
  780. {
  781. // Render base passes
  782. PROFILE(RenderBasePass);
  783. graphics_->SetTexture(TU_DIFFBUFFER, 0);
  784. graphics_->SetTexture(TU_NORMALBUFFER, 0);
  785. graphics_->SetTexture(TU_DEPTHBUFFER, 0);
  786. graphics_->SetRenderTarget(0, renderBuffer);
  787. graphics_->SetDepthStencil(depthStencil_);
  788. graphics_->SetViewport(screenRect_);
  789. RenderBatchQueue(baseQueue_, true);
  790. }
  791. if (!extraQueue_.IsEmpty())
  792. {
  793. // Render extra / custom passes
  794. PROFILE(RenderExtraPass);
  795. RenderBatchQueue(extraQueue_);
  796. }
  797. if (!transparentQueue_.IsEmpty())
  798. {
  799. // Render transparent objects last (both ambient & additive lighting)
  800. PROFILE(RenderTransparent);
  801. RenderBatchQueue(transparentQueue_, true);
  802. }
  803. // Render temporal antialiasing now if enabled
  804. if (temporalAA)
  805. {
  806. PROFILE(RenderTemporalAA);
  807. // Disable averaging if it is the first frame rendered in this view
  808. float thisFrameWeight = jitterCounter_ < 2 ? 1.0f : 0.5f;
  809. String vsName = "TemporalAA";
  810. String psName = vsName;
  811. if (camera_->IsOrthographic())
  812. {
  813. vsName += "_Ortho";
  814. psName += "_Ortho";
  815. }
  816. else if (!graphics_->GetHardwareDepthSupport())
  817. psName += "_Linear";
  818. graphics_->SetAlphaTest(false);
  819. graphics_->SetBlendMode(BLEND_REPLACE);
  820. graphics_->SetDepthTest(CMP_ALWAYS);
  821. graphics_->SetDepthWrite(false);
  822. graphics_->SetRenderTarget(0, renderTarget_);
  823. graphics_->SetDepthStencil(depthStencil_);
  824. graphics_->SetViewport(screenRect_);
  825. // Pre-select the right shaders so that we can set shader parameters that can not go into the parameter map
  826. // (matrices)
  827. float gBufferWidth = (float)graphics_->GetWidth();
  828. float gBufferHeight = (float)graphics_->GetHeight();
  829. ShaderVariation* vertexShader = renderer_->GetVertexShader(vsName);
  830. ShaderVariation* pixelShader = renderer_->GetPixelShader(psName);
  831. graphics_->SetShaders(vertexShader, pixelShader);
  832. graphics_->SetShaderParameter(VSP_CAMERAROT, camera_->GetWorldTransform().RotationMatrix());
  833. graphics_->SetShaderParameter(PSP_CAMERAPOS, camera_->GetWorldPosition());
  834. graphics_->SetShaderParameter(PSP_SAMPLEOFFSETS, Vector4(1.0f / gBufferWidth, 1.0f / gBufferHeight, thisFrameWeight, 1.0f - thisFrameWeight));
  835. graphics_->SetShaderParameter(PSP_VIEWPROJ, camera_->GetProjection(false) * lastCameraView_);
  836. graphics_->SetTexture(TU_DIFFBUFFER, graphics_->GetScreenBuffer(jitterCounter_ & 1));
  837. graphics_->SetTexture(TU_NORMALBUFFER, graphics_->GetScreenBuffer((jitterCounter_ + 1) & 1));
  838. graphics_->SetTexture(TU_DEPTHBUFFER, graphics_->GetDepthBuffer());
  839. DrawFullScreenQuad(*camera_, vertexShader, pixelShader, false, shaderParameters_);
  840. // Store view transform for next frame
  841. lastCameraView_ = camera_->GetInverseWorldTransform();
  842. }
  843. }
  844. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  845. {
  846. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  847. float halfViewSize = camera->GetHalfViewSize();
  848. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  849. Vector3 cameraPos = camera->GetWorldPosition();
  850. for (unsigned i = 0; i < occluders.Size(); ++i)
  851. {
  852. Drawable* occluder = occluders[i];
  853. occluder->UpdateDistance(frame_);
  854. bool erase = false;
  855. // Check occluder's draw distance (in main camera view)
  856. float maxDistance = occluder->GetDrawDistance();
  857. if (maxDistance > 0.0f && occluder->GetDistance() > maxDistance)
  858. erase = true;
  859. // Check that occluder is big enough on the screen
  860. const BoundingBox& box = occluder->GetWorldBoundingBox();
  861. float diagonal = (box.max_ - box.min_).LengthFast();
  862. float compare;
  863. if (!camera->IsOrthographic())
  864. compare = diagonal * halfViewSize / occluder->GetDistance();
  865. else
  866. compare = diagonal * invOrthoSize;
  867. if (compare < occluderSizeThreshold_)
  868. erase = true;
  869. if (!erase)
  870. {
  871. unsigned totalTriangles = 0;
  872. unsigned batches = occluder->GetNumBatches();
  873. Batch tempBatch;
  874. for (unsigned j = 0; j < batches; ++j)
  875. {
  876. occluder->GetBatch(frame_, j, tempBatch);
  877. if (tempBatch.geometry_)
  878. totalTriangles += tempBatch.geometry_->GetIndexCount() / 3;
  879. }
  880. // Store amount of triangles divided by screen size as a sorting key
  881. // (best occluders are big and have few triangles)
  882. occluder->SetSortValue((float)totalTriangles / compare);
  883. }
  884. else
  885. {
  886. occluders.Erase(occluders.Begin() + i);
  887. --i;
  888. }
  889. }
  890. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  891. if (occluders.Size())
  892. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  893. }
  894. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  895. {
  896. for (unsigned i = 0; i < occluders.Size(); ++i)
  897. {
  898. Drawable* occluder = occluders[i];
  899. if (i > 0)
  900. {
  901. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  902. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  903. continue;
  904. }
  905. occluder->UpdateGeometry(frame_);
  906. // Check for running out of triangles
  907. if (!occluder->DrawOcclusion(buffer))
  908. return;
  909. }
  910. }
  911. unsigned View::ProcessLight(Light* light)
  912. {
  913. unsigned numLitGeometries = 0;
  914. unsigned numShadowCasters = 0;
  915. unsigned numSplits;
  916. // Check if light should be shadowed
  917. bool isShadowed = drawShadows_ && light->GetCastShadows() && light->GetShadowIntensity() < 1.0f;
  918. // If shadow distance non-zero, check it
  919. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  920. isShadowed = false;
  921. // If light has no ramp textures defined, set defaults
  922. if (light->GetLightType() != LIGHT_DIRECTIONAL && !light->GetRampTexture())
  923. light->SetRampTexture(renderer_->GetDefaultLightRamp());
  924. if (light->GetLightType() == LIGHT_SPOT && !light->GetShapeTexture())
  925. light->SetShapeTexture(renderer_->GetDefaultLightSpot());
  926. // Split the light if necessary
  927. if (isShadowed)
  928. numSplits = SplitLight(light);
  929. else
  930. {
  931. // No splitting, use the original light
  932. splitLights_[0] = light;
  933. numSplits = 1;
  934. }
  935. // For a shadowed directional light, get occluders once using the whole (non-split) light frustum
  936. bool useOcclusion = false;
  937. OcclusionBuffer* buffer = 0;
  938. if (maxOccluderTriangles_ > 0 && isShadowed && light->GetLightType() == LIGHT_DIRECTIONAL)
  939. {
  940. // This shadow camera is never used for actually querying shadow casters, just occluders
  941. Camera* shadowCamera = renderer_->CreateShadowCamera();
  942. light->SetShadowCamera(shadowCamera);
  943. SetupShadowCamera(light, true);
  944. // Get occluders, which must be shadow-casting themselves
  945. FrustumOctreeQuery query(shadowOccluders_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask(), true,
  946. true);
  947. octree_->GetDrawables(query);
  948. UpdateOccluders(shadowOccluders_, shadowCamera);
  949. if (shadowOccluders_.Size())
  950. {
  951. // Shadow viewport is rectangular and consumes more CPU fillrate, so halve size
  952. buffer = renderer_->GetOrCreateOcclusionBuffer(shadowCamera, maxOccluderTriangles_, true);
  953. DrawOccluders(buffer, shadowOccluders_);
  954. buffer->BuildDepthHierarchy();
  955. useOcclusion = true;
  956. }
  957. }
  958. // Process each split for shadow camera update, lit geometries, and shadow casters
  959. for (unsigned i = 0; i < numSplits; ++i)
  960. {
  961. litGeometries_[i].Clear();
  962. shadowCasters_[i].Clear();
  963. }
  964. for (unsigned i = 0; i < numSplits; ++i)
  965. {
  966. Light* split = splitLights_[i];
  967. LightType type = split->GetLightType();
  968. bool isSplitShadowed = isShadowed && split->GetCastShadows();
  969. Camera* shadowCamera = 0;
  970. // If shadow casting, choose the shadow map & update shadow camera
  971. if (isSplitShadowed)
  972. {
  973. shadowCamera = renderer_->CreateShadowCamera();
  974. split->SetShadowMap(renderer_->GetShadowMap(splitLights_[i]->GetShadowResolution()));
  975. // Check if managed to get a shadow map. Otherwise must convert to non-shadowed
  976. if (split->GetShadowMap())
  977. {
  978. split->SetShadowCamera(shadowCamera);
  979. SetupShadowCamera(split);
  980. }
  981. else
  982. {
  983. isSplitShadowed = false;
  984. split->SetShadowCamera(0);
  985. }
  986. }
  987. else
  988. {
  989. split->SetShadowCamera(0);
  990. split->SetShadowMap(0);
  991. }
  992. BoundingBox geometryBox;
  993. BoundingBox shadowCasterBox;
  994. switch (type)
  995. {
  996. case LIGHT_DIRECTIONAL:
  997. // Loop through visible geometries and check if they belong to this split
  998. {
  999. float nearSplit = split->GetNearSplit() - split->GetNearFadeRange();
  1000. float farSplit = split->GetFarSplit();
  1001. // If split extends to the whole visible frustum, no depth check necessary
  1002. bool optimize = nearSplit <= camera_->GetNearClip() && farSplit >= camera_->GetFarClip();
  1003. // If whole visible scene is outside the split, can reject trivially
  1004. if (sceneViewBox_.min_.z_ > farSplit || sceneViewBox_.max_.z_ < nearSplit)
  1005. {
  1006. split->SetShadowMap(0);
  1007. continue;
  1008. }
  1009. bool generateBoxes = isSplitShadowed && split->GetShadowFocus().focus_;
  1010. Matrix3x4 lightView;
  1011. if (shadowCamera)
  1012. lightView = shadowCamera->GetInverseWorldTransform();
  1013. if (!optimize)
  1014. {
  1015. for (unsigned j = 0; j < geometries_.Size(); ++j)
  1016. {
  1017. Drawable* drawable = geometries_[j];
  1018. const GeometryDepthBounds& bounds = geometryDepthBounds_[j];
  1019. // Check bounds and light mask
  1020. if (bounds.min_ <= farSplit && bounds.max_ >= nearSplit && drawable->GetLightMask() &
  1021. split->GetLightMask())
  1022. {
  1023. litGeometries_[i].Push(drawable);
  1024. if (generateBoxes)
  1025. geometryBox.Merge(drawable->GetWorldBoundingBox().Transformed(lightView));
  1026. }
  1027. }
  1028. }
  1029. else
  1030. {
  1031. for (unsigned j = 0; j < geometries_.Size(); ++j)
  1032. {
  1033. Drawable* drawable = geometries_[j];
  1034. // Need to check light mask only
  1035. if (drawable->GetLightMask() & split->GetLightMask())
  1036. {
  1037. litGeometries_[i].Push(drawable);
  1038. if (generateBoxes)
  1039. geometryBox.Merge(drawable->GetWorldBoundingBox().Transformed(lightView));
  1040. }
  1041. }
  1042. }
  1043. }
  1044. // Then get shadow casters by shadow camera frustum query. Use occlusion because of potentially many geometries
  1045. if (isSplitShadowed && litGeometries_[i].Size())
  1046. {
  1047. Camera* shadowCamera = split->GetShadowCamera();
  1048. if (!useOcclusion)
  1049. {
  1050. // Get potential shadow casters without occlusion
  1051. FrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY,
  1052. camera_->GetViewMask());
  1053. octree_->GetDrawables(query);
  1054. }
  1055. else
  1056. {
  1057. // Get potential shadow casters with occlusion
  1058. OccludedFrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), buffer,
  1059. DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1060. octree_->GetDrawables(query);
  1061. }
  1062. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, false, isSplitShadowed);
  1063. }
  1064. break;
  1065. case LIGHT_POINT:
  1066. {
  1067. SphereOctreeQuery query(tempDrawables_, Sphere(split->GetWorldPosition(), split->GetRange()), DRAWABLE_GEOMETRY,
  1068. camera_->GetViewMask());
  1069. octree_->GetDrawables(query);
  1070. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, true, false);
  1071. }
  1072. break;
  1073. case LIGHT_SPOT:
  1074. case LIGHT_SPLITPOINT:
  1075. {
  1076. FrustumOctreeQuery query(tempDrawables_, splitLights_[i]->GetFrustum(), DRAWABLE_GEOMETRY,
  1077. camera_->GetViewMask());
  1078. octree_->GetDrawables(query);
  1079. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, true, isSplitShadowed);
  1080. }
  1081. break;
  1082. }
  1083. // Optimization: if a particular split has no shadow casters, render as unshadowed. Else finalize shadow camera view
  1084. // according to the geometries and shadow casters combined bounding boxes
  1085. if (!shadowCasters_[i].Size())
  1086. split->SetShadowMap(0);
  1087. else
  1088. FinalizeShadowCamera(split, geometryBox, shadowCasterBox);
  1089. // Update count of total lit geometries & shadow casters
  1090. numLitGeometries += litGeometries_[i].Size();
  1091. numShadowCasters += shadowCasters_[i].Size();
  1092. }
  1093. // If no lit geometries at all, no need to process further
  1094. if (!numLitGeometries)
  1095. numSplits = 0;
  1096. // If no shadow casters at all, concatenate lit geometries into one & return the original light
  1097. else if (!numShadowCasters)
  1098. {
  1099. if (numSplits > 1)
  1100. {
  1101. // Make sure there are no duplicates
  1102. allLitGeometries_.Clear();
  1103. for (unsigned i = 0; i < numSplits; ++i)
  1104. {
  1105. for (Vector<Drawable*>::Iterator j = litGeometries_[i].Begin(); j != litGeometries_[i].End(); ++j)
  1106. allLitGeometries_.Insert(*j);
  1107. }
  1108. litGeometries_[0].Resize(allLitGeometries_.Size());
  1109. unsigned index = 0;
  1110. for (HashSet<Drawable*>::Iterator i = allLitGeometries_.Begin(); i != allLitGeometries_.End(); ++i)
  1111. litGeometries_[0][index++] = *i;
  1112. }
  1113. splitLights_[0] = light;
  1114. splitLights_[0]->SetShadowMap(0);
  1115. numSplits = 1;
  1116. }
  1117. return numSplits;
  1118. }
  1119. void View::ProcessLightQuery(unsigned splitIndex, const PODVector<Drawable*>& result, BoundingBox& geometryBox,
  1120. BoundingBox& shadowCasterBox, bool getLitGeometries, bool getShadowCasters)
  1121. {
  1122. Light* light = splitLights_[splitIndex];
  1123. Matrix3x4 lightView;
  1124. Matrix4 lightProj;
  1125. Frustum lightViewFrustum;
  1126. BoundingBox lightViewFrustumBox;
  1127. bool mergeBoxes = false;
  1128. bool projectBoxes = false;
  1129. Camera* shadowCamera = light->GetShadowCamera();
  1130. if (shadowCamera)
  1131. {
  1132. mergeBoxes = light->GetLightType() != LIGHT_SPLITPOINT && light->GetShadowFocus().focus_;
  1133. projectBoxes = !shadowCamera->IsOrthographic();
  1134. lightView = shadowCamera->GetInverseWorldTransform();
  1135. lightProj = shadowCamera->GetProjection();
  1136. // Transform scene frustum into shadow camera's view space for shadow caster visibility check
  1137. // For point & spot lights, we can use the whole scene frustum. For directional lights, use the
  1138. // intersection of the scene frustum and the split frustum, so that shadow casters do not get
  1139. // rendered into unnecessary splits
  1140. if (light->GetLightType() != LIGHT_DIRECTIONAL)
  1141. lightViewFrustum = camera_->GetSplitFrustum(sceneViewBox_.min_.z_, sceneViewBox_.max_.z_).Transformed(lightView);
  1142. else
  1143. lightViewFrustum = camera_->GetSplitFrustum(Max(sceneViewBox_.min_.z_, light->GetNearSplit() -
  1144. light->GetNearFadeRange()), Min(sceneViewBox_.max_.z_, light->GetFarSplit())).Transformed(lightView);
  1145. lightViewFrustumBox.Define(lightViewFrustum);
  1146. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1147. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1148. getShadowCasters = false;
  1149. }
  1150. else
  1151. getShadowCasters = false;
  1152. BoundingBox lightViewBox;
  1153. BoundingBox lightProjBox;
  1154. for (unsigned i = 0; i < result.Size(); ++i)
  1155. {
  1156. Drawable* drawable = static_cast<Drawable*>(result[i]);
  1157. drawable->UpdateDistance(frame_);
  1158. bool boxGenerated = false;
  1159. // If draw distance non-zero, check it
  1160. float maxDistance = drawable->GetDrawDistance();
  1161. if (maxDistance > 0.0f && drawable->GetDistance() > maxDistance)
  1162. continue;
  1163. // Check light mask
  1164. if (!(drawable->GetLightMask() & light->GetLightMask()))
  1165. continue;
  1166. // Get lit geometry only if inside main camera frustum this frame
  1167. if (getLitGeometries && drawable->IsInView(frame_))
  1168. {
  1169. if (mergeBoxes)
  1170. {
  1171. // Transform bounding box into light view space, and to projection space if needed
  1172. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1173. if (!projectBoxes)
  1174. geometryBox.Merge(lightViewBox);
  1175. else
  1176. {
  1177. lightProjBox = lightViewBox.Projected(lightProj);
  1178. geometryBox.Merge(lightProjBox);
  1179. }
  1180. boxGenerated = true;
  1181. }
  1182. litGeometries_[splitIndex].Push(drawable);
  1183. }
  1184. // Shadow caster need not be inside main camera frustum: in that case try to detect whether
  1185. // the shadow projection intersects the view
  1186. if (getShadowCasters && drawable->GetCastShadows())
  1187. {
  1188. // If shadow distance non-zero, check it
  1189. float maxShadowDistance = drawable->GetShadowDistance();
  1190. if (maxShadowDistance > 0.0f && drawable->GetDistance() > maxShadowDistance)
  1191. continue;
  1192. if (!boxGenerated)
  1193. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1194. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1195. {
  1196. if (mergeBoxes)
  1197. {
  1198. if (!projectBoxes)
  1199. shadowCasterBox.Merge(lightViewBox);
  1200. else
  1201. {
  1202. if (!boxGenerated)
  1203. lightProjBox = lightViewBox.Projected(lightProj);
  1204. shadowCasterBox.Merge(lightProjBox);
  1205. }
  1206. }
  1207. // Update geometry now if not updated yet
  1208. if (!drawable->IsInView(frame_))
  1209. {
  1210. drawable->MarkInShadowView(frame_);
  1211. drawable->UpdateGeometry(frame_);
  1212. }
  1213. shadowCasters_[splitIndex].Push(drawable);
  1214. }
  1215. }
  1216. }
  1217. }
  1218. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  1219. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  1220. {
  1221. // If shadow caster is also an occluder, must let it be visible, because it has potentially already culled
  1222. // away other shadow casters (could also check the actual shadow occluder vector, but that would be slower)
  1223. if (drawable->IsOccluder())
  1224. return true;
  1225. if (shadowCamera->IsOrthographic())
  1226. {
  1227. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  1228. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  1229. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1230. }
  1231. else
  1232. {
  1233. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  1234. if (drawable->IsInView(frame_))
  1235. return true;
  1236. // For perspective lights, extrusion direction depends on the position of the shadow caster
  1237. Vector3 center = lightViewBox.Center();
  1238. Ray extrusionRay(center, center.Normalized());
  1239. float extrusionDistance = shadowCamera->GetFarClip();
  1240. float originalDistance = Clamp(center.LengthFast(), M_EPSILON, extrusionDistance);
  1241. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  1242. float sizeFactor = extrusionDistance / originalDistance;
  1243. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  1244. // than necessary, so the test will be conservative
  1245. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  1246. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  1247. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  1248. lightViewBox.Merge(extrudedBox);
  1249. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1250. }
  1251. }
  1252. void View::SetupShadowCamera(Light* light, bool shadowOcclusion)
  1253. {
  1254. Camera* shadowCamera = light->GetShadowCamera();
  1255. Node* cameraNode = shadowCamera->GetNode();
  1256. const FocusParameters& parameters = light->GetShadowFocus();
  1257. // Reset zoom
  1258. shadowCamera->SetZoom(1.0f);
  1259. switch (light->GetLightType())
  1260. {
  1261. case LIGHT_DIRECTIONAL:
  1262. {
  1263. float extrusionDistance = camera_->GetFarClip();
  1264. // Calculate initial position & rotation
  1265. Vector3 lightWorldDirection = light->GetWorldRotation() * Vector3::FORWARD;
  1266. Vector3 pos = camera_->GetWorldPosition() - extrusionDistance * lightWorldDirection;
  1267. Quaternion rot(Vector3::FORWARD, lightWorldDirection);
  1268. cameraNode->SetTransform(pos, rot);
  1269. // Calculate main camera shadowed frustum in light's view space
  1270. float sceneMaxZ = camera_->GetFarClip();
  1271. // When shadow focusing is enabled, use the scene far Z to limit maximum frustum size
  1272. if (shadowOcclusion || parameters.focus_)
  1273. sceneMaxZ = Min(sceneViewBox_.max_.z_, sceneMaxZ);
  1274. Matrix3x4 lightView(shadowCamera->GetInverseWorldTransform());
  1275. Frustum lightViewSplitFrustum = camera_->GetSplitFrustum(light->GetNearSplit() - light->GetNearFadeRange(),
  1276. Min(light->GetFarSplit(), sceneMaxZ)).Transformed(lightView);
  1277. // Fit the frustum inside a bounding box. If uniform size, use a sphere instead
  1278. BoundingBox shadowBox;
  1279. if (!shadowOcclusion && parameters.nonUniform_)
  1280. shadowBox.Define(lightViewSplitFrustum);
  1281. else
  1282. {
  1283. Sphere shadowSphere;
  1284. shadowSphere.Define(lightViewSplitFrustum);
  1285. shadowBox.Define(shadowSphere);
  1286. }
  1287. shadowCamera->SetOrthographic(true);
  1288. shadowCamera->SetNearClip(0.0f);
  1289. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1290. // Center shadow camera on the bounding box, snap to whole texels
  1291. QuantizeDirShadowCamera(light, shadowBox);
  1292. }
  1293. break;
  1294. case LIGHT_SPOT:
  1295. case LIGHT_SPLITPOINT:
  1296. {
  1297. cameraNode->SetTransform(light->GetWorldPosition(), light->GetWorldRotation());
  1298. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1299. shadowCamera->SetFarClip(light->GetRange());
  1300. shadowCamera->SetOrthographic(false);
  1301. shadowCamera->SetFov(light->GetFov());
  1302. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1303. }
  1304. break;
  1305. }
  1306. }
  1307. void View::FinalizeShadowCamera(Light* light, const BoundingBox& geometryBox, const BoundingBox& shadowCasterBox)
  1308. {
  1309. // If either no geometries or no shadow casters, do nothing
  1310. if (!geometryBox.defined_ || !shadowCasterBox.defined_)
  1311. return;
  1312. Camera* shadowCamera = light->GetShadowCamera();
  1313. const FocusParameters& parameters = light->GetShadowFocus();
  1314. switch (light->GetLightType())
  1315. {
  1316. case LIGHT_DIRECTIONAL:
  1317. if (parameters.focus_)
  1318. {
  1319. BoundingBox combinedBox;
  1320. combinedBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1321. combinedBox.max_.x_ = shadowCamera->GetAspectRatio() * combinedBox.max_.y_;
  1322. combinedBox.min_.y_ = -combinedBox.max_.y_;
  1323. combinedBox.min_.x_ = -combinedBox.max_.x_;
  1324. combinedBox.Intersect(geometryBox);
  1325. combinedBox.Intersect(shadowCasterBox);
  1326. QuantizeDirShadowCamera(light, combinedBox);
  1327. }
  1328. break;
  1329. case LIGHT_SPOT:
  1330. // For spot lights, zoom out shadowmap if far away (reduces fillrate)
  1331. if (parameters.zoomOut_)
  1332. {
  1333. // Make sure the out-zooming does not start while we are inside the spot
  1334. float distance = Max((camera_->GetInverseWorldTransform() * light->GetWorldPosition()).z_ - light->GetRange(), 1.0f);
  1335. float lightPixels = (((float)height_ * light->GetRange() * camera_->GetZoom() * 0.5f) / distance);
  1336. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  1337. if (lightPixels < SHADOW_MIN_PIXELS)
  1338. lightPixels = SHADOW_MIN_PIXELS;
  1339. shadowCamera->SetZoom(Min(lightPixels / (float)light->GetShadowMap()->GetHeight(), 1.0f));
  1340. }
  1341. // If camera was not out-zoomed, check for focusing
  1342. if (parameters.focus_ && shadowCamera->GetZoom() >= 1.0f)
  1343. {
  1344. BoundingBox combinedBox(-1.0f, 1.0f);
  1345. combinedBox.Intersect(geometryBox);
  1346. combinedBox.Intersect(shadowCasterBox);
  1347. float viewSizeX = Max(fabsf(combinedBox.min_.x_), fabsf(combinedBox.max_.x_));
  1348. float viewSizeY = Max(fabsf(combinedBox.min_.y_), fabsf(combinedBox.max_.y_));
  1349. float viewSize = Max(viewSizeX, viewSizeY);
  1350. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  1351. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  1352. float quantize = parameters.quantize_ * invOrthoSize;
  1353. float minView = parameters.minView_ * invOrthoSize;
  1354. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  1355. if (viewSize < 1.0f)
  1356. shadowCamera->SetZoom(1.0f / viewSize);
  1357. }
  1358. break;
  1359. case LIGHT_SPLITPOINT:
  1360. return;
  1361. }
  1362. // For unzoomed spot and directional lights, set a zoom factor now to ensure that we do not render to the shadow map border
  1363. // (border addressing can not be reliably used because border & hardware shadow maps is not supported by all GPUs)
  1364. if (shadowCamera->GetZoom() >= 1.0f)
  1365. {
  1366. Texture2D* shadowMap = light->GetShadowMap();
  1367. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((float)(shadowMap->GetWidth() - 2) /
  1368. (float)shadowMap->GetWidth()));
  1369. }
  1370. }
  1371. void View::QuantizeDirShadowCamera(Light* light, const BoundingBox& viewBox)
  1372. {
  1373. Camera* shadowCamera = light->GetShadowCamera();
  1374. Node* cameraNode = shadowCamera->GetNode();
  1375. const FocusParameters& parameters = light->GetShadowFocus();
  1376. float minX = viewBox.min_.x_;
  1377. float minY = viewBox.min_.y_;
  1378. float maxX = viewBox.max_.x_;
  1379. float maxY = viewBox.max_.y_;
  1380. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  1381. Vector2 viewSize(maxX - minX, maxY - minY);
  1382. // Quantize size to reduce swimming
  1383. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  1384. if (parameters.nonUniform_)
  1385. {
  1386. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1387. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  1388. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1389. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  1390. }
  1391. else if (parameters.focus_)
  1392. {
  1393. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  1394. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1395. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1396. viewSize.y_ = viewSize.x_;
  1397. }
  1398. shadowCamera->SetOrthoSize(viewSize);
  1399. // Center shadow camera to the view space bounding box
  1400. Vector3 pos = shadowCamera->GetWorldPosition();
  1401. Quaternion rot = shadowCamera->GetWorldRotation();
  1402. Vector3 adjust(center.x_, center.y_, 0.0f);
  1403. cameraNode->Translate(rot * adjust);
  1404. // If there is a shadow map, snap to its whole texels
  1405. Texture2D* shadowMap = light->GetShadowMap();
  1406. if (shadowMap)
  1407. {
  1408. Vector3 viewPos(rot.Inverse() * shadowCamera->GetWorldPosition());
  1409. // Take into account that shadow map border will not be used
  1410. float invActualSize = 1.0f / (float)(shadowMap->GetWidth() - 2);
  1411. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  1412. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  1413. cameraNode->Translate(rot * snap);
  1414. }
  1415. }
  1416. void View::OptimizeLightByScissor(Light* light)
  1417. {
  1418. if (light)
  1419. graphics_->SetScissorTest(true, GetLightScissor(light));
  1420. else
  1421. graphics_->SetScissorTest(false);
  1422. }
  1423. const Rect& View::GetLightScissor(Light* light)
  1424. {
  1425. HashMap<Light*, Rect>::Iterator i = lightScissorCache_.Find(light);
  1426. if (i != lightScissorCache_.End())
  1427. return i->second_;
  1428. Matrix3x4 view(camera_->GetInverseWorldTransform());
  1429. Matrix4 projection(camera_->GetProjection());
  1430. switch (light->GetLightType())
  1431. {
  1432. case LIGHT_POINT:
  1433. {
  1434. BoundingBox viewBox = light->GetWorldBoundingBox().Transformed(view);
  1435. return lightScissorCache_[light] = viewBox.Projected(projection);
  1436. }
  1437. case LIGHT_SPOT:
  1438. case LIGHT_SPLITPOINT:
  1439. {
  1440. Frustum viewFrustum = light->GetFrustum().Transformed(view);
  1441. return lightScissorCache_[light] = viewFrustum.Projected(projection);
  1442. }
  1443. default:
  1444. return lightScissorCache_[light] = Rect::FULL;
  1445. }
  1446. }
  1447. unsigned View::SplitLight(Light* light)
  1448. {
  1449. LightType type = light->GetLightType();
  1450. if (type == LIGHT_DIRECTIONAL)
  1451. {
  1452. const CascadeParameters& cascade = light->GetShadowCascade();
  1453. unsigned splits = cascade.splits_;
  1454. if (splits > MAX_LIGHT_SPLITS - 1)
  1455. splits = MAX_LIGHT_SPLITS - 1;
  1456. // Orthographic view actually has near clip 0, but clamp it to a theoretical minimum
  1457. float farClip = Min(cascade.shadowRange_, camera_->GetFarClip()); // Shadow range end
  1458. float nearClip = Max(camera_->GetNearClip(), M_MIN_NEARCLIP); // Shadow range start
  1459. bool createExtraSplit = farClip < camera_->GetFarClip();
  1460. // Practical split scheme (Zhang et al.)
  1461. unsigned i;
  1462. for (i = 0; i < splits; ++i)
  1463. {
  1464. // Set a minimum for the fade range to avoid boundary artifacts (missing lighting)
  1465. float splitFadeRange = Max(cascade.splitFadeRange_, 0.001f);
  1466. float iPerM = (float)i / (float)splits;
  1467. float log = nearClip * powf(farClip / nearClip, iPerM);
  1468. float uniform = nearClip + (farClip - nearClip) * iPerM;
  1469. float nearSplit = log * cascade.lambda_ + uniform * (1.0f - cascade.lambda_);
  1470. float nearFadeRange = nearSplit * splitFadeRange;
  1471. iPerM = (float)(i + 1) / (float)splits;
  1472. log = nearClip * powf(farClip / nearClip, iPerM);
  1473. uniform = nearClip + (farClip - nearClip) * iPerM;
  1474. float farSplit = log * cascade.lambda_ + uniform * (1.0f - cascade.lambda_);
  1475. float farFadeRange = farSplit * splitFadeRange;
  1476. // If split is completely beyond camera far clip, we are done
  1477. if ((nearSplit - nearFadeRange) > camera_->GetFarClip())
  1478. break;
  1479. Light* splitLight = renderer_->CreateSplitLight(light);
  1480. splitLights_[i] = splitLight;
  1481. // Though the near clip was previously clamped, use the real near clip value for the first split,
  1482. // so that there are no unlit portions
  1483. if (i)
  1484. splitLight->SetNearSplit(nearSplit);
  1485. else
  1486. splitLight->SetNearSplit(camera_->GetNearClip());
  1487. splitLight->SetNearFadeRange(nearFadeRange);
  1488. splitLight->SetFarSplit(farSplit);
  1489. // If not creating an extra split, the final split should not fade
  1490. splitLight->SetFarFadeRange((createExtraSplit || i < splits - 1) ? farFadeRange : 0.0f);
  1491. // Create an extra unshadowed split if necessary
  1492. if (createExtraSplit && i == splits - 1)
  1493. {
  1494. Light* splitLight = renderer_->CreateSplitLight(light);
  1495. splitLights_[i + 1] = splitLight;
  1496. splitLight->SetNearSplit(farSplit);
  1497. splitLight->SetNearFadeRange(farFadeRange);
  1498. splitLight->SetCastShadows(false);
  1499. }
  1500. }
  1501. if (createExtraSplit)
  1502. return i + 1;
  1503. else
  1504. return i;
  1505. }
  1506. if (type == LIGHT_POINT)
  1507. {
  1508. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1509. {
  1510. Light* splitLight = renderer_->CreateSplitLight(light);
  1511. Node* lightNode = splitLight->GetNode();
  1512. splitLights_[i] = splitLight;
  1513. splitLight->SetLightType(LIGHT_SPLITPOINT);
  1514. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1515. lightNode->SetDirection(directions[i]);
  1516. splitLight->SetFov(90.0f);
  1517. splitLight->SetAspectRatio(1.0f);
  1518. }
  1519. return MAX_CUBEMAP_FACES;
  1520. }
  1521. // A spot light does not actually need splitting. However, we may be rendering several views,
  1522. // and in some the light might be unshadowed, so better create an unique copy
  1523. Light* splitLight = renderer_->CreateSplitLight(light);
  1524. splitLights_[0] = splitLight;
  1525. return 1;
  1526. }
  1527. Technique* View::GetTechnique(Drawable* drawable, Material*& material)
  1528. {
  1529. if (!material)
  1530. material = renderer_->GetDefaultMaterial();
  1531. if (!material)
  1532. return 0;
  1533. float lodDistance = drawable->GetLodDistance();
  1534. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  1535. if (techniques.Empty())
  1536. return 0;
  1537. // Check for suitable technique. Techniques should be ordered like this:
  1538. // Most distant & highest quality
  1539. // Most distant & lowest quality
  1540. // Second most distant & highest quality
  1541. // ...
  1542. for (unsigned i = 0; i < techniques.Size(); ++i)
  1543. {
  1544. const TechniqueEntry& entry = techniques[i];
  1545. Technique* technique = entry.technique_;
  1546. if (!technique || (technique->IsSM3() && !graphics_->GetSM3Support()) || materialQuality_ < entry.qualityLevel_)
  1547. continue;
  1548. if (lodDistance >= entry.lodDistance_)
  1549. return technique;
  1550. }
  1551. // If no suitable technique found, fallback to the last
  1552. return techniques.Back().technique_;
  1553. }
  1554. void View::CheckMaterialForAuxView(Material* material)
  1555. {
  1556. const Vector<SharedPtr<Texture> >& textures = material->GetTextures();
  1557. for (unsigned i = 0; i < textures.Size(); ++i)
  1558. {
  1559. // Have to check cube & 2D textures separately
  1560. Texture* texture = textures[i];
  1561. if (texture)
  1562. {
  1563. if (texture->GetType() == Texture2D::GetTypeStatic())
  1564. {
  1565. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1566. RenderSurface* target = tex2D->GetRenderSurface();
  1567. if (target)
  1568. {
  1569. const Viewport& viewport = target->GetViewport();
  1570. if (viewport.scene_ && viewport.camera_)
  1571. renderer_->AddView(target, viewport);
  1572. }
  1573. }
  1574. else if (texture->GetType() == TextureCube::GetTypeStatic())
  1575. {
  1576. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1577. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1578. {
  1579. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  1580. if (target)
  1581. {
  1582. const Viewport& viewport = target->GetViewport();
  1583. if (viewport.scene_ && viewport.camera_)
  1584. renderer_->AddView(target, viewport);
  1585. }
  1586. }
  1587. }
  1588. }
  1589. }
  1590. // Set frame number so that we can early-out next time we come across this material on the same frame
  1591. material->MarkForAuxView(frame_.frameNumber_);
  1592. }
  1593. void View::SortBatches()
  1594. {
  1595. PROFILE(SortBatches);
  1596. if (mode_ != RENDER_FORWARD)
  1597. {
  1598. gBufferQueue_.SortFrontToBack();
  1599. noShadowLightQueue_.SortFrontToBack();
  1600. }
  1601. baseQueue_.SortFrontToBack();
  1602. extraQueue_.SortFrontToBack();
  1603. transparentQueue_.SortBackToFront();
  1604. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1605. {
  1606. lightQueues_[i].shadowBatches_.SortFrontToBack();
  1607. lightQueues_[i].litBatches_.SortFrontToBack();
  1608. }
  1609. }
  1610. void View::PrepareInstancingBuffer()
  1611. {
  1612. PROFILE(PrepareInstancingBuffer);
  1613. unsigned totalInstances = 0;
  1614. totalInstances += gBufferQueue_.GetNumInstances(renderer_);
  1615. totalInstances += baseQueue_.GetNumInstances(renderer_);
  1616. totalInstances += extraQueue_.GetNumInstances(renderer_);
  1617. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1618. {
  1619. totalInstances += lightQueues_[i].shadowBatches_.GetNumInstances(renderer_);
  1620. totalInstances += lightQueues_[i].litBatches_.GetNumInstances(renderer_);
  1621. }
  1622. // If fail to set buffer size, fall back to per-group locking
  1623. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  1624. {
  1625. unsigned freeIndex = 0;
  1626. void* lockedData = renderer_->instancingBuffer_->Lock(0, totalInstances, LOCK_DISCARD);
  1627. if (lockedData)
  1628. {
  1629. gBufferQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1630. baseQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1631. extraQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1632. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1633. {
  1634. lightQueues_[i].shadowBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  1635. lightQueues_[i].litBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  1636. }
  1637. renderer_->instancingBuffer_->Unlock();
  1638. }
  1639. }
  1640. }
  1641. void View::CalculateShaderParameters()
  1642. {
  1643. Time* time = GetSubsystem<Time>();
  1644. float farClip = camera_->GetFarClip();
  1645. float nearClip = camera_->GetNearClip();
  1646. float fogStart = Min(zone_->GetFogStart(), farClip);
  1647. float fogEnd = Min(zone_->GetFogEnd(), farClip);
  1648. if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON))
  1649. fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
  1650. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  1651. Vector4 fogParams(fogStart / farClip, fogEnd / farClip, 1.0f / (fogRange / farClip), 0.0f);
  1652. Vector4 elapsedTime((time->GetTotalMSec() & 0x3fffff) / 1000.0f, 0.0f, 0.0f, 0.0f);
  1653. Vector4 depthMode = Vector4::ZERO;
  1654. if (camera_->IsOrthographic())
  1655. {
  1656. depthMode.x_ = 1.0f;
  1657. #ifdef USE_OPENGL
  1658. depthMode.z_ = 0.5f;
  1659. depthMode.w_ = 0.5f;
  1660. #else
  1661. depthMode.z_ = 1.0f;
  1662. #endif
  1663. }
  1664. else
  1665. depthMode.w_ = 1.0f / camera_->GetFarClip();
  1666. shaderParameters_.Clear();
  1667. shaderParameters_[VSP_DEPTHMODE] = depthMode;
  1668. shaderParameters_[VSP_ELAPSEDTIME] = elapsedTime;
  1669. shaderParameters_[PSP_AMBIENTCOLOR] = zone_->GetAmbientColor().ToVector4();
  1670. shaderParameters_[PSP_ELAPSEDTIME] = elapsedTime;
  1671. shaderParameters_[PSP_FOGCOLOR] = zone_->GetFogColor().ToVector4(),
  1672. shaderParameters_[PSP_FOGPARAMS] = fogParams;
  1673. if (mode_ == RENDER_DEFERRED)
  1674. {
  1675. // Calculate shader parameters needed only in deferred rendering
  1676. Vector3 nearVector, farVector;
  1677. camera_->GetFrustumSize(nearVector, farVector);
  1678. Vector4 viewportParams(farVector.x_, farVector.y_, farVector.z_, 0.0f);
  1679. float gBufferWidth = (float)graphics_->GetWidth();
  1680. float gBufferHeight = (float)graphics_->GetHeight();
  1681. float widthRange = 0.5f * width_ / gBufferWidth;
  1682. float heightRange = 0.5f * height_ / gBufferHeight;
  1683. // Hardware depth is non-linear in perspective views, so calculate the depth reconstruction parameters
  1684. float farClip = camera_->GetFarClip();
  1685. float nearClip = camera_->GetNearClip();
  1686. Vector4 depthReconstruct = Vector4::ZERO;
  1687. depthReconstruct.x_ = farClip / (farClip - nearClip);
  1688. depthReconstruct.y_ = -nearClip / (farClip - nearClip);
  1689. shaderParameters_[PSP_DEPTHRECONSTRUCT] = depthReconstruct;
  1690. #ifdef USE_OPENGL
  1691. Vector4 bufferUVOffset(((float)screenRect_.left_) / gBufferWidth + widthRange,
  1692. ((float)screenRect_.top_) / gBufferHeight + heightRange, widthRange, heightRange);
  1693. #else
  1694. Vector4 bufferUVOffset((0.5f + (float)screenRect_.left_) / gBufferWidth + widthRange,
  1695. (0.5f + (float)screenRect_.top_) / gBufferHeight + heightRange, widthRange, heightRange);
  1696. #endif
  1697. Vector4 viewportSize((float)screenRect_.left_ / gBufferWidth, (float)screenRect_.top_ / gBufferHeight,
  1698. (float)screenRect_.right_ / gBufferWidth, (float)screenRect_.bottom_ / gBufferHeight);
  1699. shaderParameters_[VSP_FRUSTUMSIZE] = viewportParams;
  1700. shaderParameters_[VSP_GBUFFEROFFSETS] = bufferUVOffset;
  1701. shaderParameters_[PSP_GBUFFEROFFSETS] = bufferUVOffset;
  1702. }
  1703. }
  1704. void View::SetupLightBatch(Batch& batch, bool firstSplit)
  1705. {
  1706. Matrix3x4 view(batch.camera_->GetInverseWorldTransform());
  1707. Light* light = batch.light_;
  1708. float lightExtent = light->GetVolumeExtent();
  1709. float lightViewDist = (light->GetWorldPosition() - batch.camera_->GetWorldPosition()).LengthFast();
  1710. graphics_->SetAlphaTest(false);
  1711. graphics_->SetBlendMode(BLEND_ADD);
  1712. graphics_->SetDepthWrite(false);
  1713. if (light->GetLightType() == LIGHT_DIRECTIONAL)
  1714. {
  1715. // Get projection without jitter offset to ensure the whole screen is filled
  1716. Matrix4 projection(batch.camera_->GetProjection(false));
  1717. // If the light does not extend to the near plane, use a stencil test. Else just draw with depth fail
  1718. if (light->GetNearSplit() <= batch.camera_->GetNearClip())
  1719. {
  1720. graphics_->SetCullMode(CULL_NONE);
  1721. graphics_->SetDepthTest(CMP_GREATER);
  1722. graphics_->SetStencilTest(false);
  1723. }
  1724. else
  1725. {
  1726. Matrix3x4 nearTransform = light->GetDirLightTransform(*batch.camera_, true);
  1727. // Set state for stencil rendering
  1728. graphics_->SetColorWrite(false);
  1729. graphics_->SetCullMode(CULL_NONE);
  1730. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1731. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_ZERO, OP_ZERO, 1);
  1732. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1733. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1734. graphics_->SetShaderParameter(VSP_MODEL, nearTransform);
  1735. graphics_->ClearTransformSources();
  1736. // Draw to stencil
  1737. batch.geometry_->Draw(graphics_);
  1738. // Re-enable color write, set test for rendering the actual light
  1739. graphics_->SetColorWrite(true);
  1740. graphics_->SetDepthTest(CMP_GREATER);
  1741. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 1);
  1742. }
  1743. }
  1744. else
  1745. {
  1746. Matrix4 projection(batch.camera_->GetProjection());
  1747. const Matrix3x4& model = light->GetVolumeTransform(*batch.camera_);
  1748. if (light->GetLightType() == LIGHT_SPLITPOINT)
  1749. {
  1750. // Shadowed point light, split in 6 frustums: mask out overlapping pixels to prevent overlighting
  1751. // If it is the first split, zero the stencil with a scissored clear operation
  1752. if (firstSplit)
  1753. {
  1754. OptimizeLightByScissor(light->GetOriginalLight());
  1755. graphics_->Clear(CLEAR_STENCIL);
  1756. graphics_->SetScissorTest(false);
  1757. }
  1758. // Check whether we should draw front or back faces
  1759. bool drawBackFaces = lightViewDist < (lightExtent + batch.camera_->GetNearClip());
  1760. graphics_->SetColorWrite(false);
  1761. graphics_->SetCullMode(drawBackFaces ? CULL_CCW : CULL_CW);
  1762. graphics_->SetDepthTest(drawBackFaces ? CMP_GREATER : CMP_LESS);
  1763. graphics_->SetStencilTest(true, CMP_EQUAL, OP_INCR, OP_KEEP, OP_KEEP, 0);
  1764. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1765. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1766. graphics_->SetShaderParameter(VSP_MODEL, model);
  1767. // Draw the other faces to stencil to mark where we should not draw
  1768. batch.geometry_->Draw(graphics_);
  1769. graphics_->SetColorWrite(true);
  1770. graphics_->SetCullMode(drawBackFaces ? CULL_CW : CULL_CCW);
  1771. graphics_->SetStencilTest(true, CMP_EQUAL, OP_DECR, OP_DECR, OP_KEEP, 0);
  1772. }
  1773. else
  1774. {
  1775. // If light is close to near clip plane, we might be inside light volume
  1776. if (lightViewDist < (lightExtent + batch.camera_->GetNearClip()))
  1777. {
  1778. // In this case reverse cull mode & depth test and render back faces
  1779. graphics_->SetCullMode(CULL_CW);
  1780. graphics_->SetDepthTest(CMP_GREATER);
  1781. graphics_->SetStencilTest(false);
  1782. }
  1783. else
  1784. {
  1785. // If not too close to far clip plane, write the back faces to stencil for optimization,
  1786. // then render front faces. Else just render front faces.
  1787. if (lightViewDist < (batch.camera_->GetFarClip() - lightExtent))
  1788. {
  1789. // Set state for stencil rendering
  1790. graphics_->SetColorWrite(false);
  1791. graphics_->SetCullMode(CULL_CW);
  1792. graphics_->SetDepthTest(CMP_GREATER);
  1793. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_ZERO, OP_ZERO, 1);
  1794. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1795. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1796. graphics_->SetShaderParameter(VSP_MODEL, model);
  1797. // Draw to stencil
  1798. batch.geometry_->Draw(graphics_);
  1799. // Re-enable color write, set test for rendering the actual light
  1800. graphics_->SetColorWrite(true);
  1801. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 1);
  1802. graphics_->SetCullMode(CULL_CCW);
  1803. graphics_->SetDepthTest(CMP_LESS);
  1804. }
  1805. else
  1806. {
  1807. graphics_->SetStencilTest(false);
  1808. graphics_->SetCullMode(CULL_CCW);
  1809. graphics_->SetDepthTest(CMP_LESS);
  1810. }
  1811. }
  1812. }
  1813. }
  1814. }
  1815. void View::DrawSplitLightToStencil(Camera& camera, Light* light, bool firstSplit)
  1816. {
  1817. Matrix3x4 view(camera.GetInverseWorldTransform());
  1818. switch (light->GetLightType())
  1819. {
  1820. case LIGHT_SPLITPOINT:
  1821. {
  1822. // Shadowed point light, split in 6 frustums: mask out overlapping pixels to prevent overlighting
  1823. // If it is the first split, zero the stencil with a scissored clear operation
  1824. if (firstSplit)
  1825. {
  1826. OptimizeLightByScissor(light->GetOriginalLight());
  1827. graphics_->Clear(CLEAR_STENCIL);
  1828. graphics_->SetScissorTest(false);
  1829. }
  1830. Matrix4 projection(camera.GetProjection());
  1831. const Matrix3x4& model = light->GetVolumeTransform(camera);
  1832. float lightExtent = light->GetVolumeExtent();
  1833. float lightViewDist = (light->GetWorldPosition() - camera.GetWorldPosition()).LengthFast();
  1834. bool drawBackFaces = lightViewDist < (lightExtent + camera.GetNearClip());
  1835. graphics_->SetAlphaTest(false);
  1836. graphics_->SetColorWrite(false);
  1837. graphics_->SetDepthWrite(false);
  1838. graphics_->SetCullMode(drawBackFaces ? CULL_CW : CULL_CCW);
  1839. graphics_->SetDepthTest(drawBackFaces ? CMP_GREATER : CMP_LESS);
  1840. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1841. graphics_->SetShaderParameter(VSP_MODEL, model);
  1842. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1843. graphics_->ClearTransformSources();
  1844. // Draw the faces to stencil which we should draw (where no light has been rendered yet)
  1845. graphics_->SetStencilTest(true, CMP_EQUAL, OP_INCR, OP_KEEP, OP_KEEP, 0);
  1846. renderer_->spotLightGeometry_->Draw(graphics_);
  1847. // Draw the other faces to stencil to mark where we should not draw ("frees up" the pixels for other faces)
  1848. graphics_->SetCullMode(drawBackFaces ? CULL_CCW : CULL_CW);
  1849. graphics_->SetStencilTest(true, CMP_EQUAL, OP_DECR, OP_KEEP, OP_KEEP, 1);
  1850. renderer_->spotLightGeometry_->Draw(graphics_);
  1851. // Now set stencil test for rendering the lit geometries (also marks the pixels so that they will not be used again)
  1852. graphics_->SetStencilTest(true, CMP_EQUAL, OP_INCR, OP_KEEP, OP_KEEP, 1);
  1853. graphics_->SetColorWrite(true);
  1854. }
  1855. break;
  1856. case LIGHT_DIRECTIONAL:
  1857. // If light encompasses whole frustum, no drawing to stencil necessary
  1858. if (light->GetNearSplit() <= camera.GetNearClip() && light->GetFarSplit() >= camera.GetFarClip())
  1859. {
  1860. graphics_->SetStencilTest(false);
  1861. return;
  1862. }
  1863. else
  1864. {
  1865. // Get projection without jitter offset to ensure the whole screen is filled
  1866. Matrix4 projection(camera.GetProjection(false));
  1867. Matrix3x4 nearTransform(light->GetDirLightTransform(camera, true));
  1868. Matrix3x4 farTransform(light->GetDirLightTransform(camera, false));
  1869. graphics_->SetAlphaTest(false);
  1870. graphics_->SetColorWrite(false);
  1871. graphics_->SetDepthWrite(false);
  1872. graphics_->SetCullMode(CULL_NONE);
  1873. // If the split begins at the near plane (first split), draw at split far plane, otherwise at near plane
  1874. bool nearPlaneSplit = light->GetNearSplit() <= camera.GetNearClip();
  1875. graphics_->SetDepthTest(nearPlaneSplit ? CMP_GREATER : CMP_LESS);
  1876. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1877. graphics_->SetShaderParameter(VSP_MODEL, nearPlaneSplit ? farTransform : nearTransform);
  1878. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1879. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_ZERO, OP_ZERO, 1);
  1880. graphics_->ClearTransformSources();
  1881. renderer_->dirLightGeometry_->Draw(graphics_);
  1882. graphics_->SetColorWrite(true);
  1883. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 1);
  1884. }
  1885. break;
  1886. }
  1887. }
  1888. void View::DrawFullScreenQuad(Camera& camera, ShaderVariation* vs, ShaderVariation* ps, bool nearQuad, const HashMap<StringHash, Vector4>& shaderParameters)
  1889. {
  1890. Light quadDirLight(context_);
  1891. Matrix3x4 model(quadDirLight.GetDirLightTransform(camera, nearQuad));
  1892. graphics_->SetCullMode(CULL_NONE);
  1893. graphics_->SetShaders(vs, ps);
  1894. graphics_->SetShaderParameter(VSP_MODEL, model);
  1895. // Get projection without jitter offset to ensure the whole screen is filled
  1896. graphics_->SetShaderParameter(VSP_VIEWPROJ, camera.GetProjection(false));
  1897. graphics_->ClearTransformSources();
  1898. // Set global shader parameters as needed
  1899. for (HashMap<StringHash, Vector4>::ConstIterator i = shaderParameters.Begin(); i != shaderParameters.End(); ++i)
  1900. {
  1901. if (graphics_->NeedParameterUpdate(i->first_, &shaderParameters))
  1902. graphics_->SetShaderParameter(i->first_, i->second_);
  1903. }
  1904. renderer_->dirLightGeometry_->Draw(graphics_);
  1905. }
  1906. void View::RenderBatchQueue(const BatchQueue& queue, bool useScissor)
  1907. {
  1908. VertexBuffer* instancingBuffer = 0;
  1909. if (renderer_->GetDynamicInstancing())
  1910. instancingBuffer = renderer_->instancingBuffer_;
  1911. if (useScissor)
  1912. graphics_->SetScissorTest(false);
  1913. graphics_->SetStencilTest(false);
  1914. // Priority instanced
  1915. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.priorityBatchGroups_.Begin(); i !=
  1916. queue.priorityBatchGroups_.End(); ++i)
  1917. {
  1918. const BatchGroup& group = i->second_;
  1919. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1920. }
  1921. // Priority non-instanced
  1922. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1923. {
  1924. Batch* batch = *i;
  1925. batch->Draw(graphics_, shaderParameters_);
  1926. }
  1927. // Non-priority instanced
  1928. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.batchGroups_.Begin(); i !=
  1929. queue.batchGroups_.End(); ++i)
  1930. {
  1931. const BatchGroup& group = i->second_;
  1932. if (useScissor)
  1933. OptimizeLightByScissor(group.light_);
  1934. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1935. }
  1936. // Non-priority non-instanced
  1937. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1938. {
  1939. Batch* batch = *i;
  1940. // For the transparent queue, both priority and non-priority batches are copied here, so check the flag
  1941. if (useScissor)
  1942. {
  1943. if (!batch->hasPriority_)
  1944. OptimizeLightByScissor(batch->light_);
  1945. else
  1946. graphics_->SetScissorTest(false);
  1947. }
  1948. batch->Draw(graphics_, shaderParameters_);
  1949. }
  1950. }
  1951. void View::RenderForwardLightBatchQueue(const BatchQueue& queue, Light* light, bool firstSplit)
  1952. {
  1953. VertexBuffer* instancingBuffer = 0;
  1954. if (renderer_->GetDynamicInstancing())
  1955. instancingBuffer = renderer_->instancingBuffer_;
  1956. graphics_->SetScissorTest(false);
  1957. graphics_->SetStencilTest(false);
  1958. // Priority instanced
  1959. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.priorityBatchGroups_.Begin(); i !=
  1960. queue.priorityBatchGroups_.End(); ++i)
  1961. {
  1962. const BatchGroup& group = i->second_;
  1963. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1964. }
  1965. // Priority non-instanced
  1966. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1967. {
  1968. Batch* batch = *i;
  1969. batch->Draw(graphics_, shaderParameters_);
  1970. }
  1971. // All base passes have been drawn. Optimize at this point by both scissor and stencil
  1972. if (light)
  1973. {
  1974. OptimizeLightByScissor(light);
  1975. LightType type = light->GetLightType();
  1976. if (type == LIGHT_SPLITPOINT || type == LIGHT_DIRECTIONAL)
  1977. DrawSplitLightToStencil(*camera_, light, firstSplit);
  1978. }
  1979. // Non-priority instanced
  1980. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.batchGroups_.Begin(); i !=
  1981. queue.batchGroups_.End(); ++i)
  1982. {
  1983. const BatchGroup& group = i->second_;
  1984. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1985. }
  1986. // Non-priority non-instanced
  1987. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1988. {
  1989. Batch* batch = *i;
  1990. batch->Draw(graphics_, shaderParameters_);
  1991. }
  1992. }
  1993. void View::RenderShadowMap(const LightBatchQueue& queue)
  1994. {
  1995. PROFILE(RenderShadowMap);
  1996. Texture2D* shadowMap = queue.light_->GetShadowMap();
  1997. graphics_->SetColorWrite(false);
  1998. graphics_->SetTexture(TU_SHADOWMAP, 0);
  1999. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  2000. graphics_->SetDepthStencil(shadowMap);
  2001. graphics_->Clear(CLEAR_DEPTH);
  2002. // Set shadow depth bias. Adjust according to the global shadow map resolution
  2003. BiasParameters parameters = queue.light_->GetShadowBias();
  2004. unsigned shadowMapSize = renderer_->GetShadowMapSize();
  2005. if (shadowMapSize <= 512)
  2006. parameters.constantBias_ *= 2.0f;
  2007. else if (shadowMapSize >= 2048)
  2008. parameters.constantBias_ *= 0.5f;
  2009. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  2010. // Set a scissor rectangle to match possible shadow map size reduction by out-zooming
  2011. // However, do not do this for point lights, which need to render continuously across cube faces
  2012. if (queue.light_->GetLightType() != LIGHT_SPLITPOINT)
  2013. {
  2014. float zoom = Min(queue.light_->GetShadowCamera()->GetZoom(),
  2015. (float)(shadowMap->GetWidth() - 2) / (float)shadowMap->GetWidth());
  2016. Rect zoomRect(Vector2(-1.0f, -1.0f) * zoom, Vector2(1.0f, 1.0f) * zoom);
  2017. graphics_->SetScissorTest(true, zoomRect, false);
  2018. }
  2019. else
  2020. graphics_->SetScissorTest(false);
  2021. // Draw instanced and non-instanced shadow casters
  2022. RenderBatchQueue(queue.shadowBatches_);
  2023. graphics_->SetColorWrite(true);
  2024. graphics_->SetDepthBias(0.0f, 0.0f);
  2025. graphics_->SetScissorTest(false);
  2026. }