File: bulletshapemanager.cpp

package info (click to toggle)
openmw 0.49.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 33,992 kB
  • sloc: cpp: 372,479; xml: 2,149; sh: 1,403; python: 797; makefile: 26
file content (210 lines) | stat: -rw-r--r-- 7,333 bytes parent folder | download
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
#include "bulletshapemanager.hpp"

#include <cstring>

#include <osg/Drawable>
#include <osg/NodeVisitor>
#include <osg/Transform>
#include <osg/TriangleFunctor>

#include <BulletCollision/CollisionShapes/btTriangleMesh.h>

#include <components/misc/osguservalues.hpp>
#include <components/misc/pathhelpers.hpp>
#include <components/sceneutil/visitor.hpp>
#include <components/vfs/manager.hpp>
#include <components/vfs/pathutil.hpp>

#include <components/nifbullet/bulletnifloader.hpp>

#include "bulletshape.hpp"
#include "multiobjectcache.hpp"
#include "niffilemanager.hpp"
#include "objectcache.hpp"
#include "scenemanager.hpp"

namespace Resource
{

    struct GetTriangleFunctor
    {
        GetTriangleFunctor()
            : mTriMesh(nullptr)
        {
        }

        void setTriMesh(btTriangleMesh* triMesh) { mTriMesh = triMesh; }

        void setMatrix(const osg::Matrixf& matrix) { mMatrix = matrix; }

        inline btVector3 toBullet(const osg::Vec3f& vec) { return btVector3(vec.x(), vec.y(), vec.z()); }

        void inline operator()(const osg::Vec3& v1, const osg::Vec3& v2, const osg::Vec3& v3,
            bool _temp = false) // Note: unused temp argument left here for OSG versions less than 3.5.6
        {
            if (mTriMesh)
                mTriMesh->addTriangle(
                    toBullet(mMatrix.preMult(v1)), toBullet(mMatrix.preMult(v2)), toBullet(mMatrix.preMult(v3)));
        }

        btTriangleMesh* mTriMesh;
        osg::Matrixf mMatrix;
    };

    /// Creates a BulletShape out of a Node hierarchy.
    class NodeToShapeVisitor : public osg::NodeVisitor
    {
    public:
        NodeToShapeVisitor()
            : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
            , mTriangleMesh(nullptr)
        {
        }

        void apply(osg::Drawable& drawable) override
        {
            if (!mTriangleMesh)
                mTriangleMesh.reset(new btTriangleMesh);

            osg::Matrixf worldMat = osg::computeLocalToWorld(getNodePath());
            osg::TriangleFunctor<GetTriangleFunctor> functor;
            functor.setTriMesh(mTriangleMesh.get());
            functor.setMatrix(worldMat);
            drawable.accept(functor);
        }

        osg::ref_ptr<BulletShape> getShape()
        {
            if (!mTriangleMesh || mTriangleMesh->getNumTriangles() == 0)
                return osg::ref_ptr<BulletShape>();

            osg::ref_ptr<BulletShape> shape(new BulletShape);

            auto triangleMeshShape = std::make_unique<TriangleMeshShape>(mTriangleMesh.release(), true);
            btVector3 aabbMin = triangleMeshShape->getLocalAabbMin();
            btVector3 aabbMax = triangleMeshShape->getLocalAabbMax();
            shape->mCollisionBox.mExtents[0] = (aabbMax[0] - aabbMin[0]) / 2.0f;
            shape->mCollisionBox.mExtents[1] = (aabbMax[1] - aabbMin[1]) / 2.0f;
            shape->mCollisionBox.mExtents[2] = (aabbMax[2] - aabbMin[2]) / 2.0f;
            shape->mCollisionBox.mCenter = osg::Vec3f(
                (aabbMax[0] + aabbMin[0]) / 2.0f, (aabbMax[1] + aabbMin[1]) / 2.0f, (aabbMax[2] + aabbMin[2]) / 2.0f);
            shape->mCollisionShape.reset(triangleMeshShape.release());

            return shape;
        }

    private:
        std::unique_ptr<btTriangleMesh> mTriangleMesh;
    };

