Let the resource cache be told what it stores, and free its values from OSG

GenericObjectCache stored osg::ref_ptr<osg::Object>, so everything cached had to
derive from osg::Object whether that meant anything or not: NifFileHolder and
BgsmFileHolder existed for no other reason, Resource::BulletShape and
ESMTerrain::LandObject carried META_Object and a CopyOp constructor nothing ever
called, and every getter paid a static_cast on the way out. The cache and
MultiObjectCache now take their value type as a template parameter, ask "is
anything else holding this?" through a useCount overload rather than a base class
method, and constrain accept and releaseGLObjects so a value type with neither is
not an error. Both holders are deleted; BulletShape, BulletShapeInstance and
LandObject become plain classes held by std::shared_ptr across physics,
pathfinding, navmeshtool and terrain storage; MWPhysics::HeightField's
type-erased osg::Object keep-alive becomes the LandObject it was always holding;
every remaining manager names the type it actually caches through the
NodeResourceManager alias, which removes eight static_casts and stops
clang-format wrapping the declarations. The preloader needs two keep-alive sets
for now, because the render-owned entries are still osg::Object; they merge once
those move behind the render backend.
This commit is contained in:
Bret Curtis
2026-09-18 16:10:18 +02:00
parent ebee0efc6a
commit 4addabaf95
65 changed files with 527 additions and 394 deletions
+1
View File
@@ -83,6 +83,7 @@ file(GLOB UNITTEST_SRC_FILES
esmterrain/testgridsampling.cpp
resource/testmultiobjectcache.cpp
resource/testobjectcache.cpp
resource/testresourcesystem.cpp
@@ -1,4 +1,5 @@
#include "settings.hpp"
#include <memory>
#include <components/detournavigator/asyncnavmeshupdater.hpp>
#include <components/detournavigator/dbrefgeometryobject.hpp>
@@ -34,7 +35,7 @@ namespace
void addObject(const btBoxShape& shape, TileCachedRecastMeshManager& recastMeshManager)
{
const ObjectId id(&shape);
osg::ref_ptr<Resource::BulletShape> bulletShape(new Resource::BulletShape);
auto bulletShape = std::make_shared<Resource::BulletShape>();
constexpr VFS::Path::NormalizedView test("test.nif");
bulletShape->mFileName = test;
bulletShape->mFileHash = "test_hash";
@@ -43,8 +44,7 @@ namespace
std::fill(std::begin(objectTransform.mPosition.rot), std::end(objectTransform.mPosition.rot), 0.2f);
objectTransform.mScale = 3.14f;
const CollisionShape collisionShape(
osg::ref_ptr<Resource::BulletShapeInstance>(new Resource::BulletShapeInstance(bulletShape)), shape,
objectTransform);
std::make_shared<Resource::BulletShapeInstance>(bulletShape), shape, objectTransform);
recastMeshManager.addObject(id, collisionShape, btTransform::getIdentity(), AreaType_ground, nullptr);
}
@@ -115,11 +115,11 @@ namespace
}
template <class T>
osg::ref_ptr<const Resource::BulletShapeInstance> makeBulletShapeInstance(std::unique_ptr<T>&& shape)
std::shared_ptr<const Resource::BulletShapeInstance> makeBulletShapeInstance(std::unique_ptr<T>&& shape)
{
osg::ref_ptr<Resource::BulletShape> bulletShape(new Resource::BulletShape);
auto bulletShape = std::make_shared<Resource::BulletShape>();
bulletShape->mCollisionShape.reset(std::move(shape).release());
return new Resource::BulletShapeInstance(bulletShape);
return std::make_shared<Resource::BulletShapeInstance>(bulletShape);
}
template <class T>
@@ -132,10 +132,10 @@ namespace
}
T& shape() const { return static_cast<T&>(*mInstance->mCollisionShape); }
const osg::ref_ptr<const Resource::BulletShapeInstance>& instance() const { return mInstance; }
const std::shared_ptr<const Resource::BulletShapeInstance>& instance() const { return mInstance; }
private:
osg::ref_ptr<const Resource::BulletShapeInstance> mInstance;
std::shared_ptr<const Resource::BulletShapeInstance> mInstance;
};
btVector3 getHeightfieldShift(const osg::Vec2i& cellPosition, int cellSize, float minHeight, float maxHeight)
@@ -368,7 +368,7 @@ namespace
TEST_F(DetourNavigatorNavigatorTest, path_should_be_around_avoid_shape)
{
osg::ref_ptr<Resource::BulletShape> bulletShape(new Resource::BulletShape);
auto bulletShape = std::make_shared<Resource::BulletShape>();
std::unique_ptr<btHeightfieldTerrainShape> shapePtr
= makeSquareHeightfieldTerrainShape(defaultHeightfieldDataScalar);
@@ -387,7 +387,7 @@ namespace
shapeAvoidPtr->setLocalScaling(btVector3(128, 128, 1));
bulletShape->mAvoidCollisionShape.reset(shapeAvoidPtr.release());
osg::ref_ptr<const Resource::BulletShapeInstance> instance(new Resource::BulletShapeInstance(bulletShape));
auto instance = std::make_shared<const Resource::BulletShapeInstance>(bulletShape);
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addObject(
@@ -1,4 +1,5 @@
#include "operators.hpp"
#include <memory>
#include <components/detournavigator/recastmesh.hpp>
#include <components/detournavigator/recastmeshbuilder.hpp>
@@ -52,7 +53,7 @@ namespace
{
TileBounds mBounds;
const Version mVersion{ 0, 0 };
const osg::ref_ptr<const Resource::BulletShape> mSource{ nullptr };
const std::shared_ptr<const Resource::BulletShape> mSource{ nullptr };
const ObjectTransform mObjectTransform{ ESM::Position{ { 0, 0, 0 }, { 0, 0, 0 } }, 0.0f };
DetourNavigatorRecastMeshBuilderTest()
@@ -2,6 +2,7 @@
#include <components/detournavigator/debug.hpp>
#include <components/detournavigator/settingsutils.hpp>
#include <components/detournavigator/tilecachedrecastmeshmanager.hpp>
#include <memory>
#include <BulletCollision/CollisionShapes/btBoxShape.h>
@@ -19,8 +20,9 @@ namespace
{
RecastSettings mSettings;
const ObjectTransform mObjectTransform{ ESM::Position{ { 0, 0, 0 }, { 0, 0, 0 } }, 0.0f };
const osg::ref_ptr<const Resource::BulletShape> mShape = new Resource::BulletShape;
const osg::ref_ptr<const Resource::BulletShapeInstance> mInstance = new Resource::BulletShapeInstance(mShape);
const std::shared_ptr<const Resource::BulletShape> mShape = std::make_shared<Resource::BulletShape>();
const std::shared_ptr<const Resource::BulletShapeInstance> mInstance
= std::make_shared<Resource::BulletShapeInstance>(mShape);
const ESM::RefId mWorldspace = ESM::RefId::stringRefId("worldspace");
DetourNavigatorTileCachedRecastMeshManagerTest()
@@ -0,0 +1,98 @@
#include <components/resource/multiobjectcache.hpp>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <memory>
#include <string>
namespace Resource
{
namespace
{
using namespace ::testing;
// A value type that derives from nothing, which is the point of the value
// type parameter; BulletShapeInstance is the real user.
using Cache = MultiObjectCache<std::shared_ptr<const std::string>>;
constexpr VFS::Path::NormalizedView path("meshes/a.nif");
constexpr VFS::Path::NormalizedView otherPath("meshes/b.nif");
TEST(ResourceMultiObjectCacheTest, takeShouldReturnNullForAbsentKey)
{
Cache cache;
EXPECT_EQ(cache.takeFromObjectCache(path), nullptr);
}
TEST(ResourceMultiObjectCacheTest, takeShouldRemoveTheEntry)
{
Cache cache;
const auto value = std::make_shared<const std::string>("value");
cache.addEntryToObjectCache(path, value);
EXPECT_EQ(cache.takeFromObjectCache(path), value);
// "Non reusable": taking is a move out, not a read.
EXPECT_EQ(cache.takeFromObjectCache(path), nullptr);
}
TEST(ResourceMultiObjectCacheTest, shouldHoldMoreThanOneValuePerKey)
{
Cache cache;
cache.addEntryToObjectCache(path, std::make_shared<const std::string>("first"));
cache.addEntryToObjectCache(path, std::make_shared<const std::string>("second"));
EXPECT_NE(cache.takeFromObjectCache(path), nullptr);
EXPECT_NE(cache.takeFromObjectCache(path), nullptr);
EXPECT_EQ(cache.takeFromObjectCache(path), nullptr);
}
TEST(ResourceMultiObjectCacheTest, shouldRefuseNullValues)
{
Cache cache;
cache.addEntryToObjectCache(path, nullptr);
EXPECT_EQ(cache.getStats().mSize, 0u);
}
TEST(ResourceMultiObjectCacheTest, removeUnreferencedShouldKeepValuesHeldElsewhere)
{
Cache cache;
const auto held = std::make_shared<const std::string>("held");
cache.addEntryToObjectCache(path, held);
cache.addEntryToObjectCache(otherPath, std::make_shared<const std::string>("dropped"));
cache.removeUnreferencedObjectsInCache();
EXPECT_EQ(cache.takeFromObjectCache(path), held);
EXPECT_EQ(cache.takeFromObjectCache(otherPath), nullptr);
}
TEST(ResourceMultiObjectCacheTest, clearShouldRemoveEverything)
{
Cache cache;
const auto held = std::make_shared<const std::string>("held");
cache.addEntryToObjectCache(path, held);
cache.clear();
EXPECT_EQ(cache.getStats().mSize, 0u);
EXPECT_EQ(cache.takeFromObjectCache(path), nullptr);
}
TEST(ResourceMultiObjectCacheTest, statsShouldCountGetsHitsAndExpiries)
{
Cache cache;
cache.addEntryToObjectCache(path, std::make_shared<const std::string>("value"));
cache.addEntryToObjectCache(otherPath, std::make_shared<const std::string>("dropped"));
cache.takeFromObjectCache(path);
cache.takeFromObjectCache(path);
cache.removeUnreferencedObjectsInCache();
const CacheStats stats = cache.getStats();
EXPECT_EQ(stats.mGet, 2u);
EXPECT_EQ(stats.mHit, 1u);
EXPECT_EQ(stats.mExpired, 1u);
}
}
}
@@ -3,6 +3,8 @@
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <memory>
#include <osg/Object>
namespace Resource
@@ -11,15 +13,22 @@ namespace Resource
{
using namespace ::testing;
using ObjectCache = GenericObjectCache<int, osg::ref_ptr<osg::Object>>;
using StringObjectCache = GenericObjectCache<std::string, osg::ref_ptr<osg::Object>>;
// The point of the value type parameter: a type that derives from nothing at all
// is cacheable, and expiry still knows whether anything outside holds it.
using SharedCache = GenericObjectCache<int, std::shared_ptr<const std::string>>;
TEST(ResourceGenericObjectCacheTest, getRefFromObjectCacheShouldReturnNullptrByDefault)
{
GenericObjectCache<int> cache;
ObjectCache cache;
EXPECT_EQ(cache.getRefFromObjectCache(42), nullptr);
}
TEST(ResourceGenericObjectCacheTest, getRefFromObjectCacheOrNoneShouldReturnNulloptByDefault)
{
GenericObjectCache<int> cache;
ObjectCache cache;
EXPECT_EQ(cache.getRefFromObjectCacheOrNone(42), std::nullopt);
}
@@ -35,9 +44,40 @@ namespace Resource
META_Object(ResourceTest, Object)
};
TEST(ResourceGenericObjectCacheTest, shouldStoreValuesThatAreNotOsgObjects)
{
SharedCache cache;
const auto value = std::make_shared<const std::string>("value");
cache.addEntryToObjectCache(42, value);
EXPECT_EQ(cache.getRefFromObjectCache(42), value);
}
TEST(ResourceGenericObjectCacheTest, updateShouldNotDereferenceNullValues)
{
ObjectCache cache;
cache.addEntryToObjectCache(42, nullptr);
cache.update(1000, 1);
EXPECT_THAT(cache.getRefFromObjectCacheOrNone(42), Optional(nullptr));
}
TEST(ResourceGenericObjectCacheTest, updateShouldKeepSharedPtrValuesHeldElsewhere)
{
SharedCache cache;
const auto held = std::make_shared<const std::string>("held");
cache.addEntryToObjectCache(1, held);
cache.addEntryToObjectCache(2, std::make_shared<const std::string>("dropped"));
const double referenceTime = 1000;
cache.update(referenceTime, 1);
cache.update(referenceTime + 10, 1);
EXPECT_THAT(cache.getRefFromObjectCacheOrNone(1), Optional(held));
EXPECT_EQ(cache.getRefFromObjectCacheOrNone(2), std::nullopt);
}
TEST(ResourceGenericObjectCacheTest, shouldStoreValues)
{
GenericObjectCache<int> cache;
ObjectCache cache;
const int key = 42;
osg::ref_ptr<Object> value(new Object);
cache.addEntryToObjectCache(key, value);
@@ -46,7 +86,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, shouldStoreNullptrValues)
{
GenericObjectCache<int> cache;
ObjectCache cache;
const int key = 42;
cache.addEntryToObjectCache(key, nullptr);
EXPECT_THAT(cache.getRefFromObjectCacheOrNone(key), Optional(nullptr));
@@ -54,7 +94,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, updateShouldExtendLifetimeForItemsWithZeroTimestamp)
{
GenericObjectCache<int> cache;
ObjectCache cache;
const int key = 42;
osg::ref_ptr<Object> value(new Object);
@@ -69,7 +109,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, addEntryToObjectCacheShouldReplaceExistingItemByKey)
{
GenericObjectCache<int> cache;
ObjectCache cache;
const int key = 42;
osg::ref_ptr<Object> value1(new Object);
@@ -82,7 +122,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, addEntryToObjectCacheShouldMarkLifetime)
{
GenericObjectCache<int> cache;
ObjectCache cache;
const double referenceTime = 1;
const double expiryDelay = 2;
@@ -102,7 +142,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, updateShouldRemoveExpiredItems)
{
GenericObjectCache<int> cache;
ObjectCache cache;
const double referenceTime = 1;
const double expiryDelay = 1;
@@ -123,7 +163,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, updateShouldKeepExternallyReferencedItems)
{
GenericObjectCache<int> cache;
ObjectCache cache;
const double referenceTime = 1;
const double expiryDelay = 1;
@@ -141,7 +181,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, updateShouldKeepNotExpiredItems)
{
GenericObjectCache<int> cache;
ObjectCache cache;
const double referenceTime = 1;
const double expiryDelay = 2;
@@ -160,7 +200,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, updateShouldKeepNotExpiredNullptrItems)
{
GenericObjectCache<int> cache;
ObjectCache cache;
const double referenceTime = 1;
const double expiryDelay = 2;
@@ -177,7 +217,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, getRefFromObjectCacheOrNoneShouldNotExtendItemLifetime)
{
GenericObjectCache<int> cache;
ObjectCache cache;
const double referenceTime = 1;
const double expiryDelay = 2;
@@ -197,7 +237,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, lowerBoundShouldSupportHeterogeneousLookup)
{
GenericObjectCache<std::string> cache;
StringObjectCache cache;
cache.addEntryToObjectCache("a", nullptr);
cache.addEntryToObjectCache("c", nullptr);
EXPECT_THAT(cache.lowerBound(std::string_view("b")), Optional(Pair("c", _)));
@@ -205,7 +245,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, shouldSupportRemovingItems)
{
GenericObjectCache<int> cache;
ObjectCache cache;
const int key = 42;
osg::ref_ptr<Object> value(new Object);
cache.addEntryToObjectCache(key, value);
@@ -216,7 +256,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, clearShouldRemoveAllItems)
{
GenericObjectCache<int> cache;
ObjectCache cache;
const int key1 = 42;
const int key2 = 13;
@@ -236,7 +276,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, callShouldIterateOverAllItems)
{
GenericObjectCache<int> cache;
ObjectCache cache;
osg::ref_ptr<Object> value1(new Object);
osg::ref_ptr<Object> value2(new Object);
@@ -253,7 +293,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, getStatsShouldReturnNumberOrAddedItems)
{
GenericObjectCache<int> cache;
ObjectCache cache;
osg::ref_ptr<Object> value1(new Object);
osg::ref_ptr<Object> value2(new Object);
@@ -267,7 +307,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, getStatsShouldReturnNumberOrGetsAndHits)
{
GenericObjectCache<int> cache;
ObjectCache cache;
{
const CacheStats stats = cache.getStats();
@@ -291,7 +331,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, lowerBoundShouldReturnFirstNotLessThatGivenKey)
{
GenericObjectCache<int> cache;
ObjectCache cache;
osg::ref_ptr<Object> value1(new Object);
osg::ref_ptr<Object> value2(new Object);
@@ -305,7 +345,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, lowerBoundShouldReturnNulloptWhenKeyIsGreaterThanAnyOther)
{
GenericObjectCache<int> cache;
ObjectCache cache;
osg::ref_ptr<Object> value1(new Object);
osg::ref_ptr<Object> value2(new Object);
@@ -319,7 +359,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, addEntryToObjectCacheShouldSupportHeterogeneousLookup)
{
GenericObjectCache<std::string> cache;
StringObjectCache cache;
const std::string key = "key";
osg::ref_ptr<Object> value(new Object);
cache.addEntryToObjectCache(std::string_view("key"), value);
@@ -328,7 +368,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, addEntryToObjectCacheShouldKeyMoving)
{
GenericObjectCache<std::string> cache;
StringObjectCache cache;
std::string key(128, 'a');
osg::ref_ptr<Object> value(new Object);
cache.addEntryToObjectCache(std::move(key), value);
@@ -338,7 +378,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, removeFromObjectCacheShouldSupportHeterogeneousLookup)
{
GenericObjectCache<std::string> cache;
StringObjectCache cache;
const std::string key = "key";
osg::ref_ptr<Object> value(new Object);
cache.addEntryToObjectCache(key, value);
@@ -349,7 +389,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, getRefFromObjectCacheShouldSupportHeterogeneousLookup)
{
GenericObjectCache<std::string> cache;
StringObjectCache cache;
const std::string key = "key";
osg::ref_ptr<Object> value(new Object);
cache.addEntryToObjectCache(key, value);
@@ -358,7 +398,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, getRefFromObjectCacheOrNoneShouldSupportHeterogeneousLookup)
{
GenericObjectCache<std::string> cache;
StringObjectCache cache;
const std::string key = "key";
osg::ref_ptr<Object> value(new Object);
cache.addEntryToObjectCache(key, value);
@@ -367,7 +407,7 @@ namespace Resource
TEST(ResourceGenericObjectCacheTest, checkInObjectCacheShouldSupportHeterogeneousLookup)
{
GenericObjectCache<std::string> cache;
StringObjectCache cache;
const std::string key = "key";
osg::ref_ptr<Object> value(new Object);
cache.addEntryToObjectCache(key, value);
+3 -3
View File
@@ -148,7 +148,7 @@ namespace NavMeshTool
if (cellRef.mType != ESM::REC_STAT)
model = Misc::ResourceHelpers::correctActorModelPath(model, &vfs);
osg::ref_ptr<const Resource::BulletShape> shape = [&] {
std::shared_ptr<const Resource::BulletShape> shape = [&] {
try
{
return bulletShapeManager.getShape(Misc::ResourceHelpers::correctMeshPath(model));
@@ -157,14 +157,14 @@ namespace NavMeshTool
{
Log(Debug::Warning) << "Failed to load cell ref \"" << cellRef.mRefId << "\" model \"" << model
<< "\": " << e.what();
return osg::ref_ptr<const Resource::BulletShape>();
return std::shared_ptr<const Resource::BulletShape>();
}
}();
if (shape == nullptr || shape->mCollisionShape == nullptr)
continue;
osg::ref_ptr<Resource::BulletShapeInstance> shapeInstance(
std::shared_ptr<Resource::BulletShapeInstance> shapeInstance(
new Resource::BulletShapeInstance(std::move(shape)));
switch (cellRef.mType)
+6 -3
View File
@@ -47,7 +47,7 @@ namespace NavMeshTool
class BulletObject
{
public:
BulletObject(osg::ref_ptr<Resource::BulletShapeInstance>&& shapeInstance, const ESM::Position& position,
BulletObject(std::shared_ptr<Resource::BulletShapeInstance>&& shapeInstance, const ESM::Position& position,
float localScaling)
: mShapeInstance(std::move(shapeInstance))
, mObjectTransform{ position, localScaling }
@@ -58,12 +58,15 @@ namespace NavMeshTool
mShapeInstance->setLocalScaling(btVector3(localScaling, localScaling, localScaling));
}
const osg::ref_ptr<Resource::BulletShapeInstance>& getShapeInstance() const noexcept { return mShapeInstance; }
const std::shared_ptr<Resource::BulletShapeInstance>& getShapeInstance() const noexcept
{
return mShapeInstance;
}
const DetourNavigator::ObjectTransform& getObjectTransform() const noexcept { return mObjectTransform; }
btCollisionObject& getCollisionObject() const noexcept { return *mCollisionObject; }
private:
osg::ref_ptr<Resource::BulletShapeInstance> mShapeInstance;
std::shared_ptr<Resource::BulletShapeInstance> mShapeInstance;
DetourNavigator::ObjectTransform mObjectTransform;
std::unique_ptr<btCollisionObject> mCollisionObject;
};
+2 -2
View File
@@ -27,7 +27,7 @@ namespace CSVRender
resetHeights();
}
osg::ref_ptr<const ESMTerrain::LandObject> TerrainStorage::getLand(ESM::ExteriorCellLocation cellLocation)
std::shared_ptr<const ESMTerrain::LandObject> TerrainStorage::getLand(ESM::ExteriorCellLocation cellLocation)
{
// The cell isn't guaranteed to have Land. This is because the terrain implementation
// has to wrap the vertices of the last row and column to the next cell, which may be a nonexisting cell
@@ -37,7 +37,7 @@ namespace CSVRender
return nullptr;
const ESM::Land& land = mData.getLand().getRecord(index).get();
return new ESMTerrain::LandObject(
return std::make_shared<const ESMTerrain::LandObject>(
land, ESM::Land::DATA_VHGT | ESM::Land::DATA_VNML | ESM::Land::DATA_VCLR | ESM::Land::DATA_VTEX);
}
+1 -1
View File
@@ -37,7 +37,7 @@ namespace CSVRender
const CSMWorld::Data& mData;
std::array<float, ESM::Land::LAND_SIZE * ESM::Land::LAND_SIZE> mAlteredHeight;
osg::ref_ptr<const ESMTerrain::LandObject> getLand(ESM::ExteriorCellLocation cellLocation) override;
std::shared_ptr<const ESMTerrain::LandObject> getLand(ESM::ExteriorCellLocation cellLocation) override;
const VFS::Path::Normalized* getLandTexture(std::uint16_t index, int plugin) override;
void getBounds(float& minX, float& maxX, float& minY, float& maxY, ESM::RefId worldspace) override;
+5 -5
View File
@@ -19,14 +19,14 @@
namespace MWPhysics
{
Actor::Actor(const MWWorld::Ptr& ptr, const Resource::BulletShape* shape, PhysicsTaskScheduler* scheduler,
Actor::Actor(const MWWorld::Ptr& ptr, const Resource::BulletShape& shape, PhysicsTaskScheduler* scheduler,
bool canWaterWalk, DetourNavigator::CollisionShapeType collisionShapeType)
: PtrHolder(ptr, ptr.getRefData().getPosition().asVec3())
, mStandingOnPtr(nullptr)
, mCanWaterWalk(canWaterWalk)
, mWalkingOnWater(false)
, mMeshTranslation(shape->mCollisionBox.mCenter)
, mOriginalHalfExtents(shape->mCollisionBox.mExtents)
, mMeshTranslation(shape.mCollisionBox.mCenter)
, mOriginalHalfExtents(shape.mCollisionBox.mExtents)
, mStuckFrames(0)
, mLastStuckPosition{ 0, 0, 0 }
, mForce(0.f, 0.f, 0.f)
@@ -42,14 +42,14 @@ namespace MWPhysics
// (NPCs have bodyparts and use a different approach)
if (!ptr.getClass().isNpc() && mOriginalHalfExtents.length2() == 0.f)
{
if (shape->mCollisionShape)
if (shape.mCollisionShape)
{
btTransform transform;
transform.setIdentity();
btVector3 min;
btVector3 max;
shape->mCollisionShape->getAabb(transform, min, max);
shape.mCollisionShape->getAabb(transform, min, max);
mOriginalHalfExtents.x() = static_cast<float>((max[0] - min[0]) / 2.f);
mOriginalHalfExtents.y() = static_cast<float>((max[1] - min[1]) / 2.f);
mOriginalHalfExtents.z() = static_cast<float>((max[2] - min[2]) / 2.f);
+1 -1
View File
@@ -27,7 +27,7 @@ namespace MWPhysics
class Actor final : public PtrHolder
{
public:
Actor(const MWWorld::Ptr& ptr, const Resource::BulletShape* shape, PhysicsTaskScheduler* scheduler,
Actor(const MWWorld::Ptr& ptr, const Resource::BulletShape& shape, PhysicsTaskScheduler* scheduler,
bool canWaterWalk, DetourNavigator::CollisionShapeType collisionShapeType);
~Actor() override;
+1 -1
View File
@@ -53,7 +53,7 @@ namespace
namespace MWPhysics
{
HeightField::HeightField(const float* heights, int x, int y, int size, int verts, float minH, float maxH,
const osg::Object* holdObject, PhysicsTaskScheduler* scheduler)
std::shared_ptr<const ESMTerrain::LandObject> holdObject, PhysicsTaskScheduler* scheduler)
: mHoldObject(holdObject)
#if BT_BULLET_VERSION < 310
, mHeights(makeHeights(heights, verts))
+7 -2
View File
@@ -16,6 +16,11 @@ namespace osg
class Object;
}
namespace ESMTerrain
{
class LandObject;
}
namespace MWPhysics
{
class PhysicsTaskScheduler;
@@ -24,7 +29,7 @@ namespace MWPhysics
{
public:
HeightField(const float* heights, int x, int y, int size, int verts, float minH, float maxH,
const osg::Object* holdObject, PhysicsTaskScheduler* scheduler);
std::shared_ptr<const ESMTerrain::LandObject> holdObject, PhysicsTaskScheduler* scheduler);
~HeightField();
btCollisionObject* getCollisionObject();
@@ -34,7 +39,7 @@ namespace MWPhysics
private:
std::unique_ptr<btHeightfieldTerrainShape> mShape;
std::unique_ptr<btCollisionObject> mCollisionObject;
osg::ref_ptr<const osg::Object> mHoldObject;
std::shared_ptr<const ESMTerrain::LandObject> mHoldObject;
#if BT_BULLET_VERSION < 310
std::vector<btScalar> mHeights;
#endif
+4 -3
View File
@@ -1,5 +1,6 @@
#include "object.hpp"
#include "mtphysics.hpp"
#include <memory>
#include <components/bullethelpers/collisionobject.hpp>
#include <components/debug/debuglog.hpp>
@@ -14,7 +15,7 @@
namespace MWPhysics
{
Object::Object(const MWWorld::Ptr& ptr, osg::ref_ptr<Resource::BulletShapeInstance> shapeInstance,
Object::Object(const MWWorld::Ptr& ptr, std::shared_ptr<Resource::BulletShapeInstance> shapeInstance,
osg::Quat rotation, int collisionType, PhysicsTaskScheduler* scheduler)
: PtrHolder(ptr, osg::Vec3f())
, mShapeInstance(std::move(shapeInstance))
@@ -38,9 +39,9 @@ namespace MWPhysics
mTaskScheduler->removeCollisionObject(mCollisionObject.get());
}
const Resource::BulletShapeInstance* Object::getShapeInstance() const
const std::shared_ptr<Resource::BulletShapeInstance>& Object::getShapeInstance() const
{
return mShapeInstance.get();
return mShapeInstance;
}
void Object::setScale(float scale)
+5 -4
View File
@@ -2,6 +2,7 @@
#define OPENMW_MWPHYSICS_OBJECT_H
#include "ptrholder.hpp"
#include <memory>
#include <LinearMath/btTransform.h>
#include <osg/Node>
@@ -29,11 +30,11 @@ namespace MWPhysics
class Object final : public PtrHolder
{
public:
Object(const MWWorld::Ptr& ptr, osg::ref_ptr<Resource::BulletShapeInstance> shapeInstance, osg::Quat rotation,
int collisionType, PhysicsTaskScheduler* scheduler);
Object(const MWWorld::Ptr& ptr, std::shared_ptr<Resource::BulletShapeInstance> shapeInstance,
osg::Quat rotation, int collisionType, PhysicsTaskScheduler* scheduler);
~Object() override;
const Resource::BulletShapeInstance* getShapeInstance() const;
const std::shared_ptr<Resource::BulletShapeInstance>& getShapeInstance() const;
void setScale(float scale);
void setRotation(osg::Quat quat);
void updatePosition();
@@ -51,7 +52,7 @@ namespace MWPhysics
void resetCollisions();
private:
osg::ref_ptr<Resource::BulletShapeInstance> mShapeInstance;
std::shared_ptr<Resource::BulletShapeInstance> mShapeInstance;
std::map<int, osg::NodePath> mRecordIndexToNodePath;
bool mSolid;
btVector3 mScale;
+8 -8
View File
@@ -382,11 +382,11 @@ namespace MWPhysics
return MovementSolver::traceDown(ptr, position, found->second.get(), mCollisionWorld.get(), maxHeight);
}
void PhysicsSystem::addHeightField(
const float* heights, int x, int y, int size, int verts, float minH, float maxH, const osg::Object* holdObject)
void PhysicsSystem::addHeightField(const float* heights, int x, int y, int size, int verts, float minH, float maxH,
std::shared_ptr<const ESMTerrain::LandObject> holdObject)
{
mHeightFields[std::make_pair(x, y)]
= std::make_unique<HeightField>(heights, x, y, size, verts, minH, maxH, holdObject, mTaskScheduler.get());
mHeightFields[std::make_pair(x, y)] = std::make_unique<HeightField>(
heights, x, y, size, verts, minH, maxH, std::move(holdObject), mTaskScheduler.get());
}
void PhysicsSystem::removeHeightField(int x, int y)
@@ -413,7 +413,7 @@ namespace MWPhysics
const VFS::Path::Normalized animationMesh = ptr.getClass().useAnim()
? Misc::ResourceHelpers::correctActorModelPath(mesh, mResourceSystem->getVFS())
: VFS::Path::Normalized(mesh);
osg::ref_ptr<Resource::BulletShapeInstance> shapeInstance = mShapeManager->getInstance(animationMesh);
std::shared_ptr<Resource::BulletShapeInstance> shapeInstance = mShapeManager->getInstance(animationMesh);
if (!shapeInstance || !shapeInstance->mCollisionShape)
return;
@@ -562,7 +562,7 @@ namespace MWPhysics
{
const VFS::Path::Normalized animationMesh
= Misc::ResourceHelpers::correctActorModelPath(mesh, mResourceSystem->getVFS());
osg::ref_ptr<const Resource::BulletShape> shape = mShapeManager->getShape(animationMesh);
std::shared_ptr<const Resource::BulletShape> shape = mShapeManager->getShape(animationMesh);
// Try to get shape from basic model as fallback for creatures
if (!ptr.getClass().isNpc() && shape && shape->mCollisionBox.mExtents.length2() == 0)
@@ -581,7 +581,7 @@ namespace MWPhysics
const bool canWaterWalk = effects.getOrDefault(ESM::MagicEffect::WaterWalking).getMagnitude() > 0;
auto actor = std::make_shared<Actor>(
ptr, shape, mTaskScheduler.get(), canWaterWalk, Settings::game().mActorCollisionShapeType);
ptr, *shape, mTaskScheduler.get(), canWaterWalk, Settings::game().mActorCollisionShapeType);
mActors.emplace(ptr.mRef, std::move(actor));
}
@@ -589,7 +589,7 @@ namespace MWPhysics
int PhysicsSystem::addProjectile(
const MWWorld::Ptr& caster, const osg::Vec3f& position, VFS::Path::NormalizedView mesh, bool computeRadius)
{
osg::ref_ptr<Resource::BulletShapeInstance> shapeInstance = mShapeManager->getInstance(mesh);
std::shared_ptr<Resource::BulletShapeInstance> shapeInstance = mShapeManager->getInstance(mesh);
assert(shapeInstance);
float radius = computeRadius ? shapeInstance->mCollisionBox.mExtents.length() / 2.f : 1.f;
+6 -1
View File
@@ -49,6 +49,11 @@ class btCollisionObject;
class btCollisionShape;
class btVector3;
namespace ESMTerrain
{
class LandObject;
}
namespace MWPhysics
{
class HeightField;
@@ -187,7 +192,7 @@ namespace MWPhysics
void updatePosition(const MWWorld::Ptr& ptr);
void addHeightField(const float* heights, int x, int y, int size, int verts, float minH, float maxH,
const osg::Object* holdObject);
std::shared_ptr<const ESMTerrain::LandObject> holdObject);
void removeHeightField(int x, int y);
+1 -1
View File
@@ -345,7 +345,7 @@ namespace MWRender
Groundcover::Groundcover(
Resource::SceneManager* sceneManager, float density, float viewDistance, const MWWorld::GroundcoverStore& store)
: GenericResourceManager<GroundcoverChunkId>(nullptr, Settings::cells().mCacheExpiryDelay)
: Resource::NodeResourceManager<GroundcoverChunkId>(nullptr, Settings::cells().mCacheExpiryDelay)
, mSceneManager(sceneManager)
, mDensity(density)
, mStateset(new osg::StateSet)
+1 -1
View File
@@ -19,7 +19,7 @@ namespace osg
namespace MWRender
{
typedef std::tuple<osg::Vec2f, float> GroundcoverChunkId; // Center, Size
class Groundcover : public Resource::GenericResourceManager<GroundcoverChunkId>,
class Groundcover : public Resource::NodeResourceManager<GroundcoverChunkId>,
public Terrain::QuadTreeWorld::ChunkManager
{
public:
+9 -8
View File
@@ -12,12 +12,13 @@ namespace MWRender
{
LandManager::LandManager(int loadFlags)
: GenericResourceManager<ESM::ExteriorCellLocation>(nullptr, Settings::cells().mCacheExpiryDelay)
: GenericResourceManager<ESM::ExteriorCellLocation, std::shared_ptr<const ESMTerrain::LandObject>>(
nullptr, Settings::cells().mCacheExpiryDelay)
, mLoadFlags(loadFlags)
{
}
osg::ref_ptr<ESMTerrain::LandObject> LandManager::getLand(ESM::ExteriorCellLocation cellIndex)
std::shared_ptr<const ESMTerrain::LandObject> LandManager::getLand(ESM::ExteriorCellLocation cellIndex)
{
const MWBase::World& world = *MWBase::Environment::get().getWorld();
if (ESM::isEsm4Ext(cellIndex.mWorldspace))
@@ -27,25 +28,25 @@ namespace MWRender
cellIndex.mWorldspace = worldspace->mParent;
}
if (const std::optional<osg::ref_ptr<osg::Object>> obj = mCache->getRefFromObjectCacheOrNone(cellIndex))
return static_cast<ESMTerrain::LandObject*>(obj->get());
if (const auto cached = mCache->getRefFromObjectCacheOrNone(cellIndex))
return *cached;
osg::ref_ptr<ESMTerrain::LandObject> landObj = nullptr;
std::shared_ptr<const ESMTerrain::LandObject> landObj = nullptr;
if (ESM::isEsm4Ext(cellIndex.mWorldspace))
{
const ESM4::Land* land = world.getStore().get<ESM4::Land>().search(cellIndex);
if (land != nullptr)
landObj = new ESMTerrain::LandObject(*land, mLoadFlags);
landObj = std::make_shared<const ESMTerrain::LandObject>(*land, mLoadFlags);
}
else
{
const ESM::Land* land = world.getStore().get<ESM::Land>().search(cellIndex.mX, cellIndex.mY);
if (land != nullptr)
landObj = new ESMTerrain::LandObject(*land, mLoadFlags);
landObj = std::make_shared<const ESMTerrain::LandObject>(*land, mLoadFlags);
}
mCache->addEntryToObjectCache(cellIndex, landObj.get());
mCache->addEntryToObjectCache(cellIndex, landObj);
return landObj;
}
+3 -2
View File
@@ -15,13 +15,14 @@ namespace ESM
namespace MWRender
{
class LandManager : public Resource::GenericResourceManager<ESM::ExteriorCellLocation>
class LandManager : public Resource::GenericResourceManager<ESM::ExteriorCellLocation,
std::shared_ptr<const ESMTerrain::LandObject>>
{
public:
LandManager(int loadFlags);
/// @note Will return nullptr if not found.
osg::ref_ptr<ESMTerrain::LandObject> getLand(ESM::ExteriorCellLocation cellIndex);
std::shared_ptr<const ESMTerrain::LandObject> getLand(ESM::ExteriorCellLocation cellIndex);
void reportStats(unsigned int frameNumber, osg::Stats* stats) const override;
+1 -1
View File
@@ -461,7 +461,7 @@ namespace MWRender
}
ObjectPaging::ObjectPaging(Resource::SceneManager* sceneManager, ESM::RefId worldspace)
: GenericResourceManager<ChunkId>(nullptr, Settings::cells().mCacheExpiryDelay)
: Resource::NodeResourceManager<ChunkId>(nullptr, Settings::cells().mCacheExpiryDelay)
, Terrain::QuadTreeWorld::ChunkManager(worldspace)
, mSceneManager(sceneManager)
, mActiveGrid(Settings::terrain().mObjectPagingActiveGrid)
+1 -1
View File
@@ -17,7 +17,7 @@ namespace MWRender
typedef std::tuple<osg::Vec2f, float, bool> ChunkId; // Center, Size, ActiveGrid
class ObjectPaging : public Resource::GenericResourceManager<ChunkId>, public Terrain::QuadTreeWorld::ChunkManager
class ObjectPaging : public Resource::NodeResourceManager<ChunkId>, public Terrain::QuadTreeWorld::ChunkManager
{
public:
ObjectPaging(Resource::SceneManager* sceneManager, ESM::RefId worldspace);
+1 -1
View File
@@ -102,7 +102,7 @@ namespace MWRender
return mLandManager.get();
}
osg::ref_ptr<const ESMTerrain::LandObject> TerrainStorage::getLand(ESM::ExteriorCellLocation cellLocation)
std::shared_ptr<const ESMTerrain::LandObject> TerrainStorage::getLand(ESM::ExteriorCellLocation cellLocation)
{
return mLandManager->getLand(cellLocation);
}
+1 -1
View File
@@ -21,7 +21,7 @@ namespace MWRender
std::string_view specularMapPattern = {}, bool autoUseSpecularMaps = false);
~TerrainStorage();
osg::ref_ptr<const ESMTerrain::LandObject> getLand(ESM::ExteriorCellLocation cellLocation) override;
std::shared_ptr<const ESMTerrain::LandObject> getLand(ESM::ExteriorCellLocation cellLocation) override;
const VFS::Path::Normalized* getLandTexture(std::uint16_t index, int plugin) override;
const ESM4::LandTexture* getEsm4LandTexture(ESM::RefId ltexId) const override;
+7 -4
View File
@@ -97,7 +97,7 @@ namespace MWWorld
try
{
mTerrain->cacheCell(mTerrainView.get(), mCellLocation.mX, mCellLocation.mY);
mPreloadedObjects.insert(mLandManager->getLand(mCellLocation));
mPreloadedOwnedObjects.insert(mLandManager->getLand(mCellLocation));
}
catch (const std::exception& e)
{
@@ -134,9 +134,9 @@ namespace MWWorld
mPreloadedObjects.insert(mSceneManager->getTemplate(mesh));
if (mPreloadInstances)
mPreloadedObjects.insert(mBulletShapeManager->cacheInstance(mesh));
mPreloadedOwnedObjects.insert(mBulletShapeManager->cacheInstance(mesh));
else
mPreloadedObjects.insert(mBulletShapeManager->getShape(mesh));
mPreloadedOwnedObjects.insert(mBulletShapeManager->getShape(mesh));
}
catch (const std::exception& e)
{
@@ -162,8 +162,11 @@ namespace MWWorld
osg::ref_ptr<Terrain::View> mTerrainView;
// keep a ref to the loaded objects to make sure it stays loaded as long as this cell is in the preloaded state
// Keep the loaded objects alive for as long as this cell is preloaded. Two sets
// because the render-owned ones are still osg::Object; they merge once those move
// behind the render backend.
std::set<osg::ref_ptr<const osg::Object>> mPreloadedObjects;
std::set<std::shared_ptr<const void>> mPreloadedOwnedObjects;
};
class TerrainPreloadItem : public SceneUtil::WorkItem
+3 -3
View File
@@ -442,7 +442,7 @@ namespace MWWorld
if (cellVariant.isExterior())
{
osg::ref_ptr<const ESMTerrain::LandObject> land = mRendering.getLandManager()->getLand(cellIndex);
std::shared_ptr<const ESMTerrain::LandObject> land = mRendering.getLandManager()->getLand(cellIndex);
const ESM::LandData* data = land ? land->getData(ESM::Land::DATA_VHGT) : nullptr;
const int verts = ESM::getLandSize(worldspace);
const int worldsize = ESM::getCellSize(worldspace);
@@ -450,13 +450,13 @@ namespace MWWorld
if (data)
{
mPhysics->addHeightField(data->getHeights().data(), cellX, cellY, worldsize, verts,
data->getMinHeight(), data->getMaxHeight(), land.get());
data->getMinHeight(), data->getMaxHeight(), land);
}
else if (!ESM::isEsm4Ext(worldspace))
{
static const std::vector<float> defaultHeight(verts * verts, ESM::Land::DEFAULT_HEIGHT);
mPhysics->addHeightField(defaultHeight.data(), cellX, cellY, worldsize, verts,
ESM::Land::DEFAULT_HEIGHT, ESM::Land::DEFAULT_HEIGHT, land.get());
ESM::Land::DEFAULT_HEIGHT, ESM::Land::DEFAULT_HEIGHT, land);
}
if (mPhysics->getHeightField(cellX, cellY))
{
+1 -1
View File
@@ -128,7 +128,7 @@ add_component_dir (vfs
)
add_component_dir (resource
scenemanager keyframemanager imagemanager animblendrulesmanager bulletshapemanager bulletshape niffilemanager objectcache multiobjectcache resourcesystem
scenemanager keyframemanager imagemanager animblendrulesmanager bulletshapemanager bulletshape niffilemanager objectcache resourcesystem
resourcemanager stats animation foreachbulletobject errormarker selectionmarker cachestats bgsmfilemanager
)
+4 -3
View File
@@ -3,6 +3,7 @@
#include <cassert>
#include <filesystem>
#include <memory>
#include <optional>
#include "cellgridbounds.hpp"
@@ -37,11 +38,11 @@ namespace DetourNavigator
struct ObjectShapes
{
osg::ref_ptr<const Resource::BulletShapeInstance> mShapeInstance;
std::shared_ptr<const Resource::BulletShapeInstance> mShapeInstance;
ObjectTransform mTransform;
ObjectShapes(
const osg::ref_ptr<const Resource::BulletShapeInstance>& shapeInstance, const ObjectTransform& transform)
const std::shared_ptr<const Resource::BulletShapeInstance>& shapeInstance, const ObjectTransform& transform)
: mShapeInstance(shapeInstance)
, mTransform(transform)
{
@@ -54,7 +55,7 @@ namespace DetourNavigator
osg::Vec3f mConnectionStart;
osg::Vec3f mConnectionEnd;
DoorShapes(const osg::ref_ptr<const Resource::BulletShapeInstance>& shapeInstance,
DoorShapes(const std::shared_ptr<const Resource::BulletShapeInstance>& shapeInstance,
const ObjectTransform& transform, const osg::Vec3f& connectionStart, const osg::Vec3f& connectionEnd)
: ObjectShapes(shapeInstance, transform)
, mConnectionStart(connectionStart)
+2 -1
View File
@@ -4,6 +4,7 @@
#include "areatype.hpp"
#include "objecttransform.hpp"
#include "version.hpp"
#include <memory>
#include <components/resource/bulletshape.hpp>
@@ -119,7 +120,7 @@ namespace DetourNavigator
struct MeshSource
{
osg::ref_ptr<const Resource::BulletShape> mShape;
std::shared_ptr<const Resource::BulletShape> mShape;
ObjectTransform mObjectTransform;
AreaType mAreaType;
};
@@ -1,5 +1,6 @@
#include "recastmeshbuilder.hpp"
#include "exceptions.hpp"
#include <memory>
#include <components/bullethelpers/heightfield.hpp>
#include <components/bullethelpers/processtrianglecallback.hpp>
@@ -138,7 +139,7 @@ namespace DetourNavigator
}
void RecastMeshBuilder::addObject(const btCollisionShape& shape, const btTransform& transform,
const AreaType areaType, osg::ref_ptr<const Resource::BulletShape> source,
const AreaType areaType, std::shared_ptr<const Resource::BulletShape> source,
const ObjectTransform& objectTransform)
{
addObject(shape, transform, areaType);
@@ -41,7 +41,7 @@ namespace DetourNavigator
explicit RecastMeshBuilder(const TileBounds& bounds) noexcept;
void addObject(const btCollisionShape& shape, const btTransform& transform, const AreaType areaType,
osg::ref_ptr<const Resource::BulletShape> source, const ObjectTransform& objectTransform);
std::shared_ptr<const Resource::BulletShape> source, const ObjectTransform& objectTransform);
void addObject(const btCompoundShape& shape, const btTransform& transform, const AreaType areaType);
@@ -3,6 +3,7 @@
#include "areatype.hpp"
#include "objecttransform.hpp"
#include <memory>
#include <components/resource/bulletshape.hpp>
@@ -21,7 +22,7 @@ namespace DetourNavigator
class CollisionShape
{
public:
CollisionShape(osg::ref_ptr<const Resource::BulletShapeInstance> instance, const btCollisionShape& shape,
CollisionShape(std::shared_ptr<const Resource::BulletShapeInstance> instance, const btCollisionShape& shape,
const ObjectTransform& transform)
: mInstance(std::move(instance))
, mShape(shape)
@@ -29,12 +30,12 @@ namespace DetourNavigator
{
}
const osg::ref_ptr<const Resource::BulletShapeInstance>& getInstance() const { return mInstance; }
const std::shared_ptr<const Resource::BulletShapeInstance>& getInstance() const { return mInstance; }
const btCollisionShape& getShape() const { return mShape; }
const ObjectTransform& getObjectTransform() const { return mObjectTransform; }
private:
osg::ref_ptr<const Resource::BulletShapeInstance> mInstance;
std::shared_ptr<const Resource::BulletShapeInstance> mInstance;
std::reference_wrapper<const btCollisionShape> mShape;
ObjectTransform mObjectTransform;
};
@@ -67,7 +68,7 @@ namespace DetourNavigator
bool update(const btTransform& transform, const AreaType areaType) { return mImpl.update(transform, areaType); }
const osg::ref_ptr<const Resource::BulletShapeInstance>& getInstance() const { return mInstance; }
const std::shared_ptr<const Resource::BulletShapeInstance>& getInstance() const { return mInstance; }
const btCollisionShape& getShape() const { return mImpl.getShape(); }
@@ -78,7 +79,7 @@ namespace DetourNavigator
const ObjectTransform& getObjectTransform() const { return mObjectTransform; }
private:
osg::ref_ptr<const Resource::BulletShapeInstance> mInstance;
std::shared_ptr<const Resource::BulletShapeInstance> mInstance;
ObjectTransform mObjectTransform;
ChildRecastMeshObject mImpl;
};
@@ -1,4 +1,5 @@
#include "tilecachedrecastmeshmanager.hpp"
#include <memory>
#include "changetype.hpp"
#include "gettilespositions.hpp"
@@ -515,7 +516,7 @@ namespace DetourNavigator
std::shared_ptr<RecastMesh> TileCachedRecastMeshManager::makeMesh(const TilePosition& tilePosition) const
{
RecastMeshBuilder builder(makeRealTileBoundsWithBorder(mSettings, tilePosition));
using Object = std::tuple<osg::ref_ptr<const Resource::BulletShapeInstance>, ObjectTransform,
using Object = std::tuple<std::shared_ptr<const Resource::BulletShapeInstance>, ObjectTransform,
std::reference_wrapper<const btCollisionShape>, btTransform, AreaType>;
std::vector<Object> objects;
Version version;
+5 -10
View File
@@ -64,7 +64,7 @@ namespace ESMTerrain
return std::nullopt;
}
void insert(int x, int y, osg::ref_ptr<const LandObject>&& value)
void insert(int x, int y, std::shared_ptr<const LandObject>&& value)
{
const std::size_t index = getIndex(x, y);
mValues[index] = std::move(value);
@@ -74,7 +74,7 @@ namespace ESMTerrain
int mOffsetX;
int mOffsetY;
std::size_t mSize;
std::vector<std::optional<osg::ref_ptr<const LandObject>>> mValues;
std::vector<std::optional<std::shared_ptr<const LandObject>>> mValues;
std::size_t getIndex(int x, int y) const
{
@@ -101,11 +101,6 @@ namespace ESMTerrain
{
}
LandObject::LandObject(const LandObject& /*copy*/, const osg::CopyOp& /*copyOp*/)
{
throw std::logic_error("LandObject copy constructor is not implemented");
}
const float defaultHeight = ESM::Land::DEFAULT_HEIGHT;
Storage::Storage(const VFS::Manager* vfs, std::string_view normalMapPattern,
@@ -128,7 +123,7 @@ namespace ESMTerrain
int cellX = static_cast<int>(std::floor(origin.x()));
int cellY = static_cast<int>(std::floor(origin.y()));
osg::ref_ptr<const LandObject> land = getLand(ESM::ExteriorCellLocation(cellX, cellY, worldspace));
std::shared_ptr<const LandObject> land = getLand(ESM::ExteriorCellLocation(cellX, cellY, worldspace));
const ESM::LandData* data = land ? land->getData(ESM::Land::DATA_VHGT) : nullptr;
const int landSize = ESM::getLandSize(worldspace);
int startRow = static_cast<int>((origin.x() - cellX) * landSize);
@@ -573,7 +568,7 @@ namespace ESMTerrain
int cellX = static_cast<int>(std::floor(worldPos.x() / cellSize));
int cellY = static_cast<int>(std::floor(worldPos.y() / cellSize));
osg::ref_ptr<const LandObject> land = getLand(ESM::ExteriorCellLocation(cellX, cellY, worldspace));
std::shared_ptr<const LandObject> land = getLand(ESM::ExteriorCellLocation(cellX, cellY, worldspace));
if (!land)
return ESM::isEsm4Ext(worldspace) ? std::numeric_limits<float>::lowest() : defaultHeight;
@@ -655,7 +650,7 @@ namespace ESMTerrain
{
if (const auto land = cache.find(cellLocation.mX, cellLocation.mY))
return *land;
osg::ref_ptr<const LandObject> land = getLand(cellLocation);
std::shared_ptr<const LandObject> land = getLand(cellLocation);
const LandObject* result = land.get();
cache.insert(cellLocation.mX, cellLocation.mY, std::move(land));
return result;
+3 -8
View File
@@ -38,17 +38,14 @@ namespace ESMTerrain
class LandCache;
/// @brief Wrapper around Land Data with reference counting. The wrapper needs to be held as long as the data is
/// still in use
class LandObject : public osg::Object
/// @brief Wrapper around Land Data. Held as long as the data is still in use.
class LandObject
{
public:
LandObject() = default;
LandObject(const ESM::Land& land, int loadFlags);
LandObject(const ESM4::Land& land, int loadFlags);
META_Object(ESMTerrain, LandObject)
const ESM::LandData* getData(int flags) const
{
if ((mData.getLoadFlags() & flags) != flags)
@@ -65,8 +62,6 @@ namespace ESMTerrain
ESM::LandData mData;
Terrain::LayerInfo mEsm4DefaultLayerInfo;
LandObject(const LandObject& copy, const osg::CopyOp& copyOp);
};
// Since plugins can define new texture palettes, we need to know the plugin index too
@@ -84,7 +79,7 @@ namespace ESMTerrain
std::string_view specularMapPattern = {}, bool autoUseSpecularMaps = false);
// Not implemented in this class, because we need different Store implementations for game and editor
virtual osg::ref_ptr<const LandObject> getLand(ESM::ExteriorCellLocation cellLocation) = 0;
virtual std::shared_ptr<const LandObject> getLand(ESM::ExteriorCellLocation cellLocation) = 0;
virtual const VFS::Path::Normalized* getLandTexture(std::uint16_t index, int plugin) = 0;
// Not implemented in this class because requires ESMStore
+3 -2
View File
@@ -1,4 +1,5 @@
#include "bulletnifloader.hpp"
#include <memory>
#include <cassert>
#include <sstream>
@@ -30,9 +31,9 @@ namespace
namespace NifBullet
{
osg::ref_ptr<Resource::BulletShape> BulletNifLoader::load(Nif::FileView nif)
std::shared_ptr<Resource::BulletShape> BulletNifLoader::load(Nif::FileView nif)
{
mShape = new Resource::BulletShape;
mShape = std::make_shared<Resource::BulletShape>();
mCompoundShape.reset();
mAvoidCompoundShape.reset();
+3 -2
View File
@@ -3,6 +3,7 @@
#include <cassert>
#include <map>
#include <memory>
#include <set>
#include <string>
@@ -45,7 +46,7 @@ namespace NifBullet
abort();
}
osg::ref_ptr<Resource::BulletShape> load(Nif::FileView file);
std::shared_ptr<Resource::BulletShape> load(Nif::FileView file);
private:
bool findBoundingBox(const Nif::NiAVObject& node);
@@ -67,7 +68,7 @@ namespace NifBullet
std::unique_ptr<btCompoundShape, Resource::DeleteCollisionShape> mCompoundShape;
std::unique_ptr<btCompoundShape, Resource::DeleteCollisionShape> mAvoidCompoundShape;
osg::ref_ptr<Resource::BulletShape> mShape;
std::shared_ptr<Resource::BulletShape> mShape;
};
}
@@ -57,11 +57,8 @@ namespace Resource
osg::ref_ptr<const AnimBlendRules> AnimBlendRulesManager::loadRules(VFS::Path::NormalizedView path)
{
std::optional<osg::ref_ptr<osg::Object>> obj = mCache->getRefFromObjectCacheOrNone(path);
if (obj.has_value())
{
return osg::ref_ptr<AnimBlendRules>(static_cast<AnimBlendRules*>(obj->get()));
}
if (std::optional<osg::ref_ptr<const AnimBlendRules>> cached = mCache->getRefFromObjectCacheOrNone(path))
return *cached;
osg::ref_ptr<AnimBlendRules> blendRules = AnimBlendRules::fromFile(mVFS, path);
mCache->addEntryToObjectCache(path.value(), blendRules);
@@ -12,7 +12,7 @@ namespace Resource
{
/// @brief Managing of keyframe resources
/// @note May be used from any thread.
class AnimBlendRulesManager : public ResourceManager
class AnimBlendRulesManager : public ResourceManager<osg::ref_ptr<const SceneUtil::AnimBlendRules>>
{
public:
explicit AnimBlendRulesManager(const VFS::Manager* vfs, double expiryDelay);
+6 -31
View File
@@ -1,7 +1,5 @@
#include "bgsmfilemanager.hpp"
#include <osg/Object>
#include <components/vfs/manager.hpp>
#include "objectcache.hpp"
@@ -9,25 +7,6 @@
namespace Resource
{
class BgsmFileHolder : public osg::Object
{
public:
BgsmFileHolder(const Bgsm::MaterialFilePtr& file)
: mBgsmFile(file)
{
}
BgsmFileHolder(const BgsmFileHolder& copy, const osg::CopyOp& copyop)
: mBgsmFile(copy.mBgsmFile)
{
}
BgsmFileHolder() = default;
META_Object(Resource, BgsmFileHolder)
Bgsm::MaterialFilePtr mBgsmFile;
};
BgsmFileManager::BgsmFileManager(const VFS::Manager* vfs, double expiryDelay)
: ResourceManager(vfs, expiryDelay)
{
@@ -35,16 +14,12 @@ namespace Resource
Bgsm::MaterialFilePtr BgsmFileManager::get(VFS::Path::NormalizedView name)
{
osg::ref_ptr<osg::Object> obj = mCache->getRefFromObjectCache(name);
if (obj)
return static_cast<BgsmFileHolder*>(obj.get())->mBgsmFile;
else
{
Bgsm::MaterialFilePtr file = Bgsm::parse(mVFS->get(name));
obj = new BgsmFileHolder(file);
mCache->addEntryToObjectCache(name.value(), obj);
return file;
}
if (Bgsm::MaterialFilePtr cached = mCache->getRefFromObjectCache(name))
return cached;
Bgsm::MaterialFilePtr file = Bgsm::parse(mVFS->get(name));
mCache->addEntryToObjectCache(name.value(), file);
return file;
}
void BgsmFileManager::reportStats(unsigned int frameNumber, osg::Stats* stats) const
+1 -1
View File
@@ -10,7 +10,7 @@ namespace Resource
/// @brief Handles caching of material files.
/// @note May be used from any thread.
class BgsmFileManager : public ResourceManager
class BgsmFileManager : public ResourceManager<Bgsm::MaterialFilePtr>
{
public:
BgsmFileManager(const VFS::Manager* vfs, double expiryDelay);
+5 -6
View File
@@ -78,9 +78,8 @@ namespace Resource
deleteShape(shape);
}
BulletShape::BulletShape(const BulletShape& other, const osg::CopyOp& copyOp)
: Object(other, copyOp)
, mCollisionShape(duplicateCollisionShape(other.mCollisionShape.get()))
BulletShape::BulletShape(const BulletShape& other)
: mCollisionShape(duplicateCollisionShape(other.mCollisionShape.get()))
, mAvoidCollisionShape(duplicateCollisionShape(other.mAvoidCollisionShape.get()))
, mCollisionBox(other.mCollisionBox)
, mAnimatedShapes(other.mAnimatedShapes)
@@ -97,12 +96,12 @@ namespace Resource
mAvoidCollisionShape->setLocalScaling(scale);
}
osg::ref_ptr<BulletShapeInstance> makeInstance(osg::ref_ptr<const BulletShape> source)
std::shared_ptr<BulletShapeInstance> makeInstance(std::shared_ptr<const BulletShape> source)
{
return { new BulletShapeInstance(std::move(source)) };
return std::make_shared<BulletShapeInstance>(std::move(source));
}
BulletShapeInstance::BulletShapeInstance(osg::ref_ptr<const BulletShape> source)
BulletShapeInstance::BulletShapeInstance(std::shared_ptr<const BulletShape> source)
: BulletShape(*source)
, mSource(std::move(source))
{
+7 -11
View File
@@ -4,9 +4,7 @@
#include <map>
#include <memory>
#include <osg/Object>
#include <osg/Vec3f>
#include <osg/ref_ptr>
#include <BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h>
#include <BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h>
@@ -42,7 +40,7 @@ namespace Resource
Camera
};
struct BulletShape : public osg::Object
struct BulletShape
{
CollisionShapePtr mCollisionShape;
CollisionShapePtr mAvoidCollisionShape;
@@ -64,9 +62,7 @@ namespace Resource
BulletShape() = default;
// Note this is always a shallow copy and the copy will not autodelete underlying vertex data
BulletShape(const BulletShape& other, const osg::CopyOp& copyOp = osg::CopyOp());
META_Object(Resource, BulletShape)
BulletShape(const BulletShape& other);
void setLocalScaling(const btVector3& scale);
@@ -74,20 +70,20 @@ namespace Resource
};
// An instance of a BulletShape that may have its own unique scaling set on collision shapes.
// Vertex data is shallow-copied where possible. A ref_ptr to the original shape is held to keep vertex pointers
// Vertex data is shallow-copied where possible. A shared_ptr to the original shape is held to keep vertex pointers
// intact.
class BulletShapeInstance : public BulletShape
{
public:
explicit BulletShapeInstance(osg::ref_ptr<const BulletShape> source);
explicit BulletShapeInstance(std::shared_ptr<const BulletShape> source);
const osg::ref_ptr<const BulletShape>& getSource() const { return mSource; }
const std::shared_ptr<const BulletShape>& getSource() const { return mSource; }
private:
osg::ref_ptr<const BulletShape> mSource;
std::shared_ptr<const BulletShape> mSource;
};
osg::ref_ptr<BulletShapeInstance> makeInstance(osg::ref_ptr<const BulletShape> source);
std::shared_ptr<BulletShapeInstance> makeInstance(std::shared_ptr<const BulletShape> source);
// Subclass btBhvTriangleMeshShape to auto-delete the meshInterface
struct TriangleMeshShape : public btBvhTriangleMeshShape
+21 -20
View File
@@ -1,4 +1,5 @@
#include "bulletshapemanager.hpp"
#include <memory>
#include <cstring>
@@ -72,12 +73,12 @@ namespace Resource
drawable.accept(functor);
}
osg::ref_ptr<BulletShape> getShape()
std::shared_ptr<BulletShape> getShape()
{
if (!mTriangleMesh || mTriangleMesh->getNumTriangles() == 0)
return osg::ref_ptr<BulletShape>();
return std::shared_ptr<BulletShape>();
osg::ref_ptr<BulletShape> shape(new BulletShape);
auto shape = std::make_shared<BulletShape>();
auto triangleMeshShape = std::make_unique<TriangleMeshShape>(mTriangleMesh.release(), true);
btVector3 aabbMin = triangleMeshShape->getLocalAabbMin();
@@ -99,7 +100,7 @@ namespace Resource
BulletShapeManager::BulletShapeManager(
const VFS::Manager* vfs, SceneManager* sceneMgr, NifFileManager* nifFileManager, double expiryDelay)
: ResourceManager(vfs, expiryDelay)
, mInstanceCache(std::make_unique<MultiObjectCache>())
, mInstanceCache(std::make_unique<MultiObjectCache<std::shared_ptr<BulletShapeInstance>>>())
, mSceneManager(sceneMgr)
, mNifFileManager(nifFileManager)
{
@@ -107,12 +108,12 @@ namespace Resource
BulletShapeManager::~BulletShapeManager() = default;
osg::ref_ptr<const BulletShape> BulletShapeManager::getShape(VFS::Path::NormalizedView name)
std::shared_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()));
if (std::shared_ptr<const BulletShape> cached = mCache->getRefFromObjectCache(name))
return cached;
osg::ref_ptr<BulletShape> shape;
std::shared_ptr<BulletShape> shape;
if (Misc::getFileExtension(name.value()) == "nif")
{
@@ -149,7 +150,7 @@ namespace Resource
node->accept(visitor);
shape = visitor.getShape();
if (!shape)
return osg::ref_ptr<BulletShape>();
return std::shared_ptr<BulletShape>();
}
if (shape != nullptr)
@@ -164,38 +165,38 @@ namespace Resource
return shape;
}
osg::ref_ptr<BulletShapeInstance> BulletShapeManager::cacheInstance(VFS::Path::NormalizedView name)
std::shared_ptr<BulletShapeInstance> BulletShapeManager::cacheInstance(VFS::Path::NormalizedView name)
{
osg::ref_ptr<BulletShapeInstance> instance = createInstance(name);
std::shared_ptr<BulletShapeInstance> instance = createInstance(name);
if (instance != nullptr)
mInstanceCache->addEntryToObjectCache(name, instance.get());
mInstanceCache->addEntryToObjectCache(name, instance);
return instance;
}
osg::ref_ptr<BulletShapeInstance> BulletShapeManager::getInstance(VFS::Path::NormalizedView name)
std::shared_ptr<BulletShapeInstance> BulletShapeManager::getInstance(VFS::Path::NormalizedView name)
{
if (osg::ref_ptr<osg::Object> obj = mInstanceCache->takeFromObjectCache(name))
return static_cast<BulletShapeInstance*>(obj.get());
if (std::shared_ptr<BulletShapeInstance> cached = mInstanceCache->takeFromObjectCache(name))
return cached;
return createInstance(name);
}
osg::ref_ptr<BulletShapeInstance> BulletShapeManager::createInstance(VFS::Path::NormalizedView name)
std::shared_ptr<BulletShapeInstance> BulletShapeManager::createInstance(VFS::Path::NormalizedView name)
{
if (osg::ref_ptr<const BulletShape> shape = getShape(name))
if (std::shared_ptr<const BulletShape> shape = getShape(name))
return makeInstance(std::move(shape));
return osg::ref_ptr<BulletShapeInstance>();
return std::shared_ptr<BulletShapeInstance>();
}
void BulletShapeManager::updateCache(double referenceTime)
{
ResourceManager::updateCache(referenceTime);
ResourceManager<std::shared_ptr<const BulletShape>>::updateCache(referenceTime);
mInstanceCache->removeUnreferencedObjectsInCache();
}
void BulletShapeManager::clearCache()
{
ResourceManager::clearCache();
ResourceManager<std::shared_ptr<const BulletShape>>::clearCache();
mInstanceCache->clear();
}
+9 -10
View File
@@ -8,6 +8,7 @@
#include <components/vfs/pathutil.hpp>
#include "bulletshape.hpp"
#include "multiobjectcache.hpp"
#include "resourcemanager.hpp"
namespace Resource
@@ -18,12 +19,10 @@ namespace Resource
struct BulletShape;
class BulletShapeInstance;
class MultiObjectCache;
/// Handles loading, caching and "instancing" of bullet shapes.
/// A shape 'instance' is a clone of another shape, with the goal of setting a different scale on this instance.
/// @note May be used from any thread.
class BulletShapeManager : public ResourceManager
class BulletShapeManager : public ResourceManager<std::shared_ptr<const BulletShape>>
{
public:
BulletShapeManager(
@@ -31,16 +30,16 @@ namespace Resource
~BulletShapeManager();
/// @note May return a null pointer if the object has no shape.
osg::ref_ptr<const BulletShape> getShape(VFS::Path::NormalizedView name);
std::shared_ptr<const BulletShape> getShape(VFS::Path::NormalizedView name);
/// Create an instance of the given shape and cache it for later use, so that future calls to getInstance() can
/// simply return the cached instance instead of having to create a new one.
/// @note The returned ref_ptr may be kept by the caller to ensure that the instance stays in cache for as long
/// as needed.
osg::ref_ptr<BulletShapeInstance> cacheInstance(VFS::Path::NormalizedView name);
/// @note The returned shared_ptr may be kept by the caller to ensure that the instance stays in cache for as
/// long as needed.
std::shared_ptr<BulletShapeInstance> cacheInstance(VFS::Path::NormalizedView name);
/// @note May return a null pointer if the object has no shape.
osg::ref_ptr<BulletShapeInstance> getInstance(VFS::Path::NormalizedView name);
std::shared_ptr<BulletShapeInstance> getInstance(VFS::Path::NormalizedView name);
/// @see ResourceManager::updateCache
void updateCache(double referenceTime) override;
@@ -50,9 +49,9 @@ namespace Resource
void reportStats(unsigned int frameNumber, osg::Stats* stats) const override;
private:
osg::ref_ptr<BulletShapeInstance> createInstance(VFS::Path::NormalizedView name);
std::shared_ptr<BulletShapeInstance> createInstance(VFS::Path::NormalizedView name);
std::unique_ptr<MultiObjectCache> mInstanceCache;
std::unique_ptr<MultiObjectCache<std::shared_ptr<BulletShapeInstance>>> mInstanceCache;
SceneManager* mSceneManager;
NifFileManager* mNifFileManager;
};
+3 -2
View File
@@ -1,4 +1,5 @@
#include "foreachbulletobject.hpp"
#include <memory>
#include <components/debug/debuglog.hpp>
#include <components/esm3/cellref.hpp>
@@ -100,7 +101,7 @@ namespace Resource
if (cellRef.mType != ESM::REC_STAT)
model = Misc::ResourceHelpers::correctActorModelPath(model, &vfs);
osg::ref_ptr<const Resource::BulletShape> shape = [&] {
std::shared_ptr<const Resource::BulletShape> shape = [&] {
try
{
constexpr VFS::Path::NormalizedView prefix("meshes");
@@ -110,7 +111,7 @@ namespace Resource
{
Log(Debug::Warning) << "Failed to load cell ref \"" << cellRef.mRefId << "\" model \"" << model
<< "\": " << e.what();
return osg::ref_ptr<const Resource::BulletShape>();
return std::shared_ptr<const Resource::BulletShape>();
}
}();
+2 -1
View File
@@ -3,6 +3,7 @@
#include <components/esm/position.hpp>
#include <components/resource/bulletshape.hpp>
#include <memory>
#include <osg/ref_ptr>
@@ -34,7 +35,7 @@ namespace Resource
{
struct BulletObject
{
osg::ref_ptr<const Resource::BulletShape> mShape;
std::shared_ptr<const Resource::BulletShape> mShape;
ESM::Position mPosition;
float mScale;
};
+1 -1
View File
@@ -19,7 +19,7 @@ namespace Resource
/// @brief Handles loading/caching of Images.
/// @note May be used from any thread.
class ImageManager : public ResourceManager
class ImageManager : public ResourceManager<osg::ref_ptr<osg::Image>>
{
public:
explicit ImageManager(const VFS::Manager* vfs, double expiryDelay);
+2 -4
View File
@@ -209,10 +209,8 @@ namespace Resource
osg::ref_ptr<const SceneUtil::KeyframeHolder> KeyframeManager::get(VFS::Path::NormalizedView name)
{
osg::ref_ptr<osg::Object> obj = mCache->getRefFromObjectCache(name);
if (obj != nullptr)
return osg::ref_ptr<const SceneUtil::KeyframeHolder>(static_cast<SceneUtil::KeyframeHolder*>(obj.get()));
if (osg::ref_ptr<const SceneUtil::KeyframeHolder> cached = mCache->getRefFromObjectCache(name))
return cached;
osg::ref_ptr<SceneUtil::KeyframeHolder> loaded(new SceneUtil::KeyframeHolder);
constexpr VFS::Path::ExtensionView kf("kf");
+1 -1
View File
@@ -47,7 +47,7 @@ namespace Resource
/// @brief Managing of keyframe resources
/// @note May be used from any thread.
class KeyframeManager : public ResourceManager
class KeyframeManager : public ResourceManager<osg::ref_ptr<const SceneUtil::KeyframeHolder>>
{
public:
explicit KeyframeManager(const VFS::Manager* vfs, SceneManager* sceneManager, double expiryDelay,
-91
View File
@@ -1,91 +0,0 @@
#include "multiobjectcache.hpp"
#include <vector>
#include <osg/Object>
namespace Resource
{
void MultiObjectCache::removeUnreferencedObjectsInCache()
{
std::vector<osg::ref_ptr<osg::Object>> objectsToRemove;
{
std::lock_guard<std::mutex> lock(mObjectCacheMutex);
// Remove unreferenced entries from object cache
ObjectCacheMap::iterator oitr = mObjectCache.begin();
while (oitr != mObjectCache.end())
{
if (oitr->second->referenceCount() <= 1)
{
objectsToRemove.push_back(oitr->second);
mObjectCache.erase(oitr++);
++mExpired;
}
else
{
++oitr;
}
}
}
// note, actual unref happens outside of the lock
objectsToRemove.clear();
}
void MultiObjectCache::clear()
{
std::lock_guard<std::mutex> lock(mObjectCacheMutex);
mObjectCache.clear();
}
void MultiObjectCache::addEntryToObjectCache(VFS::Path::NormalizedView filename, osg::Object* object)
{
if (!object)
{
OSG_ALWAYS << " trying to add NULL object to cache for " << filename << std::endl;
return;
}
std::lock_guard<std::mutex> lock(mObjectCacheMutex);
mObjectCache.emplace(filename, object);
}
osg::ref_ptr<osg::Object> MultiObjectCache::takeFromObjectCache(VFS::Path::NormalizedView fileName)
{
std::lock_guard<std::mutex> lock(mObjectCacheMutex);
++mGet;
const auto it = mObjectCache.find(fileName);
if (it != mObjectCache.end())
{
osg::ref_ptr<osg::Object> object = std::move(it->second);
mObjectCache.erase(it);
++mHit;
return object;
}
return nullptr;
}
void MultiObjectCache::releaseGLObjects(osg::State* state)
{
std::lock_guard<std::mutex> lock(mObjectCacheMutex);
for (ObjectCacheMap::iterator itr = mObjectCache.begin(); itr != mObjectCache.end(); ++itr)
{
osg::Object* object = itr->second.get();
object->releaseGLObjects(state);
}
}
CacheStats MultiObjectCache::getStats() const
{
std::lock_guard<std::mutex> lock(mObjectCacheMutex);
return CacheStats{
.mSize = mObjectCache.size(),
.mGet = mGet,
.mHit = mHit,
.mExpired = mExpired,
};
}
}
+81 -14
View File
@@ -3,43 +3,111 @@
#include <map>
#include <mutex>
#include <utility>
#include <vector>
#include <osg/ref_ptr>
#include <components/debug/debuglog.hpp>
#include <components/vfs/pathutil.hpp>
#include "cachestats.hpp"
#include "objectcache.hpp"
namespace osg
{
class Object;
class State;
}
namespace Resource
{
/// @brief Cache for "non reusable" objects.
/// @brief Cache for "non reusable" objects. Templated on its value type for the
/// same reason GenericObjectCache is; see objectcache.hpp.
template <class ValueType>
class MultiObjectCache
{
public:
void removeUnreferencedObjectsInCache();
void removeUnreferencedObjectsInCache()
{
std::vector<ValueType> objectsToRemove;
{
std::lock_guard<std::mutex> lock(mObjectCacheMutex);
auto oitr = mObjectCache.begin();
while (oitr != mObjectCache.end())
{
if (useCount(oitr->second) <= 1)
{
objectsToRemove.push_back(oitr->second);
mObjectCache.erase(oitr++);
++mExpired;
}
else
{
++oitr;
}
}
}
// note, actual release happens outside of the lock
objectsToRemove.clear();
}
/** Remove all objects from the cache. */
void clear();
void clear()
{
std::lock_guard<std::mutex> lock(mObjectCacheMutex);
mObjectCache.clear();
}
void addEntryToObjectCache(VFS::Path::NormalizedView filename, osg::Object* object);
void addEntryToObjectCache(VFS::Path::NormalizedView filename, ValueType object)
{
if (object == nullptr)
{
Log(Debug::Warning) << "Trying to add NULL object to cache for " << filename;
return;
}
std::lock_guard<std::mutex> lock(mObjectCacheMutex);
mObjectCache.emplace(filename, std::move(object));
}
/** Take an Object from cache. Return nullptr if no object found. */
osg::ref_ptr<osg::Object> takeFromObjectCache(VFS::Path::NormalizedView fileName);
/** Take an object from cache. Return nullptr if no object found. */
ValueType takeFromObjectCache(VFS::Path::NormalizedView fileName)
{
std::lock_guard<std::mutex> lock(mObjectCacheMutex);
++mGet;
const auto it = mObjectCache.find(fileName);
if (it != mObjectCache.end())
{
ValueType object = std::move(it->second);
mObjectCache.erase(it);
++mHit;
return object;
}
/** call releaseGLObjects on all objects attached to the object cache.*/
void releaseGLObjects(osg::State* state);
return ValueType();
}
CacheStats getStats() const;
/** call releaseGLObjects on all objects attached to the object cache. */
void releaseGLObjects(osg::State* state) requires ReleasesGLObjects<ValueType>
{
std::lock_guard<std::mutex> lock(mObjectCacheMutex);
for (const auto& [key, value] : mObjectCache)
value->releaseGLObjects(state);
}
CacheStats getStats() const
{
std::lock_guard<std::mutex> lock(mObjectCacheMutex);
return CacheStats{
.mSize = mObjectCache.size(),
.mGet = mGet,
.mHit = mHit,
.mExpired = mExpired,
};
}
protected:
typedef std::multimap<VFS::Path::Normalized, osg::ref_ptr<osg::Object>, std::less<>> ObjectCacheMap;
using ObjectCacheMap = std::multimap<VFS::Path::Normalized, ValueType, std::less<>>;
ObjectCacheMap mObjectCache;
mutable std::mutex mObjectCacheMutex;
@@ -47,7 +115,6 @@ namespace Resource
std::size_t mHit = 0;
std::size_t mExpired = 0;
};
}
#endif
+3 -26
View File
@@ -2,8 +2,6 @@
#include <iostream>
#include <osg/Object>
#include <components/vfs/manager.hpp>
#include "objectcache.hpp"
@@ -11,25 +9,6 @@
namespace Resource
{
class NifFileHolder : public osg::Object
{
public:
NifFileHolder(const Nif::NIFFilePtr& file)
: mNifFile(file)
{
}
NifFileHolder(const NifFileHolder& copy, const osg::CopyOp& copyop)
: mNifFile(copy.mNifFile)
{
}
NifFileHolder() = default;
META_Object(Resource, NifFileHolder)
Nif::NIFFilePtr mNifFile;
};
NifFileManager::NifFileManager(const VFS::Manager* vfs, const ToUTF8::StatelessUtf8Encoder* encoder)
// NIF files aren't needed any more once the converted objects are cached in SceneManager / BulletShapeManager,
// so no point in using an expiry delay.
@@ -42,15 +21,13 @@ namespace Resource
Nif::NIFFilePtr NifFileManager::get(VFS::Path::NormalizedView name)
{
osg::ref_ptr<osg::Object> obj = mCache->getRefFromObjectCache(name);
if (obj != nullptr)
return static_cast<NifFileHolder*>(obj.get())->mNifFile;
if (Nif::NIFFilePtr cached = mCache->getRefFromObjectCache(name))
return cached;
auto file = std::make_shared<Nif::NIFFile>(name);
Nif::Reader reader(*file, mEncoder);
reader.parse(mVFS->get(name));
obj = new NifFileHolder(file);
mCache->addEntryToObjectCache(name.value(), obj);
mCache->addEntryToObjectCache(name.value(), file);
return file;
}
+1 -1
View File
@@ -15,7 +15,7 @@ namespace Resource
/// @brief Handles caching of NIFFiles.
/// @note May be used from any thread.
class NifFileManager : public ResourceManager
class NifFileManager : public ResourceManager<Nif::NIFFilePtr>
{
const ToUTF8::StatelessUtf8Encoder* mEncoder;
+58 -17
View File
@@ -27,9 +27,11 @@
#include <algorithm>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <type_traits>
#include <vector>
namespace osg
@@ -42,13 +44,49 @@ namespace osg
namespace Resource
{
// How the cache asks "is anything outside the cache still holding this?".
//
// Free overloads rather than a member, so the cache never has to name a base
// class its values are expected to derive from. This is the extension point: a
// value type the cache has not seen before is supported by adding an overload
// here, not by changing the cache or the type. A second rendering backend would
// add one for its own pointer, since scene-graph objects must be owned by the
// pointer their library refs them with — a graph holds references to its own
// children, so a second refcount over the same object would be a bug, not a
// design choice.
template <class T>
long useCount(const std::shared_ptr<T>& value)
{
return value.use_count();
}
template <class T>
long useCount(const osg::ref_ptr<T>& value)
{
// nullptr is a storable value, so this has to answer for it; shared_ptr's
// use_count() already returns 0 for an empty pointer.
return value == nullptr ? 0 : value->referenceCount();
}
// The two things a value type may or may not be able to do. Named, because an
// inline requires-expression on the member declaration formats unreadably.
template <class T>
concept ReleasesGLObjects = requires(T value, osg::State* state)
{
value->releaseGLObjects(state);
};
template <class T>
concept HoldsOsgObject = std::is_convertible_v<decltype(std::declval<T>().get()), osg::Object*>;
template <class ValueType>
struct GenericObjectCacheItem
{
osg::ref_ptr<osg::Object> mValue;
ValueType mValue;
double mLastUsage;
};
template <typename KeyType>
template <typename KeyType, typename ValueType>
class GenericObjectCache
{
public:
@@ -68,7 +106,7 @@ namespace Resource
*/
void update(double referenceTime, double expiryDelay)
{
std::vector<osg::ref_ptr<osg::Object>> objectsToRemove;
std::vector<ValueType> objectsToRemove;
{
const double expiryTime = referenceTime - expiryDelay;
std::lock_guard<std::mutex> lock(mMutex);
@@ -78,7 +116,7 @@ namespace Resource
// update last usage timestamp if item is being referenced externally
// or initialize if not set
if ((item.mValue != nullptr && item.mValue->referenceCount() > 1) || item.mLastUsage == 0)
if (useCount(item.mValue) > 1 || item.mLastUsage == 0)
item.mLastUsage = referenceTime;
// skip items that have been accessed since expiryTime
@@ -107,14 +145,14 @@ namespace Resource
/** Add a key,object,timestamp triple to the Registry::ObjectCache.*/
template <class K>
void addEntryToObjectCache(K&& key, osg::Object* object, double timestamp = 0.0)
void addEntryToObjectCache(K&& key, ValueType object, double timestamp = 0.0)
{
std::lock_guard<std::mutex> lock(mMutex);
const auto it = mItems.find(key);
if (it == mItems.end())
mItems.emplace_hint(it, std::forward<K>(key), Item{ object, timestamp });
mItems.emplace_hint(it, std::forward<K>(key), Item{ std::move(object), timestamp });
else
it->second = Item{ object, timestamp };
it->second = Item{ std::move(object), timestamp };
}
/** Remove Object from cache.*/
@@ -126,16 +164,16 @@ namespace Resource
mItems.erase(itr);
}
/** Get an ref_ptr<Object> from the object cache*/
osg::ref_ptr<osg::Object> getRefFromObjectCache(const auto& key)
/** Get a value from the object cache; a default-constructed one if absent. */
ValueType getRefFromObjectCache(const auto& key)
{
std::lock_guard<std::mutex> lock(mMutex);
if (Item* const item = find(key))
return item->mValue;
return nullptr;
return ValueType();
}
std::optional<osg::ref_ptr<osg::Object>> getRefFromObjectCacheOrNone(const auto& key)
std::optional<ValueType> getRefFromObjectCacheOrNone(const auto& key)
{
const std::lock_guard<std::mutex> lock(mMutex);
if (Item* const item = find(key))
@@ -155,16 +193,19 @@ namespace Resource
return false;
}
/** call releaseGLObjects on all objects attached to the object cache.*/
void releaseGLObjects(osg::State* state)
/** call releaseGLObjects on all objects attached to the object cache.
Constrained, so instantiating the cache with a value type that has no such
method is not an error — it simply does not offer this. */
void releaseGLObjects(osg::State* state) requires ReleasesGLObjects<ValueType>
{
std::lock_guard<std::mutex> lock(mMutex);
for (const auto& [k, v] : mItems)
v.mValue->releaseGLObjects(state);
}
/** call node->accept(nv); for all nodes in the objectCache. */
void accept(osg::NodeVisitor& nv)
/** call node->accept(nv); for all nodes in the objectCache. Constrained for
the same reason as releaseGLObjects. */
void accept(osg::NodeVisitor& nv) requires HoldsOsgObject<ValueType>
{
std::lock_guard<std::mutex> lock(mMutex);
for (const auto& [k, v] : mItems)
@@ -183,7 +224,7 @@ namespace Resource
}
template <class K>
std::optional<std::pair<KeyType, osg::ref_ptr<osg::Object>>> lowerBound(K&& key)
std::optional<std::pair<KeyType, ValueType>> lowerBound(K&& key)
{
const std::lock_guard<std::mutex> lock(mMutex);
const auto it = mItems.lower_bound(std::forward<K>(key));
@@ -204,7 +245,7 @@ namespace Resource
}
protected:
using Item = GenericObjectCacheItem;
using Item = GenericObjectCacheItem<ValueType>;
std::map<KeyType, Item, std::less<>> mItems;
mutable std::mutex mMutex;
+21 -5
View File
@@ -3,6 +3,7 @@
#include <memory>
#include <osg/Node>
#include <osg/ref_ptr>
#include <components/vfs/pathutil.hpp>
@@ -37,11 +38,11 @@ namespace Resource
/// @brief Base class for managers that require a virtual file system and object cache.
/// @par This base class implements clearing of the cache, but populating it and what it's used for is up to the
/// individual sub classes.
template <class KeyType>
template <class KeyType, class ValueType>
class GenericResourceManager : public BaseResourceManager
{
public:
typedef GenericObjectCache<KeyType> CacheType;
typedef GenericObjectCache<KeyType, ValueType> CacheType;
explicit GenericResourceManager(const VFS::Manager* vfs, double expiryDelay)
: mVFS(vfs)
@@ -66,7 +67,12 @@ namespace Resource
void reportStats(unsigned int frameNumber, osg::Stats* stats) const override {}
void releaseGLObjects(osg::State* state) override { mCache->releaseGLObjects(state); }
void releaseGLObjects(osg::State* state) override
{
// Only meaningful for caches whose values are GL-backed; see objectcache.hpp.
if constexpr (requires { mCache->releaseGLObjects(state); })
mCache->releaseGLObjects(state);
}
protected:
const VFS::Manager* mVFS;
@@ -74,13 +80,23 @@ namespace Resource
double mExpiryDelay;
};
class ResourceManager : public GenericResourceManager<std::string>
/// Caching a scene graph is the common case, so it gets a name rather than the
/// same template arguments at every use.
template <class KeyType>
using NodeResourceManager = GenericResourceManager<KeyType, osg::ref_ptr<osg::Node>>;
template <class ValueType>
class ResourceManager : public GenericResourceManager<std::string, ValueType>
{
public:
explicit ResourceManager(const VFS::Manager* vfs, double expiryDelay)
: GenericResourceManager(vfs, expiryDelay)
: GenericResourceManager<std::string, ValueType>(vfs, expiryDelay)
{
}
protected:
using GenericResourceManager<std::string, ValueType>::mCache;
using GenericResourceManager<std::string, ValueType>::mVFS;
};
}
+3 -3
View File
@@ -494,7 +494,7 @@ namespace Resource
SceneManager::SceneManager(const VFS::Manager* vfs, Resource::ImageManager* imageManager,
Resource::NifFileManager* nifFileManager, Resource::BgsmFileManager* bgsmFileManager, double expiryDelay)
: ResourceManager(vfs, expiryDelay)
: NodeResourceManager<std::string>(vfs, expiryDelay)
, mShaderManager(new Shader::ShaderManager)
, mSharedStateManager(new SharedStateManager)
, mImageManager(imageManager)
@@ -1197,7 +1197,7 @@ namespace Resource
void SceneManager::updateCache(double referenceTime)
{
ResourceManager::updateCache(referenceTime);
NodeResourceManager<std::string>::updateCache(referenceTime);
mSharedStateMutex.lock();
mSharedStateManager->prune();
@@ -1225,7 +1225,7 @@ namespace Resource
void SceneManager::clearCache()
{
ResourceManager::clearCache();
NodeResourceManager<std::string>::clearCache();
std::lock_guard<std::mutex> lock(mSharedStateMutex);
mSharedStateManager->clearCache();
+1 -1
View File
@@ -87,7 +87,7 @@ namespace Resource
/// @brief Handles loading and caching of scenes, e.g. .nif files or .osg files
/// @note Some methods of the scene manager can be used from any thread, see the methods documentation for more
/// details.
class SceneManager : public ResourceManager
class SceneManager : public NodeResourceManager<std::string>
{
public:
explicit SceneManager(const VFS::Manager* vfs, Resource::ImageManager* imageManager,
+3 -3
View File
@@ -38,7 +38,7 @@ namespace Terrain
ChunkManager::ChunkManager(Storage* storage, Resource::SceneManager* sceneMgr, TextureManager* textureManager,
CompositeMapRenderer* renderer, ESM::RefId worldspace, double expiryDelay)
: GenericResourceManager<ChunkKey>(nullptr, expiryDelay)
: Resource::NodeResourceManager<ChunkKey>(nullptr, expiryDelay)
, QuadTreeWorld::ChunkManager(worldspace)
, mStorage(storage)
, mSceneManager(sceneMgr)
@@ -93,14 +93,14 @@ namespace Terrain
void ChunkManager::clearCache()
{
GenericResourceManager<ChunkKey>::clearCache();
Resource::NodeResourceManager<ChunkKey>::clearCache();
mBufferCache.clearCache();
}
void ChunkManager::releaseGLObjects(osg::State* state)
{
GenericResourceManager<ChunkKey>::releaseGLObjects(state);
Resource::NodeResourceManager<ChunkKey>::releaseGLObjects(state);
mBufferCache.releaseGLObjects(state);
}
+1 -1
View File
@@ -72,7 +72,7 @@ namespace Terrain
}
/// @brief Handles loading and caching of terrain chunks
class ChunkManager : public Resource::GenericResourceManager<ChunkKey>, public QuadTreeWorld::ChunkManager
class ChunkManager : public Resource::NodeResourceManager<ChunkKey>, public QuadTreeWorld::ChunkManager
{
public:
explicit ChunkManager(Storage* storage, Resource::SceneManager* sceneMgr, TextureManager* textureManager,
+1 -1
View File
@@ -10,7 +10,7 @@ namespace Terrain
{
TextureManager::TextureManager(Resource::SceneManager* sceneMgr, double expiryDelay)
: ResourceManager(sceneMgr->getVFS(), expiryDelay)
: ResourceManager<osg::ref_ptr<osg::Texture2D>>(sceneMgr->getVFS(), expiryDelay)
, mSceneManager(sceneMgr)
{
}
+3 -6
View File
@@ -1,6 +1,8 @@
#ifndef OPENMW_COMPONENTS_TERRAIN_TEXTUREMANAGER_H
#define OPENMW_COMPONENTS_TERRAIN_TEXTUREMANAGER_H
#include <osg/Texture2D>
#include <components/resource/resourcemanager.hpp>
#include <components/vfs/pathutil.hpp>
@@ -9,15 +11,10 @@ namespace Resource
class SceneManager;
}
namespace osg
{
class Texture2D;
}
namespace Terrain
{
class TextureManager : public Resource::ResourceManager
class TextureManager : public Resource::ResourceManager<osg::ref_ptr<osg::Texture2D>>
{
public:
explicit TextureManager(Resource::SceneManager* sceneMgr, double expiryDelay);