Coverage Report

Created: 2026-05-23 06:04

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
7.19k
RemoveRedundantMatsProcess::RemoveRedundantMatsProcess() : mConfigFixedMaterials() {}
58
59
// ------------------------------------------------------------------------------------------------
60
// Returns whether the processing step is present in the given flag field.
61
1.64k
bool RemoveRedundantMatsProcess::IsActive( unsigned int pFlags) const {
62
1.64k
    return (pFlags & aiProcess_RemoveRedundantMaterials) != 0;
63
1.64k
}
64
65
// ------------------------------------------------------------------------------------------------
66
// Setup import properties
67
1.64k
void RemoveRedundantMatsProcess::SetupProperties(const Importer* pImp) {
68
    // Get value of AI_CONFIG_PP_RRM_EXCLUDE_LIST
69
1.64k
    mConfigFixedMaterials = pImp->GetPropertyString(AI_CONFIG_PP_RRM_EXCLUDE_LIST,"");
70
1.64k
}
71
72
// ------------------------------------------------------------------------------------------------
73
// Executes the post processing step on the given imported data.
74
1.64k
void RemoveRedundantMatsProcess::Execute( aiScene* pScene) {
75
1.64k
    ASSIMP_LOG_DEBUG("RemoveRedundantMatsProcess begin");
76
77
1.64k
    unsigned int redundantRemoved = 0, unreferencedRemoved = 0;
78
1.64k
    if (pScene->mNumMaterials == 0) {
79
0
        return;
80
0
    }
81
82
    // Find out which materials are referenced by meshes
83
1.64k
    std::vector<bool> abReferenced(pScene->mNumMaterials,false);
84
3.18k
    for (unsigned int i = 0;i < pScene->mNumMeshes;++i) {
85
1.54k
        abReferenced[pScene->mMeshes[i]->mMaterialIndex] = true;
86
1.54k
    }
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
1.64k
    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
1.64k
    unsigned int *aiMappingTable = new unsigned int[pScene->mNumMaterials];
119
4.40k
    for ( unsigned int i=0; i<pScene->mNumMaterials; i++ ) {
120
2.75k
        aiMappingTable[ i ] = 0;
121
2.75k
    }
122
1.64k
    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
1.64k
    uint32_t *aiHashes = new uint32_t[ pScene->mNumMaterials ];
129
4.40k
    for (unsigned int i = 0; i < pScene->mNumMaterials;++i) {
130
        // No mesh is referencing this material, remove it.
131
2.75k
        if (!abReferenced[i]) {
132
1.25k
            ++unreferencedRemoved;
133
1.25k
            delete pScene->mMaterials[i];
134
1.25k
            pScene->mMaterials[i] = nullptr;
135
1.25k
            continue;
136
1.25k
        }
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
1.50k
        uint32_t me = aiHashes[i] = ComputeMaterialHash(pScene->mMaterials[i]);
141
1.85k
        for (unsigned int a = 0; a < i;++a) {
142
384
            if (abReferenced[a] && me == aiHashes[a]) {
143
35
                ++redundantRemoved;
144
35
                me = 0;
145
35
                aiMappingTable[i] = aiMappingTable[a];
146
35
                delete pScene->mMaterials[i];
147
35
                pScene->mMaterials[i] = nullptr;
148
35
                break;
149
35
            }
150
384
        }
151
        // This is a new material that is referenced, add to the map.
152
1.50k
        if (me) {
153
1.46k
            aiMappingTable[i] = iNewNum++;
154
1.46k
        }
155
1.50k
    }
156
    // If the new material count differs from the original,
157
    // we need to rebuild the material list and remap mesh material indexes.
158
1.64k
    if (iNewNum < 1) {
159
345
        delete [] aiMappingTable;
160
345
        delete [] aiHashes;
161
345
        pScene->mNumMaterials = 0;
162
345
        return;
163
345
    }
164
1.29k
    if (iNewNum != pScene->mNumMaterials) {
165
937
        ai_assert(iNewNum > 0);
166
937
        aiMaterial** ppcMaterials = new aiMaterial*[iNewNum];
167
937
        ::memset(ppcMaterials,0,sizeof(void*)*iNewNum);
168
2.92k
        for (unsigned int p = 0; p < pScene->mNumMaterials;++p) {
169
            // if the material is not referenced ... remove it
170
1.98k
            if (!abReferenced[p]) {
171
910
                continue;
172
910
            }
173
174
            // generate new names for modified materials that had no names
175
1.07k
            const unsigned int idx = aiMappingTable[p];
176
1.07k
            if (ppcMaterials[idx]) {
177
35
                aiString sz;
178
35
                if( ppcMaterials[idx]->Get(AI_MATKEY_NAME, sz) != AI_SUCCESS ) {
179
22
                    sz.length = ::ai_snprintf(sz.data, AI_MAXLEN,"JoinedMaterial_#%u",p);
180
22
                    ((aiMaterial*)ppcMaterials[idx])->AddProperty(&sz,AI_MATKEY_NAME);
181
22
                }
182
1.03k
            } else {
183
1.03k
                ppcMaterials[idx] = pScene->mMaterials[p];
184
1.03k
            }
185
1.07k
        }
186
        // update all material indices
187
2.03k
        for (unsigned int p = 0; p < pScene->mNumMeshes;++p) {
188
1.10k
            aiMesh* mesh = pScene->mMeshes[p];
189
1.10k
            ai_assert(nullptr != mesh);
190
1.10k
            mesh->mMaterialIndex = aiMappingTable[mesh->mMaterialIndex];
191
1.10k
        }
192
        // delete the old material list
193
937
        delete[] pScene->mMaterials;
194
937
        pScene->mMaterials = ppcMaterials;
195
937
        pScene->mNumMaterials = iNewNum;
196
937
    }
197
    // delete temporary storage
198
1.29k
    delete[] aiHashes;
199
1.29k
    delete[] aiMappingTable;
200
201
1.29k
    if (redundantRemoved == 0 && unreferencedRemoved == 0) {
202
360
        ASSIMP_LOG_DEBUG("RemoveRedundantMatsProcess finished ");
203
937
    } else {
204
        ASSIMP_LOG_INFO("RemoveRedundantMatsProcess finished. Removed ", redundantRemoved, " redundant and ",
205
937
            unreferencedRemoved, " unused materials.");
206
937
    }
207
1.29k
}