summaryrefslogtreecommitdiff
path: root/components/nifbullet/bulletnifloader.cpp
blob: 4be07525a683f1883e27935177dcf7612c6bacb2 (plain)
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#include "bulletnifloader.hpp"

#include <cassert>
#include <vector>
#include <variant>

#include <BulletCollision/CollisionShapes/btBoxShape.h>
#include <BulletCollision/CollisionShapes/btTriangleMesh.h>
#include <BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h>

#include <components/debug/debuglog.hpp>

#include <components/misc/convert.hpp>
#include <components/misc/stringops.hpp>

#include <components/nif/node.hpp>
#include <components/nif/data.hpp>
#include <components/nif/extra.hpp>

namespace
{

osg::Matrixf getWorldTransform(const Nif::Node& node)
{
    if(node.parent != nullptr)
        return node.trafo.toMatrix() * getWorldTransform(*node.parent);
    return node.trafo.toMatrix();
}

bool pathFileNameStartsWithX(const std::string& path)
{
    const std::size_t slashpos = path.find_last_of("/\\");
    const std::size_t letterPos = slashpos == std::string::npos ? 0 : slashpos + 1;
    return letterPos < path.size() && (path[letterPos] == 'x' || path[letterPos] == 'X');
}

void fillTriangleMesh(btTriangleMesh& mesh, const Nif::NiTriShapeData& data, const osg::Matrixf &transform)
{
    const std::vector<osg::Vec3f> &vertices = data.vertices;
    const std::vector<unsigned short> &triangles = data.triangles;
    mesh.preallocateVertices(static_cast<int>(vertices.size()));
    mesh.preallocateIndices(static_cast<int>(triangles.size()));

    for (std::size_t i = 0; i < triangles.size(); i += 3)
    {
        mesh.addTriangle(
            Misc::Convert::toBullet(vertices[triangles[i + 0]] * transform),
            Misc::Convert::toBullet(vertices[triangles[i + 1]] * transform),
            Misc::Convert::toBullet(vertices[triangles[i + 2]] * transform)
        );
    }
}

void fillTriangleMesh(btTriangleMesh& mesh, const Nif::NiTriStripsData& data, const osg::Matrixf &transform)
{
    const std::vector<osg::Vec3f> &vertices = data.vertices;
    const std::vector<std::vector<unsigned short>> &strips = data.strips;
    mesh.preallocateVertices(static_cast<int>(vertices.size()));
    int numTriangles = 0;
    for (const std::vector<unsigned short>& strip : strips)
    {
        // Each strip with N points contains information about N-2 triangles.
        if (strip.size() >= 3)
            numTriangles += static_cast<int>(strip.size()-2);
    }
    mesh.preallocateIndices(static_cast<int>(numTriangles));

    // It's triangulation time. Totally not a NifSkope spell ripoff.
    for (const std::vector<unsigned short>& strip : strips)
    {
        // Can't make a triangle from less than 3 points.
        if (strip.size() < 3)
            continue;

        unsigned short a = strip[0], b = strip[0], c = strip[1];
        for (size_t i = 2; i < strip.size(); i++)
        {
            a = b;
            b = c;
            c = strip[i];
            if (a != b && b != c && a != c)
            {
                if (i%2==0)
                {
                    mesh.addTriangle(
                        Misc::Convert::toBullet(vertices[a] * transform),
                        Misc::Convert::toBullet(vertices[b] * transform),
                        Misc::Convert::toBullet(vertices[c] * transform)
                    );
                }
                else
                {
                    mesh.addTriangle(
                        Misc::Convert::toBullet(vertices[a] * transform),
                        Misc::Convert::toBullet(vertices[c] * transform),
                        Misc::Convert::toBullet(vertices[b] * transform)
                    );
                }
            }
        }
    }
}

template <class Function>
auto handleNiGeometry(const Nif::NiGeometry& geometry, Function&& function)
    -> decltype(function(static_cast<const Nif::NiTriShapeData&>(geometry.data.get())))
{
    if (geometry.recType == Nif::RC_NiTriShape || geometry.recType == Nif::RC_BSLODTriShape)
    {
        if (geometry.data->recType != Nif::RC_NiTriShapeData)
            return {};

        auto data = static_cast<const Nif::NiTriShapeData*>(geometry.data.getPtr());
        if (data->triangles.empty())
            return {};

        return function(static_cast<const Nif::NiTriShapeData&>(*data));
    }

    if (geometry.recType == Nif::RC_NiTriStrips)
    {
        if (geometry.data->recType != Nif::RC_NiTriStripsData)
            return {};

        auto data = static_cast<const Nif::NiTriStripsData*>(geometry.data.getPtr());
        if (data->strips.empty())
            return {};

        return function(static_cast<const Nif::NiTriStripsData&>(*data));
    }

    return {};
}

std::monostate fillTriangleMesh(std::unique_ptr<btTriangleMesh>& mesh, const Nif::NiGeometry& geometry, const osg::Matrixf &transform)
{
    return handleNiGeometry(geometry, [&] (const auto& data)
    {
        if (mesh == nullptr)
            mesh.reset(new btTriangleMesh(false));
        fillTriangleMesh(*mesh, data, transform);
        return std::monostate {};
    });
}

std::unique_ptr<btTriangleMesh> makeChildMesh(const Nif::NiGeometry& geometry)
{
    return handleNiGeometry(geometry, [&] (const auto& data)
    {
        std::unique_ptr<btTriangleMesh> mesh(new btTriangleMesh);
        fillTriangleMesh(*mesh, data, osg::Matrixf());
        return mesh;
    });
}

}

