LCOV - code coverage report
Current view: top level - source/renderer - ModelRenderer.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 0 251 0.0 %
Date: 2026-12-03 01:19:39 Functions: 0 7 0.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 "graphics/Camera.h"
      21             : #include "graphics/Color.h"
      22             : #include "graphics/LightEnv.h"
      23             : #include "graphics/Material.h"
      24             : #include "graphics/Model.h"
      25             : #include "graphics/ModelDef.h"
      26             : #include "graphics/SColor.h"
      27             : #include "graphics/ShaderDefines.h"
      28             : #include "graphics/ShaderManager.h"
      29             : #include "graphics/ShaderTechnique.h"
      30             : #include "graphics/ShaderTechniquePtr.h"
      31             : #include "graphics/Texture.h"
      32             : #include "graphics/TextureManager.h"
      33             : #include "lib/alignment.h"
      34             : #include "lib/debug.h"
      35             : #include "lib/hash.h"
      36             : #include "maths/Matrix3D.h"
      37             : #include "maths/Vector2D.h"
      38             : #include "maths/Vector3D.h"
      39             : #include "ps/CLogger.h"
      40             : #include "ps/CStrIntern.h"
      41             : #include "ps/CStrInternStatic.h"
      42             : #include "ps/memory/AllocatorAdapter.h"
      43             : #include "ps/memory/LinearAllocator.h"
      44             : #include "ps/Profile.h"
      45             : #include "renderer/MikktspaceWrap.h"
      46             : #include "renderer/ModelRenderer.h"
      47             : #include "renderer/ModelVertexRenderer.h"
      48             : #include "renderer/RenderModifiers.h"
      49             : #include "renderer/Renderer.h"
      50             : #include "renderer/SceneRenderer.h"
      51             : #include "renderer/SkyManager.h"
      52             : #include "renderer/TimeManager.h"
      53             : #include "renderer/VertexArray.h"
      54             : #include "renderer/WaterManager.h"
      55             : #include "renderer/backend/IDeviceCommandContext.h"
      56             : #include "renderer/backend/IShaderProgram.h"
      57             : 
      58             : #include <algorithm>
      59             : #include <cstddef>
      60             : #include <cstdint>
      61             : #include <functional>
      62             : #include <span>
      63             : #include <string>
      64             : #include <unordered_map>
      65             : #include <utility>
      66             : 
      67             : 
      68             : namespace
      69             : {
      70             : 
      71           0 : CMaterial::Pass GetMaterialPassFromCullGroup(const int cullGroup, const ERenderMode renderMode)
      72             : {
      73           0 :     switch (renderMode)
      74             :     {
      75             :     case ERenderMode::WIREFRAME:
      76             :         return CMaterial::Pass::WIREFRAME;
      77           0 :     case ERenderMode::EDGED_FACES:
      78           0 :         return CMaterial::Pass::WIREFRAME_SOLID;
      79             :     case ERenderMode::SOLID:
      80             :         break;
      81             :     }
      82             : 
      83           0 :     switch (cullGroup)
      84             :     {
      85             :     case CSceneRenderer::CULL_SHADOWS_CASCADE_0: [[fallthrough]];
      86             :     case CSceneRenderer::CULL_SHADOWS_CASCADE_1: [[fallthrough]];
      87             :     case CSceneRenderer::CULL_SHADOWS_CASCADE_2: [[fallthrough]];
      88             :     case CSceneRenderer::CULL_SHADOWS_CASCADE_3:
      89             :         return CMaterial::Pass::SHADOW_CASTER;
      90             :     case CSceneRenderer::CULL_SILHOUETTE_OCCLUDER:
      91             :         return CMaterial::Pass::SILHOUETTE_OCCLUDER;
      92             :     case CSceneRenderer::CULL_SILHOUETTE_CASTER:
      93             :         return CMaterial::Pass::SILHOUETTE_CASTER;
      94             :     case CSceneRenderer::CULL_DEFAULT:
      95             :         return CMaterial::Pass::MAIN;
      96             :     default:
      97             :         break;
      98             :     }
      99             : 
     100             :     return CMaterial::Pass::MAIN;
     101             : }
     102             : 
     103             : }
     104             : 
     105             : // static
     106           0 : void ModelRenderer::CopyPositionAndNormals(
     107             :     const CModelDefPtr& mdef,
     108             :     const VertexArrayIterator<CVector3D>& Position,
     109             :     const VertexArrayIterator<CVector3D>& Normal)
     110             : {
     111           0 :     size_t numVertices = mdef->GetNumVertices();
     112           0 :     SModelVertex* vertices = mdef->GetVertices();
     113             : 
     114           0 :     for (size_t j = 0; j < numVertices; ++j)
     115             :     {
     116           0 :         Position[j] = vertices[j].m_Coords;
     117           0 :         Normal[j] = vertices[j].m_Norm;
     118             :     }
     119           0 : }
     120             : 
     121             : // static
     122           0 : void ModelRenderer::BuildPositionAndNormals(
     123             :     CModel* model,
     124             :     const VertexArrayIterator<CVector3D>& Position,
     125             :     const VertexArrayIterator<CVector3D>& Normal)
     126             : {
     127           0 :     CModelDefPtr mdef = model->GetModelDef();
     128           0 :     size_t numVertices = mdef->GetNumVertices();
     129           0 :     SModelVertex* vertices = mdef->GetVertices();
     130             : 
     131           0 :     if (model->IsSkinned())
     132             :     {
     133             :         // boned model - calculate skinned vertex positions/normals
     134             : 
     135             :         // Avoid the noisy warnings that occur inside SkinPoint/SkinNormal in
     136             :         // some broken situations
     137           0 :         if (numVertices && vertices[0].m_Blend.m_Bone[0] == 0xff)
     138             :         {
     139           0 :             LOGERROR("Model {} is boned with unboned animation", mdef->GetName().string8());
     140           0 :             return;
     141             :         }
     142             : 
     143           0 :         CModelDef::SkinPointsAndNormals(numVertices, Position, Normal, vertices, mdef->GetBlendIndices(), model->GetAnimatedBoneMatrices());
     144             :     }
     145             :     else
     146             :     {
     147           0 :         PROFILE("software transform");
     148             :         // just copy regular positions, transform normals to world space
     149           0 :         const CMatrix3D& transform = model->GetTransform();
     150           0 :         const CMatrix3D& invtransform = model->GetInvTransform();
     151           0 :         for (size_t j = 0; j < numVertices; ++j)
     152             :         {
     153           0 :             transform.Transform(vertices[j].m_Coords, Position[j]);
     154           0 :             invtransform.RotateTransposed(vertices[j].m_Norm, Normal[j]);
     155             :         }
     156           0 :     }
     157           0 : }
     158             : 
     159             : // static
     160           0 : void ModelRenderer::GenTangents(const CModelDefPtr& mdef, std::vector<float>& newVertices, bool gpuSkinning)
     161             : {
     162           0 :     MikkTSpace ms(mdef, newVertices, gpuSkinning);
     163           0 :     ms.Generate();
     164           0 : }
     165             : 
     166             : // static
     167           0 : void ModelRenderer::BuildUV(
     168             :     const CModelDefPtr& mdef, const VertexArrayIterator<float[2]>& UV, int UVset)
     169             : {
     170           0 :     const size_t numVertices = mdef->GetNumVertices();
     171             :     const size_t numberOfUVPerVertex = mdef->GetNumUVsPerVertex();
     172             : 
     173           0 :     for (size_t j = 0; j < numVertices; ++j)
     174             :     {
     175           0 :         const CVector2D& uv = mdef->GetUVCoordinates()[j * numberOfUVPerVertex + UVset];
     176           0 :         UV[j][0] = uv.X;
     177           0 :         UV[j][1] = 1.0 - uv.Y;
     178             :     }
     179           0 : }
     180             : 
     181             : // static
     182           0 : void ModelRenderer::BuildIndices(
     183             :     const CModelDefPtr& mdef, const VertexArrayIterator<std::uint16_t>& Indices)
     184             : {
     185           0 :     size_t idxidx = 0;
     186           0 :     SModelFace* faces = mdef->GetFaces();
     187             : 
     188           0 :     for (size_t j = 0; j < mdef->GetNumFaces(); ++j)
     189             :     {
     190           0 :         SModelFace& face = faces[j];
     191           0 :         Indices[idxidx++] = face.m_Verts[0];
     192           0 :         Indices[idxidx++] = face.m_Verts[1];
     193           0 :         Indices[idxidx++] = face.m_Verts[2];
     194             :     }
     195           0 : }
     196             : 
     197             : // Helper structs for ShaderModelRenderer::Render():
     198             : 
     199             : struct SMRSortByDistItem
     200             : {
     201             :     size_t techIdx;
     202             :     CModel* model;
     203             :     float dist;
     204             : };
     205             : 
     206             : struct SMRBatchModel
     207             : {
     208           0 :     bool operator()(CModel* a, CModel* b)
     209             :     {
     210           0 :         if (a->GetModelDef() < b->GetModelDef())
     211             :             return true;
     212           0 :         if (b->GetModelDef() < a->GetModelDef())
     213             :             return false;
     214             : 
     215           0 :         if (a->GetMaterial().GetDiffuseTexture() < b->GetMaterial().GetDiffuseTexture())
     216             :             return true;
     217           0 :         if (b->GetMaterial().GetDiffuseTexture() < a->GetMaterial().GetDiffuseTexture())
     218             :             return false;
     219             : 
     220           0 :         return a->GetMaterial().GetStaticUniforms() < b->GetMaterial().GetStaticUniforms();
     221             :     }
     222             : };
     223             : 
     224             : struct SMRCompareSortByDistItem
     225             : {
     226           0 :     bool operator()(const SMRSortByDistItem& a, const SMRSortByDistItem& b)
     227             :     {
     228             :         // Prefer items with greater distance, so we draw back-to-front
     229           0 :         return (a.dist > b.dist);
     230             : 
     231             :         // (Distances will almost always be distinct, so we don't need to bother
     232             :         // tie-breaking on modeldef/texture/etc)
     233             :     }
     234             : };
     235             : 
     236             : class SMRMaterialBucketKey
     237             : {
     238             : public:
     239           0 :     SMRMaterialBucketKey(CStrIntern effect, const CShaderDefines& defines)
     240           0 :         : effect(effect), defines(defines) { }
     241             : 
     242             :     SMRMaterialBucketKey(const SMRMaterialBucketKey& entity) = default;
     243             : 
     244             :     CStrIntern effect;
     245             :     CShaderDefines defines;
     246             : 
     247           0 :     bool operator==(const SMRMaterialBucketKey& b) const
     248             :     {
     249           0 :         return (effect == b.effect && defines == b.defines);
     250             :     }
     251             : 
     252             : private:
     253             :     SMRMaterialBucketKey& operator=(const SMRMaterialBucketKey&);
     254             : };
     255             : 
     256             : struct SMRMaterialBucketKeyHash
     257             : {
     258           0 :     size_t operator()(const SMRMaterialBucketKey& key) const
     259             :     {
     260           0 :         size_t hash = 0;
     261           0 :         hash_combine(hash, key.effect.GetHash());
     262           0 :         hash_combine(hash, key.defines.GetHash());
     263           0 :         return hash;
     264             :     }
     265             : };
     266             : 
     267           0 : struct SMRTechBucket
     268             : {
     269             :     CShaderTechniquePtr tech;
     270             :     std::span<CModel*> models;
     271             : 
     272             :     // Model list is stored as pointers, not as a std::vector,
     273             :     // so that sorting lists of this struct is fast
     274             : };
     275             : 
     276             : struct SMRCompareTechBucket
     277             : {
     278           0 :     bool operator()(const SMRTechBucket& a, const SMRTechBucket& b)
     279             :     {
     280           0 :         return a.tech < b.tech;
     281             :     }
     282             : };
     283             : 
     284           0 : void ModelRenderer::Render(
     285             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
     286             :     ModelVertexRenderer& modelVertexRenderer, RenderModifier& modifier, const CShaderDefines& context,
     287             :     int cullGroup, int flags, const ERenderMode renderMode, std::span<CModel*> submissions)
     288             : {
     289           0 :     if (submissions.empty())
     290           0 :         return;
     291             : 
     292           0 :     CMatrix3D worldToCam;
     293           0 :     g_Renderer.GetSceneRenderer().GetViewCamera().GetOrientation().GetInverse(worldToCam);
     294             : 
     295           0 :     const CMaterial::Pass materialPass{GetMaterialPassFromCullGroup(cullGroup, renderMode)};
     296             : 
     297             :     /*
     298             :      * Rendering approach:
     299             :      *
     300             :      * submissions contains the list of CModels to render.
     301             :      *
     302             :      * The data we need to render a model is:
     303             :      *  - CShaderTechnique
     304             :      *  - CTexture
     305             :      *  - CShaderUniforms
     306             :      *  - CModelDef (mesh data)
     307             :      *  - CModel (model instance data)
     308             :      *
     309             :      * For efficient rendering, we need to batch the draw calls to minimise state changes.
     310             :      * (Uniform and texture changes are assumed to be cheaper than binding new mesh data,
     311             :      * and shader changes are assumed to be most expensive.)
     312             :      * First, group all models that share a technique to render them together.
     313             :      * Within those groups, sub-group by CModelDef.
     314             :      * Within those sub-groups, sub-sub-group by CTexture.
     315             :      * Within those sub-sub-groups, sub-sub-sub-group by CShaderUniforms.
     316             :      *
     317             :      * Alpha-blended models have to be sorted by distance from camera,
     318             :      * then we can batch as long as the order is preserved.
     319             :      * Non-alpha-blended models can be arbitrarily reordered to maximise batching.
     320             :      *
     321             :      * For each model, the CShaderTechnique is derived from:
     322             :      *  - The current global 'context' defines
     323             :      *  - The CModel's material's defines
     324             :      *  - The CModel's material's shader effect name
     325             :      *
     326             :      * There are a smallish number of materials, and a smaller number of techniques.
     327             :      *
     328             :      * To minimise technique lookups, we first group models by material,
     329             :      * in 'materialBuckets' (a hash table).
     330             :      *
     331             :      * For each material bucket we then look up the appropriate shader technique.
     332             :      * If the technique requires sort-by-distance, the model is added to the
     333             :      * 'sortByDistItems' list with its computed distance.
     334             :      * Otherwise, the bucket's list of models is sorted by modeldef+texture+uniforms,
     335             :      * then the technique and model list is added to 'techBuckets'.
     336             :      *
     337             :      * 'techBuckets' is then sorted by technique, to improve batching when multiple
     338             :      * materials map onto the same technique.
     339             :      *
     340             :      * (Note that this isn't perfect batching: we don't sort across models in
     341             :      * multiple buckets that share a technique. In practice that shouldn't reduce
     342             :      * batching much (we rarely have one mesh used with multiple materials),
     343             :      * and it saves on copying and lets us sort smaller lists.)
     344             :      *
     345             :      * Extra tech buckets are added for the sorted-by-distance models without reordering.
     346             :      * Finally we render by looping over each tech bucket, then looping over the model
     347             :      * list in each, rebinding the GL state whenever it changes.
     348             :      */
     349             : 
     350           0 :     PS::Memory::ScopedLinearAllocator scopedLinearAllocator{g_Renderer.GetLinearAllocator()};
     351             : 
     352           0 :     using ModelListAllocator = PS::Memory::AllocatorAdapter<CModel*, PS::Memory::ScopedLinearAllocator>;
     353           0 :     using ModelList_t = std::vector<CModel*, ModelListAllocator>;
     354           0 :     using MaterialBuckets_t = std::unordered_map<
     355             :         SMRMaterialBucketKey,
     356             :         ModelList_t,
     357             :         SMRMaterialBucketKeyHash,
     358             :         std::equal_to<SMRMaterialBucketKey>,
     359             :         PS::Memory::AllocatorAdapter<
     360             :             std::pair<const SMRMaterialBucketKey, ModelList_t>,
     361             :             PS::Memory::ScopedLinearAllocator>>;
     362             : 
     363           0 :     MaterialBuckets_t materialBuckets((MaterialBuckets_t::allocator_type(scopedLinearAllocator)));
     364             : 
     365           0 :     {
     366           0 :         PROFILE3("bucketing by material");
     367             : 
     368           0 :         for (CModel* model : submissions)
     369             :         {
     370           0 :             const CMaterial& material{model->GetMaterial()};
     371           0 :             const auto& shader{material.GetShader(materialPass)};
     372           0 :             const SMRMaterialBucketKey key{shader.effect, shader.defines};
     373             : 
     374           0 :             MaterialBuckets_t::iterator it = materialBuckets.find(key);
     375           0 :             if (it == materialBuckets.end())
     376             :             {
     377           0 :                 std::pair<MaterialBuckets_t::iterator, bool> inserted = materialBuckets.insert(
     378           0 :                     std::make_pair(key, ModelList_t(ModelList_t::allocator_type(scopedLinearAllocator))));
     379           0 :                 inserted.first->second.reserve(32);
     380           0 :                 inserted.first->second.push_back(model);
     381             :             }
     382             :             else
     383             :             {
     384           0 :                 it->second.push_back(model);
     385             :             }
     386             :         }
     387           0 :     }
     388             : 
     389           0 :     using SortByDistItemsAllocator = PS::Memory::AllocatorAdapter<SMRSortByDistItem, PS::Memory::ScopedLinearAllocator>;
     390           0 :     std::vector<SMRSortByDistItem, SortByDistItemsAllocator> sortByDistItems((SortByDistItemsAllocator(scopedLinearAllocator)));
     391             : 
     392           0 :     using SortByTechItemsAllocator = PS::Memory::AllocatorAdapter<CShaderTechniquePtr, PS::Memory::ScopedLinearAllocator>;
     393           0 :     std::vector<CShaderTechniquePtr, SortByTechItemsAllocator> sortByDistTechs((SortByTechItemsAllocator(scopedLinearAllocator)));
     394             :         // indexed by sortByDistItems[i].techIdx
     395             :         // (which stores indexes instead of CShaderTechniquePtr directly
     396             :         // to avoid the shared_ptr copy cost when sorting; maybe it'd be better
     397             :         // if we just stored raw CShaderTechnique* and assumed the shader manager
     398             :         // will keep it alive long enough)
     399             : 
     400           0 :     using TechBucketsAllocator = PS::Memory::AllocatorAdapter<SMRTechBucket, PS::Memory::ScopedLinearAllocator>;
     401           0 :     std::vector<SMRTechBucket, TechBucketsAllocator> techBuckets((TechBucketsAllocator(scopedLinearAllocator)));
     402             : 
     403           0 :     {
     404           0 :         PROFILE3("processing material buckets");
     405           0 :         for (MaterialBuckets_t::iterator it = materialBuckets.begin(); it != materialBuckets.end(); ++it)
     406             :         {
     407           0 :             CShaderDefines defines = context;
     408           0 :             defines.SetMany(it->first.defines);
     409           0 :             CShaderTechniquePtr tech = g_Renderer.GetShaderManager().LoadEffect(it->first.effect, defines);
     410             : 
     411             :             // Skip invalid techniques (e.g. from data file errors)
     412           0 :             if (!tech)
     413           0 :                 continue;
     414             : 
     415           0 :             if (tech->GetSortByDistance())
     416             :             {
     417             :                 // Add the tech into a vector so we can index it
     418             :                 // (There might be duplicates in this list, but that doesn't really matter)
     419           0 :                 if (sortByDistTechs.empty() || sortByDistTechs.back() != tech)
     420           0 :                     sortByDistTechs.push_back(tech);
     421           0 :                 size_t techIdx = sortByDistTechs.size() - 1;
     422             : 
     423             :                 // Add each model into sortByDistItems
     424           0 :                 for (size_t i = 0; i < it->second.size(); ++i)
     425             :                 {
     426           0 :                     SMRSortByDistItem itemWithDist;
     427           0 :                     itemWithDist.techIdx = techIdx;
     428             : 
     429           0 :                     CModel* model = it->second[i];
     430           0 :                     itemWithDist.model = model;
     431             : 
     432           0 :                     CVector3D modelpos = model->GetTransform().GetTranslation();
     433           0 :                     itemWithDist.dist = worldToCam.Transform(modelpos).Z;
     434             : 
     435           0 :                     sortByDistItems.push_back(itemWithDist);
     436             :                 }
     437             :             }
     438             :             else
     439             :             {
     440             :                 // Sort model list by modeldef+texture, for batching
     441             :                 // TODO: This only sorts by base texture. While this is an OK approximation
     442             :                 // for most cases (as related samplers are usually used together), it would be better
     443             :                 // to take all the samplers into account when sorting here.
     444           0 :                 std::sort(it->second.begin(), it->second.end(), SMRBatchModel());
     445             : 
     446             :                 // Add a tech bucket pointing at this model list
     447           0 :                 SMRTechBucket techBucket{tech, it->second};
     448           0 :                 techBuckets.push_back(techBucket);
     449           0 :             }
     450           0 :         }
     451           0 :     }
     452             : 
     453           0 :     {
     454           0 :         PROFILE3("sorting tech buckets");
     455             :         // Sort by technique, for better batching
     456           0 :         std::sort(techBuckets.begin(), techBuckets.end(), SMRCompareTechBucket());
     457           0 :     }
     458             : 
     459             :     // List of models corresponding to sortByDistItems[i].model
     460             :     // (This exists primarily because techBuckets wants a CModel**;
     461             :     // we could avoid the cost of copying into this list by adding
     462             :     // a stride length into techBuckets and not requiring contiguous CModel*s)
     463           0 :     std::vector<CModel*, ModelListAllocator> sortByDistModels((ModelListAllocator(scopedLinearAllocator)));
     464             : 
     465           0 :     if (!sortByDistItems.empty())
     466             :     {
     467           0 :         {
     468           0 :             PROFILE3("sorting items by dist");
     469           0 :             std::sort(sortByDistItems.begin(), sortByDistItems.end(), SMRCompareSortByDistItem());
     470           0 :         }
     471             : 
     472           0 :         {
     473           0 :             PROFILE3("batching dist-sorted items");
     474             : 
     475           0 :             sortByDistModels.reserve(sortByDistItems.size());
     476             : 
     477             :             // Find runs of distance-sorted models that share a technique,
     478             :             // and create a new tech bucket for each run
     479             : 
     480           0 :             size_t start = 0; // start of current run
     481           0 :             size_t currentTechIdx = sortByDistItems[start].techIdx;
     482             : 
     483           0 :             for (size_t end = 0; end < sortByDistItems.size(); ++end)
     484             :             {
     485           0 :                 sortByDistModels.push_back(sortByDistItems[end].model);
     486             : 
     487           0 :                 size_t techIdx = sortByDistItems[end].techIdx;
     488           0 :                 if (techIdx != currentTechIdx)
     489             :                 {
     490             :                     // Start of a new run - push the old run into a new tech bucket
     491           0 :                     SMRTechBucket techBucket{sortByDistTechs[currentTechIdx],
     492           0 :                         {sortByDistModels.data() + start, end - start}};
     493           0 :                     techBuckets.push_back(techBucket);
     494           0 :                     start = end;
     495           0 :                     currentTechIdx = techIdx;
     496           0 :                 }
     497             :             }
     498             : 
     499             :             // Add the tech bucket for the final run
     500           0 :             SMRTechBucket techBucket{sortByDistTechs[currentTechIdx],
     501           0 :                 {sortByDistModels.data() + start, sortByDistItems.size() - start}};
     502           0 :             techBuckets.push_back(techBucket);
     503           0 :         }
     504             :     }
     505             : 
     506           0 :     const double time = g_Renderer.GetTimeManager().GetGlobalTime();
     507             : 
     508           0 :     {
     509           0 :         PROFILE3("rendering bucketed submissions");
     510             : 
     511           0 :         size_t idxTechStart = 0;
     512             : 
     513             :         // This vector keeps track of texture changes during rendering. It is kept outside the
     514             :         // loops to avoid excessive reallocations. The token allocation of 64 elements
     515             :         // should be plenty, though it is reallocated below (at a cost) if necessary.
     516           0 :         using TextureListAllocator = PS::Memory::AllocatorAdapter<CTexture*, PS::Memory::ScopedLinearAllocator>;
     517           0 :         std::vector<CTexture*, TextureListAllocator> currentTexs((TextureListAllocator(scopedLinearAllocator)));
     518           0 :         currentTexs.reserve(64);
     519             : 
     520             :         // texBindings holds the identifier bindings in the shader, which can no longer be defined
     521             :         // statically in the ShaderRenderModifier class. texBindingNames uses interned strings to
     522             :         // keep track of when bindings need to be reevaluated.
     523           0 :         using BindingListAllocator = PS::Memory::AllocatorAdapter<int32_t, PS::Memory::ScopedLinearAllocator>;
     524           0 :         std::vector<int32_t, BindingListAllocator> texBindings((BindingListAllocator(scopedLinearAllocator)));
     525           0 :         texBindings.reserve(64);
     526             : 
     527           0 :         using BindingNamesListAllocator = PS::Memory::AllocatorAdapter<CStrIntern, PS::Memory::ScopedLinearAllocator>;
     528           0 :         std::vector<CStrIntern, BindingNamesListAllocator> texBindingNames((BindingNamesListAllocator(scopedLinearAllocator)));
     529           0 :         texBindingNames.reserve(64);
     530             : 
     531           0 :         while (idxTechStart < techBuckets.size())
     532             :         {
     533           0 :             CShaderTechniquePtr currentTech = techBuckets[idxTechStart].tech;
     534             : 
     535             :             // Find runs [idxTechStart, idxTechEnd) in techBuckets of the same technique
     536           0 :             size_t idxTechEnd;
     537           0 :             for (idxTechEnd = idxTechStart + 1; idxTechEnd < techBuckets.size(); ++idxTechEnd)
     538             :             {
     539           0 :                 if (techBuckets[idxTechEnd].tech != currentTech)
     540             :                     break;
     541             :             }
     542             : 
     543             :             // For each of the technique's passes, render all the models in this run
     544           0 :             for (int pass = 0; pass < currentTech->GetNumPasses(); ++pass)
     545             :             {
     546           0 :                 deviceCommandContext->SetGraphicsPipelineState(
     547             :                     currentTech->GetGraphicsPipelineState(pass));
     548           0 :                 deviceCommandContext->BeginPass();
     549             : 
     550           0 :                 Renderer::Backend::IShaderProgram* shader = currentTech->GetShader(pass);
     551             : 
     552           0 :                 modifier.BeginPass(deviceCommandContext, shader);
     553             : 
     554             :                 // TODO: Use a more generic approach to handle bound queries.
     555           0 :                 bool boundTime = false;
     556           0 :                 bool boundWaterTexture = false;
     557           0 :                 bool boundSkyCube = false;
     558             : 
     559             :                 // When the shader technique changes, textures need to be
     560             :                 // rebound, so ensure there are no remnants from the last pass.
     561             :                 // (the vector size is set to 0, but memory is not freed)
     562           0 :                 currentTexs.clear();
     563           0 :                 texBindings.clear();
     564           0 :                 texBindingNames.clear();
     565             : 
     566           0 :                 CModelDef* currentModeldef = NULL;
     567           0 :                 CShaderUniforms currentStaticUniforms;
     568             : 
     569           0 :                 for (size_t idx = idxTechStart; idx < idxTechEnd; ++idx)
     570             :                 {
     571           0 :                     for (CModel* model : techBuckets[idx].models)
     572             :                     {
     573           0 :                         if (flags && !(model->GetFlags() & flags))
     574           0 :                             continue;
     575             : 
     576           0 :                         const CMaterial::SamplersVector& samplers = model->GetMaterial().GetSamplers();
     577           0 :                         size_t samplersNum = samplers.size();
     578             : 
     579             :                         // make sure the vectors are the right virtual sizes, and also
     580             :                         // reallocate if there are more samplers than expected.
     581           0 :                         if (currentTexs.size() != samplersNum)
     582             :                         {
     583           0 :                             currentTexs.resize(samplersNum, NULL);
     584           0 :                             texBindings.resize(samplersNum, -1);
     585           0 :                             texBindingNames.resize(samplersNum, CStrIntern());
     586             : 
     587             :                             // ensure they are definitely empty
     588           0 :                             std::fill(texBindings.begin(), texBindings.end(), -1);
     589           0 :                             std::fill(currentTexs.begin(), currentTexs.end(), nullptr);
     590           0 :                             std::fill(texBindingNames.begin(), texBindingNames.end(), CStrIntern());
     591             :                         }
     592             : 
     593             :                         // bind the samplers to the shader
     594           0 :                         for (size_t s = 0; s < samplersNum; ++s)
     595             :                         {
     596           0 :                             const CMaterial::TextureSampler& samp = samplers[s];
     597             : 
     598             :                             // check that the handles are current
     599             :                             // and reevaluate them if necessary
     600           0 :                             if (texBindingNames[s] != samp.Name || texBindings[s] < 0)
     601             :                             {
     602           0 :                                 texBindings[s] = shader->GetBindingSlot(samp.Name);
     603           0 :                                 texBindingNames[s] = samp.Name;
     604             :                             }
     605             : 
     606             :                             // same with the actual sampler bindings
     607           0 :                             CTexture* newTex = samp.Sampler.get();
     608           0 :                             if (texBindings[s] >= 0 && newTex != currentTexs[s])
     609             :                             {
     610           0 :                                 newTex->UploadBackendTextureIfNeeded(deviceCommandContext);
     611           0 :                                 deviceCommandContext->SetTexture(
     612           0 :                                     texBindings[s], newTex->GetBackendTexture());
     613           0 :                                 currentTexs[s] = newTex;
     614             :                             }
     615             :                         }
     616             : 
     617             :                         // Bind modeldef when it changes
     618           0 :                         CModelDef* newModeldef = model->GetModelDef().get();
     619           0 :                         if (newModeldef != currentModeldef)
     620             :                         {
     621           0 :                             currentModeldef = newModeldef;
     622           0 :                             modelVertexRenderer.PrepareModelDef(deviceCommandContext, *currentModeldef);
     623             :                         }
     624             : 
     625             :                         // Bind all uniforms when any change
     626           0 :                         CShaderUniforms newStaticUniforms = model->GetMaterial().GetStaticUniforms();
     627           0 :                         if (newStaticUniforms != currentStaticUniforms)
     628             :                         {
     629           0 :                             currentStaticUniforms = newStaticUniforms;
     630           0 :                             currentStaticUniforms.BindUniforms(deviceCommandContext, shader);
     631             :                         }
     632             : 
     633             :                         const CShaderRenderQueries& renderQueries = model->GetMaterial().GetRenderQueries();
     634             : 
     635           0 :                         for (size_t q = 0; q < renderQueries.GetSize(); ++q)
     636             :                         {
     637           0 :                             CShaderRenderQueries::RenderQuery rq = renderQueries.GetItem(q);
     638           0 :                             if (rq.first == RQUERY_TIME)
     639             :                             {
     640           0 :                                 if (!boundTime)
     641             :                                 {
     642           0 :                                     deviceCommandContext->SetUniform(
     643           0 :                                         shader->GetBindingSlot(rq.second), time);
     644             :                                     boundTime = true;
     645             :                                 }
     646             :                             }
     647           0 :                             else if (rq.first == RQUERY_WATER_TEX)
     648             :                             {
     649           0 :                                 if (!boundWaterTexture)
     650             :                                 {
     651           0 :                                     const double period = 1.6;
     652           0 :                                     const WaterManager& waterManager = g_Renderer.GetSceneRenderer().GetWaterManager();
     653           0 :                                     if (waterManager.m_RenderWater && waterManager.WillRenderFancyWater())
     654             :                                     {
     655           0 :                                         const CTexturePtr& waterTexture = waterManager.m_NormalMap[waterManager.GetCurrentTextureIndex(period)];
     656           0 :                                         waterTexture->UploadBackendTextureIfNeeded(deviceCommandContext);
     657           0 :                                         deviceCommandContext->SetTexture(
     658           0 :                                             shader->GetBindingSlot(str_waterTex),
     659             :                                             waterTexture->GetBackendTexture());
     660             :                                     }
     661             :                                     else
     662             :                                     {
     663           0 :                                         deviceCommandContext->SetTexture(
     664           0 :                                             shader->GetBindingSlot(str_waterTex),
     665           0 :                                             g_Renderer.GetTextureManager().GetErrorTexture()->GetBackendTexture());
     666             :                                     }
     667           0 :                                     boundWaterTexture = true;
     668             :                                 }
     669             :                             }
     670           0 :                             else if (rq.first == RQUERY_SKY_CUBE)
     671             :                             {
     672           0 :                                 if (!boundSkyCube)
     673             :                                 {
     674           0 :                                     deviceCommandContext->SetTexture(
     675           0 :                                         shader->GetBindingSlot(str_skyCube),
     676           0 :                                         g_Renderer.GetSceneRenderer().GetSkyManager().GetSkyCube());
     677             :                                     boundSkyCube = true;
     678             :                                 }
     679             :                             }
     680             :                         }
     681             : 
     682           0 :                         modifier.PrepareModel(deviceCommandContext, model);
     683             : 
     684           0 :                         CModelRData* rdata = static_cast<CModelRData*>(model->GetRenderData());
     685           0 :                         ENSURE(rdata->GetKey() == &modelVertexRenderer);
     686             : 
     687           0 :                         modelVertexRenderer.RenderModel(deviceCommandContext, shader, model, rdata);
     688             :                     }
     689             :                 }
     690             : 
     691           0 :                 deviceCommandContext->EndPass();
     692             :             }
     693             : 
     694           0 :             idxTechStart = idxTechEnd;
     695           0 :         }
     696           0 :     }
     697           0 : }

Generated by: LCOV version 1.16