0.2.0-dev Download ZIP
92 lines ·2.1 KB Raw
| 1 | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics) |
| 2 | // SPDX-FileCopyrightText: 2021 Jorrit Rouwe |
| 3 | // SPDX-License-Identifier: MIT |
| 4 | |
| 5 | #include <Jolt/Jolt.h> |
| 6 | |
| 7 | #include <Jolt/Core/Factory.h> |
| 8 | |
| 9 | JPH_NAMESPACE_BEGIN |
| 10 | |
| 11 | Factory *Factory::sInstance = nullptr; |
| 12 | |
| 13 | void *Factory::CreateObject(const char *inName) |
| 14 | { |
| 15 | const RTTI *ci = Find(inName); |
| 16 | return ci != nullptr? ci->CreateObject() : nullptr; |
| 17 | } |
| 18 | |
| 19 | const RTTI *Factory::Find(const char *inName) |
| 20 | { |
| 21 | ClassNameMap::iterator c = mClassNameMap.find(inName); |
| 22 | return c != mClassNameMap.end()? c->second : nullptr; |
| 23 | } |
| 24 | |
| 25 | const RTTI *Factory::Find(uint32 inHash) |
| 26 | { |
| 27 | ClassHashMap::iterator c = mClassHashMap.find(inHash); |
| 28 | return c != mClassHashMap.end()? c->second : nullptr; |
| 29 | } |
| 30 | |
| 31 | bool Factory::Register(const RTTI *inRTTI) |
| 32 | { |
| 33 | // Check if we already know the type |
| 34 | if (Find(inRTTI->GetName()) != nullptr) |
| 35 | return true; |
| 36 | |
| 37 | // Insert this class by name |
| 38 | mClassNameMap.try_emplace(inRTTI->GetName(), inRTTI); |
| 39 | |
| 40 | // Insert this class by hash |
| 41 | if (!mClassHashMap.try_emplace(inRTTI->GetHash(), inRTTI).second) |
| 42 | { |
| 43 | JPH_ASSERT(false, "Hash collision registering type!"); |
| 44 | return false; |
| 45 | } |
| 46 | |
| 47 | // Register base classes |
| 48 | for (int i = 0; i < inRTTI->GetBaseClassCount(); ++i) |
| 49 | if (!Register(inRTTI->GetBaseClass(i))) |
| 50 | return false; |
| 51 | |
| 52 | #ifdef JPH_OBJECT_STREAM |
| 53 | // Register attribute classes |
| 54 | for (int i = 0; i < inRTTI->GetAttributeCount(); ++i) |
| 55 | { |
| 56 | const RTTI *rtti = inRTTI->GetAttribute(i).GetMemberPrimitiveType(); |
| 57 | if (rtti != nullptr && !Register(rtti)) |
| 58 | return false; |
| 59 | } |
| 60 | #endif // JPH_OBJECT_STREAM |
| 61 | |
| 62 | return true; |
| 63 | } |
| 64 | |
| 65 | bool Factory::Register(const RTTI **inRTTIs, uint inNumber) |
| 66 | { |
| 67 | mClassHashMap.reserve(mClassHashMap.size() + inNumber); |
| 68 | mClassNameMap.reserve(mClassNameMap.size() + inNumber); |
| 69 | |
| 70 | for (const RTTI **rtti = inRTTIs; rtti < inRTTIs + inNumber; ++rtti) |
| 71 | if (!Register(*rtti)) |
| 72 | return false; |
| 73 | |
| 74 | return true; |
| 75 | } |
| 76 | |
| 77 | void Factory::Clear() |
| 78 | { |
| 79 | mClassNameMap.clear(); |
| 80 | mClassHashMap.clear(); |
| 81 | } |
| 82 | |
| 83 | Array<const RTTI *> Factory::GetAllClasses() const |
| 84 | { |
| 85 | Array<const RTTI *> all_classes; |
| 86 | all_classes.reserve(mClassNameMap.size()); |
| 87 | for (const ClassNameMap::value_type &c : mClassNameMap) |
| 88 | all_classes.push_back(c.second); |
| 89 | return all_classes; |
| 90 | } |
| 91 | |
| 92 | JPH_NAMESPACE_END |