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
6#pragma once
7
8namespace flecs
9{
10
22template <typename T>
23struct 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) {
35 }
36
37#ifdef FLECS_DEBUG
38 flecs::entity_t type = ecs_get_typeid(world, id);
40 ecs_assert(ti && ti->size != 0, ECS_INVALID_PARAMETER,
41 "cannot create ref to empty type");
42#endif
43 ref_ = ecs_ref_init_id(world_, entity, id);
44 }
45
46 ref(flecs::entity entity, flecs::id_t id = 0)
47 : ref(entity.world(), entity.id(), id) { }
48
49 T* operator->() {
50 T* result = static_cast<T*>(ecs_ref_get_id(
51 world_, &ref_, this->ref_.id));
52
53 ecs_assert(result != NULL, ECS_INVALID_PARAMETER,
54 "nullptr dereference by flecs::ref");
55
56 return result;
57 }
58
59 T* get() {
60 return static_cast<T*>(ecs_ref_get_id(
61 world_, &ref_, this->ref_.id));
62 }
63
64 T* try_get() {
65 if (!world_ || !ref_.entity) {
66 return nullptr;
67 }
68
69 return get();
70 }
71
72 bool has() {
73 return !!try_get();
74 }
75
77 operator bool() {
78 return has();
79 }
80
82 flecs::entity entity() const;
83
85 flecs::id component() const;
86
87private:
88 world_t *world_;
89 flecs::ref_t ref_;
90};
91
94}
#define ecs_assert(condition, error_code,...)
Assert.
Definition log.h:368
const ecs_type_info_t * ecs_get_type_info(const ecs_world_t *world, ecs_id_t id)
Get the type for an 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.
void * ecs_ref_get_id(const ecs_world_t *world, ecs_ref_t *ref, ecs_id_t id)
Get component from ref.
ecs_entity_t ecs_get_typeid(const ecs_world_t *world, ecs_id_t id)
Get the type for an id.
const ecs_world_t * ecs_get_world(const ecs_poly_t *poly)
Get world from poly.
Type that contains component information (passed to ctors/dtors/...)
Definition flecs.h:953
ecs_size_t size
Size of type.
Definition flecs.h:954
entity_t id() const
Get entity id.
Entity.
Definition entity.hpp:30
Class that wraps around a flecs::id_t.
Definition decl.hpp:27
Component reference.
Definition ref.hpp:23
flecs::entity entity() const
Return entity associated with reference.
Definition impl.hpp:11
flecs::id component() const
Return component associated with reference.
Definition impl.hpp:16
Type class.
Definition type.hpp:21
The world.
Definition world.hpp:137