View.cpp 97 KB

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