whiteoutlib 0.2.0

Read and write Blizzard game assets from Rust: models (MDX, M2, M3), textures (BLP, DDS, PNG, JPEG, BMP, TGA, TIFF, GIF) and archives (CASC, MPQ).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2026 Fernando Sahmkow

#include <whiteout/models/wem/geometry/repair.h>

#include <algorithm>
#include <cmath>
#include <limits>
#include <unordered_map>
#include <unordered_set>

namespace whiteout {
namespace models {
namespace wem {
namespace geom {

namespace {

// The edge and face-key tables below are hash maps, which the determinism rule
// permits for one reason only: they are *looked up*, never iterated. Every
// ordered decision the repair makes — which face is processed first, which
// vertex is duplicated next — comes from the input's own order.

constexpr u64 pairKey(u32 a, u32 b) {
    return (static_cast<u64>(a) << 32) | static_cast<u64>(b);
}

constexpr u64 undirectedKey(u32 a, u32 b) {
    return a < b ? pairKey(a, b) : pairKey(b, a);
}

/// The sorted corner set of a face, as one hashable key. Faces here have at most
/// a handful of corners, so a sorted vector hashed by FNV is cheaper than any
/// clever alternative and — unlike a sum or an xor — does not collide on
/// permutations of different sets.
u64 faceKey(std::span<const u32> corners) {
    u32 sorted[16];
    const std::size_t count = corners.size() < 16 ? corners.size() : 16;
    for (std::size_t i = 0; i < count; ++i) {
        sorted[i] = corners[i];
    }
    std::sort(sorted, sorted + count);
    u64 hash = 1469598103934665603ull;
    for (std::size_t i = 0; i < count; ++i) {
        hash ^= sorted[i];
        hash *= 1099511628211ull;
    }
    // Mix the valence in so a 3-corner and a 4-corner face cannot share a key
    // when the extra corner happens to hash away.
    hash ^= static_cast<u64>(corners.size()) << 56;
    return hash;
}

bool hasRepeatedCorner(std::span<const u32> corners) {
    for (std::size_t i = 0; i < corners.size(); ++i) {
        for (std::size_t j = i + 1; j < corners.size(); ++j) {
            if (corners[i] == corners[j]) {
                return true;
            }
        }
    }
    return false;
}

/// Whether the face has no surface to shade: twice its area (the Newell
/// normal's length) within the float noise of its own corners.
///
/// A corner is only stored to `|p| * FLT_EPSILON`, so a face whose longest edge
/// is `L` cannot be told from a line once its area is below about
/// `L * |p| * FLT_EPSILON`. Small is not degenerate: the bound follows the
/// face's own edge and coordinates, never the model's unit. The old one compared
/// the area squared against the coordinates squared and dropped every face under
/// ~1.4e-6 units² three units from the origin — the ear screws of
/// SM_ArmorySpectreCrate's helmets, 271 faces of one region.
bool isZeroArea(std::span<const u32> corners, std::span<const Vector3f> positions) {
    if (positions.empty() || corners.empty()) {
        return false;
    }
    for (u32 corner : corners) {
        if (corner >= positions.size()) {
            return false;
        }
    }
    // Edges from the first corner, in double: the sum of their cross products is
    // the same normal, without cancelling against the corners' distance from
    // the origin.
    const Vector3f& origin = positions[corners[0]];
    f64 nx = 0.0;
    f64 ny = 0.0;
    f64 nz = 0.0;
    f64 longestSquared = 0.0;
    f64 reach = 0.0;
    for (std::size_t i = 0; i < corners.size(); ++i) {
        const Vector3f& a = positions[corners[i]];
        const Vector3f& b = positions[corners[(i + 1) % corners.size()]];
        const f64 ax = static_cast<f64>(a.x) - origin.x;
        const f64 ay = static_cast<f64>(a.y) - origin.y;
        const f64 az = static_cast<f64>(a.z) - origin.z;
        const f64 bx = static_cast<f64>(b.x) - origin.x;
        const f64 by = static_cast<f64>(b.y) - origin.y;
        const f64 bz = static_cast<f64>(b.z) - origin.z;
        nx += ay * bz - az * by;
        ny += az * bx - ax * bz;
        nz += ax * by - ay * bx;
        longestSquared = std::max(longestSquared, (bx - ax) * (bx - ax) + (by - ay) * (by - ay) +
                                                      (bz - az) * (bz - az));
        reach = std::max({reach, std::abs(static_cast<f64>(a.x)), std::abs(static_cast<f64>(a.y)),
                          std::abs(static_cast<f64>(a.z))});
    }
    const f64 twiceArea = std::sqrt(nx * nx + ny * ny + nz * nz);
    const f64 longest = std::sqrt(longestSquared);
    // A few ULPs of slack: a corner that was itself computed in f32 (a midpoint,
    // a weld) carries its own rounding on top of the storage.
    const f64 noise = longest * std::max(reach, longest) * 4.0 *
                      static_cast<f64>(std::numeric_limits<f32>::epsilon());
    return twiceArea <= noise;
}

/// Union-find over global corner indices, for the bowtie pass.
class DisjointSet {
public:
    explicit DisjointSet(std::size_t count) : parent_(count) {
        for (std::size_t i = 0; i < count; ++i) {
            parent_[i] = static_cast<u32>(i);
        }
    }
    u32 find(u32 x) {
        while (parent_[x] != x) {
            parent_[x] = parent_[parent_[x]];
            x = parent_[x];
        }
        return x;
    }
    void unite(u32 a, u32 b) {
        a = find(a);
        b = find(b);
        if (a != b) {
            // Always attach the higher root to the lower one, so the surviving
            // root of a group is its smallest member and the choice of "which
            // fan keeps the original vertex" is deterministic.
            if (a < b) {
                parent_[b] = a;
            } else {
                parent_[a] = b;
            }
        }
    }

private:
    std::vector<u32> parent_;
};

} // namespace

// ============================================================================

RepairResult Repair(const FaceSet& faces, std::span<const u32> sections,
                    std::span<const Vector3f> positions) {
    RepairResult result;
    result.faces.vertexCount = faces.vertexCount;

    u32 nextVertex = faces.vertexCount;

    // --- pass 1: per-face edge conflicts ------------------------------------
    //
    // Faces are visited in input order and each is made compatible with what is
    // already there, so the result never depends on a global view.

    std::unordered_map<u64, u32> directedEdgeOwner; // (from, to) -> output face
    std::unordered_map<u64, u32> undirectedEdgeUses;
    std::unordered_set<u64> faceKeysSeen;

    std::vector<std::vector<u32>> outFaces;
    outFaces.reserve(faces.faceCount());
    result.sections.reserve(faces.faceCount());

    std::vector<u32> corners;
    std::vector<u8> marked;

    std::size_t cursor = 0;
    for (std::size_t f = 0; f < faces.faceCount(); ++f) {
        const u32 valence = faces.faceValence[f];
        const u32 section = f < sections.size() ? sections[f] : 0;
        corners.assign(faces.cornerVertex.begin() + static_cast<std::ptrdiff_t>(cursor),
                       faces.cornerVertex.begin() + static_cast<std::ptrdiff_t>(cursor + valence));
        cursor += valence;

        // Degenerate: a repeated corner, too few corners, or no area at all.
        if (valence < 3 || hasRepeatedCorner(corners) || isZeroArea(corners, positions)) {
            FaceRecord dropped;
            dropped.corners = corners;
            dropped.section = section;
            dropped.index = static_cast<u32>(f);
            result.log.droppedFaces.push_back(std::move(dropped));
            result.changed = true;
            continue;
        }

        marked.assign(valence, 0);

        // A face on a vertex set another face already used is the cheap
        // two-sided trick; every corner is duplicated so the two surfaces come
        // apart cleanly.
        if (faceKeysSeen.count(faceKey(corners)) != 0) {
            for (u32 i = 0; i < valence; ++i) {
                marked[i] = 1;
            }
        }

        for (u32 i = 0; i < valence; ++i) {
            const u32 a = corners[i];
            const u32 b = corners[(i + 1) % valence];
            const bool sameDirection = directedEdgeOwner.count(pairKey(a, b)) != 0;
            const auto uses = undirectedEdgeUses.find(undirectedKey(a, b));
            const bool full = uses != undirectedEdgeUses.end() && uses->second >= 2;
            if (sameDirection || full) {
                // Both endpoints, per §5.3: a third fan gets its own copy of the
                // edge, and a face wound against its neighbour is split rather
                // than flipped.
                marked[i] = 1;
                marked[(i + 1) % valence] = 1;
            }
        }

        for (u32 i = 0; i < valence; ++i) {
            if (marked[i] == 0) {
                continue;
            }
            const u32 original = corners[i];
            const u32 created = nextVertex++;
            result.log.splits.push_back(VertexSplit{original, created});
            corners[i] = created;
            result.changed = true;
        }

        const u32 outIndex = static_cast<u32>(outFaces.size());
        for (u32 i = 0; i < valence; ++i) {
            const u32 a = corners[i];
            const u32 b = corners[(i + 1) % valence];
            directedEdgeOwner[pairKey(a, b)] = outIndex;
            ++undirectedEdgeUses[undirectedKey(a, b)];
        }
        faceKeysSeen.insert(faceKey(corners));
        outFaces.push_back(corners);
        result.sections.push_back(section);
    }

    // --- pass 2: bowtie vertices --------------------------------------------
    //
    // Every edge now carries at most two faces with opposite orientation, but a
    // vertex may still be the meeting point of several fans. Two corners at a
    // vertex belong to the same fan exactly when a two-faced edge joins them, so
    // the fans are the connected components of that relation.

    std::vector<u32> cornerBase(outFaces.size(), 0);
    u32 cornerTotal = 0;
    for (std::size_t f = 0; f < outFaces.size(); ++f) {
        cornerBase[f] = cornerTotal;
        cornerTotal += static_cast<u32>(outFaces[f].size());
    }

    if (cornerTotal != 0) {
        // corner -> (face, position), so a rewrite is a lookup and not a scan.
        std::vector<u32> cornerFace(cornerTotal, 0);
        for (std::size_t f = 0; f < outFaces.size(); ++f) {
            for (u32 i = 0; i < outFaces[f].size(); ++i) {
                cornerFace[cornerBase[f] + i] = static_cast<u32>(f);
            }
        }

        DisjointSet fans(cornerTotal);

        // Keyed by the *directed* pair (thisEndpoint, otherEndpoint), so the two
        // faces of an edge agree on which endpoint they are talking about even
        // though they traverse it in opposite directions. The second claim on a
        // slot unites its corner with the first: the two are the same fan.
        std::unordered_map<u64, u32> edgeCornerAt;
        const auto claim = [&](u32 vertex, u32 other, u32 corner) {
            const u64 slot = pairKey(vertex, other);
            const auto found = edgeCornerAt.find(slot);
            if (found == edgeCornerAt.end()) {
                edgeCornerAt.emplace(slot, corner);
            } else {
                fans.unite(found->second, corner);
            }
        };

        for (std::size_t f = 0; f < outFaces.size(); ++f) {
            const auto& face = outFaces[f];
            const u32 valence = static_cast<u32>(face.size());
            for (u32 i = 0; i < valence; ++i) {
                const u32 next = (i + 1) % valence;
                claim(face[i], face[next], cornerBase[f] + i);
                claim(face[next], face[i], cornerBase[f] + next);
            }
        }

        // Corners grouped per vertex, in ascending corner order — which is what
        // makes "the first fan keeps the original vertex" a deterministic rule.
        std::vector<std::vector<u32>> cornersOfVertex(nextVertex);
        for (std::size_t f = 0; f < outFaces.size(); ++f) {
            const auto& face = outFaces[f];
            for (u32 i = 0; i < face.size(); ++i) {
                cornersOfVertex[face[i]].push_back(cornerBase[f] + i);
            }
        }

        const u32 vertexLimit = nextVertex;
        for (u32 v = 0; v < vertexLimit; ++v) {
            const auto& owned = cornersOfVertex[v];
            if (owned.size() < 2) {
                continue;
            }
            const u32 firstRoot = fans.find(owned[0]);
            // Roots seen after the first, each mapped to the vertex it got.
            std::vector<std::pair<u32, u32>> extraFans;
            for (u32 corner : owned) {
                const u32 root = fans.find(corner);
                if (root == firstRoot) {
                    continue;
                }
                u32 replacement = kInvalidId;
                for (const auto& entry : extraFans) {
                    if (entry.first == root) {
                        replacement = entry.second;
                        break;
                    }
                }
                if (replacement == kInvalidId) {
                    replacement = nextVertex++;
                    result.log.splits.push_back(VertexSplit{v, replacement});
                    extraFans.emplace_back(root, replacement);
                    result.changed = true;
                }
                const u32 face = cornerFace[corner];
                outFaces[face][corner - cornerBase[face]] = replacement;
            }
        }
    }

    // --- assemble ------------------------------------------------------------

    result.faces.vertexCount = nextVertex;
    result.faces.faceValence.reserve(outFaces.size());
    for (const auto& face : outFaces) {
        result.faces.faceValence.push_back(static_cast<u32>(face.size()));
        result.faces.cornerVertex.insert(result.faces.cornerVertex.end(), face.begin(), face.end());
    }
    return result;
}

// ============================================================================

std::vector<u32> BuildMergeGroups(u32 vertexCount, const RepairLog& log) {
    std::vector<u32> groups(vertexCount);
    for (u32 v = 0; v < vertexCount; ++v) {
        groups[v] = v;
    }
    // Splits are in application order, so a split whose original is itself a
    // created vertex already has its group resolved.
    for (const VertexSplit& split : log.splits) {
        if (split.created < vertexCount && split.original < vertexCount) {
            groups[split.created] = groups[split.original];
        }
    }
    return groups;
}

FaceSet Unrepair(const FaceSet& faces, const RepairLog& log) {
    FaceSet out;
    const u32 originalCount = faces.vertexCount >= static_cast<u32>(log.splits.size())
                                  ? faces.vertexCount - static_cast<u32>(log.splits.size())
                                  : faces.vertexCount;
    out.vertexCount = originalCount;

    const std::vector<u32> groups = BuildMergeGroups(faces.vertexCount, log);

    // Walk the surviving faces and the dropped ones together, so each dropped
    // face lands back at the index it came from.
    std::size_t droppedCursor = 0;
    std::size_t cursor = 0;
    std::size_t survivor = 0;
    const std::size_t totalFaces = faces.faceCount() + log.droppedFaces.size();

    for (std::size_t index = 0; index < totalFaces; ++index) {
        if (droppedCursor < log.droppedFaces.size() &&
            log.droppedFaces[droppedCursor].index == index) {
            const FaceRecord& record = log.droppedFaces[droppedCursor++];
            out.faceValence.push_back(static_cast<u32>(record.corners.size()));
            out.cornerVertex.insert(out.cornerVertex.end(), record.corners.begin(),
                                    record.corners.end());
            continue;
        }
        if (survivor >= faces.faceCount()) {
            break;
        }
        const u32 valence = faces.faceValence[survivor];
        out.faceValence.push_back(valence);
        for (u32 i = 0; i < valence; ++i) {
            const u32 v = faces.cornerVertex[cursor + i];
            out.cornerVertex.push_back(v < groups.size() ? groups[v] : v);
        }
        cursor += valence;
        ++survivor;
    }

    return out;
}

} // namespace geom
} // namespace wem
} // namespace models
} // namespace whiteout