Flecs: include/flecs/addons/cpp/ref.hpp Source File
Description: A fast entity component system (ECS) for C & C++

| Flecs v4.0 A fast entity component system (ECS) for C & C++

Loading...
Searching...
No Matches
ref.hpp
Go to the documentation of this file.
1
5
6#pragma once
7
8namespace flecs
9{
10
18
22template <typename T>
23 struct ref {
24 ref() : world_(nullptr), ref_{} { }
25
26 ref(world_t *world, entity_t entity, flecs::id_t id = 0)
27 : ref_()
28 {
29 // the world we were called with may be a stage; convert it to a world
30 // here if that is the case
31 world_ = world ? const_cast<flecs::world_t *>(ecs_get_world(world))
32 : nullptr;
33 if (!id) {
34 id = _::type<T>::id(world);
35 }
36
37 ecs_assert(_::type<T>::size() != 0, ECS_INVALID_PARAMETER,
38 "operation invalid for empty type");
39
40 ref_ = ecs_ref_init_id(world_, entity, id);
41 }
42
43 ref(flecs::entity entity, flecs::id_t id = 0)
44 : ref(entity.world(), entity.id(), id) { }
45
46 T* operator->() {
47 T* result = static_cast<T*>(ecs_ref_get_id(
48 world_, &ref_, this->ref_.id));
49
50 ecs_assert(result != NULL, ECS_INVALID_PARAMETER,
51 "nullptr dereference by flecs::ref");
52
53 return result;
54 }
55
56 T* get() {
57 return static_cast<T*>(ecs_ref_get_id(
58 world_, &ref_, this->ref_.id));
59 }
60
61 T* try_get() {
62 if (!world_ || !ref_.entity) {
63 return nullptr;
64 }
65
66 return get();
67 }
68
69 bool has() {
70 return !!try_get();
71 }
72
74 operator bool() {
75 return has();
76 }
77
78 flecs::entity entity() const;
79
80private:
81 world_t *world_;
82 flecs::ref_t ref_;
83};
84
86
87}
ecs_assert
#define ecs_assert(condition, error_code,...)
Assert.
Definition log.h:368
ecs_ref_init_id
ecs_ref_t ecs_ref_init_id(const ecs_world_t *world, ecs_entity_t entity, ecs_id_t id)
Create a component ref.
ecs_ref_get_id
void * ecs_ref_get_id(const ecs_world_t *world, ecs_ref_t *ref, ecs_id_t id)
Get component from ref.
ecs_get_world
const ecs_world_t * ecs_get_world(const ecs_poly_t *poly)
Get world from poly.
flecs::_::type
Definition flecs.hpp:38
flecs::entity
Entity.
Definition entity.hpp:30
flecs::world
The world.
Definition world.hpp:137