Coverage Report

Created: 2026-01-25 07:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/assimp/code/PostProcessing/RemoveRedundantMaterials.cpp
Line
Count
Source
1
/*
2
---------------------------------------------------------------------------
3
Open Asset Import Library (assimp)
4
---------------------------------------------------------------------------
5
6
Copyright (c) 2006-2026, assimp team
7
8
All rights reserved.
9
10
Redistribution and use of this software in source and binary forms,
11
with or without modification, are permitted provided that the following
12
conditions are met:
13
14
* Redistributions of source code must retain the above
15
  copyright notice, this list of conditions and the
16
  following disclaimer.
17
18
* Redistributions in binary form must reproduce the above
19
  copyright notice, this list of conditions and the
20
  following disclaimer in the documentation and/or other
21
  materials provided with the distribution.
22
23
* Neither the name of the assimp team, nor the names of its
24
  contributors may be used to endorse or promote products
25
  derived from this software without specific prior
26
  written permission of the assimp team.
27
28
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39
---------------------------------------------------------------------------
40
*/
41
/** @file RemoveRedundantMaterials.cpp
42
 *  @brief Implementation of the "RemoveRedundantMaterials" post processing step
43
*/
44
45
// internal headers
46
#include "RemoveRedundantMaterials.h"
47
#include <assimp/ParsingUtils.h>
48
#include "ProcessHelper.h"
49
#include "Material/MaterialSystem.h"
50
#include <assimp/Exceptional.h>
51
#include <stdio.h>
52
53
using namespace Assimp;
54
55
// ------------------------------------------------------------------------------------------------
56
// Constructor to be privately used by Importer
57
26.3k
RemoveRedundantMatsProcess::RemoveRedundantMatsProcess() : mConfigFixedMaterials() {}
58
59
// ------------------------------------------------------------------------------------------------
60
// Returns whether the processing step is present in the given flag field.
61
8.63k
bool RemoveRedundantMatsProcess::IsActive( unsigned int pFlags) const {
62
8.63k
    return (pFlags & aiProcess_RemoveRedundantMaterials) != 0;
63
8.63k
}
64
65
// ------------------------------------------------------------------------------------------------
66
// Setup import properties
67
8.52k
void RemoveRedundantMatsProcess::SetupProperties(const Importer* pImp) {
68
    // Get value of AI_CONFIG_PP_RRM_EXCLUDE_LIST
69
8.52k
    mConfigFixedMaterials = pImp->GetPropertyString(AI_CONFIG_PP_RRM_EXCLUDE_LIST,"");
70
8.52k
}
71
72
// ------------------------------------------------------------------------------------------------
73
// Executes the post processing step on the given imported data.
74
8.52k
void RemoveRedundantMatsProcess::Execute( aiScene* pScene) {
75
8.52k
    ASSIMP_LOG_DEBUG("RemoveRedundantMatsProcess begin");
76
77
8.52k
    unsigned int redundantRemoved = 0, unreferencedRemoved = 0;
78
8.52k
    if (pScene->mNumMaterials == 0) {
79
1.39k
        return;
80
1.39k
    }
81
82
    // Find out which materials are referenced by meshes
83
7.13k
    std::vector<bool> abReferenced(pScene->mNumMaterials,false);
84
59.3k
    for (unsigned int i = 0;i < pScene->mNumMeshes;++i) {
85
52.2k
        abReferenced[pScene->mMeshes[i]->mMaterialIndex] = true;
86
52.2k
    }
87
88
    // If a list of materials to be excluded was given, match the list with
89
    // our imported materials and 'salt' all positive matches to ensure that
90
    // we get unique hashes later.
91
7.13k
    if (mConfigFixedMaterials.length()) {
92
0
        std::list<std::string> strings;
93
0
        ConvertListToStrings(mConfigFixedMaterials,strings);
94
95
0
        for (unsigned int i = 0; i < pScene->mNumMaterials;++i) {
96
0
            aiMaterial* mat = pScene->mMaterials[i];
97
0
            ai_assert(mat != nullptr);
98
0
            aiString name;
99
0
            mat->Get(AI_MATKEY_NAME,name);
100
101
0
            if (name.length != 0) {
102
0
                std::list<std::string>::const_iterator it = std::find(strings.begin(), strings.end(), name.data);
103
0
                if (it != strings.end()) {
104
                    // Our brilliant 'salt': A single material property with ~ as first
105
                    // character to mark it as internal and temporary.
106
0
                    const int dummy = 1;
107
0
                    ((aiMaterial*)mat)->AddProperty(&dummy,1,"~RRM.UniqueMaterial",0,0);
108
109
                    // Keep this material even if no mesh references it
110
0
                    abReferenced[i] = true;
111
0
                    ASSIMP_LOG_VERBOSE_DEBUG( "Found positive match in exclusion list: \'", name.data, "\'");
112
0
                }
113
0
            }
114
0
        }
115
0
    }
116
117
    // TODO: re-implement this algorithm to work in-place
118
7.13k
    unsigned int *aiMappingTable = new unsigned int[pScene->mNumMaterials];
119
23.8k
    for ( unsigned int i=0; i<pScene->mNumMaterials; i++ ) {
120
16.7k
        aiMappingTable[ i ] = 0;
121
16.7k
    }
122
7.13k
    unsigned int iNewNum = 0;
123
124
    // Iterate through all materials and calculate a hash for them
125
    // store all hashes in a list and so a quick search whether
126
    // we do already have a specific hash. This allows us to
127
    // determine which materials are identical.
128
7.13k
    uint32_t *aiHashes = new uint32_t[ pScene->mNumMaterials ];
129
23.8k
    for (unsigned int i = 0; i < pScene->mNumMaterials;++i) {
130
        // No mesh is referencing this material, remove it.
131
16.7k
        if (!abReferenced[i]) {
132
5.67k
            ++unreferencedRemoved;
133
5.67k
            delete pScene->mMaterials[i];
134
5.67k
            pScene->mMaterials[i] = nullptr;
135
5.67k
            continue;
136
5.67k
        }
137
138
        // Check all previously mapped materials for a matching hash.
139
        // On a match we can delete this material and just make it ref to the same index.
140
11.0k
        uint32_t me = aiHashes[i] = ComputeMaterialHash(pScene->mMaterials[i]);
141
23.4k
        for (unsigned int a = 0; a < i;++a) {
142
14.6k
            if (abReferenced[a] && me == aiHashes[a]) {
143
2.24k
                ++redundantRemoved;
144
2.24k
                me = 0;
145
2.24k
                aiMappingTable[i] = aiMappingTable[a];
146
2.24k
                delete pScene->mMaterials[i];
147
2.24k
                pScene->mMaterials[i] = nullptr;
148
2.24k
                break;
149
2.24k
            }
150
14.6k
        }
151
        // This is a new material that is referenced, add to the map.
152
11.0k
        if (me) {
153
8.81k
            aiMappingTable[i] = iNewNum++;
154
8.81k
        }
155
11.0k
    }
156
    // If the new material count differs from the original,
157
    // we need to rebuild the material list and remap mesh material indexes.
158
7.13k
    if (iNewNum < 1) {
159
95
        delete [] aiMappingTable;
160
95
        delete [] aiHashes;
161
95
        pScene->mNumMaterials = 0;
162
95
        return;
163
95
    }
164
7.03k
    if (iNewNum != pScene->mNumMaterials) {
165
3.24k
        ai_assert(iNewNum > 0);
166
3.24k
        aiMaterial** ppcMaterials = new aiMaterial*[iNewNum];
167
3.24k
        ::memset(ppcMaterials,0,sizeof(void*)*iNewNum);
168
14.8k
        for (unsigned int p = 0; p < pScene->mNumMaterials;++p) {
169
            // if the material is not referenced ... remove it
170
11.5k
            if (!abReferenced[p]) {
171
5.58k
                continue;
172
5.58k
            }
173
174
            // generate new names for modified materials that had no names
175
6.00k
            const unsigned int idx = aiMappingTable[p];
176
6.00k
            if (ppcMaterials[idx]) {
177
2.24k
                aiString sz;
178
2.24k
                if( ppcMaterials[idx]->Get(AI_MATKEY_NAME, sz) != AI_SUCCESS ) {
179
2
                    sz.length = ::ai_snprintf(sz.data, AI_MAXLEN,"JoinedMaterial_#%u",p);
180
2
                    ((aiMaterial*)ppcMaterials[idx])->AddProperty(&sz,AI_MATKEY_NAME);
181
2
                }
182
3.75k
            } else {
183
3.75k
                ppcMaterials[idx] = pScene->mMaterials[p];
184
3.75k
            }
185
6.00k
        }
186
        // update all material indices
187
29.9k
        for (unsigned int p = 0; p < pScene->mNumMeshes;++p) {
188
26.6k
            aiMesh* mesh = pScene->mMeshes[p];
189
26.6k
            ai_assert(nullptr != mesh);
190
26.6k
            mesh->mMaterialIndex = aiMappingTable[mesh->mMaterialIndex];
191
26.6k
        }
192
        // delete the old material list
193
3.24k
        delete[] pScene->mMaterials;
194
3.24k
        pScene->mMaterials = ppcMaterials;
195
3.24k
        pScene->mNumMaterials = iNewNum;
196
3.24k
    }
197
    // delete temporary storage
198
7.03k
    delete[] aiHashes;
199
7.03k
    delete[] aiMappingTable;
200
201
7.03k
    if (redundantRemoved == 0 && unreferencedRemoved == 0) {
202
3.79k
        ASSIMP_LOG_DEBUG("RemoveRedundantMatsProcess finished ");
203
3.79k
    } else {
204
        ASSIMP_LOG_INFO("RemoveRedundantMatsProcess finished. Removed ", redundantRemoved, " redundant and ",
205
3.24k
            unreferencedRemoved, " unused materials.");
206
3.24k
    }
207
7.03k
}