namespace NifBullet
{

osg::ref_ptr<Resource::BulletShape> BulletNifLoader::load(const Nif::File& nif)
{
    mShape = new Resource::BulletShape;

    mCompoundShape.reset();
    mStaticMesh.reset();
    mAvoidStaticMesh.reset();

    mShape->mFileHash = nif.getHash();

    const size_t numRoots = nif.numRoots();
    std::vector<const Nif::Node*> roots;
    for (size_t i = 0; i < numRoots; ++i)
    {
        const Nif::Record* r = nif.getRoot(i);
        if (!r)
            continue;
        const Nif::Node* node = dynamic_cast<const Nif::Node*>(r);
        if (node)
            roots.emplace_back(node);
    }
    const std::string filename = nif.getFilename();
    mShape->mFileName = filename;
    if (roots.empty())
    {
        warn("Found no root nodes in NIF file " + filename);
        return mShape;
    }

    // Try to find a valid bounding box first. If one's found for any root node, use that.
    for (const Nif::Node* node : roots)
    {
        if (findBoundingBox(*node, filename))
        {
            const btVector3 extents = Misc::Convert::toBullet(mShape->mCollisionBox.mExtents);
            const btVector3 center = Misc::Convert::toBullet(mShape->mCollisionBox.mCenter);
            std::unique_ptr<btCompoundShape> compound (new btCompoundShape);
            std::unique_ptr<btBoxShape> boxShape(new btBoxShape(extents));
            btTransform transform = btTransform::getIdentity();
            transform.setOrigin(center);
            compound->addChildShape(transform, boxShape.get());
            boxShape.release();

            mShape->mCollisionShape.reset(compound.release());
            return mShape;
        }
    }
    // files with the name convention xmodel.nif usually have keyframes stored in a separate file xmodel.kf (see Animation::addAnimSource).
    // assume all nodes in the file will be animated
    const bool isAnimated = pathFileNameStartsWithX(filename);

    // If there's no bounding box, we'll have to generate a Bullet collision shape
    // from the collision data present in every root node.
    for (const Nif::Node* node : roots)
    {
        bool autogenerated = hasAutoGeneratedCollision(*node);
        handleNode(filename, *node, 0, autogenerated, isAnimated, autogenerated);
    }

    if (mCompoundShape)
    {
        if (mStaticMesh != nullptr && mStaticMesh->getNumTriangles() > 0)
        {
            btTransform trans;
            trans.setIdentity();
            std::unique_ptr<btCollisionShape> child(new Resource::TriangleMeshShape(mStaticMesh.get(), true));
            mCompoundShape->addChildShape(trans, child.get());
            child.release();
            mStaticMesh.release();
        }
        mShape->mCollisionShape = std::move(mCompoundShape);
    }
    else if (mStaticMesh != nullptr && mStaticMesh->getNumTriangles() > 0)
    {
        mShape->mCollisionShape.reset(new Resource::TriangleMeshShape(mStaticMesh.get(), true));
        mStaticMesh.release();
    }

    if (mAvoidStaticMesh != nullptr && mAvoidStaticMesh->getNumTriangles() > 0)
    {
        mShape->mAvoidCollisionShape.reset(new Resource::TriangleMeshShape(mAvoidStaticMesh.get(), false));
        mAvoidStaticMesh.release();
    }

    return mShape;
}

// Find a boundingBox in the node hierarchy.
// Return: use bounding box for collision?
bool BulletNifLoader::findBoundingBox(const Nif::Node& node, const std::string& filename)
{
    if (node.hasBounds)
    {
        unsigned int type = node.bounds.type;
        switch (type)
        {
            case Nif::NiBoundingVolume::Type::BOX_BV:
                mShape->mCollisionBox.mExtents = node.bounds.box.extents;
                mShape->mCollisionBox.mCenter = node.bounds.box.center;
                break;
            default:
            {
                std::stringstream warning;
                warning << "Unsupported NiBoundingVolume type " << type << " in node " << node.recIndex;
                warning << " in file " << filename;
                warn(warning.str());
            }
        }

        if (node.flags & Nif::NiNode::Flag_BBoxCollision)
        {
            return true;
        }
    }

    if (const Nif::NiNode *ninode = dynamic_cast<const Nif::NiNode*>(&node))
    {
        const Nif::NodeList &list = ninode->children;
        for(size_t i = 0;i < list.length();i++)
        {
            if(!list[i].empty())
            {
                if (findBoundingBox(list[i].get(), filename))
                    return true;
            }
        }
    }
    return false;
}

bool BulletNifLoader::hasAutoGeneratedCollision(const Nif::Node& rootNode)
{
    if (const Nif::NiNode* ninode = dynamic_cast<const Nif::NiNode*>(&rootNode))
    {
        const Nif::NodeList &list = ninode->children;
        for(size_t i = 0;i < list.length();i++)
        {
            if(!list[i].empty())
            {
                if(list[i].getPtr()->recType == Nif::RC_RootCollisionNode)
                    return false;
            }
        }
    }
    return true;
}

void BulletNifLoader::handleNode(const std::string& fileName, const Nif::Node& node, int flags,
        bool isCollisionNode, bool isAnimated, bool autogenerated, bool avoid)
{
    // TODO: allow on-the fly collision switching via toggling this flag
    if (node.recType == Nif::RC_NiCollisionSwitch && !(node.flags & Nif::NiNode::Flag_ActiveCollision))
        return;

    // Accumulate the flags from all the child nodes. This works for all
    // the flags we currently use, at least.
    flags |= node.flags;

    if (!node.controller.empty() && node.controller->recType == Nif::RC_NiKeyframeController
            && (node.controller->flags & Nif::NiNode::ControllerFlag_Active))
        isAnimated = true;

    isCollisionNode = isCollisionNode || (node.recType == Nif::RC_RootCollisionNode);

    // Don't collide with AvoidNode shapes
    avoid = avoid || (node.recType == Nif::RC_AvoidNode);

    // We encountered a RootCollisionNode inside autogenerated mesh. It is not right.
    if (node.recType == Nif::RC_RootCollisionNode && autogenerated)
        Log(Debug::Info) << "RootCollisionNode is not attached to the root node in " << fileName << ". Treating it as a common NiTriShape.";

    // Check for extra data
    for (Nif::ExtraPtr e = node.extra; !e.empty(); e = e->next)
    {
        if (e->recType == Nif::RC_NiStringExtraData)
        {
            // String markers may contain important information
            // affecting the entire subtree of this node
            Nif::NiStringExtraData *sd = (Nif::NiStringExtraData*)e.getPtr();

            if (Misc::StringUtils::ciCompareLen(sd->string, "NC", 2) == 0)
            {
                // No collision. Use an internal flag setting to mark this.
                flags |= 0x800;
            }
            else if (sd->string == "MRK" && autogenerated)
            {
                // Marker can still have collision if the model explicitely specifies it via a RootCollisionNode.
                return;
            }

        }
    }

    if (isCollisionNode)
    {
        // NOTE: a trishape with hasBounds=true, but no BBoxCollision flag should NOT go through handleNiTriShape!
        // It must be ignored completely.
        // (occurs in tr_ex_imp_wall_arch_04.nif)
        if(!node.hasBounds && (node.recType == Nif::RC_NiTriShape
                                || node.recType == Nif::RC_NiTriStrips
                                || node.recType == Nif::RC_BSLODTriShape))
        {
            handleNiTriShape(node, flags, getWorldTransform(node), isAnimated, avoid);
        }
    }

    // For NiNodes, loop through children
    if (const Nif::NiNode *ninode = dynamic_cast<const Nif::NiNode*>(&node))
    {
        const Nif::NodeList &list = ninode->children;
        for(size_t i = 0;i < list.length();i++)
        {
            if (list[i].empty())
                continue;

            assert(list[i].get().parent == &node);
            handleNode(fileName, list[i].get(), flags, isCollisionNode, isAnimated, autogenerated, avoid);
        }
    }
}

void BulletNifLoader::handleNiTriShape(const Nif::Node& nifNode, int flags, const osg::Matrixf &transform,
                                       bool isAnimated, bool avoid)
{
    // If the object was marked "NCO" earlier, it shouldn't collide with
    // anything. So don't do anything.
    if ((flags & 0x800))
        return;

    handleNiTriShape(static_cast<const Nif::NiGeometry&>(nifNode), transform, isAnimated, avoid);
}

void BulletNifLoader::handleNiTriShape(const Nif::NiGeometry& niGeometry, const osg::Matrixf &transform,
    bool isAnimated, bool avoid)
{
    if (niGeometry.data.empty() || niGeometry.data->vertices.empty())
        return;

    if (!niGeometry.skin.empty())
        isAnimated = false;

    if (isAnimated)
    {
        std::unique_ptr<btTriangleMesh> childMesh = makeChildMesh(niGeometry);
        if (childMesh == nullptr || childMesh->getNumTriangles() == 0)
            return;

        if (!mCompoundShape)
            mCompoundShape.reset(new btCompoundShape);

        std::unique_ptr<Resource::TriangleMeshShape> childShape(new Resource::TriangleMeshShape(childMesh.get(), true));
        childMesh.release();

        float scale = niGeometry.trafo.scale;
        for (const Nif::Node* parent = niGeometry.parent; parent != nullptr; parent = parent->parent)
            scale *= parent->trafo.scale;
        osg::Quat q = transform.getRotate();
        osg::Vec3f v = transform.getTrans();
        childShape->setLocalScaling(btVector3(scale, scale, scale));

        btTransform trans(btQuaternion(q.x(), q.y(), q.z(), q.w()), btVector3(v.x(), v.y(), v.z()));

        mShape->mAnimatedShapes.emplace(niGeometry.recIndex, mCompoundShape->getNumChildShapes());

        mCompoundShape->addChildShape(trans, childShape.get());
        childShape.release();
    }
    else if (avoid)
        fillTriangleMesh(mAvoidStaticMesh, niGeometry, transform);
    else
        fillTriangleMesh(mStaticMesh, niGeometry, transform);
}

} // namespace NifBullet