LCOV - code coverage report
Current view: top level - source/renderer - SceneRenderer.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 29 603 4.8 %
Date: 2026-12-03 01:19:39 Functions: 7 54 13.0 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "SceneRenderer.h"
      21             : 
      22             : #include "graphics/Camera.h"
      23             : #include "graphics/Color.h"
      24             : #include "graphics/LOSTexture.h"
      25             : #include "graphics/LightEnv.h"
      26             : #include "graphics/Material.h"
      27             : #include "graphics/MaterialManager.h"
      28             : #include "graphics/MiniMapTexture.h"
      29             : #include "graphics/Model.h"
      30             : #include "graphics/ModelAbstract.h"
      31             : #include "graphics/ModelDef.h"
      32             : #include "graphics/ParticleManager.h"
      33             : #include "graphics/Patch.h"
      34             : #include "graphics/ShaderDefines.h"
      35             : #include "graphics/TerritoryTexture.h"
      36             : #include "lib/code_annotation.h"
      37             : #include "lib/config2.h"
      38             : #include "lib/debug.h"
      39             : #include "maths/Frustum.h"
      40             : #include "maths/MathUtil.h"
      41             : #include "maths/Matrix3D.h"
      42             : #include "maths/Plane.h"
      43             : #include "maths/Vector3D.h"
      44             : #include "maths/Vector4D.h"
      45             : #include "ps/CStrIntern.h"
      46             : #include "ps/CStrInternStatic.h"
      47             : #include "ps/Game.h"
      48             : #include "ps/Profile.h"
      49             : #include "renderer/CPUSkinnedModelRenderer.h"
      50             : #include "renderer/DebugRenderer.h"
      51             : #include "renderer/GPUSkinnedModelRenderer.h"
      52             : #include "renderer/InstancingModelRenderer.h"
      53             : #include "renderer/ModelRenderer.h"
      54             : #include "renderer/OverlayRenderer.h"
      55             : #include "renderer/ParticleRenderer.h"
      56             : #include "renderer/RenderModifiers.h"
      57             : #include "renderer/Renderer.h"
      58             : #include "renderer/RenderingOptions.h"
      59             : #include "renderer/ShadowMap.h"
      60             : #include "renderer/SilhouetteRenderer.h"
      61             : #include "renderer/SkyManager.h"
      62             : #include "renderer/TerrainOverlay.h"
      63             : #include "renderer/TerrainRenderer.h"
      64             : #include "renderer/WaterManager.h"
      65             : #include "renderer/backend/Backend.h"
      66             : #include "renderer/backend/IDevice.h"
      67             : #include "renderer/backend/IDeviceCommandContext.h"
      68             : 
      69             : #include <algorithm>
      70             : #include <cmath>
      71             : #include <optional>
      72             : 
      73             : struct SScreenRect
      74             : {
      75             :     int x1, y1, x2, y2;
      76             : };
      77             : 
      78             : /**
      79             :  * Struct CSceneRendererInternals: Truly hide data that is supposed to be hidden
      80             :  * in this structure so it won't even appear in header files.
      81             :  */
      82             : class CSceneRenderer::Internals
      83             : {
      84             :     NONCOPYABLE(Internals);
      85             : public:
      86          10 :     Internals(Renderer::Backend::IDevice* device)
      87          10 :         : waterManager(device), particleManager(*device), shadow(device)
      88             :     {
      89          10 :     }
      90             : 
      91          10 :     ~Internals() = default;
      92             : 
      93             :     /// Water manager
      94             :     WaterManager waterManager;
      95             : 
      96             :     /// Sky manager
      97             :     SkyManager skyManager;
      98             : 
      99             :     /// Terrain renderer
     100             :     TerrainRenderer terrainRenderer;
     101             : 
     102             :     /// Overlay renderer
     103             :     OverlayRenderer overlayRenderer;
     104             : 
     105             :     /// Particle manager
     106             :     CParticleManager particleManager;
     107             : 
     108             :     /// Particle renderer
     109             :     ParticleRenderer particleRenderer;
     110             : 
     111             :     /// Material manager
     112             :     CMaterialManager materialManager;
     113             : 
     114             :     /// Shadow map
     115             :     ShadowMap shadow;
     116             : 
     117             :     SilhouetteRenderer silhouetteRenderer;
     118             : 
     119             :     // Various model renderers
     120             :     struct Models
     121             :     {
     122             :         // Submitted models are split on two axes:
     123             :         //  - Opaque vs Transparent - alpha-blended models are stored in a separate
     124             :         //    list so we can draw them above/below the alpha-blended water plane correctly
     125             :         //  - Skinned vs Unskinned - we don't need to duplicate mesh data per
     126             :         //    model instance (except for skinned models), so non-skinned models
     127             :         //    get different ModelVertexRenderers
     128             : 
     129             :         struct Submissions
     130             :         {
     131             :             std::vector<CModel*> submissions[CSceneRenderer::CULL_MAX];
     132             :         };
     133             : 
     134             :         // Unskinned submissions should be prepared and rendered with
     135             :         // VertexInstancingShader. Skinned - with Vertex*SkinningShader
     136             :         // depending on whether GPU skinning is enabled.
     137             :         Submissions OpaqueSkinned;
     138             :         Submissions OpaqueUnskinned;
     139             :         Submissions TransparentSkinned;
     140             :         Submissions TransparentUnskinned;
     141             : 
     142             :         std::vector<CModel*> uniqueSkinnedSubmissionsForUpdate;
     143             : 
     144             :         ModelRenderer modelRenderer;
     145             : 
     146             :         InstancingModelRenderer VertexInstancingShader;
     147             :         CPUSkinnedModelVertexRenderer VertexCPUSkinningShader;
     148             :         // We can't create GPU skinning renderer for renderer devices without
     149             :         // its support.
     150             :         std::optional<GPUSkinnedModelModelRenderer> VertexGPUSkinningShader;
     151             : 
     152             :         ShaderRenderModifier ModShader;
     153             : 
     154             :         bool GPUSkinningEnabled{false};
     155             :     } Model;
     156             : 
     157             :     CShaderDefines globalContext;
     158             : 
     159             :     /**
     160             :      * Upload renderer data for all previously submitted models to backend.
     161             :      *
     162             :      * Must be called before any rendering calls and after all models
     163             :      * for this frame have been prepared.
     164             :      */
     165           0 :     void UploadModels(Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
     166             :     {
     167           0 :         PROFILE3("upload models");
     168             : 
     169           0 :         ModelVertexRenderer& modelVertexSkinningRenderer{
     170           0 :             Model.GPUSkinningEnabled
     171           0 :                 ? static_cast<ModelVertexRenderer&>(*Model.VertexGPUSkinningShader)
     172           0 :                 : static_cast<ModelVertexRenderer&>(Model.VertexCPUSkinningShader)};
     173           0 :         modelVertexSkinningRenderer.UploadModelsData(deviceCommandContext, Model.uniqueSkinnedSubmissionsForUpdate);
     174             : 
     175           0 :         for (int cullGroup{0}; cullGroup < CSceneRenderer::CULL_MAX; ++cullGroup)
     176             :         {
     177           0 :             Model.VertexInstancingShader.UploadModelsData(deviceCommandContext, Model.OpaqueUnskinned.submissions[cullGroup]);
     178           0 :             Model.VertexInstancingShader.UploadModelsData(deviceCommandContext, Model.TransparentUnskinned.submissions[cullGroup]);
     179             :         }
     180           0 :     }
     181             : 
     182             :     /**
     183             :      * PrepareModels: Calculate renderer data for all previously
     184             :      * submitted models.
     185             :      *
     186             :      * Must be called before any rendering calls and after all models
     187             :      * for this frame have been submitted.
     188             :      */
     189           0 :     void PrepareModels(
     190             :         Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
     191             :     {
     192           0 :         PROFILE3("prepare models");
     193             : 
     194           0 :         ModelVertexRenderer& modelVertexSkinningRenderer{
     195           0 :             Model.GPUSkinningEnabled
     196           0 :                 ? static_cast<ModelVertexRenderer&>(*Model.VertexGPUSkinningShader)
     197           0 :                 : static_cast<ModelVertexRenderer&>(Model.VertexCPUSkinningShader)};
     198             : 
     199           0 :         for (int cullGroup{0}; cullGroup < CSceneRenderer::CULL_MAX; ++cullGroup)
     200             :         {
     201           0 :             PrepareModels(modelVertexSkinningRenderer, Model.OpaqueSkinned.submissions[cullGroup]);
     202           0 :             PrepareModels(modelVertexSkinningRenderer, Model.TransparentSkinned.submissions[cullGroup]);
     203             :         }
     204             : 
     205           0 :         modelVertexSkinningRenderer.UpdateModelsData(deviceCommandContext, Model.uniqueSkinnedSubmissionsForUpdate);
     206             : 
     207             :         // See CPUSkinnedModelVertexRenderer::PrepareForRendering comment.
     208           0 :         if (!Model.GPUSkinningEnabled)
     209             :         {
     210           0 :             for (int cullGroup{0}; cullGroup < CSceneRenderer::CULL_MAX; ++cullGroup)
     211             :             {
     212           0 :                 Model.VertexCPUSkinningShader.PrepareForRendering(Model.OpaqueSkinned.submissions[cullGroup]);
     213           0 :                 Model.VertexCPUSkinningShader.PrepareForRendering(Model.TransparentSkinned.submissions[cullGroup]);
     214             :             }
     215             :         }
     216             : 
     217             :         // We don't need to update unskinned models.
     218           0 :     }
     219             : 
     220           0 :     void PrepareModels(
     221             :         ModelVertexRenderer& modelVertexRenderer, std::span<CModel*> submissions)
     222             :     {
     223           0 :         for (CModel* model : submissions)
     224             :         {
     225           0 :             model->ValidatePosition();
     226             : 
     227           0 :             CModelRData* rdata{static_cast<CModelRData*>(model->GetRenderData())};
     228           0 :             ENSURE(rdata->GetKey() == &modelVertexRenderer);
     229             : 
     230           0 :             if (rdata->m_UpdateFlags & RENDERDATA_UPDATE_VERTICES)
     231             :             {
     232           0 :                 Model.uniqueSkinnedSubmissionsForUpdate.emplace_back(model);
     233           0 :                 rdata->m_UpdateFlags = 0;
     234             :             }
     235             :         }
     236           0 :     }
     237             : 
     238             :     /**
     239             :      * Submit: Submit a model for rendering this frame.
     240             :      *
     241             :      * preconditions : The model must not have been submitted to any
     242             :      * ModelRenderer in this frame. Submit may only be called
     243             :      * after EndFrame and before PrepareModels.
     244             :      *
     245             :      * @param model The model that will be added to the list of models
     246             :      * submitted this frame.
     247             :      */
     248           0 :     void Submit(const int cullGroup, ModelVertexRenderer& modelVertexRenderer, Models::Submissions& submissions, CModel* model)
     249             :     {
     250           0 :         CModelRData* rdata{static_cast<CModelRData*>(model->GetRenderData())};
     251             : 
     252             :         // Ensure model data is valid.
     253             :         // TODO: using a pointer as a key is unsafe.
     254           0 :         const void* key{&modelVertexRenderer};
     255           0 :         if (!rdata || rdata->GetKey() != key)
     256             :         {
     257           0 :             model->InvalidatePosition();
     258           0 :             rdata = modelVertexRenderer.CreateModelData(key, model);
     259           0 :             model->SetRenderData(rdata);
     260           0 :             model->SetDirty(~0u);
     261             :         }
     262             : 
     263           0 :         submissions.submissions[cullGroup].push_back(model);
     264           0 :     }
     265             : 
     266             :     /**
     267             :      * Renders all non-alpha-blended models with the given context.
     268             :      */
     269           0 :     void CallOpaqueModelRenderers(
     270             :         Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
     271             :         const CShaderDefines& context, int cullGroup, int flags, const ERenderMode renderMode)
     272             :     {
     273           0 :         ModelVertexRenderer& modelVertexSkinningRenderer{
     274           0 :             Model.GPUSkinningEnabled
     275           0 :                 ? static_cast<ModelVertexRenderer&>(*Model.VertexGPUSkinningShader)
     276           0 :                 : static_cast<ModelVertexRenderer&>(Model.VertexCPUSkinningShader)};
     277             : 
     278           0 :         CShaderDefines contextSkinned = context;
     279           0 :         if (Model.GPUSkinningEnabled)
     280           0 :             contextSkinned.Add(str_USE_INSTANCING, str_1);
     281           0 :         Model.modelRenderer.Render(deviceCommandContext, modelVertexSkinningRenderer, Model.ModShader, contextSkinned, cullGroup, flags, renderMode, Model.OpaqueSkinned.submissions[cullGroup]);
     282             : 
     283           0 :         CShaderDefines contextUnskinned = context;
     284           0 :         contextUnskinned.Add(str_USE_INSTANCING, str_1);
     285           0 :         Model.modelRenderer.Render(deviceCommandContext, Model.VertexInstancingShader, Model.ModShader, contextUnskinned, cullGroup, flags, renderMode, Model.OpaqueUnskinned.submissions[cullGroup]);
     286           0 :     }
     287             : 
     288             :     /**
     289             :      * Renders all alpha-blended models with the given context.
     290             :      */
     291           0 :     void CallTransparentModelRenderers(
     292             :         Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
     293             :         const CShaderDefines& context, int cullGroup, int flags, const ERenderMode renderMode)
     294             :     {
     295           0 :         ModelVertexRenderer& modelVertexSkinningRenderer{
     296           0 :             Model.GPUSkinningEnabled
     297           0 :                 ? static_cast<ModelVertexRenderer&>(*Model.VertexGPUSkinningShader)
     298           0 :                 : static_cast<ModelVertexRenderer&>(Model.VertexCPUSkinningShader)};
     299             : 
     300           0 :         CShaderDefines contextSkinned = context;
     301           0 :         if (Model.GPUSkinningEnabled)
     302           0 :             contextSkinned.Add(str_USE_INSTANCING, str_1);
     303           0 :         Model.modelRenderer.Render(deviceCommandContext, modelVertexSkinningRenderer, Model.ModShader, contextSkinned, cullGroup, flags, renderMode, Model.TransparentSkinned.submissions[cullGroup]);
     304             : 
     305           0 :         CShaderDefines contextUnskinned = context;
     306           0 :         contextUnskinned.Add(str_USE_INSTANCING, str_1);
     307           0 :         Model.modelRenderer.Render(deviceCommandContext, Model.VertexInstancingShader, Model.ModShader, contextUnskinned, cullGroup, flags, renderMode, Model.TransparentUnskinned.submissions[cullGroup]);
     308           0 :     }
     309             : };
     310             : 
     311          10 : CSceneRenderer::CSceneRenderer(Renderer::Backend::IDevice* device)
     312             : {
     313          10 :     m = std::make_unique<Internals>(device);
     314             : 
     315          10 :     m_TerrainRenderMode = SOLID;
     316          10 :     m_WaterRenderMode = SOLID;
     317          10 :     m_ModelRenderMode = SOLID;
     318          10 :     m_OverlayRenderMode = SOLID;
     319             : 
     320          10 :     m_DisplayTerrainPriorities = false;
     321             : 
     322          10 :     m_LightEnv = nullptr;
     323             : 
     324          10 :     m_CurrentScene = nullptr;
     325          10 : }
     326             : 
     327          10 : CSceneRenderer::~CSceneRenderer()
     328             : {
     329             :     // We no longer UnloadWaterTextures here -
     330             :     // that is the responsibility of the module that asked for
     331             :     // them to be loaded (i.e. CGameView).
     332          10 :     m.reset();
     333          10 : }
     334             : 
     335           0 : void CSceneRenderer::ReloadShaders([[maybe_unused]] Renderer::Backend::IDevice* device)
     336             : {
     337           0 :     m->globalContext = CShaderDefines();
     338             : 
     339           0 :     if (g_RenderingOptions.GetShadows())
     340             :     {
     341           0 :         m->globalContext.Add(str_USE_SHADOW, str_1);
     342           0 :         if (g_RenderingOptions.GetShadowPCF())
     343           0 :             m->globalContext.Add(str_USE_SHADOW_PCF, str_1);
     344           0 :         const int cascadeCount = m->shadow.GetCascadeCount();
     345           0 :         ENSURE(1 <= cascadeCount && cascadeCount <= 4);
     346           0 :         const CStrIntern cascadeCountStr[5] = {str_0, str_1, str_2, str_3, str_4};
     347           0 :         m->globalContext.Add(str_SHADOWS_CASCADE_COUNT, cascadeCountStr[cascadeCount]);
     348             : #if CONFIG2_GLES
     349             :         const bool useShadowSampler{device->GetBackend() != Renderer::Backend::Backend::GL};
     350             : #else
     351           0 :         const bool useShadowSampler{true};
     352             : #endif
     353           0 :         if (useShadowSampler)
     354           0 :             m->globalContext.Add(str_USE_SHADOW_SAMPLER, str_1);
     355             :     }
     356             : 
     357           0 :     m->globalContext.Add(str_RENDER_DEBUG_MODE,
     358             :         RenderDebugModeEnum::ToString(g_RenderingOptions.GetRenderDebugMode()));
     359             : 
     360           0 :     m->Model.GPUSkinningEnabled = g_RenderingOptions.GetGPUSkinning();
     361           0 :     if (m->Model.GPUSkinningEnabled)
     362             :     {
     363           0 :         if (!m->Model.VertexGPUSkinningShader.has_value())
     364           0 :             m->Model.VertexGPUSkinningShader.emplace();
     365             :     }
     366           0 : }
     367             : 
     368          10 : void CSceneRenderer::Initialize(const uint32_t width, const uint32_t height)
     369             : {
     370             :     // Let component renderers perform one-time initialization after graphics capabilities and
     371             :     // the shader path have been determined.
     372          10 :     m->waterManager.Initialize();
     373          10 :     m->terrainRenderer.Initialize();
     374          10 :     m->overlayRenderer.Initialize();
     375             : 
     376          10 :     CreateViewSizeDependentObjects(width, height);
     377          10 : }
     378             : 
     379          10 : void CSceneRenderer::CreateViewSizeDependentObjects(const uint32_t width, const uint32_t height)
     380             : {
     381             :     // need to recreate the shadow map object to resize the shadow texture
     382          10 :     m->shadow.CreateViewSizeDependentObjects(width, height);
     383             : 
     384          10 :     m->waterManager.CreateViewSizeDependentObjects(width, height);
     385          10 : }
     386             : 
     387           0 : void CSceneRenderer::DestroyViewSizeDependentObjects()
     388             : {
     389           0 :     m->waterManager.DestroyViewSizeDependentObjects();
     390             : 
     391           0 :     m->shadow.DestroyViewSizeDependentObjects();
     392           0 : }
     393             : 
     394           0 : void CSceneRenderer::BeginFrame()
     395             : {
     396             :     // choose model renderers for this frame
     397           0 :     m->Model.ModShader.SetShadowMap(&m->shadow);
     398           0 :     m->Model.ModShader.SetLightEnv(m_LightEnv);
     399           0 : }
     400             : 
     401           0 : void CSceneRenderer::SetSimulation(CSimulation2* simulation)
     402             : {
     403             :     // set current simulation context for terrain renderer
     404           0 :     m->terrainRenderer.SetSimulation(simulation);
     405           0 : }
     406             : 
     407           0 : void CSceneRenderer::RenderShadowMap(
     408             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
     409             : {
     410           0 :     PROFILE3_GPU(deviceCommandContext, "shadow map");
     411           0 :     GPU_SCOPED_LABEL(deviceCommandContext, "Render shadow map");
     412             : 
     413           0 :     m->shadow.BeginRender(deviceCommandContext);
     414             : 
     415           0 :     const int cascadeCount = m->shadow.GetCascadeCount();
     416           0 :     ENSURE(0 <= cascadeCount && cascadeCount <= 4);
     417           0 :     for (int cascade = 0; cascade < cascadeCount; ++cascade)
     418             :     {
     419           0 :         m->shadow.PrepareCamera(deviceCommandContext, cascade);
     420             : 
     421           0 :         const int cullGroup = CULL_SHADOWS_CASCADE_0 + cascade;
     422           0 :         {
     423           0 :             PROFILE("render patches");
     424           0 :             m->terrainRenderer.RenderPatches(
     425           0 :                 deviceCommandContext, cullGroup, {}, CColor(0.0f, 0.0f, 0.0f, 1.0f), false);
     426           0 :         }
     427             : 
     428           0 :         {
     429           0 :             PROFILE("render models");
     430           0 :             m->CallOpaqueModelRenderers(deviceCommandContext, {}, cullGroup, ModelFlag::CAST_SHADOWS, ERenderMode::SOLID);
     431           0 :         }
     432             : 
     433           0 :         {
     434           0 :             PROFILE("render transparent models");
     435           0 :             m->CallTransparentModelRenderers(deviceCommandContext, {}, cullGroup, ModelFlag::CAST_SHADOWS, ERenderMode::SOLID);
     436           0 :         }
     437             :     }
     438             : 
     439           0 :     m->shadow.EndRender(deviceCommandContext);
     440           0 : }
     441             : 
     442           0 : void CSceneRenderer::RenderPatches(
     443             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
     444             :     const CShaderDefines& context, int cullGroup)
     445             : {
     446           0 :     PROFILE3("patches");
     447           0 :     GPU_SCOPED_LABEL(deviceCommandContext, "Render patches");
     448             : 
     449             :     // Render all the patches, including blend pass.
     450           0 :     m->terrainRenderer.RenderTerrainShader(deviceCommandContext, context, cullGroup,
     451           0 :         g_RenderingOptions.GetShadows() ? &m->shadow : nullptr, m_TerrainRenderMode == WIREFRAME);
     452             : 
     453           0 :     if (m_TerrainRenderMode == EDGED_FACES)
     454             :     {
     455             :         // Edged faces: need to make a second pass over the data.
     456             : 
     457             :         // Render tiles edges.
     458           0 :         m->terrainRenderer.RenderPatches(
     459           0 :             deviceCommandContext, cullGroup, context, CColor(0.5f, 0.5f, 1.0f, 1.0f), true);
     460             : 
     461             :         // Render outline of each patch.
     462           0 :         m->terrainRenderer.RenderOutlines(deviceCommandContext, cullGroup);
     463             :     }
     464           0 : }
     465             : 
     466           0 : void CSceneRenderer::RenderModels(
     467             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
     468             :     const CShaderDefines& context, int cullGroup)
     469             : {
     470           0 :     PROFILE3("models");
     471           0 :     GPU_SCOPED_LABEL(deviceCommandContext, "Render models");
     472             : 
     473           0 :     int flags = 0;
     474             : 
     475           0 :     const ERenderMode modelRenderMode{
     476           0 :         m_ModelRenderMode == WIREFRAME ? WIREFRAME : SOLID};
     477             : 
     478           0 :     m->CallOpaqueModelRenderers(deviceCommandContext, context, cullGroup, flags, modelRenderMode);
     479             : 
     480           0 :     if (m_ModelRenderMode == EDGED_FACES)
     481           0 :         m->CallOpaqueModelRenderers(deviceCommandContext, {}, cullGroup, flags, EDGED_FACES);
     482           0 : }
     483             : 
     484           0 : void CSceneRenderer::RenderTransparentModels(
     485             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
     486             :     const CShaderDefines& context, int cullGroup, ETransparentMode transparentMode)
     487             : {
     488           0 :     PROFILE3("transparent models");
     489           0 :     GPU_SCOPED_LABEL(deviceCommandContext, "Render transparent models");
     490             : 
     491           0 :     int flags = 0;
     492             : 
     493           0 :     CShaderDefines contextOpaque = context;
     494           0 :     contextOpaque.Add(str_ALPHABLEND_PASS_OPAQUE, str_1);
     495             : 
     496           0 :     CShaderDefines contextBlend = context;
     497           0 :     contextBlend.Add(str_ALPHABLEND_PASS_BLEND, str_1);
     498             : 
     499           0 :     const ERenderMode modelRenderMode{
     500           0 :         m_ModelRenderMode == WIREFRAME ? WIREFRAME : SOLID};
     501             : 
     502           0 :     if (transparentMode == TRANSPARENT || transparentMode == TRANSPARENT_OPAQUE)
     503           0 :         m->CallTransparentModelRenderers(deviceCommandContext, contextOpaque, cullGroup, flags, modelRenderMode);
     504             : 
     505           0 :     if (transparentMode == TRANSPARENT || transparentMode == TRANSPARENT_BLEND)
     506           0 :         m->CallTransparentModelRenderers(deviceCommandContext, contextBlend, cullGroup, flags, modelRenderMode);
     507             : 
     508           0 :     if (m_ModelRenderMode == EDGED_FACES)
     509           0 :         m->CallTransparentModelRenderers(deviceCommandContext, {}, cullGroup, flags, EDGED_FACES);
     510           0 : }
     511             : 
     512             : // SetObliqueFrustumClipping: change the near plane to the given clip plane (in world space)
     513             : // Based on code from Game Programming Gems 5, from http://www.terathon.com/code/oblique.html
     514             : // - worldPlane is a clip plane in world space (worldPlane.Dot(v) >= 0 for any vector v passing the clipping test)
     515           0 : void CSceneRenderer::SetObliqueFrustumClipping(CCamera& camera, const CVector4D& worldPlane) const
     516             : {
     517             :     // First, we'll convert the given clip plane to camera space, then we'll
     518             :     // Get the view matrix and normal matrix (top 3x3 part of view matrix)
     519           0 :     CMatrix3D normalMatrix = camera.GetOrientation().GetTranspose();
     520           0 :     CVector4D camPlane = normalMatrix.Transform(worldPlane);
     521             : 
     522           0 :     CMatrix3D matrix = camera.GetProjection();
     523             : 
     524             :     // Calculate the clip-space corner point opposite the clipping plane
     525             :     // as (sgn(camPlane.x), sgn(camPlane.y), 1, 1) and
     526             :     // transform it into camera space by multiplying it
     527             :     // by the inverse of the projection matrix
     528             : 
     529           0 :     CVector4D q;
     530           0 :     q.X = (Sign(camPlane.X) - matrix[8] / matrix[11]) / matrix[0];
     531           0 :     q.Y = (Sign(camPlane.Y) - matrix[9] / matrix[11]) / matrix[5];
     532           0 :     q.Z = 1.0f / matrix[11];
     533           0 :     q.W = (1.0f - matrix[10] / matrix[11]) / matrix[14];
     534             : 
     535             :     // Calculate the scaled plane vector
     536           0 :     CVector4D c = camPlane * (2.0f * matrix[11] / camPlane.Dot(q));
     537             : 
     538             :     // Replace the third row of the projection matrix
     539           0 :     matrix[2] = c.X;
     540           0 :     matrix[6] = c.Y;
     541           0 :     matrix[10] = c.Z - matrix[11];
     542           0 :     matrix[14] = c.W;
     543             : 
     544             :     // Load it back into the camera
     545           0 :     camera.SetProjection(matrix);
     546           0 : }
     547             : 
     548           0 : void CSceneRenderer::ComputeReflectionCamera(CCamera& camera, const CBoundingBoxAligned& scissor) const
     549             : {
     550           0 :     WaterManager& wm = m->waterManager;
     551             : 
     552           0 :     CMatrix3D projection;
     553           0 :     if (m_ViewCamera.GetProjectionType() == CCamera::ProjectionType::PERSPECTIVE)
     554             :     {
     555           0 :         const float aspectRatio = 1.0f;
     556             :         // Expand fov slightly since ripples can reflect parts of the scene that
     557             :         // are slightly outside the normal camera view, and we want to avoid any
     558             :         // noticeable edge-filtering artifacts
     559           0 :         projection.SetPerspective(m_ViewCamera.GetFOV() * 1.05f, aspectRatio, m_ViewCamera.GetNearPlane(), m_ViewCamera.GetFarPlane());
     560             :     }
     561             :     else
     562           0 :         projection = m_ViewCamera.GetProjection();
     563             : 
     564           0 :     camera = m_ViewCamera;
     565             : 
     566             :     // Temporarily change the camera to one that is reflected.
     567             :     // Also, for texturing purposes, make it render to a view port the size of the
     568             :     // water texture, stretch the image according to our aspect ratio so it covers
     569             :     // the whole screen despite being rendered into a square, and cover slightly more
     570             :     // of the view so we can see wavy reflections of slightly off-screen objects.
     571           0 :     camera.m_Orientation.Scale(1, -1, 1);
     572           0 :     camera.m_Orientation.Translate(0, 2 * wm.m_WaterHeight, 0);
     573           0 :     camera.UpdateFrustum(scissor);
     574             :     // Clip slightly above the water to improve reflections of objects on the water
     575             :     // when the reflections are distorted.
     576           0 :     camera.ClipFrustum(CVector4D(0, 1, 0, -wm.m_WaterHeight + 2.0f));
     577             : 
     578           0 :     SViewPort vp;
     579           0 :     vp.m_Height = wm.m_RefTextureSize;
     580           0 :     vp.m_Width = wm.m_RefTextureSize;
     581           0 :     vp.m_X = 0;
     582           0 :     vp.m_Y = 0;
     583           0 :     camera.SetViewPort(vp);
     584           0 :     camera.SetProjection(projection);
     585           0 :     CMatrix3D scaleMat;
     586           0 :     scaleMat.SetScaling(g_Renderer.GetHeight() / static_cast<float>(std::max(1, g_Renderer.GetWidth())), 1.0f, 1.0f);
     587           0 :     camera.SetProjection(scaleMat * camera.GetProjection());
     588             : 
     589           0 :     CVector4D camPlane(0, 1, 0, -wm.m_WaterHeight + 0.5f);
     590           0 :     SetObliqueFrustumClipping(camera, camPlane);
     591           0 : }
     592             : 
     593           0 : void CSceneRenderer::ComputeRefractionCamera(CCamera& camera, const CBoundingBoxAligned& scissor) const
     594             : {
     595           0 :     WaterManager& wm = m->waterManager;
     596             : 
     597           0 :     CMatrix3D projection;
     598           0 :     if (m_ViewCamera.GetProjectionType() == CCamera::ProjectionType::PERSPECTIVE)
     599             :     {
     600           0 :         const float aspectRatio = 1.0f;
     601             :         // Expand fov slightly since ripples can reflect parts of the scene that
     602             :         // are slightly outside the normal camera view, and we want to avoid any
     603             :         // noticeable edge-filtering artifacts
     604           0 :         projection.SetPerspective(m_ViewCamera.GetFOV() * 1.05f, aspectRatio, m_ViewCamera.GetNearPlane(), m_ViewCamera.GetFarPlane());
     605             :     }
     606             :     else
     607           0 :         projection = m_ViewCamera.GetProjection();
     608             : 
     609           0 :     camera = m_ViewCamera;
     610             : 
     611             :     // Temporarily change the camera to make it render to a view port the size of the
     612             :     // water texture, stretch the image according to our aspect ratio so it covers
     613             :     // the whole screen despite being rendered into a square, and cover slightly more
     614             :     // of the view so we can see wavy refractions of slightly off-screen objects.
     615           0 :     camera.UpdateFrustum(scissor);
     616           0 :     camera.ClipFrustum(CVector4D(0, -1, 0, wm.m_WaterHeight + 0.5f));   // add some to avoid artifacts near steep shores.
     617             : 
     618           0 :     SViewPort vp;
     619           0 :     vp.m_Height = wm.m_RefTextureSize;
     620           0 :     vp.m_Width = wm.m_RefTextureSize;
     621           0 :     vp.m_X = 0;
     622           0 :     vp.m_Y = 0;
     623           0 :     camera.SetViewPort(vp);
     624           0 :     camera.SetProjection(projection);
     625           0 :     CMatrix3D scaleMat;
     626           0 :     scaleMat.SetScaling(g_Renderer.GetHeight() / static_cast<float>(std::max(1, g_Renderer.GetWidth())), 1.0f, 1.0f);
     627           0 :     camera.SetProjection(scaleMat * camera.GetProjection());
     628           0 : }
     629             : 
     630             : // RenderReflections: render the water reflections to the reflection texture
     631           0 : void CSceneRenderer::RenderReflections(
     632             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
     633             :     const CShaderDefines& context, const CBoundingBoxAligned& scissor)
     634             : {
     635           0 :     PROFILE3_GPU(deviceCommandContext, "water reflections");
     636           0 :     GPU_SCOPED_LABEL(deviceCommandContext, "Render water reflections");
     637             : 
     638           0 :     WaterManager& wm = m->waterManager;
     639             : 
     640             :     // Remember old camera
     641           0 :     CCamera normalCamera = m_ViewCamera;
     642             : 
     643           0 :     ComputeReflectionCamera(m_ViewCamera, scissor);
     644           0 :     const CBoundingBoxAligned reflectionScissor =
     645           0 :         m->terrainRenderer.ScissorWater(CULL_DEFAULT, m_ViewCamera);
     646           0 :     if (reflectionScissor.IsEmpty())
     647             :     {
     648           0 :         if (!wm.m_ReflectionFramebufferInitialized)
     649             :         {
     650           0 :             wm.m_ReflectionFramebufferInitialized = true;
     651           0 :             deviceCommandContext->BeginFramebufferPass(wm.m_ReflectionFramebuffer.get());
     652           0 :             deviceCommandContext->EndFramebufferPass();
     653             :         }
     654           0 :         m_ViewCamera = normalCamera;
     655           0 :         return;
     656             :     }
     657             : 
     658             :     // Save the model-view-projection matrix so the shaders can use it for projective texturing
     659           0 :     wm.m_ReflectionMatrix = m_ViewCamera.GetViewProjection();
     660           0 :     if (deviceCommandContext->GetDevice()->GetBackend() == Renderer::Backend::Backend::VULKAN)
     661             :     {
     662           0 :         CMatrix3D flip;
     663           0 :         flip.SetIdentity();
     664           0 :         flip._22 = -1.0f;
     665           0 :         wm.m_ReflectionMatrix = flip * wm.m_ReflectionMatrix;
     666             :     }
     667             : 
     668           0 :     float vpHeight = wm.m_RefTextureSize;
     669           0 :     float vpWidth = wm.m_RefTextureSize;
     670             : 
     671           0 :     SScreenRect screenScissor;
     672           0 :     screenScissor.x1 = static_cast<int>(floor((reflectionScissor[0].X * 0.5f + 0.5f) * vpWidth));
     673           0 :     screenScissor.y1 = static_cast<int>(floor((reflectionScissor[0].Y * 0.5f + 0.5f) * vpHeight));
     674           0 :     screenScissor.x2 = static_cast<int>(ceil((reflectionScissor[1].X * 0.5f + 0.5f) * vpWidth));
     675           0 :     screenScissor.y2 = static_cast<int>(ceil((reflectionScissor[1].Y * 0.5f + 0.5f) * vpHeight));
     676             : 
     677           0 :     deviceCommandContext->BeginFramebufferPass(wm.m_ReflectionFramebuffer.get());
     678             : 
     679           0 :     Renderer::Backend::IDeviceCommandContext::Rect viewportRect{};
     680           0 :     viewportRect.width = vpWidth;
     681           0 :     viewportRect.height = vpHeight;
     682           0 :     deviceCommandContext->SetViewports(1, &viewportRect);
     683             : 
     684           0 :     Renderer::Backend::IDeviceCommandContext::Rect scissorRect;
     685           0 :     scissorRect.x = screenScissor.x1;
     686           0 :     scissorRect.y = screenScissor.y1;
     687           0 :     scissorRect.width = screenScissor.x2 - screenScissor.x1;
     688           0 :     scissorRect.height = screenScissor.y2 - screenScissor.y1;
     689           0 :     deviceCommandContext->SetScissors(1, &scissorRect);
     690             : 
     691             :     // Render terrain and models
     692           0 :     RenderPatches(deviceCommandContext, context, CULL_REFLECTIONS);
     693           0 :     RenderModels(deviceCommandContext, context, CULL_REFLECTIONS);
     694           0 :     RenderTransparentModels(deviceCommandContext, context, CULL_REFLECTIONS, TRANSPARENT);
     695             : 
     696             :     // Particles are always oriented to face the camera in the vertex shader,
     697             :     // so they don't need the inverted cull face.
     698           0 :     if (g_RenderingOptions.GetParticles())
     699             :     {
     700           0 :         RenderParticles(deviceCommandContext, CULL_REFLECTIONS);
     701             :     }
     702             : 
     703           0 :     deviceCommandContext->SetScissors(0, nullptr);
     704           0 :     deviceCommandContext->EndFramebufferPass();
     705             : 
     706           0 :     wm.m_ReflectionFramebufferInitialized = true;
     707             : 
     708             :     // Reset old camera
     709           0 :     m_ViewCamera = normalCamera;
     710           0 : }
     711             : 
     712             : // RenderRefractions: render the water refractions to the refraction texture
     713           0 : void CSceneRenderer::RenderRefractions(
     714             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
     715             :     const CShaderDefines& context, const CBoundingBoxAligned &scissor)
     716             : {
     717           0 :     PROFILE3_GPU(deviceCommandContext, "water refractions");
     718           0 :     GPU_SCOPED_LABEL(deviceCommandContext, "Render water refractions");
     719             : 
     720           0 :     WaterManager& wm = m->waterManager;
     721             : 
     722             :     // Remember old camera
     723           0 :     CCamera normalCamera = m_ViewCamera;
     724             : 
     725           0 :     ComputeRefractionCamera(m_ViewCamera, scissor);
     726           0 :     const CBoundingBoxAligned refractionScissor =
     727           0 :         m->terrainRenderer.ScissorWater(CULL_DEFAULT, m_ViewCamera);
     728           0 :     if (refractionScissor.IsEmpty())
     729             :     {
     730           0 :         if (!wm.m_RefractionFramebufferInitialized)
     731             :         {
     732           0 :             wm.m_RefractionFramebufferInitialized = true;
     733           0 :             deviceCommandContext->BeginFramebufferPass(wm.m_ReflectionFramebuffer.get());
     734           0 :             deviceCommandContext->EndFramebufferPass();
     735             :         }
     736           0 :         m_ViewCamera = normalCamera;
     737           0 :         return;
     738             :     }
     739             : 
     740           0 :     CVector4D camPlane(0, -1, 0, wm.m_WaterHeight + 2.0f);
     741           0 :     SetObliqueFrustumClipping(m_ViewCamera, camPlane);
     742             : 
     743             :     // Save the model-view-projection matrix so the shaders can use it for projective texturing
     744           0 :     wm.m_RefractionMatrix = m_ViewCamera.GetViewProjection();
     745           0 :     wm.m_RefractionProjInvMatrix = m_ViewCamera.GetProjection().GetInverse();
     746           0 :     wm.m_RefractionViewInvMatrix = m_ViewCamera.GetOrientation();
     747             : 
     748           0 :     if (deviceCommandContext->GetDevice()->GetBackend() == Renderer::Backend::Backend::VULKAN)
     749             :     {
     750           0 :         CMatrix3D flip;
     751           0 :         flip.SetIdentity();
     752           0 :         flip._22 = -1.0f;
     753           0 :         wm.m_RefractionMatrix = flip * wm.m_RefractionMatrix;
     754           0 :         wm.m_RefractionProjInvMatrix = wm.m_RefractionProjInvMatrix * flip;
     755             :     }
     756             : 
     757           0 :     float vpHeight = wm.m_RefTextureSize;
     758           0 :     float vpWidth = wm.m_RefTextureSize;
     759             : 
     760           0 :     SScreenRect screenScissor;
     761           0 :     screenScissor.x1 = static_cast<int>(floor((refractionScissor[0].X * 0.5f + 0.5f) * vpWidth));
     762           0 :     screenScissor.y1 = static_cast<int>(floor((refractionScissor[0].Y * 0.5f + 0.5f) * vpHeight));
     763           0 :     screenScissor.x2 = static_cast<int>(ceil((refractionScissor[1].X * 0.5f + 0.5f) * vpWidth));
     764           0 :     screenScissor.y2 = static_cast<int>(ceil((refractionScissor[1].Y * 0.5f + 0.5f) * vpHeight));
     765             : 
     766           0 :     deviceCommandContext->BeginFramebufferPass(wm.m_RefractionFramebuffer.get());
     767             : 
     768           0 :     Renderer::Backend::IDeviceCommandContext::Rect viewportRect{};
     769           0 :     viewportRect.width = vpWidth;
     770           0 :     viewportRect.height = vpHeight;
     771           0 :     deviceCommandContext->SetViewports(1, &viewportRect);
     772             : 
     773           0 :     Renderer::Backend::IDeviceCommandContext::Rect scissorRect;
     774           0 :     scissorRect.x = screenScissor.x1;
     775           0 :     scissorRect.y = screenScissor.y1;
     776           0 :     scissorRect.width = screenScissor.x2 - screenScissor.x1;
     777           0 :     scissorRect.height = screenScissor.y2 - screenScissor.y1;
     778           0 :     deviceCommandContext->SetScissors(1, &scissorRect);
     779             : 
     780             :     // Render terrain and models
     781           0 :     RenderPatches(deviceCommandContext, context, CULL_REFRACTIONS);
     782             : 
     783             :     // Render debug-related terrain overlays to make it visible under water.
     784           0 :     ITerrainOverlay::RenderOverlaysBeforeWater(deviceCommandContext);
     785             : 
     786           0 :     RenderModels(deviceCommandContext, context, CULL_REFRACTIONS);
     787           0 :     RenderTransparentModels(deviceCommandContext, context, CULL_REFRACTIONS, TRANSPARENT_OPAQUE);
     788             : 
     789           0 :     deviceCommandContext->SetScissors(0, nullptr);
     790           0 :     deviceCommandContext->EndFramebufferPass();
     791             : 
     792           0 :     wm.m_RefractionFramebufferInitialized = true;
     793             : 
     794             :     // Reset old camera
     795           0 :     m_ViewCamera = normalCamera;
     796           0 : }
     797             : 
     798           0 : void CSceneRenderer::RenderSilhouettes(
     799             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
     800             : {
     801           0 :     PROFILE3("silhouettes");
     802           0 :     GPU_SCOPED_LABEL(deviceCommandContext, "Render silhouettes");
     803             : 
     804             :     // Render silhouettes of units hidden behind terrain or occluders.
     805             :     // To avoid breaking the standard rendering of alpha-blended objects, this
     806             :     // has to be done in a separate pass.
     807             :     // First we render all occluders into depth, then render all units with
     808             :     // inverted depth test so any behind an occluder will get drawn in a constant
     809             :     // color.
     810             : 
     811             :     // TODO: do we need clear here?
     812           0 :     deviceCommandContext->ClearFramebuffer(false, true, true);
     813             : 
     814             :     // Render occluders:
     815             : 
     816           0 :     {
     817           0 :         PROFILE("render patches");
     818           0 :         m->terrainRenderer.RenderPatches(
     819           0 :             deviceCommandContext, CULL_SILHOUETTE_OCCLUDER, {}, CColor(0.0f, 0.0f, 0.0f, 1.0f), false);
     820           0 :     }
     821             : 
     822           0 :     {
     823           0 :         PROFILE("render model occluders");
     824           0 :         m->CallOpaqueModelRenderers(deviceCommandContext, {}, CULL_SILHOUETTE_OCCLUDER, 0, ERenderMode::SOLID);
     825           0 :     }
     826             : 
     827           0 :     {
     828           0 :         PROFILE("render transparent occluders");
     829           0 :         m->CallTransparentModelRenderers(deviceCommandContext, {}, CULL_SILHOUETTE_OCCLUDER, 0, ERenderMode::SOLID);
     830           0 :     }
     831             : 
     832             :     // Since we can't sort, we'll use the stencil buffer to ensure we only draw
     833             :     // a pixel once (using the color of whatever model happens to be drawn first).
     834           0 :     {
     835           0 :         PROFILE("render model casters");
     836           0 :         m->CallOpaqueModelRenderers(deviceCommandContext, {}, CULL_SILHOUETTE_CASTER, 0, ERenderMode::SOLID);
     837           0 :     }
     838             : 
     839           0 :     {
     840           0 :         PROFILE("render transparent casters");
     841           0 :         m->CallTransparentModelRenderers(deviceCommandContext, {}, CULL_SILHOUETTE_CASTER, 0, ERenderMode::SOLID);
     842           0 :     }
     843           0 : }
     844             : 
     845           0 : void CSceneRenderer::RenderParticles(
     846             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
     847             :     int cullGroup)
     848             : {
     849           0 :     PROFILE3("particles");
     850           0 :     GPU_SCOPED_LABEL(deviceCommandContext, "Render particles");
     851             : 
     852           0 :     m->particleRenderer.RenderParticles(
     853           0 :         deviceCommandContext, cullGroup, m_ModelRenderMode == WIREFRAME);
     854             : 
     855           0 :     if (m_ModelRenderMode == EDGED_FACES)
     856             :     {
     857           0 :         m->particleRenderer.RenderParticles(
     858             :             deviceCommandContext, cullGroup, true);
     859           0 :         m->particleRenderer.RenderBounds(*deviceCommandContext, cullGroup);
     860             :     }
     861           0 : }
     862             : 
     863           0 : void CSceneRenderer::PrepareSubmissions(
     864             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
     865             : {
     866           0 :     PROFILE3_GPU(deviceCommandContext, "prepare submissions");
     867           0 :     GPU_SCOPED_LABEL(deviceCommandContext, "Prepare submissions");
     868             : 
     869           0 :     if (m->waterManager.m_RenderWater && m_WaterScissor.GetVolume() > 0 && m->waterManager.WillRenderFancyWater())
     870             :     {
     871             :         // Render the waves to the Fancy effects texture
     872           0 :         m->waterManager.RenderWaves(deviceCommandContext, m_CullCamera.GetFrustum());
     873             :     }
     874             : 
     875           0 :     m->skyManager.LoadAndUploadSkyTexturesIfNeeded(deviceCommandContext);
     876             : 
     877           0 :     GetScene().GetLOSTexture().InterpolateLOS(deviceCommandContext);
     878           0 :     GetScene().GetTerritoryTexture().UpdateIfNeeded(deviceCommandContext);
     879           0 :     GetScene().GetMiniMapTexture().Render(
     880           0 :         deviceCommandContext, GetScene().GetLOSTexture(), GetScene().GetTerritoryTexture());
     881             : 
     882           0 :     CShaderDefines context = m->globalContext;
     883             : 
     884             :     // Prepare model renderers
     885           0 :     m->PrepareModels(deviceCommandContext);
     886             : 
     887           0 :     m->terrainRenderer.PrepareForRendering();
     888             : 
     889           0 :     m->overlayRenderer.PrepareForRendering();
     890             : 
     891           0 :     m->particleRenderer.PrepareForRendering(context);
     892             : 
     893           0 :     m->UploadModels(deviceCommandContext);
     894             : 
     895           0 :     m->overlayRenderer.Upload(deviceCommandContext);
     896             : 
     897           0 :     m->particleRenderer.Upload(deviceCommandContext);
     898             : 
     899           0 :     if (g_RenderingOptions.GetShadows())
     900             :     {
     901           0 :         RenderShadowMap(deviceCommandContext);
     902             :     }
     903             : 
     904           0 :     if (m->waterManager.m_RenderWater)
     905             :     {
     906           0 :         if (m_WaterScissor.GetVolume() > 0 && m->waterManager.WillRenderFancyWater())
     907             :         {
     908           0 :             m->waterManager.UpdateQuality();
     909             : 
     910           0 :             PROFILE3_GPU(deviceCommandContext, "water scissor");
     911           0 :             if (g_RenderingOptions.GetWaterReflection())
     912           0 :                 RenderReflections(deviceCommandContext, context, m_WaterScissor);
     913             : 
     914           0 :             if (g_RenderingOptions.GetWaterRefraction())
     915           0 :                 RenderRefractions(deviceCommandContext, context, m_WaterScissor);
     916             : 
     917           0 :             if (g_RenderingOptions.GetWaterFancyEffects())
     918           0 :                 m->terrainRenderer.RenderWaterFoamOccluders(deviceCommandContext, CULL_DEFAULT);
     919           0 :         }
     920             :     }
     921           0 : }
     922             : 
     923           0 : void CSceneRenderer::RenderSubmissions(
     924             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
     925             : {
     926           0 :     PROFILE3("render submissions");
     927           0 :     GPU_SCOPED_LABEL(deviceCommandContext, "Render submissions");
     928             : 
     929           0 :     ENSURE(m_CurrentScene);
     930             : 
     931           0 :     CShaderDefines context = m->globalContext;
     932             : 
     933           0 :     constexpr int cullGroup = CULL_DEFAULT;
     934             : 
     935           0 :     m->skyManager.RenderSky(deviceCommandContext);
     936             : 
     937             :     // render submitted patches and models
     938           0 :     RenderPatches(deviceCommandContext, context, cullGroup);
     939             : 
     940             :     // render debug-related terrain overlays
     941           0 :     ITerrainOverlay::RenderOverlaysBeforeWater(deviceCommandContext);
     942             : 
     943             :     // render other debug-related overlays before water (so they can be seen when underwater)
     944           0 :     if (!g_RenderingOptions.GetCutsceneMode())
     945           0 :         m->overlayRenderer.RenderOverlaysBeforeWater(deviceCommandContext);
     946             : 
     947           0 :     RenderModels(deviceCommandContext, context, cullGroup);
     948             : 
     949             :     // render water
     950           0 :     if (m->waterManager.m_RenderWater && g_Game && m_WaterScissor.GetVolume() > 0)
     951             :     {
     952           0 :         if (m->waterManager.WillRenderFancyWater())
     953             :         {
     954             :             // Render transparent stuff, but only the solid parts that can occlude block water.
     955           0 :             RenderTransparentModels(deviceCommandContext, context, cullGroup, TRANSPARENT_OPAQUE);
     956             : 
     957           0 :             m->terrainRenderer.RenderWater(deviceCommandContext, context, cullGroup, &m->shadow);
     958             : 
     959             :             // Render transparent stuff again, but only the blended parts that overlap water.
     960           0 :             RenderTransparentModels(deviceCommandContext, context, cullGroup, TRANSPARENT_BLEND);
     961             :         }
     962             :         else
     963             :         {
     964           0 :             m->terrainRenderer.RenderWater(deviceCommandContext, context, cullGroup, &m->shadow);
     965             : 
     966             :             // Render transparent stuff, so it can overlap models/terrain.
     967           0 :             RenderTransparentModels(deviceCommandContext, context, cullGroup, TRANSPARENT);
     968             :         }
     969             :     }
     970             :     else
     971             :     {
     972             :         // render transparent stuff, so it can overlap models/terrain
     973           0 :         RenderTransparentModels(deviceCommandContext, context, cullGroup, TRANSPARENT);
     974             :     }
     975             : 
     976             :     // render debug-related terrain overlays
     977           0 :     ITerrainOverlay::RenderOverlaysAfterWater(deviceCommandContext, cullGroup);
     978             : 
     979           0 :     if (!g_RenderingOptions.GetCutsceneMode())
     980             :         // render some other overlays after water (so they can be displayed on top of water)
     981           0 :         m->overlayRenderer.RenderOverlaysAfterWater(deviceCommandContext);
     982             : 
     983             :     // particles are transparent so render after water
     984           0 :     if (g_RenderingOptions.GetParticles())
     985             :     {
     986           0 :         RenderParticles(deviceCommandContext, cullGroup);
     987             :     }
     988             : 
     989             :     // render debug lines
     990           0 :     if (g_RenderingOptions.GetDisplayFrustum())
     991           0 :         DisplayFrustum(*deviceCommandContext);
     992             : 
     993           0 :     if (g_RenderingOptions.GetDisplayShadowsFrustum())
     994           0 :         m->shadow.RenderDebugBounds(*deviceCommandContext);
     995             : 
     996           0 :     m->silhouetteRenderer.RenderDebugBounds(deviceCommandContext);
     997           0 : }
     998             : 
     999           0 : void CSceneRenderer::EndFrame()
    1000             : {
    1001             :     // empty lists
    1002           0 :     m->terrainRenderer.EndFrame();
    1003           0 :     m->overlayRenderer.EndFrame();
    1004           0 :     m->particleRenderer.EndFrame();
    1005           0 :     m->silhouetteRenderer.EndFrame();
    1006             : 
    1007           0 :     for (int cullGroup{0}; cullGroup < CSceneRenderer::CULL_MAX; ++cullGroup)
    1008             :     {
    1009           0 :         m->Model.OpaqueSkinned.submissions[cullGroup].clear();
    1010           0 :         m->Model.TransparentSkinned.submissions[cullGroup].clear();
    1011           0 :         m->Model.OpaqueUnskinned.submissions[cullGroup].clear();
    1012           0 :         m->Model.TransparentUnskinned.submissions[cullGroup].clear();
    1013             :     }
    1014           0 :     m->Model.uniqueSkinnedSubmissionsForUpdate.clear();
    1015           0 : }
    1016             : 
    1017           0 : void CSceneRenderer::DisplayFrustum(Renderer::Backend::IDeviceCommandContext& deviceCommandContext)
    1018             : {
    1019           0 :     g_Renderer.GetDebugRenderer().DrawCameraFrustum(deviceCommandContext, m_CullCamera, CColor(1.0f, 1.0f, 1.0f, 0.25f), 2);
    1020           0 :     g_Renderer.GetDebugRenderer().DrawCameraFrustum(deviceCommandContext, m_CullCamera, CColor(1.0f, 1.0f, 1.0f, 1.0f), 2, true);
    1021           0 : }
    1022             : 
    1023             : // Text overlay rendering
    1024           0 : void CSceneRenderer::RenderTextOverlays(CCanvas2D& canvas)
    1025             : {
    1026           0 :     PROFILE3("text overlays");
    1027             : 
    1028           0 :     if (m_DisplayTerrainPriorities)
    1029           0 :         m->terrainRenderer.RenderPriorities(canvas, CULL_DEFAULT);
    1030           0 : }
    1031             : 
    1032             : // SetSceneCamera: setup projection and transform of camera and adjust viewport to current view
    1033             : // The camera always represents the actual camera used to render a scene, not any virtual camera
    1034             : // used for shadow rendering or reflections.
    1035           0 : void CSceneRenderer::SetSceneCamera(const CCamera& viewCamera, const CCamera& cullCamera)
    1036             : {
    1037           0 :     m_ViewCamera = viewCamera;
    1038           0 :     m_CullCamera = cullCamera;
    1039             : 
    1040           0 :     if (g_RenderingOptions.GetShadows())
    1041           0 :         m->shadow.SetupFrame(m_CullCamera, m_LightEnv->GetSunDir());
    1042           0 : }
    1043             : 
    1044           0 : void CSceneRenderer::Submit(CPatch* patch)
    1045             : {
    1046           0 :     if (m_CurrentCullGroup == CULL_DEFAULT)
    1047             :     {
    1048           0 :         m->shadow.AddShadowReceiverBound(patch->GetWorldBounds());
    1049           0 :         m->silhouetteRenderer.AddOccluder(patch);
    1050             :     }
    1051             : 
    1052           0 :     if (CULL_SHADOWS_CASCADE_0 <= m_CurrentCullGroup && m_CurrentCullGroup <= CULL_SHADOWS_CASCADE_3)
    1053             :     {
    1054           0 :         const int cascade = m_CurrentCullGroup - CULL_SHADOWS_CASCADE_0;
    1055           0 :         m->shadow.AddShadowCasterBound(cascade, patch->GetWorldBounds());
    1056             :     }
    1057             : 
    1058           0 :     m->terrainRenderer.Submit(m_CurrentCullGroup, patch);
    1059           0 : }
    1060             : 
    1061           0 : void CSceneRenderer::Submit(SOverlayLine* overlay)
    1062             : {
    1063             :     // Overlays are only needed in the default cull group for now,
    1064             :     // so just ignore submissions to any other group
    1065           0 :     if (m_CurrentCullGroup == CULL_DEFAULT)
    1066           0 :         m->overlayRenderer.Submit(overlay);
    1067           0 : }
    1068             : 
    1069           0 : void CSceneRenderer::Submit(SOverlayTexturedLine* overlay)
    1070             : {
    1071           0 :     if (m_CurrentCullGroup == CULL_DEFAULT)
    1072           0 :         m->overlayRenderer.Submit(overlay);
    1073           0 : }
    1074             : 
    1075           0 : void CSceneRenderer::Submit(SOverlaySprite* overlay)
    1076             : {
    1077           0 :     if (m_CurrentCullGroup == CULL_DEFAULT)
    1078           0 :         m->overlayRenderer.Submit(overlay);
    1079           0 : }
    1080             : 
    1081           0 : void CSceneRenderer::Submit(SOverlayQuad* overlay)
    1082             : {
    1083           0 :     if (m_CurrentCullGroup == CULL_DEFAULT)
    1084           0 :         m->overlayRenderer.Submit(overlay);
    1085           0 : }
    1086             : 
    1087           0 : void CSceneRenderer::Submit(SOverlaySphere* overlay)
    1088             : {
    1089           0 :     if (m_CurrentCullGroup == CULL_DEFAULT)
    1090           0 :         m->overlayRenderer.Submit(overlay);
    1091           0 : }
    1092             : 
    1093           0 : void CSceneRenderer::Submit(CModelDecal* decal)
    1094             : {
    1095             :     // Decals can't cast shadows since they're flat on the terrain.
    1096             :     // They can receive shadows, but the terrain under them will have
    1097             :     // already been passed to AddShadowCasterBound, so don't bother
    1098             :     // doing it again here.
    1099             : 
    1100           0 :     m->terrainRenderer.Submit(m_CurrentCullGroup, decal);
    1101           0 : }
    1102             : 
    1103           0 : void CSceneRenderer::Submit(CParticleEmitter* emitter)
    1104             : {
    1105           0 :     m->particleRenderer.Submit(m_CurrentCullGroup, emitter);
    1106           0 : }
    1107             : 
    1108           0 : void CSceneRenderer::SubmitNonRecursive(CModel* model)
    1109             : {
    1110           0 :     if (m_CurrentCullGroup == CULL_DEFAULT)
    1111             :     {
    1112           0 :         m->shadow.AddShadowReceiverBound(model->GetWorldBounds());
    1113             : 
    1114           0 :         if (model->GetFlags() & ModelFlag::SILHOUETTE_OCCLUDER)
    1115           0 :             m->silhouetteRenderer.AddOccluder(model);
    1116           0 :         if (model->GetFlags() & ModelFlag::SILHOUETTE_DISPLAY)
    1117           0 :             m->silhouetteRenderer.AddCaster(model);
    1118             :     }
    1119             : 
    1120           0 :     if (CULL_SHADOWS_CASCADE_0 <= m_CurrentCullGroup && m_CurrentCullGroup <= CULL_SHADOWS_CASCADE_3)
    1121             :     {
    1122           0 :         if (!(model->GetFlags() & ModelFlag::CAST_SHADOWS))
    1123             :             return;
    1124             : 
    1125           0 :         const int cascade = m_CurrentCullGroup - CULL_SHADOWS_CASCADE_0;
    1126           0 :         m->shadow.AddShadowCasterBound(cascade, model->GetWorldBounds());
    1127             :     }
    1128             : 
    1129           0 :     const bool requiresSkinning{model->GetModelDef()->GetNumBones() != 0};
    1130           0 :     ModelVertexRenderer& modelVertexSkinningRenderer{
    1131           0 :         m->Model.GPUSkinningEnabled
    1132           0 :             ? static_cast<ModelVertexRenderer&>(*m->Model.VertexGPUSkinningShader)
    1133           0 :             : static_cast<ModelVertexRenderer&>(m->Model.VertexCPUSkinningShader)};
    1134             : 
    1135           0 :     if (model->GetMaterial().UsesAlphaBlending())
    1136             :     {
    1137           0 :         if (requiresSkinning)
    1138           0 :             m->Submit(m_CurrentCullGroup, modelVertexSkinningRenderer, m->Model.TransparentSkinned, model);
    1139             :         else
    1140           0 :             m->Submit(m_CurrentCullGroup, m->Model.VertexInstancingShader, m->Model.TransparentUnskinned, model);
    1141             :     }
    1142             :     else
    1143             :     {
    1144           0 :         if (requiresSkinning)
    1145           0 :             m->Submit(m_CurrentCullGroup, modelVertexSkinningRenderer, m->Model.OpaqueSkinned, model);
    1146             :         else
    1147           0 :             m->Submit(m_CurrentCullGroup, m->Model.VertexInstancingShader, m->Model.OpaqueUnskinned, model);
    1148             :     }
    1149             : }
    1150             : 
    1151           0 : void CSceneRenderer::EnumerateSceneObjects(Scene& scene)
    1152             : {
    1153           0 :     m_CurrentScene = &scene;
    1154             : 
    1155           0 :     const CFrustum& frustum{m_CullCamera.GetFrustum()};
    1156             : 
    1157           0 :     m_CurrentCullGroup = CULL_DEFAULT;
    1158             : 
    1159           0 :     scene.EnumerateObjects(frustum, this);
    1160             : 
    1161           0 :     m->particleManager.RenderSubmit(*this, frustum);
    1162             : 
    1163           0 :     if (!g_RenderingOptions.GetCutsceneMode() && g_RenderingOptions.GetSilhouettes())
    1164             :     {
    1165           0 :         m->silhouetteRenderer.ComputeSubmissions(m_ViewCamera);
    1166             : 
    1167           0 :         m_CurrentCullGroup = CULL_DEFAULT;
    1168           0 :         m->silhouetteRenderer.RenderSubmitOverlays(*this);
    1169             : 
    1170           0 :         m_CurrentCullGroup = CULL_SILHOUETTE_OCCLUDER;
    1171           0 :         m->silhouetteRenderer.RenderSubmitOccluders(*this);
    1172             : 
    1173           0 :         m_CurrentCullGroup = CULL_SILHOUETTE_CASTER;
    1174           0 :         m->silhouetteRenderer.RenderSubmitCasters(*this);
    1175             :     }
    1176             : 
    1177           0 :     if (g_RenderingOptions.GetShadows())
    1178             :     {
    1179           0 :         for (int cascade = 0; cascade < m->shadow.GetCascadeCount(); ++cascade)
    1180             :         {
    1181           0 :             m_CurrentCullGroup = CULL_SHADOWS_CASCADE_0 + cascade;
    1182           0 :             const CFrustum shadowFrustum = m->shadow.GetShadowCasterCullFrustum(cascade);
    1183           0 :             scene.EnumerateObjects(shadowFrustum, this);
    1184           0 :         }
    1185             :     }
    1186             : 
    1187           0 :     if (m->waterManager.m_RenderWater)
    1188             :     {
    1189           0 :         m_WaterScissor = m->terrainRenderer.ScissorWater(CULL_DEFAULT, m_ViewCamera);
    1190             : 
    1191           0 :         if (m_WaterScissor.GetVolume() > 0 && m->waterManager.WillRenderFancyWater())
    1192             :         {
    1193           0 :             if (g_RenderingOptions.GetWaterReflection())
    1194             :             {
    1195           0 :                 m_CurrentCullGroup = CULL_REFLECTIONS;
    1196             : 
    1197           0 :                 CCamera reflectionCamera;
    1198           0 :                 ComputeReflectionCamera(reflectionCamera, m_WaterScissor);
    1199             : 
    1200           0 :                 scene.EnumerateObjects(reflectionCamera.GetFrustum(), this);
    1201           0 :             }
    1202             : 
    1203           0 :             if (g_RenderingOptions.GetWaterRefraction())
    1204             :             {
    1205           0 :                 m_CurrentCullGroup = CULL_REFRACTIONS;
    1206             : 
    1207           0 :                 CCamera refractionCamera;
    1208           0 :                 ComputeRefractionCamera(refractionCamera, m_WaterScissor);
    1209             : 
    1210           0 :                 scene.EnumerateObjects(refractionCamera.GetFrustum(), this);
    1211           0 :             }
    1212             :         }
    1213             :     }
    1214             :     else
    1215           0 :         m_WaterScissor = CBoundingBoxAligned{};
    1216             : 
    1217           0 :     m_CurrentCullGroup = -1;
    1218           0 : }
    1219             : 
    1220           0 : void CSceneRenderer::RenderSceneOverlays(
    1221             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
    1222             : {
    1223           0 :     if (!g_RenderingOptions.GetCutsceneMode())
    1224             :     {
    1225           0 :         if (g_RenderingOptions.GetSilhouettes())
    1226           0 :             RenderSilhouettes(deviceCommandContext);
    1227             : 
    1228           0 :         m->silhouetteRenderer.RenderDebugOverlays(deviceCommandContext);
    1229             : 
    1230             :         // Render overlays that should appear on top of all other objects.
    1231           0 :         m->overlayRenderer.RenderForegroundOverlays(deviceCommandContext, m_ViewCamera);
    1232             :     }
    1233             : 
    1234           0 :     m_CurrentScene = nullptr;
    1235           0 : }
    1236             : 
    1237           0 : Scene& CSceneRenderer::GetScene()
    1238             : {
    1239           0 :     ENSURE(m_CurrentScene);
    1240           0 :     return *m_CurrentScene;
    1241             : }
    1242             : 
    1243           0 : void CSceneRenderer::MakeShadersDirty()
    1244             : {
    1245           0 :     m->waterManager.m_NeedsReloading = true;
    1246           0 : }
    1247             : 
    1248           0 : WaterManager& CSceneRenderer::GetWaterManager()
    1249             : {
    1250           0 :     return m->waterManager;
    1251             : }
    1252             : 
    1253           0 : SkyManager& CSceneRenderer::GetSkyManager()
    1254             : {
    1255           0 :     return m->skyManager;
    1256             : }
    1257             : 
    1258           0 : CParticleManager& CSceneRenderer::GetParticleManager()
    1259             : {
    1260           0 :     return m->particleManager;
    1261             : }
    1262             : 
    1263           0 : TerrainRenderer& CSceneRenderer::GetTerrainRenderer()
    1264             : {
    1265           0 :     return m->terrainRenderer;
    1266             : }
    1267             : 
    1268           1 : CMaterialManager& CSceneRenderer::GetMaterialManager()
    1269             : {
    1270           1 :     return m->materialManager;
    1271             : }
    1272             : 
    1273           0 : ShadowMap& CSceneRenderer::GetShadowMap()
    1274             : {
    1275           0 :     return m->shadow;
    1276             : }
    1277             : 
    1278           0 : void CSceneRenderer::ResetState()
    1279             : {
    1280             :     // Clear all emitters, that were created in previous games
    1281           0 :     GetParticleManager().ClearUnattachedEmitters();
    1282           0 : }

Generated by: LCOV version 1.16