View.cpp 95 KB

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