From 4addabaf95e5fba4ae3853cf9512c858558b9e4e Mon Sep 17 00:00:00 2001 From: Bret Curtis Date: Fri, 18 Sep 2026 14:31:26 +0200 Subject: [PATCH] Let the resource cache be told what it stores, and free its values from OSG GenericObjectCache stored osg::ref_ptr, 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. --- apps/components_tests/CMakeLists.txt | 1 + .../detournavigator/asyncnavmeshupdater.cpp | 6 +- .../detournavigator/navigator.cpp | 14 +-- .../detournavigator/recastmeshbuilder.cpp | 3 +- .../tilecachedrecastmeshmanager.cpp | 6 +- .../resource/testmultiobjectcache.cpp | 98 +++++++++++++++++++ .../resource/testobjectcache.cpp | 92 ++++++++++++----- apps/navmeshtool/worldspacedata.cpp | 6 +- apps/navmeshtool/worldspacedata.hpp | 9 +- apps/opencs/view/render/terrainstorage.cpp | 4 +- apps/opencs/view/render/terrainstorage.hpp | 2 +- apps/openmw/mwphysics/actor.cpp | 10 +- apps/openmw/mwphysics/actor.hpp | 2 +- apps/openmw/mwphysics/heightfield.cpp | 2 +- apps/openmw/mwphysics/heightfield.hpp | 9 +- apps/openmw/mwphysics/object.cpp | 7 +- apps/openmw/mwphysics/object.hpp | 9 +- apps/openmw/mwphysics/physicssystem.cpp | 16 +-- apps/openmw/mwphysics/physicssystem.hpp | 7 +- apps/openmw/mwrender/groundcover.cpp | 2 +- apps/openmw/mwrender/groundcover.hpp | 2 +- apps/openmw/mwrender/landmanager.cpp | 17 ++-- apps/openmw/mwrender/landmanager.hpp | 5 +- apps/openmw/mwrender/objectpaging.cpp | 2 +- apps/openmw/mwrender/objectpaging.hpp | 2 +- apps/openmw/mwrender/terrainstorage.cpp | 2 +- apps/openmw/mwrender/terrainstorage.hpp | 2 +- apps/openmw/mwworld/cellpreloader.cpp | 11 ++- apps/openmw/mwworld/scene.cpp | 6 +- components/CMakeLists.txt | 2 +- components/detournavigator/navigator.hpp | 7 +- components/detournavigator/recastmesh.hpp | 3 +- .../detournavigator/recastmeshbuilder.cpp | 3 +- .../detournavigator/recastmeshbuilder.hpp | 2 +- .../detournavigator/recastmeshobject.hpp | 11 ++- .../tilecachedrecastmeshmanager.cpp | 3 +- components/esmterrain/storage.cpp | 15 +-- components/esmterrain/storage.hpp | 11 +-- components/nifbullet/bulletnifloader.cpp | 5 +- components/nifbullet/bulletnifloader.hpp | 5 +- components/resource/animblendrulesmanager.cpp | 7 +- components/resource/animblendrulesmanager.hpp | 2 +- components/resource/bgsmfilemanager.cpp | 37 ++----- components/resource/bgsmfilemanager.hpp | 2 +- components/resource/bulletshape.cpp | 11 +-- components/resource/bulletshape.hpp | 18 ++-- components/resource/bulletshapemanager.cpp | 41 ++++---- components/resource/bulletshapemanager.hpp | 19 ++-- components/resource/foreachbulletobject.cpp | 5 +- components/resource/foreachbulletobject.hpp | 3 +- components/resource/imagemanager.hpp | 2 +- components/resource/keyframemanager.cpp | 6 +- components/resource/keyframemanager.hpp | 2 +- components/resource/multiobjectcache.cpp | 91 ----------------- components/resource/multiobjectcache.hpp | 95 +++++++++++++++--- components/resource/niffilemanager.cpp | 29 +----- components/resource/niffilemanager.hpp | 2 +- components/resource/objectcache.hpp | 75 ++++++++++---- components/resource/resourcemanager.hpp | 26 ++++- components/resource/scenemanager.cpp | 6 +- components/resource/scenemanager.hpp | 2 +- components/terrain/chunkmanager.cpp | 6 +- components/terrain/chunkmanager.hpp | 2 +- components/terrain/texturemanager.cpp | 2 +- components/terrain/texturemanager.hpp | 9 +- 65 files changed, 527 insertions(+), 394 deletions(-) create mode 100644 apps/components_tests/resource/testmultiobjectcache.cpp delete mode 100644 components/resource/multiobjectcache.cpp diff --git a/apps/components_tests/CMakeLists.txt b/apps/components_tests/CMakeLists.txt index e0df874e76..3ff257e778 100644 --- a/apps/components_tests/CMakeLists.txt +++ b/apps/components_tests/CMakeLists.txt @@ -83,6 +83,7 @@ file(GLOB UNITTEST_SRC_FILES esmterrain/testgridsampling.cpp + resource/testmultiobjectcache.cpp resource/testobjectcache.cpp resource/testresourcesystem.cpp diff --git a/apps/components_tests/detournavigator/asyncnavmeshupdater.cpp b/apps/components_tests/detournavigator/asyncnavmeshupdater.cpp index d5f8ca3500..2fb912f931 100644 --- a/apps/components_tests/detournavigator/asyncnavmeshupdater.cpp +++ b/apps/components_tests/detournavigator/asyncnavmeshupdater.cpp @@ -1,4 +1,5 @@ #include "settings.hpp" +#include #include #include @@ -34,7 +35,7 @@ namespace void addObject(const btBoxShape& shape, TileCachedRecastMeshManager& recastMeshManager) { const ObjectId id(&shape); - osg::ref_ptr bulletShape(new Resource::BulletShape); + auto bulletShape = std::make_shared(); 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(new Resource::BulletShapeInstance(bulletShape)), shape, - objectTransform); + std::make_shared(bulletShape), shape, objectTransform); recastMeshManager.addObject(id, collisionShape, btTransform::getIdentity(), AreaType_ground, nullptr); } diff --git a/apps/components_tests/detournavigator/navigator.cpp b/apps/components_tests/detournavigator/navigator.cpp index 45b602c6b2..9dfcc0cb54 100644 --- a/apps/components_tests/detournavigator/navigator.cpp +++ b/apps/components_tests/detournavigator/navigator.cpp @@ -115,11 +115,11 @@ namespace } template - osg::ref_ptr makeBulletShapeInstance(std::unique_ptr&& shape) + std::shared_ptr makeBulletShapeInstance(std::unique_ptr&& shape) { - osg::ref_ptr bulletShape(new Resource::BulletShape); + auto bulletShape = std::make_shared(); bulletShape->mCollisionShape.reset(std::move(shape).release()); - return new Resource::BulletShapeInstance(bulletShape); + return std::make_shared(bulletShape); } template @@ -132,10 +132,10 @@ namespace } T& shape() const { return static_cast(*mInstance->mCollisionShape); } - const osg::ref_ptr& instance() const { return mInstance; } + const std::shared_ptr& instance() const { return mInstance; } private: - osg::ref_ptr mInstance; + std::shared_ptr 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 bulletShape(new Resource::BulletShape); + auto bulletShape = std::make_shared(); std::unique_ptr shapePtr = makeSquareHeightfieldTerrainShape(defaultHeightfieldDataScalar); @@ -387,7 +387,7 @@ namespace shapeAvoidPtr->setLocalScaling(btVector3(128, 128, 1)); bulletShape->mAvoidCollisionShape.reset(shapeAvoidPtr.release()); - osg::ref_ptr instance(new Resource::BulletShapeInstance(bulletShape)); + auto instance = std::make_shared(bulletShape); ASSERT_TRUE(mNavigator->addAgent(mAgentBounds)); mNavigator->addObject( diff --git a/apps/components_tests/detournavigator/recastmeshbuilder.cpp b/apps/components_tests/detournavigator/recastmeshbuilder.cpp index 89a097820d..1d73389536 100644 --- a/apps/components_tests/detournavigator/recastmeshbuilder.cpp +++ b/apps/components_tests/detournavigator/recastmeshbuilder.cpp @@ -1,4 +1,5 @@ #include "operators.hpp" +#include #include #include @@ -52,7 +53,7 @@ namespace { TileBounds mBounds; const Version mVersion{ 0, 0 }; - const osg::ref_ptr mSource{ nullptr }; + const std::shared_ptr mSource{ nullptr }; const ObjectTransform mObjectTransform{ ESM::Position{ { 0, 0, 0 }, { 0, 0, 0 } }, 0.0f }; DetourNavigatorRecastMeshBuilderTest() diff --git a/apps/components_tests/detournavigator/tilecachedrecastmeshmanager.cpp b/apps/components_tests/detournavigator/tilecachedrecastmeshmanager.cpp index 66c865be6c..fb8f8882fe 100644 --- a/apps/components_tests/detournavigator/tilecachedrecastmeshmanager.cpp +++ b/apps/components_tests/detournavigator/tilecachedrecastmeshmanager.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include @@ -19,8 +20,9 @@ namespace { RecastSettings mSettings; const ObjectTransform mObjectTransform{ ESM::Position{ { 0, 0, 0 }, { 0, 0, 0 } }, 0.0f }; - const osg::ref_ptr mShape = new Resource::BulletShape; - const osg::ref_ptr mInstance = new Resource::BulletShapeInstance(mShape); + const std::shared_ptr mShape = std::make_shared(); + const std::shared_ptr mInstance + = std::make_shared(mShape); const ESM::RefId mWorldspace = ESM::RefId::stringRefId("worldspace"); DetourNavigatorTileCachedRecastMeshManagerTest() diff --git a/apps/components_tests/resource/testmultiobjectcache.cpp b/apps/components_tests/resource/testmultiobjectcache.cpp new file mode 100644 index 0000000000..9e74459fb1 --- /dev/null +++ b/apps/components_tests/resource/testmultiobjectcache.cpp @@ -0,0 +1,98 @@ +#include + +#include +#include + +#include +#include + +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>; + + 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("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("first")); + cache.addEntryToObjectCache(path, std::make_shared("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("held"); + cache.addEntryToObjectCache(path, held); + cache.addEntryToObjectCache(otherPath, std::make_shared("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("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("value")); + cache.addEntryToObjectCache(otherPath, std::make_shared("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); + } + } +} diff --git a/apps/components_tests/resource/testobjectcache.cpp b/apps/components_tests/resource/testobjectcache.cpp index c5cea5a34a..7a47b53c2d 100644 --- a/apps/components_tests/resource/testobjectcache.cpp +++ b/apps/components_tests/resource/testobjectcache.cpp @@ -3,6 +3,8 @@ #include #include +#include + #include namespace Resource @@ -11,15 +13,22 @@ namespace Resource { using namespace ::testing; + using ObjectCache = GenericObjectCache>; + using StringObjectCache = GenericObjectCache>; + + // 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>; + TEST(ResourceGenericObjectCacheTest, getRefFromObjectCacheShouldReturnNullptrByDefault) { - GenericObjectCache cache; + ObjectCache cache; EXPECT_EQ(cache.getRefFromObjectCache(42), nullptr); } TEST(ResourceGenericObjectCacheTest, getRefFromObjectCacheOrNoneShouldReturnNulloptByDefault) { - GenericObjectCache 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("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("held"); + cache.addEntryToObjectCache(1, held); + cache.addEntryToObjectCache(2, std::make_shared("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 cache; + ObjectCache cache; const int key = 42; osg::ref_ptr value(new Object); cache.addEntryToObjectCache(key, value); @@ -46,7 +86,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, shouldStoreNullptrValues) { - GenericObjectCache 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 cache; + ObjectCache cache; const int key = 42; osg::ref_ptr value(new Object); @@ -69,7 +109,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, addEntryToObjectCacheShouldReplaceExistingItemByKey) { - GenericObjectCache cache; + ObjectCache cache; const int key = 42; osg::ref_ptr value1(new Object); @@ -82,7 +122,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, addEntryToObjectCacheShouldMarkLifetime) { - GenericObjectCache cache; + ObjectCache cache; const double referenceTime = 1; const double expiryDelay = 2; @@ -102,7 +142,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, updateShouldRemoveExpiredItems) { - GenericObjectCache cache; + ObjectCache cache; const double referenceTime = 1; const double expiryDelay = 1; @@ -123,7 +163,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, updateShouldKeepExternallyReferencedItems) { - GenericObjectCache cache; + ObjectCache cache; const double referenceTime = 1; const double expiryDelay = 1; @@ -141,7 +181,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, updateShouldKeepNotExpiredItems) { - GenericObjectCache cache; + ObjectCache cache; const double referenceTime = 1; const double expiryDelay = 2; @@ -160,7 +200,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, updateShouldKeepNotExpiredNullptrItems) { - GenericObjectCache cache; + ObjectCache cache; const double referenceTime = 1; const double expiryDelay = 2; @@ -177,7 +217,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, getRefFromObjectCacheOrNoneShouldNotExtendItemLifetime) { - GenericObjectCache cache; + ObjectCache cache; const double referenceTime = 1; const double expiryDelay = 2; @@ -197,7 +237,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, lowerBoundShouldSupportHeterogeneousLookup) { - GenericObjectCache 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 cache; + ObjectCache cache; const int key = 42; osg::ref_ptr value(new Object); cache.addEntryToObjectCache(key, value); @@ -216,7 +256,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, clearShouldRemoveAllItems) { - GenericObjectCache cache; + ObjectCache cache; const int key1 = 42; const int key2 = 13; @@ -236,7 +276,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, callShouldIterateOverAllItems) { - GenericObjectCache cache; + ObjectCache cache; osg::ref_ptr value1(new Object); osg::ref_ptr value2(new Object); @@ -253,7 +293,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, getStatsShouldReturnNumberOrAddedItems) { - GenericObjectCache cache; + ObjectCache cache; osg::ref_ptr value1(new Object); osg::ref_ptr value2(new Object); @@ -267,7 +307,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, getStatsShouldReturnNumberOrGetsAndHits) { - GenericObjectCache cache; + ObjectCache cache; { const CacheStats stats = cache.getStats(); @@ -291,7 +331,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, lowerBoundShouldReturnFirstNotLessThatGivenKey) { - GenericObjectCache cache; + ObjectCache cache; osg::ref_ptr value1(new Object); osg::ref_ptr value2(new Object); @@ -305,7 +345,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, lowerBoundShouldReturnNulloptWhenKeyIsGreaterThanAnyOther) { - GenericObjectCache cache; + ObjectCache cache; osg::ref_ptr value1(new Object); osg::ref_ptr value2(new Object); @@ -319,7 +359,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, addEntryToObjectCacheShouldSupportHeterogeneousLookup) { - GenericObjectCache cache; + StringObjectCache cache; const std::string key = "key"; osg::ref_ptr value(new Object); cache.addEntryToObjectCache(std::string_view("key"), value); @@ -328,7 +368,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, addEntryToObjectCacheShouldKeyMoving) { - GenericObjectCache cache; + StringObjectCache cache; std::string key(128, 'a'); osg::ref_ptr value(new Object); cache.addEntryToObjectCache(std::move(key), value); @@ -338,7 +378,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, removeFromObjectCacheShouldSupportHeterogeneousLookup) { - GenericObjectCache cache; + StringObjectCache cache; const std::string key = "key"; osg::ref_ptr value(new Object); cache.addEntryToObjectCache(key, value); @@ -349,7 +389,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, getRefFromObjectCacheShouldSupportHeterogeneousLookup) { - GenericObjectCache cache; + StringObjectCache cache; const std::string key = "key"; osg::ref_ptr value(new Object); cache.addEntryToObjectCache(key, value); @@ -358,7 +398,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, getRefFromObjectCacheOrNoneShouldSupportHeterogeneousLookup) { - GenericObjectCache cache; + StringObjectCache cache; const std::string key = "key"; osg::ref_ptr value(new Object); cache.addEntryToObjectCache(key, value); @@ -367,7 +407,7 @@ namespace Resource TEST(ResourceGenericObjectCacheTest, checkInObjectCacheShouldSupportHeterogeneousLookup) { - GenericObjectCache cache; + StringObjectCache cache; const std::string key = "key"; osg::ref_ptr value(new Object); cache.addEntryToObjectCache(key, value); diff --git a/apps/navmeshtool/worldspacedata.cpp b/apps/navmeshtool/worldspacedata.cpp index 533cb5ee96..feeb698784 100644 --- a/apps/navmeshtool/worldspacedata.cpp +++ b/apps/navmeshtool/worldspacedata.cpp @@ -148,7 +148,7 @@ namespace NavMeshTool if (cellRef.mType != ESM::REC_STAT) model = Misc::ResourceHelpers::correctActorModelPath(model, &vfs); - osg::ref_ptr shape = [&] { + std::shared_ptr 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(); + return std::shared_ptr(); } }(); if (shape == nullptr || shape->mCollisionShape == nullptr) continue; - osg::ref_ptr shapeInstance( + std::shared_ptr shapeInstance( new Resource::BulletShapeInstance(std::move(shape))); switch (cellRef.mType) diff --git a/apps/navmeshtool/worldspacedata.hpp b/apps/navmeshtool/worldspacedata.hpp index 74846200b3..aa38cf36d6 100644 --- a/apps/navmeshtool/worldspacedata.hpp +++ b/apps/navmeshtool/worldspacedata.hpp @@ -47,7 +47,7 @@ namespace NavMeshTool class BulletObject { public: - BulletObject(osg::ref_ptr&& shapeInstance, const ESM::Position& position, + BulletObject(std::shared_ptr&& 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& getShapeInstance() const noexcept { return mShapeInstance; } + const std::shared_ptr& getShapeInstance() const noexcept + { + return mShapeInstance; + } const DetourNavigator::ObjectTransform& getObjectTransform() const noexcept { return mObjectTransform; } btCollisionObject& getCollisionObject() const noexcept { return *mCollisionObject; } private: - osg::ref_ptr mShapeInstance; + std::shared_ptr mShapeInstance; DetourNavigator::ObjectTransform mObjectTransform; std::unique_ptr mCollisionObject; }; diff --git a/apps/opencs/view/render/terrainstorage.cpp b/apps/opencs/view/render/terrainstorage.cpp index 287d8979d5..2e426da6d5 100644 --- a/apps/opencs/view/render/terrainstorage.cpp +++ b/apps/opencs/view/render/terrainstorage.cpp @@ -27,7 +27,7 @@ namespace CSVRender resetHeights(); } - osg::ref_ptr TerrainStorage::getLand(ESM::ExteriorCellLocation cellLocation) + std::shared_ptr 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( land, ESM::Land::DATA_VHGT | ESM::Land::DATA_VNML | ESM::Land::DATA_VCLR | ESM::Land::DATA_VTEX); } diff --git a/apps/opencs/view/render/terrainstorage.hpp b/apps/opencs/view/render/terrainstorage.hpp index 473b4ede01..d6b5cab454 100644 --- a/apps/opencs/view/render/terrainstorage.hpp +++ b/apps/opencs/view/render/terrainstorage.hpp @@ -37,7 +37,7 @@ namespace CSVRender const CSMWorld::Data& mData; std::array mAlteredHeight; - osg::ref_ptr getLand(ESM::ExteriorCellLocation cellLocation) override; + std::shared_ptr 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; diff --git a/apps/openmw/mwphysics/actor.cpp b/apps/openmw/mwphysics/actor.cpp index 31659275e3..f2e9cffec1 100644 --- a/apps/openmw/mwphysics/actor.cpp +++ b/apps/openmw/mwphysics/actor.cpp @@ -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((max[0] - min[0]) / 2.f); mOriginalHalfExtents.y() = static_cast((max[1] - min[1]) / 2.f); mOriginalHalfExtents.z() = static_cast((max[2] - min[2]) / 2.f); diff --git a/apps/openmw/mwphysics/actor.hpp b/apps/openmw/mwphysics/actor.hpp index e53477506c..da8ae1ab44 100644 --- a/apps/openmw/mwphysics/actor.hpp +++ b/apps/openmw/mwphysics/actor.hpp @@ -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; diff --git a/apps/openmw/mwphysics/heightfield.cpp b/apps/openmw/mwphysics/heightfield.cpp index 4ec8dda881..06d670d7ad 100644 --- a/apps/openmw/mwphysics/heightfield.cpp +++ b/apps/openmw/mwphysics/heightfield.cpp @@ -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 holdObject, PhysicsTaskScheduler* scheduler) : mHoldObject(holdObject) #if BT_BULLET_VERSION < 310 , mHeights(makeHeights(heights, verts)) diff --git a/apps/openmw/mwphysics/heightfield.hpp b/apps/openmw/mwphysics/heightfield.hpp index a54685fda1..97df65ed2a 100644 --- a/apps/openmw/mwphysics/heightfield.hpp +++ b/apps/openmw/mwphysics/heightfield.hpp @@ -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 holdObject, PhysicsTaskScheduler* scheduler); ~HeightField(); btCollisionObject* getCollisionObject(); @@ -34,7 +39,7 @@ namespace MWPhysics private: std::unique_ptr mShape; std::unique_ptr mCollisionObject; - osg::ref_ptr mHoldObject; + std::shared_ptr mHoldObject; #if BT_BULLET_VERSION < 310 std::vector mHeights; #endif diff --git a/apps/openmw/mwphysics/object.cpp b/apps/openmw/mwphysics/object.cpp index 376a9d7541..594c0f4f01 100644 --- a/apps/openmw/mwphysics/object.cpp +++ b/apps/openmw/mwphysics/object.cpp @@ -1,5 +1,6 @@ #include "object.hpp" #include "mtphysics.hpp" +#include #include #include @@ -14,7 +15,7 @@ namespace MWPhysics { - Object::Object(const MWWorld::Ptr& ptr, osg::ref_ptr shapeInstance, + Object::Object(const MWWorld::Ptr& ptr, std::shared_ptr 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& Object::getShapeInstance() const { - return mShapeInstance.get(); + return mShapeInstance; } void Object::setScale(float scale) diff --git a/apps/openmw/mwphysics/object.hpp b/apps/openmw/mwphysics/object.hpp index bacf68f7f8..5ef5239fc9 100644 --- a/apps/openmw/mwphysics/object.hpp +++ b/apps/openmw/mwphysics/object.hpp @@ -2,6 +2,7 @@ #define OPENMW_MWPHYSICS_OBJECT_H #include "ptrholder.hpp" +#include #include #include @@ -29,11 +30,11 @@ namespace MWPhysics class Object final : public PtrHolder { public: - Object(const MWWorld::Ptr& ptr, osg::ref_ptr shapeInstance, osg::Quat rotation, - int collisionType, PhysicsTaskScheduler* scheduler); + Object(const MWWorld::Ptr& ptr, std::shared_ptr shapeInstance, + osg::Quat rotation, int collisionType, PhysicsTaskScheduler* scheduler); ~Object() override; - const Resource::BulletShapeInstance* getShapeInstance() const; + const std::shared_ptr& 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 mShapeInstance; + std::shared_ptr mShapeInstance; std::map mRecordIndexToNodePath; bool mSolid; btVector3 mScale; diff --git a/apps/openmw/mwphysics/physicssystem.cpp b/apps/openmw/mwphysics/physicssystem.cpp index 3c2238bac3..c0d9b8f127 100644 --- a/apps/openmw/mwphysics/physicssystem.cpp +++ b/apps/openmw/mwphysics/physicssystem.cpp @@ -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 holdObject) { - mHeightFields[std::make_pair(x, y)] - = std::make_unique(heights, x, y, size, verts, minH, maxH, holdObject, mTaskScheduler.get()); + mHeightFields[std::make_pair(x, y)] = std::make_unique( + 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 shapeInstance = mShapeManager->getInstance(animationMesh); + std::shared_ptr 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 shape = mShapeManager->getShape(animationMesh); + std::shared_ptr 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( - 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 shapeInstance = mShapeManager->getInstance(mesh); + std::shared_ptr shapeInstance = mShapeManager->getInstance(mesh); assert(shapeInstance); float radius = computeRadius ? shapeInstance->mCollisionBox.mExtents.length() / 2.f : 1.f; diff --git a/apps/openmw/mwphysics/physicssystem.hpp b/apps/openmw/mwphysics/physicssystem.hpp index 0ab0cf91a0..55b4da7e7d 100644 --- a/apps/openmw/mwphysics/physicssystem.hpp +++ b/apps/openmw/mwphysics/physicssystem.hpp @@ -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 holdObject); void removeHeightField(int x, int y); diff --git a/apps/openmw/mwrender/groundcover.cpp b/apps/openmw/mwrender/groundcover.cpp index 4c8e60da6a..934349a154 100644 --- a/apps/openmw/mwrender/groundcover.cpp +++ b/apps/openmw/mwrender/groundcover.cpp @@ -345,7 +345,7 @@ namespace MWRender Groundcover::Groundcover( Resource::SceneManager* sceneManager, float density, float viewDistance, const MWWorld::GroundcoverStore& store) - : GenericResourceManager(nullptr, Settings::cells().mCacheExpiryDelay) + : Resource::NodeResourceManager(nullptr, Settings::cells().mCacheExpiryDelay) , mSceneManager(sceneManager) , mDensity(density) , mStateset(new osg::StateSet) diff --git a/apps/openmw/mwrender/groundcover.hpp b/apps/openmw/mwrender/groundcover.hpp index ecbc990da0..6f839a03d8 100644 --- a/apps/openmw/mwrender/groundcover.hpp +++ b/apps/openmw/mwrender/groundcover.hpp @@ -19,7 +19,7 @@ namespace osg namespace MWRender { typedef std::tuple GroundcoverChunkId; // Center, Size - class Groundcover : public Resource::GenericResourceManager, + class Groundcover : public Resource::NodeResourceManager, public Terrain::QuadTreeWorld::ChunkManager { public: diff --git a/apps/openmw/mwrender/landmanager.cpp b/apps/openmw/mwrender/landmanager.cpp index d17933b2b7..b5311215a1 100644 --- a/apps/openmw/mwrender/landmanager.cpp +++ b/apps/openmw/mwrender/landmanager.cpp @@ -12,12 +12,13 @@ namespace MWRender { LandManager::LandManager(int loadFlags) - : GenericResourceManager(nullptr, Settings::cells().mCacheExpiryDelay) + : GenericResourceManager>( + nullptr, Settings::cells().mCacheExpiryDelay) , mLoadFlags(loadFlags) { } - osg::ref_ptr LandManager::getLand(ESM::ExteriorCellLocation cellIndex) + std::shared_ptr 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> obj = mCache->getRefFromObjectCacheOrNone(cellIndex)) - return static_cast(obj->get()); + if (const auto cached = mCache->getRefFromObjectCacheOrNone(cellIndex)) + return *cached; - osg::ref_ptr landObj = nullptr; + std::shared_ptr landObj = nullptr; if (ESM::isEsm4Ext(cellIndex.mWorldspace)) { const ESM4::Land* land = world.getStore().get().search(cellIndex); if (land != nullptr) - landObj = new ESMTerrain::LandObject(*land, mLoadFlags); + landObj = std::make_shared(*land, mLoadFlags); } else { const ESM::Land* land = world.getStore().get().search(cellIndex.mX, cellIndex.mY); if (land != nullptr) - landObj = new ESMTerrain::LandObject(*land, mLoadFlags); + landObj = std::make_shared(*land, mLoadFlags); } - mCache->addEntryToObjectCache(cellIndex, landObj.get()); + mCache->addEntryToObjectCache(cellIndex, landObj); return landObj; } diff --git a/apps/openmw/mwrender/landmanager.hpp b/apps/openmw/mwrender/landmanager.hpp index 1b82f32ce9..64d0a0bfb3 100644 --- a/apps/openmw/mwrender/landmanager.hpp +++ b/apps/openmw/mwrender/landmanager.hpp @@ -15,13 +15,14 @@ namespace ESM namespace MWRender { - class LandManager : public Resource::GenericResourceManager + class LandManager : public Resource::GenericResourceManager> { public: LandManager(int loadFlags); /// @note Will return nullptr if not found. - osg::ref_ptr getLand(ESM::ExteriorCellLocation cellIndex); + std::shared_ptr getLand(ESM::ExteriorCellLocation cellIndex); void reportStats(unsigned int frameNumber, osg::Stats* stats) const override; diff --git a/apps/openmw/mwrender/objectpaging.cpp b/apps/openmw/mwrender/objectpaging.cpp index d1db97f228..683e81339a 100644 --- a/apps/openmw/mwrender/objectpaging.cpp +++ b/apps/openmw/mwrender/objectpaging.cpp @@ -461,7 +461,7 @@ namespace MWRender } ObjectPaging::ObjectPaging(Resource::SceneManager* sceneManager, ESM::RefId worldspace) - : GenericResourceManager(nullptr, Settings::cells().mCacheExpiryDelay) + : Resource::NodeResourceManager(nullptr, Settings::cells().mCacheExpiryDelay) , Terrain::QuadTreeWorld::ChunkManager(worldspace) , mSceneManager(sceneManager) , mActiveGrid(Settings::terrain().mObjectPagingActiveGrid) diff --git a/apps/openmw/mwrender/objectpaging.hpp b/apps/openmw/mwrender/objectpaging.hpp index 6359aa9b0c..fcd75701fd 100644 --- a/apps/openmw/mwrender/objectpaging.hpp +++ b/apps/openmw/mwrender/objectpaging.hpp @@ -17,7 +17,7 @@ namespace MWRender typedef std::tuple ChunkId; // Center, Size, ActiveGrid - class ObjectPaging : public Resource::GenericResourceManager, public Terrain::QuadTreeWorld::ChunkManager + class ObjectPaging : public Resource::NodeResourceManager, public Terrain::QuadTreeWorld::ChunkManager { public: ObjectPaging(Resource::SceneManager* sceneManager, ESM::RefId worldspace); diff --git a/apps/openmw/mwrender/terrainstorage.cpp b/apps/openmw/mwrender/terrainstorage.cpp index be62311858..178993619c 100644 --- a/apps/openmw/mwrender/terrainstorage.cpp +++ b/apps/openmw/mwrender/terrainstorage.cpp @@ -102,7 +102,7 @@ namespace MWRender return mLandManager.get(); } - osg::ref_ptr TerrainStorage::getLand(ESM::ExteriorCellLocation cellLocation) + std::shared_ptr TerrainStorage::getLand(ESM::ExteriorCellLocation cellLocation) { return mLandManager->getLand(cellLocation); } diff --git a/apps/openmw/mwrender/terrainstorage.hpp b/apps/openmw/mwrender/terrainstorage.hpp index 00cf04cbab..4f7593a73a 100644 --- a/apps/openmw/mwrender/terrainstorage.hpp +++ b/apps/openmw/mwrender/terrainstorage.hpp @@ -21,7 +21,7 @@ namespace MWRender std::string_view specularMapPattern = {}, bool autoUseSpecularMaps = false); ~TerrainStorage(); - osg::ref_ptr getLand(ESM::ExteriorCellLocation cellLocation) override; + std::shared_ptr 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; diff --git a/apps/openmw/mwworld/cellpreloader.cpp b/apps/openmw/mwworld/cellpreloader.cpp index 4ed0d20129..1982d13915 100644 --- a/apps/openmw/mwworld/cellpreloader.cpp +++ b/apps/openmw/mwworld/cellpreloader.cpp @@ -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 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> mPreloadedObjects; + std::set> mPreloadedOwnedObjects; }; class TerrainPreloadItem : public SceneUtil::WorkItem diff --git a/apps/openmw/mwworld/scene.cpp b/apps/openmw/mwworld/scene.cpp index 6db420a71a..c18dae9264 100644 --- a/apps/openmw/mwworld/scene.cpp +++ b/apps/openmw/mwworld/scene.cpp @@ -442,7 +442,7 @@ namespace MWWorld if (cellVariant.isExterior()) { - osg::ref_ptr land = mRendering.getLandManager()->getLand(cellIndex); + std::shared_ptr 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 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)) { diff --git a/components/CMakeLists.txt b/components/CMakeLists.txt index dd897a7fad..7175ebdf08 100644 --- a/components/CMakeLists.txt +++ b/components/CMakeLists.txt @@ -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 ) diff --git a/components/detournavigator/navigator.hpp b/components/detournavigator/navigator.hpp index 3f27bc1479..8c3c9e5d2e 100644 --- a/components/detournavigator/navigator.hpp +++ b/components/detournavigator/navigator.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include "cellgridbounds.hpp" @@ -37,11 +38,11 @@ namespace DetourNavigator struct ObjectShapes { - osg::ref_ptr mShapeInstance; + std::shared_ptr mShapeInstance; ObjectTransform mTransform; ObjectShapes( - const osg::ref_ptr& shapeInstance, const ObjectTransform& transform) + const std::shared_ptr& 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& shapeInstance, + DoorShapes(const std::shared_ptr& shapeInstance, const ObjectTransform& transform, const osg::Vec3f& connectionStart, const osg::Vec3f& connectionEnd) : ObjectShapes(shapeInstance, transform) , mConnectionStart(connectionStart) diff --git a/components/detournavigator/recastmesh.hpp b/components/detournavigator/recastmesh.hpp index 1a67bb5495..c3e7a28e67 100644 --- a/components/detournavigator/recastmesh.hpp +++ b/components/detournavigator/recastmesh.hpp @@ -4,6 +4,7 @@ #include "areatype.hpp" #include "objecttransform.hpp" #include "version.hpp" +#include #include @@ -119,7 +120,7 @@ namespace DetourNavigator struct MeshSource { - osg::ref_ptr mShape; + std::shared_ptr mShape; ObjectTransform mObjectTransform; AreaType mAreaType; }; diff --git a/components/detournavigator/recastmeshbuilder.cpp b/components/detournavigator/recastmeshbuilder.cpp index eb03ee569b..05cc9189d1 100644 --- a/components/detournavigator/recastmeshbuilder.cpp +++ b/components/detournavigator/recastmeshbuilder.cpp @@ -1,5 +1,6 @@ #include "recastmeshbuilder.hpp" #include "exceptions.hpp" +#include #include #include @@ -138,7 +139,7 @@ namespace DetourNavigator } void RecastMeshBuilder::addObject(const btCollisionShape& shape, const btTransform& transform, - const AreaType areaType, osg::ref_ptr source, + const AreaType areaType, std::shared_ptr source, const ObjectTransform& objectTransform) { addObject(shape, transform, areaType); diff --git a/components/detournavigator/recastmeshbuilder.hpp b/components/detournavigator/recastmeshbuilder.hpp index 31a773bd56..a3a83e8c84 100644 --- a/components/detournavigator/recastmeshbuilder.hpp +++ b/components/detournavigator/recastmeshbuilder.hpp @@ -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 source, const ObjectTransform& objectTransform); + std::shared_ptr source, const ObjectTransform& objectTransform); void addObject(const btCompoundShape& shape, const btTransform& transform, const AreaType areaType); diff --git a/components/detournavigator/recastmeshobject.hpp b/components/detournavigator/recastmeshobject.hpp index e2d6f7a200..cc2adc96ba 100644 --- a/components/detournavigator/recastmeshobject.hpp +++ b/components/detournavigator/recastmeshobject.hpp @@ -3,6 +3,7 @@ #include "areatype.hpp" #include "objecttransform.hpp" +#include #include @@ -21,7 +22,7 @@ namespace DetourNavigator class CollisionShape { public: - CollisionShape(osg::ref_ptr instance, const btCollisionShape& shape, + CollisionShape(std::shared_ptr instance, const btCollisionShape& shape, const ObjectTransform& transform) : mInstance(std::move(instance)) , mShape(shape) @@ -29,12 +30,12 @@ namespace DetourNavigator { } - const osg::ref_ptr& getInstance() const { return mInstance; } + const std::shared_ptr& getInstance() const { return mInstance; } const btCollisionShape& getShape() const { return mShape; } const ObjectTransform& getObjectTransform() const { return mObjectTransform; } private: - osg::ref_ptr mInstance; + std::shared_ptr mInstance; std::reference_wrapper 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& getInstance() const { return mInstance; } + const std::shared_ptr& 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 mInstance; + std::shared_ptr mInstance; ObjectTransform mObjectTransform; ChildRecastMeshObject mImpl; }; diff --git a/components/detournavigator/tilecachedrecastmeshmanager.cpp b/components/detournavigator/tilecachedrecastmeshmanager.cpp index 5ea19db0e9..ee8a6e32ae 100644 --- a/components/detournavigator/tilecachedrecastmeshmanager.cpp +++ b/components/detournavigator/tilecachedrecastmeshmanager.cpp @@ -1,4 +1,5 @@ #include "tilecachedrecastmeshmanager.hpp" +#include #include "changetype.hpp" #include "gettilespositions.hpp" @@ -515,7 +516,7 @@ namespace DetourNavigator std::shared_ptr TileCachedRecastMeshManager::makeMesh(const TilePosition& tilePosition) const { RecastMeshBuilder builder(makeRealTileBoundsWithBorder(mSettings, tilePosition)); - using Object = std::tuple, ObjectTransform, + using Object = std::tuple, ObjectTransform, std::reference_wrapper, btTransform, AreaType>; std::vector objects; Version version; diff --git a/components/esmterrain/storage.cpp b/components/esmterrain/storage.cpp index 25dab4395c..f5566fbee7 100644 --- a/components/esmterrain/storage.cpp +++ b/components/esmterrain/storage.cpp @@ -64,7 +64,7 @@ namespace ESMTerrain return std::nullopt; } - void insert(int x, int y, osg::ref_ptr&& value) + void insert(int x, int y, std::shared_ptr&& 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>> mValues; + std::vector>> 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(std::floor(origin.x())); int cellY = static_cast(std::floor(origin.y())); - osg::ref_ptr land = getLand(ESM::ExteriorCellLocation(cellX, cellY, worldspace)); + std::shared_ptr 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((origin.x() - cellX) * landSize); @@ -573,7 +568,7 @@ namespace ESMTerrain int cellX = static_cast(std::floor(worldPos.x() / cellSize)); int cellY = static_cast(std::floor(worldPos.y() / cellSize)); - osg::ref_ptr land = getLand(ESM::ExteriorCellLocation(cellX, cellY, worldspace)); + std::shared_ptr land = getLand(ESM::ExteriorCellLocation(cellX, cellY, worldspace)); if (!land) return ESM::isEsm4Ext(worldspace) ? std::numeric_limits::lowest() : defaultHeight; @@ -655,7 +650,7 @@ namespace ESMTerrain { if (const auto land = cache.find(cellLocation.mX, cellLocation.mY)) return *land; - osg::ref_ptr land = getLand(cellLocation); + std::shared_ptr land = getLand(cellLocation); const LandObject* result = land.get(); cache.insert(cellLocation.mX, cellLocation.mY, std::move(land)); return result; diff --git a/components/esmterrain/storage.hpp b/components/esmterrain/storage.hpp index 25fa1a4355..17b4f049d8 100644 --- a/components/esmterrain/storage.hpp +++ b/components/esmterrain/storage.hpp @@ -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 getLand(ESM::ExteriorCellLocation cellLocation) = 0; + virtual std::shared_ptr 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 diff --git a/components/nifbullet/bulletnifloader.cpp b/components/nifbullet/bulletnifloader.cpp index 855fec934a..0194105efa 100644 --- a/components/nifbullet/bulletnifloader.cpp +++ b/components/nifbullet/bulletnifloader.cpp @@ -1,4 +1,5 @@ #include "bulletnifloader.hpp" +#include #include #include @@ -30,9 +31,9 @@ namespace namespace NifBullet { - osg::ref_ptr BulletNifLoader::load(Nif::FileView nif) + std::shared_ptr BulletNifLoader::load(Nif::FileView nif) { - mShape = new Resource::BulletShape; + mShape = std::make_shared(); mCompoundShape.reset(); mAvoidCompoundShape.reset(); diff --git a/components/nifbullet/bulletnifloader.hpp b/components/nifbullet/bulletnifloader.hpp index 3331f4b06e..e227e5f60c 100644 --- a/components/nifbullet/bulletnifloader.hpp +++ b/components/nifbullet/bulletnifloader.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -45,7 +46,7 @@ namespace NifBullet abort(); } - osg::ref_ptr load(Nif::FileView file); + std::shared_ptr load(Nif::FileView file); private: bool findBoundingBox(const Nif::NiAVObject& node); @@ -67,7 +68,7 @@ namespace NifBullet std::unique_ptr mCompoundShape; std::unique_ptr mAvoidCompoundShape; - osg::ref_ptr mShape; + std::shared_ptr mShape; }; } diff --git a/components/resource/animblendrulesmanager.cpp b/components/resource/animblendrulesmanager.cpp index 550315cace..04aaaad19d 100644 --- a/components/resource/animblendrulesmanager.cpp +++ b/components/resource/animblendrulesmanager.cpp @@ -57,11 +57,8 @@ namespace Resource osg::ref_ptr AnimBlendRulesManager::loadRules(VFS::Path::NormalizedView path) { - std::optional> obj = mCache->getRefFromObjectCacheOrNone(path); - if (obj.has_value()) - { - return osg::ref_ptr(static_cast(obj->get())); - } + if (std::optional> cached = mCache->getRefFromObjectCacheOrNone(path)) + return *cached; osg::ref_ptr blendRules = AnimBlendRules::fromFile(mVFS, path); mCache->addEntryToObjectCache(path.value(), blendRules); diff --git a/components/resource/animblendrulesmanager.hpp b/components/resource/animblendrulesmanager.hpp index 5b167f932d..57f6a92df6 100644 --- a/components/resource/animblendrulesmanager.hpp +++ b/components/resource/animblendrulesmanager.hpp @@ -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> { public: explicit AnimBlendRulesManager(const VFS::Manager* vfs, double expiryDelay); diff --git a/components/resource/bgsmfilemanager.cpp b/components/resource/bgsmfilemanager.cpp index 7d93608603..31aca200b4 100644 --- a/components/resource/bgsmfilemanager.cpp +++ b/components/resource/bgsmfilemanager.cpp @@ -1,7 +1,5 @@ #include "bgsmfilemanager.hpp" -#include - #include #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 obj = mCache->getRefFromObjectCache(name); - if (obj) - return static_cast(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 diff --git a/components/resource/bgsmfilemanager.hpp b/components/resource/bgsmfilemanager.hpp index 3c77c2c665..1cbc13087d 100644 --- a/components/resource/bgsmfilemanager.hpp +++ b/components/resource/bgsmfilemanager.hpp @@ -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 { public: BgsmFileManager(const VFS::Manager* vfs, double expiryDelay); diff --git a/components/resource/bulletshape.cpp b/components/resource/bulletshape.cpp index 70348e956d..8c4f2b7415 100644 --- a/components/resource/bulletshape.cpp +++ b/components/resource/bulletshape.cpp @@ -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 makeInstance(osg::ref_ptr source) + std::shared_ptr makeInstance(std::shared_ptr source) { - return { new BulletShapeInstance(std::move(source)) }; + return std::make_shared(std::move(source)); } - BulletShapeInstance::BulletShapeInstance(osg::ref_ptr source) + BulletShapeInstance::BulletShapeInstance(std::shared_ptr source) : BulletShape(*source) , mSource(std::move(source)) { diff --git a/components/resource/bulletshape.hpp b/components/resource/bulletshape.hpp index d9aad0f092..a67cd6d982 100644 --- a/components/resource/bulletshape.hpp +++ b/components/resource/bulletshape.hpp @@ -4,9 +4,7 @@ #include #include -#include #include -#include #include #include @@ -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 source); + explicit BulletShapeInstance(std::shared_ptr source); - const osg::ref_ptr& getSource() const { return mSource; } + const std::shared_ptr& getSource() const { return mSource; } private: - osg::ref_ptr mSource; + std::shared_ptr mSource; }; - osg::ref_ptr makeInstance(osg::ref_ptr source); + std::shared_ptr makeInstance(std::shared_ptr source); // Subclass btBhvTriangleMeshShape to auto-delete the meshInterface struct TriangleMeshShape : public btBvhTriangleMeshShape diff --git a/components/resource/bulletshapemanager.cpp b/components/resource/bulletshapemanager.cpp index a2e8809258..89f6c281e5 100644 --- a/components/resource/bulletshapemanager.cpp +++ b/components/resource/bulletshapemanager.cpp @@ -1,4 +1,5 @@ #include "bulletshapemanager.hpp" +#include #include @@ -72,12 +73,12 @@ namespace Resource drawable.accept(functor); } - osg::ref_ptr getShape() + std::shared_ptr getShape() { if (!mTriangleMesh || mTriangleMesh->getNumTriangles() == 0) - return osg::ref_ptr(); + return std::shared_ptr(); - osg::ref_ptr shape(new BulletShape); + auto shape = std::make_shared(); auto triangleMeshShape = std::make_unique(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()) + , mInstanceCache(std::make_unique>>()) , mSceneManager(sceneMgr) , mNifFileManager(nifFileManager) { @@ -107,12 +108,12 @@ namespace Resource BulletShapeManager::~BulletShapeManager() = default; - osg::ref_ptr BulletShapeManager::getShape(VFS::Path::NormalizedView name) + std::shared_ptr BulletShapeManager::getShape(VFS::Path::NormalizedView name) { - if (osg::ref_ptr obj = mCache->getRefFromObjectCache(name)) - return osg::ref_ptr(static_cast(obj.get())); + if (std::shared_ptr cached = mCache->getRefFromObjectCache(name)) + return cached; - osg::ref_ptr shape; + std::shared_ptr 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(); + return std::shared_ptr(); } if (shape != nullptr) @@ -164,38 +165,38 @@ namespace Resource return shape; } - osg::ref_ptr BulletShapeManager::cacheInstance(VFS::Path::NormalizedView name) + std::shared_ptr BulletShapeManager::cacheInstance(VFS::Path::NormalizedView name) { - osg::ref_ptr instance = createInstance(name); + std::shared_ptr instance = createInstance(name); if (instance != nullptr) - mInstanceCache->addEntryToObjectCache(name, instance.get()); + mInstanceCache->addEntryToObjectCache(name, instance); return instance; } - osg::ref_ptr BulletShapeManager::getInstance(VFS::Path::NormalizedView name) + std::shared_ptr BulletShapeManager::getInstance(VFS::Path::NormalizedView name) { - if (osg::ref_ptr obj = mInstanceCache->takeFromObjectCache(name)) - return static_cast(obj.get()); + if (std::shared_ptr cached = mInstanceCache->takeFromObjectCache(name)) + return cached; return createInstance(name); } - osg::ref_ptr BulletShapeManager::createInstance(VFS::Path::NormalizedView name) + std::shared_ptr BulletShapeManager::createInstance(VFS::Path::NormalizedView name) { - if (osg::ref_ptr shape = getShape(name)) + if (std::shared_ptr shape = getShape(name)) return makeInstance(std::move(shape)); - return osg::ref_ptr(); + return std::shared_ptr(); } void BulletShapeManager::updateCache(double referenceTime) { - ResourceManager::updateCache(referenceTime); + ResourceManager>::updateCache(referenceTime); mInstanceCache->removeUnreferencedObjectsInCache(); } void BulletShapeManager::clearCache() { - ResourceManager::clearCache(); + ResourceManager>::clearCache(); mInstanceCache->clear(); } diff --git a/components/resource/bulletshapemanager.hpp b/components/resource/bulletshapemanager.hpp index 65311cc125..fea45465d2 100644 --- a/components/resource/bulletshapemanager.hpp +++ b/components/resource/bulletshapemanager.hpp @@ -8,6 +8,7 @@ #include #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> { public: BulletShapeManager( @@ -31,16 +30,16 @@ namespace Resource ~BulletShapeManager(); /// @note May return a null pointer if the object has no shape. - osg::ref_ptr getShape(VFS::Path::NormalizedView name); + std::shared_ptr 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 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 cacheInstance(VFS::Path::NormalizedView name); /// @note May return a null pointer if the object has no shape. - osg::ref_ptr getInstance(VFS::Path::NormalizedView name); + std::shared_ptr 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 createInstance(VFS::Path::NormalizedView name); + std::shared_ptr createInstance(VFS::Path::NormalizedView name); - std::unique_ptr mInstanceCache; + std::unique_ptr>> mInstanceCache; SceneManager* mSceneManager; NifFileManager* mNifFileManager; }; diff --git a/components/resource/foreachbulletobject.cpp b/components/resource/foreachbulletobject.cpp index 9c205c8228..ef132b7e6c 100644 --- a/components/resource/foreachbulletobject.cpp +++ b/components/resource/foreachbulletobject.cpp @@ -1,4 +1,5 @@ #include "foreachbulletobject.hpp" +#include #include #include @@ -100,7 +101,7 @@ namespace Resource if (cellRef.mType != ESM::REC_STAT) model = Misc::ResourceHelpers::correctActorModelPath(model, &vfs); - osg::ref_ptr shape = [&] { + std::shared_ptr 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(); + return std::shared_ptr(); } }(); diff --git a/components/resource/foreachbulletobject.hpp b/components/resource/foreachbulletobject.hpp index d7e99cf0b5..405a4ab235 100644 --- a/components/resource/foreachbulletobject.hpp +++ b/components/resource/foreachbulletobject.hpp @@ -3,6 +3,7 @@ #include #include +#include #include @@ -34,7 +35,7 @@ namespace Resource { struct BulletObject { - osg::ref_ptr mShape; + std::shared_ptr mShape; ESM::Position mPosition; float mScale; }; diff --git a/components/resource/imagemanager.hpp b/components/resource/imagemanager.hpp index 8183c8db8e..305488b20b 100644 --- a/components/resource/imagemanager.hpp +++ b/components/resource/imagemanager.hpp @@ -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> { public: explicit ImageManager(const VFS::Manager* vfs, double expiryDelay); diff --git a/components/resource/keyframemanager.cpp b/components/resource/keyframemanager.cpp index fdc4e05774..48c9670bca 100644 --- a/components/resource/keyframemanager.cpp +++ b/components/resource/keyframemanager.cpp @@ -209,10 +209,8 @@ namespace Resource osg::ref_ptr KeyframeManager::get(VFS::Path::NormalizedView name) { - osg::ref_ptr obj = mCache->getRefFromObjectCache(name); - - if (obj != nullptr) - return osg::ref_ptr(static_cast(obj.get())); + if (osg::ref_ptr cached = mCache->getRefFromObjectCache(name)) + return cached; osg::ref_ptr loaded(new SceneUtil::KeyframeHolder); constexpr VFS::Path::ExtensionView kf("kf"); diff --git a/components/resource/keyframemanager.hpp b/components/resource/keyframemanager.hpp index ef7e7e4e4a..4810f40f27 100644 --- a/components/resource/keyframemanager.hpp +++ b/components/resource/keyframemanager.hpp @@ -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> { public: explicit KeyframeManager(const VFS::Manager* vfs, SceneManager* sceneManager, double expiryDelay, diff --git a/components/resource/multiobjectcache.cpp b/components/resource/multiobjectcache.cpp deleted file mode 100644 index af5df2e6b3..0000000000 --- a/components/resource/multiobjectcache.cpp +++ /dev/null @@ -1,91 +0,0 @@ -#include "multiobjectcache.hpp" - -#include - -#include - -namespace Resource -{ - void MultiObjectCache::removeUnreferencedObjectsInCache() - { - std::vector> objectsToRemove; - { - std::lock_guard 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 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 lock(mObjectCacheMutex); - mObjectCache.emplace(filename, object); - } - - osg::ref_ptr MultiObjectCache::takeFromObjectCache(VFS::Path::NormalizedView fileName) - { - std::lock_guard lock(mObjectCacheMutex); - ++mGet; - const auto it = mObjectCache.find(fileName); - if (it != mObjectCache.end()) - { - osg::ref_ptr object = std::move(it->second); - mObjectCache.erase(it); - ++mHit; - return object; - } - - return nullptr; - } - - void MultiObjectCache::releaseGLObjects(osg::State* state) - { - std::lock_guard 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 lock(mObjectCacheMutex); - return CacheStats{ - .mSize = mObjectCache.size(), - .mGet = mGet, - .mHit = mHit, - .mExpired = mExpired, - }; - } - -} diff --git a/components/resource/multiobjectcache.hpp b/components/resource/multiobjectcache.hpp index 781394cfa3..287b528226 100644 --- a/components/resource/multiobjectcache.hpp +++ b/components/resource/multiobjectcache.hpp @@ -3,43 +3,111 @@ #include #include +#include +#include -#include - +#include #include #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 MultiObjectCache { public: - void removeUnreferencedObjectsInCache(); + void removeUnreferencedObjectsInCache() + { + std::vector objectsToRemove; + { + std::lock_guard 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 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 lock(mObjectCacheMutex); + mObjectCache.emplace(filename, std::move(object)); + } - /** Take an Object from cache. Return nullptr if no object found. */ - osg::ref_ptr 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 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 + { + std::lock_guard lock(mObjectCacheMutex); + for (const auto& [key, value] : mObjectCache) + value->releaseGLObjects(state); + } + + CacheStats getStats() const + { + std::lock_guard lock(mObjectCacheMutex); + return CacheStats{ + .mSize = mObjectCache.size(), + .mGet = mGet, + .mHit = mHit, + .mExpired = mExpired, + }; + } protected: - typedef std::multimap, std::less<>> ObjectCacheMap; + using ObjectCacheMap = std::multimap>; ObjectCacheMap mObjectCache; mutable std::mutex mObjectCacheMutex; @@ -47,7 +115,6 @@ namespace Resource std::size_t mHit = 0; std::size_t mExpired = 0; }; - } #endif diff --git a/components/resource/niffilemanager.cpp b/components/resource/niffilemanager.cpp index d670f41ee9..9c9b171108 100644 --- a/components/resource/niffilemanager.cpp +++ b/components/resource/niffilemanager.cpp @@ -2,8 +2,6 @@ #include -#include - #include #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 obj = mCache->getRefFromObjectCache(name); - if (obj != nullptr) - return static_cast(obj.get())->mNifFile; + if (Nif::NIFFilePtr cached = mCache->getRefFromObjectCache(name)) + return cached; auto file = std::make_shared(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; } diff --git a/components/resource/niffilemanager.hpp b/components/resource/niffilemanager.hpp index a5395fef7e..99a09643d3 100644 --- a/components/resource/niffilemanager.hpp +++ b/components/resource/niffilemanager.hpp @@ -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 { const ToUTF8::StatelessUtf8Encoder* mEncoder; diff --git a/components/resource/objectcache.hpp b/components/resource/objectcache.hpp index a9a5e9d772..711c18ce53 100644 --- a/components/resource/objectcache.hpp +++ b/components/resource/objectcache.hpp @@ -27,9 +27,11 @@ #include #include +#include #include #include #include +#include #include 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 + long useCount(const std::shared_ptr& value) + { + return value.use_count(); + } + + template + long useCount(const osg::ref_ptr& 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 + concept ReleasesGLObjects = requires(T value, osg::State* state) + { + value->releaseGLObjects(state); + }; + + template + concept HoldsOsgObject = std::is_convertible_v().get()), osg::Object*>; + + template struct GenericObjectCacheItem { - osg::ref_ptr mValue; + ValueType mValue; double mLastUsage; }; - template + template class GenericObjectCache { public: @@ -68,7 +106,7 @@ namespace Resource */ void update(double referenceTime, double expiryDelay) { - std::vector> objectsToRemove; + std::vector objectsToRemove; { const double expiryTime = referenceTime - expiryDelay; std::lock_guard 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 - void addEntryToObjectCache(K&& key, osg::Object* object, double timestamp = 0.0) + void addEntryToObjectCache(K&& key, ValueType object, double timestamp = 0.0) { std::lock_guard lock(mMutex); const auto it = mItems.find(key); if (it == mItems.end()) - mItems.emplace_hint(it, std::forward(key), Item{ object, timestamp }); + mItems.emplace_hint(it, std::forward(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 from the object cache*/ - osg::ref_ptr 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 lock(mMutex); if (Item* const item = find(key)) return item->mValue; - return nullptr; + return ValueType(); } - std::optional> getRefFromObjectCacheOrNone(const auto& key) + std::optional getRefFromObjectCacheOrNone(const auto& key) { const std::lock_guard 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 { std::lock_guard 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 { std::lock_guard lock(mMutex); for (const auto& [k, v] : mItems) @@ -183,7 +224,7 @@ namespace Resource } template - std::optional>> lowerBound(K&& key) + std::optional> lowerBound(K&& key) { const std::lock_guard lock(mMutex); const auto it = mItems.lower_bound(std::forward(key)); @@ -204,7 +245,7 @@ namespace Resource } protected: - using Item = GenericObjectCacheItem; + using Item = GenericObjectCacheItem; std::map> mItems; mutable std::mutex mMutex; diff --git a/components/resource/resourcemanager.hpp b/components/resource/resourcemanager.hpp index 58e6cf613c..f55f0c47f1 100644 --- a/components/resource/resourcemanager.hpp +++ b/components/resource/resourcemanager.hpp @@ -3,6 +3,7 @@ #include +#include #include #include @@ -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 + template class GenericResourceManager : public BaseResourceManager { public: - typedef GenericObjectCache CacheType; + typedef GenericObjectCache 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 + /// Caching a scene graph is the common case, so it gets a name rather than the + /// same template arguments at every use. + template + using NodeResourceManager = GenericResourceManager>; + + template + class ResourceManager : public GenericResourceManager { public: explicit ResourceManager(const VFS::Manager* vfs, double expiryDelay) - : GenericResourceManager(vfs, expiryDelay) + : GenericResourceManager(vfs, expiryDelay) { } + + protected: + using GenericResourceManager::mCache; + using GenericResourceManager::mVFS; }; } diff --git a/components/resource/scenemanager.cpp b/components/resource/scenemanager.cpp index 3561b0fb6a..6765cc2e7a 100644 --- a/components/resource/scenemanager.cpp +++ b/components/resource/scenemanager.cpp @@ -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(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::updateCache(referenceTime); mSharedStateMutex.lock(); mSharedStateManager->prune(); @@ -1225,7 +1225,7 @@ namespace Resource void SceneManager::clearCache() { - ResourceManager::clearCache(); + NodeResourceManager::clearCache(); std::lock_guard lock(mSharedStateMutex); mSharedStateManager->clearCache(); diff --git a/components/resource/scenemanager.hpp b/components/resource/scenemanager.hpp index b22f07ae29..2f06563ace 100644 --- a/components/resource/scenemanager.hpp +++ b/components/resource/scenemanager.hpp @@ -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 { public: explicit SceneManager(const VFS::Manager* vfs, Resource::ImageManager* imageManager, diff --git a/components/terrain/chunkmanager.cpp b/components/terrain/chunkmanager.cpp index 404efbb63f..4147a91529 100644 --- a/components/terrain/chunkmanager.cpp +++ b/components/terrain/chunkmanager.cpp @@ -38,7 +38,7 @@ namespace Terrain ChunkManager::ChunkManager(Storage* storage, Resource::SceneManager* sceneMgr, TextureManager* textureManager, CompositeMapRenderer* renderer, ESM::RefId worldspace, double expiryDelay) - : GenericResourceManager(nullptr, expiryDelay) + : Resource::NodeResourceManager(nullptr, expiryDelay) , QuadTreeWorld::ChunkManager(worldspace) , mStorage(storage) , mSceneManager(sceneMgr) @@ -93,14 +93,14 @@ namespace Terrain void ChunkManager::clearCache() { - GenericResourceManager::clearCache(); + Resource::NodeResourceManager::clearCache(); mBufferCache.clearCache(); } void ChunkManager::releaseGLObjects(osg::State* state) { - GenericResourceManager::releaseGLObjects(state); + Resource::NodeResourceManager::releaseGLObjects(state); mBufferCache.releaseGLObjects(state); } diff --git a/components/terrain/chunkmanager.hpp b/components/terrain/chunkmanager.hpp index b4f327e699..5e906e291c 100644 --- a/components/terrain/chunkmanager.hpp +++ b/components/terrain/chunkmanager.hpp @@ -72,7 +72,7 @@ namespace Terrain } /// @brief Handles loading and caching of terrain chunks - class ChunkManager : public Resource::GenericResourceManager, public QuadTreeWorld::ChunkManager + class ChunkManager : public Resource::NodeResourceManager, public QuadTreeWorld::ChunkManager { public: explicit ChunkManager(Storage* storage, Resource::SceneManager* sceneMgr, TextureManager* textureManager, diff --git a/components/terrain/texturemanager.cpp b/components/terrain/texturemanager.cpp index 06f3243330..1a52b1eff7 100644 --- a/components/terrain/texturemanager.cpp +++ b/components/terrain/texturemanager.cpp @@ -10,7 +10,7 @@ namespace Terrain { TextureManager::TextureManager(Resource::SceneManager* sceneMgr, double expiryDelay) - : ResourceManager(sceneMgr->getVFS(), expiryDelay) + : ResourceManager>(sceneMgr->getVFS(), expiryDelay) , mSceneManager(sceneMgr) { } diff --git a/components/terrain/texturemanager.hpp b/components/terrain/texturemanager.hpp index a79ef53b88..6eccb020f8 100644 --- a/components/terrain/texturemanager.hpp +++ b/components/terrain/texturemanager.hpp @@ -1,6 +1,8 @@ #ifndef OPENMW_COMPONENTS_TERRAIN_TEXTUREMANAGER_H #define OPENMW_COMPONENTS_TERRAIN_TEXTUREMANAGER_H +#include + #include #include @@ -9,15 +11,10 @@ namespace Resource class SceneManager; } -namespace osg -{ - class Texture2D; -} - namespace Terrain { - class TextureManager : public Resource::ResourceManager + class TextureManager : public Resource::ResourceManager> { public: explicit TextureManager(Resource::SceneManager* sceneMgr, double expiryDelay);