Skip to content

Commit

Permalink
Add BodyComponent system for dynamic composition
Browse files Browse the repository at this point in the history
Sort of a mini-ECS approach, it's by no means fast, but it is functional.
Only intended as a transitional system to move to an ECS.
  • Loading branch information
sturnclaw committed Jun 14, 2022
1 parent 7fb1190 commit cbd3d23
Show file tree
Hide file tree
Showing 4 changed files with 212 additions and 3 deletions.
17 changes: 17 additions & 0 deletions licenses/zlib.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
Copyright (c) <year> <copyright holders>

This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
21 changes: 19 additions & 2 deletions src/Body.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#include "Body.h"

#include "BodyComponent.h"
#include "CargoBody.h"
#include "Frame.h"
#include "GameSaveError.h"
Expand All @@ -17,9 +18,13 @@
#include "Star.h"
#include "lua/LuaEvent.h"

size_t BodyComponentDB::m_componentIdx = 0;
std::map<size_t, std::unique_ptr<BodyComponentDB::PoolBase>> BodyComponentDB::m_componentPools;
std::map<std::string, std::unique_ptr<BodyComponentDB::SerializerBase>> BodyComponentDB::m_componentSerializers;
std::vector<size_t> BodyComponentDB::m_componentTypes;

Body::Body() :
PropertiedObject(),
m_flags(0),
m_interpPos(0.0),
m_interpOrient(matrix3x3d::Identity()),
m_pos(0.0),
Expand All @@ -34,7 +39,6 @@ Body::Body() :

Body::Body(const Json &jsonObj, Space *space) :
PropertiedObject(),
m_flags(0),
m_interpPos(0.0),
m_interpOrient(matrix3x3d::Identity()),
m_frame(FrameId::Invalid)
Expand All @@ -52,13 +56,26 @@ Body::Body(const Json &jsonObj, Space *space) :
m_orient = bodyObj["orient"];
m_physRadius = bodyObj["phys_radius"];
m_clipRadius = bodyObj["clip_radius"];

Json components = jsonObj["components"];
} catch (Json::type_error &) {
throw SavedGameCorruptException();
}
}

Body::~Body()
{
size_t idx = 0;
while (m_components) {
// get the bit index for each active component and delete it.
while (!(m_components & 1)) {
m_components >>= 1;
idx++;
}
BodyComponentDB::GetComponentType(idx)->deleteComponent(this);
m_components >>= 1;
idx++;
}
}

void Body::SaveToJson(Json &jsonObj, Space *space)
Expand Down
35 changes: 34 additions & 1 deletion src/Body.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#ifndef _BODY_H
#define _BODY_H

#include "BodyComponent.h"
#include "DeleteEmitter.h"
#include "FrameId.h"
#include "lua/PropertiedObject.h"
Expand Down Expand Up @@ -125,6 +126,35 @@ class Body : public DeleteEmitter, public PropertiedObject {
m_flags &= ~flag;
}

// Check if a specific component is present. This involves a lookup through std::map
// so it's not quite as efficient as it should be.
template <typename T>
bool HasComponent() const
{
return m_components & (1 << uint8_t(BodyComponentDB::GetComponentType<T>()->componentIndex));
}

// Return a pointer to the component of type T attached to this instance or nullptr.
// This returns a non-const pointer for simplicity as the component is technically
// not part of the object.
template <typename T>
T *GetComponent() const
{
auto *type = BodyComponentDB::GetComponentType<T>();
return m_components & (1 << uint8_t(type->componentIndex)) ? type->get(this) : nullptr;
}

template <typename T>
T *AddComponent()
{
auto *type = BodyComponentDB::GetComponentType<T>();
if (m_components & (1 << uint8_t(type->componentIndex)))
return type->get(this);

m_components |= (1 << uint8_t(type->componentIndex));
return type->newComponent(this);
}

// Only Space::KillBody() should call this method.
void MarkDead() { m_dead = true; }
bool IsDead() const { return m_dead; }
Expand Down Expand Up @@ -159,9 +189,12 @@ class Body : public DeleteEmitter, public PropertiedObject {
FLAG_DRAW_EXCLUDE = (1 << 3) // do not draw this body, intended for e.g. when camera is inside
};

private:
uint64_t m_components = 0;

protected:
virtual void SaveToJson(Json &jsonObj, Space *space);
unsigned int m_flags;
unsigned int m_flags = 0;

// Interpolated draw orientation-position
vector3d m_interpPos;
Expand Down
142 changes: 142 additions & 0 deletions src/BodyComponent.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// Copyright © 2008-2020 Pioneer Developers. See AUTHORS.txt for details
// Licensed under the terms of the GPL v3. See licenses/GPL-3.txt