    BulletShapeManager::BulletShapeManager(
        const VFS::Manager* vfs, SceneManager* sceneMgr, NifFileManager* nifFileManager, double expiryDelay)
        : ResourceManager(vfs, expiryDelay)
        , mInstanceCache(new MultiObjectCache)
        , mSceneManager(sceneMgr)
        , mNifFileManager(nifFileManager)
    {
    }

    BulletShapeManager::~BulletShapeManager() = default;

    osg::ref_ptr<const BulletShape> BulletShapeManager::getShape(VFS::Path::NormalizedView name)
    {
        if (osg::ref_ptr<osg::Object> obj = mCache->getRefFromObjectCache(name))
            return osg::ref_ptr<BulletShape>(static_cast<BulletShape*>(obj.get()));

        osg::ref_ptr<BulletShape> shape;

        if (Misc::getFileExtension(name.value()) == "nif")
        {
            NifBullet::BulletNifLoader loader;
            shape = loader.load(*mNifFileManager->get(name));
        }
        else
        {
            // TODO: support .bullet shape files

            osg::ref_ptr<const osg::Node> constNode(mSceneManager->getTemplate(name));
            // const-trickery required because there is no const version of NodeVisitor
            osg::ref_ptr<osg::Node> node(const_cast<osg::Node*>(constNode.get()));

            // Check first if there's a custom collision node
            unsigned int visitAllNodesMask = 0xffffffff;
            SceneUtil::FindByNameVisitor nameFinder("Collision");
            nameFinder.setTraversalMask(visitAllNodesMask);
            nameFinder.setNodeMaskOverride(visitAllNodesMask);
            node->accept(nameFinder);
            if (nameFinder.mFoundNode)
            {
                NodeToShapeVisitor visitor;
                visitor.setTraversalMask(visitAllNodesMask);
                visitor.setNodeMaskOverride(visitAllNodesMask);
                nameFinder.mFoundNode->accept(visitor);
                shape = visitor.getShape();
            }

            // Generate a collision shape from the mesh
            if (!shape)
            {
                NodeToShapeVisitor visitor;
                node->accept(visitor);
                shape = visitor.getShape();
                if (!shape)
                    return osg::ref_ptr<BulletShape>();
            }

            if (shape != nullptr)
            {
                shape->mFileName = name;
                constNode->getUserValue(Misc::OsgUserValues::sFileHash, shape->mFileHash);
            }
        }

        mCache->addEntryToObjectCache(name.value(), shape);

        return shape;
    }

    osg::ref_ptr<BulletShapeInstance> BulletShapeManager::cacheInstance(VFS::Path::NormalizedView name)
    {
        osg::ref_ptr<BulletShapeInstance> instance = createInstance(name);
        if (instance != nullptr)
            mInstanceCache->addEntryToObjectCache(name, instance.get());
        return instance;
    }

    osg::ref_ptr<BulletShapeInstance> BulletShapeManager::getInstance(VFS::Path::NormalizedView name)
    {
        if (osg::ref_ptr<osg::Object> obj = mInstanceCache->takeFromObjectCache(name))
            return static_cast<BulletShapeInstance*>(obj.get());
        return createInstance(name);
    }

    osg::ref_ptr<BulletShapeInstance> BulletShapeManager::createInstance(VFS::Path::NormalizedView name)
    {
        if (osg::ref_ptr<const BulletShape> shape = getShape(name))
            return makeInstance(std::move(shape));
        return osg::ref_ptr<BulletShapeInstance>();
    }

    void BulletShapeManager::updateCache(double referenceTime)
    {
        ResourceManager::updateCache(referenceTime);

        mInstanceCache->removeUnreferencedObjectsInCache();
    }

    void BulletShapeManager::clearCache()
    {
        ResourceManager::clearCache();

        mInstanceCache->clear();
    }

    void BulletShapeManager::reportStats(unsigned int frameNumber, osg::Stats* stats) const
    {
        Resource::reportStats("Shape", frameNumber, mCache->getStats(), *stats);
        Resource::reportStats("Shape Instance", frameNumber, mInstanceCache->getStats(), *stats);
    }

}