PixelBullet  0.0.1
A C++ game engine
Loading...
Searching...
No Matches
entity_id.h
1#pragma once
2
3#include "pixelbullet/serialization/node.h"
4#include "pixelbullet/serialization/node_reader.h"
5
6#include <cstdint>
7#include <limits>
8
9namespace pixelbullet
10{
11class EntityId
12{
13public:
14 using ValueType = std::uint64_t;
15
16 static constexpr uint32_t index_bits = 32;
17 static constexpr uint32_t generation_bits = 32;
18 static constexpr ValueType IndexMask = (ValueType{ 1 } << index_bits) - 1;
19 static constexpr ValueType GenerationMask = (ValueType{ 1 } << generation_bits) - 1;
20
21 constexpr EntityId() noexcept
22 : value_(Invalid().value_)
23 {
24 }
25 constexpr EntityId(uint32_t index, uint32_t generation) noexcept
26 : value_((static_cast<ValueType>(generation) << index_bits) | (static_cast<ValueType>(index) & IndexMask))
27 {
28 }
29
30 static constexpr EntityId Invalid() noexcept
31 {
32 return EntityId(std::numeric_limits<ValueType>::max());
33 }
34
35 static constexpr EntityId FromRaw(ValueType raw) noexcept
36 {
37 return EntityId(raw);
38 }
39
40 [[nodiscard]] constexpr uint32_t Index() const noexcept
41 {
42 return static_cast<uint32_t>(value_ & IndexMask);
43 }
44
45 [[nodiscard]] constexpr uint32_t Generation() const noexcept
46 {
47 return static_cast<uint32_t>((value_ >> index_bits) & GenerationMask);
48 }
49
50 [[nodiscard]] constexpr ValueType Raw() const noexcept
51 {
52 return value_;
53 }
54
55 constexpr bool operator==(const EntityId& other) const noexcept = default;
56 constexpr bool operator!=(const EntityId& other) const noexcept = default;
57
58 constexpr explicit operator bool() const noexcept
59 {
60 return value_ != Invalid().value_;
61 }
62
63private:
64 explicit constexpr EntityId(ValueType raw) noexcept
65 : value_(raw)
66 {
67 }
68 ValueType value_;
69};
70
71inline Node& operator<<(Node& node, const EntityId& entityId)
72{
73 return node << entityId.Raw();
74}
75
76inline const Node& operator>>(const Node& node, EntityId& entityId)
77{
78 EntityId::ValueType raw = 0;
79 node >> raw;
80 entityId = EntityId::FromRaw(raw);
81 return node;
82}
83
84[[nodiscard]] inline bool TryReadNode(const Node& node, EntityId& entityId, serialization::NodeReader& reader)
85{
86 EntityId::ValueType raw = 0;
87 if (!serialization::TryReadNode(node, raw, reader))
88 {
89 return false;
90 }
91 entityId = EntityId::FromRaw(raw);
92 return true;
93}
94} // namespace pixelbullet
Definition entity_id.h:12
Represents a hierarchical node capable of storing various data types and supporting YAML serializatio...
Definition node.h:49
Definition node_reader.h:48