#pragma once

#include "JsonFwd.h"
#include "core/TypeId.h"

#include <cassert>
#include <cstddef>
#include <map>
#include <vector>

class Body;
class Space;
class BodyComponent {};

/*
BodyComponentDB provides a simple interface to support dynamic composition
of game objects.
It is intended for use as a transitional interface to facilitate the
migration of Pioneer's inheritance-hierarchy based object model to an ECS-
style system, and thus is not and never will be a permanent solution.
Please direct all concerns about speed and efficiency to /dev/null
Improvements to compile times are welcomed wherever possible.
*/
class BodyComponentDB {
public:
// Polymorphic interface to support generic serialization operations
// This functionality is separated to facilitate components that do not wish
// to be serialized.
struct SerializerBase {
SerializerBase(std::string name) :
typeName(name) {}
std::string typeName;
virtual void toJson(const Body *body, Json &obj, Space *space) = 0;
virtual BodyComponent *fromJson(Body *body, const Json &obj, Space *space) = 0;
};

// Polymorphic interface to support generic deletion operations
struct PoolBase {
PoolBase(size_t i) :
componentIndex(i) {}
size_t componentIndex = 0;
SerializerBase *serializer = nullptr;

virtual void deleteComponent(Body *body) = 0;
};

template <typename T>
struct Serializer;

// Type-specific component pool; uses std::map as a backing store.
// This is not meant to be particularly performant, merely to transition API usage.
template <typename T>
struct Pool final : public PoolBase {
using PoolBase::PoolBase;

virtual void deleteComponent(Body *body) override { m_components.erase(body); }
// Create a new component, or return the existing one.
T *newComponent(const Body *body) { return &m_components[body]; }
// Assert that a component exists for this body and return it
T *get(const Body *body) { return &m_components.at(body); }

private:
template <typename U>
friend struct BodyComponentDB::Serializer;
std::map<const Body *, T> m_components;
};

// Type-specific serialization implementation. Delegates to the type's
// internal serialization methods and provides the needed glue code.
template <typename T>
struct Serializer final : public SerializerBase {
Serializer(std::string name, Pool<T> *pool) :
SerializerBase(name),
pool(pool)
{}
Pool<T> *pool;

virtual void toJson(const Body *body, Json &obj, Space *space) override
{
pool->get(body)->SaveToJson(obj, space);
}

virtual BodyComponent *fromJson(Body *body, const Json &obj, Space *space) override
{
pool->deleteComponent(body);
auto *component = pool->newComponent(body);
component->LoadFromJson(obj, space);
return component;
}
};

// Returns (and creates) a type-specific pool.
template <typename T>
static Pool<T> *GetComponentType()
{
auto iter = m_componentPools.find(TypeId<T>::Get());
if (iter == m_componentPools.end()) {
iter = m_componentPools.emplace(TypeId<T>::Get(), new Pool<T>(m_componentIdx++, TypeId<T>::Get())).first;
m_componentTypes.push_back(TypeId<T>::Get());
}

return static_cast<Pool<T> *>(iter->second.get());
}

// Returns (if present) the polymorphic interface to component associated with the given index
// This differs from the type-ID and is volatile between program restarts
static PoolBase *GetComponentType(size_t componentIndex) { return m_componentPools.at(m_componentTypes[componentIndex]).get(); }

// Register a serializer for the given type.
template <typename T>
static bool RegisterSerializer(std::string typeName)
{
assert(!m_componentSerializers.count(typeName));
SerializerBase *serial = new Serializer<T>(typeName, GetComponentType<T>());
m_componentSerializers.emplace(typeName, serial);
GetComponentType<T>()->serializer = serial;
return true;
}

// Returns a pointer to the registered Serializer instance for a type identified by the given name, or nullptr.
// To retrieve the serializer instance for a given type index, use GetComponentType(idx)->serializer
// or GetComponentType<T>()->serializer.
static SerializerBase *GetSerializer(const std::string &typeName)
{
auto iter = m_componentSerializers.find(typeName);
if (iter != m_componentSerializers.end())
return iter->second.get();

return nullptr;
}

private:
static std::map<size_t, std::unique_ptr<PoolBase>> m_componentPools;
static std::map<std::string, std::unique_ptr<SerializerBase>> m_componentSerializers;
static std::vector<size_t> m_componentTypes;
static size_t m_componentIdx;
};

0 comments on commit cbd3d23

Please sign in to comment.