forked from skypjack/entt
-
Notifications
You must be signed in to change notification settings - Fork 0
Tutorial
Alan Jefferson edited this page Jan 17, 2020
·
4 revisions
Let's ensure we grok how an ECS works by reimplementing the core mechanics of EnTT.
- Entities
- Components
- Systems
Here's what we'll be able to do once finished with our implementation.
main.cpp
#include <iostream>
#include "entt11.hpp"
struct Vector3 {
float x, y, z;
};
struct Quaternion {
float x, y, z , w;
};
struct Pose {
Vector3 p;
Quaternion q;
};
std::ostream& operator<<(std::ostream& out, Vector3 vec) {
out << "Vector3(" << vec.x << ", " << vec.y << ", " << vec.z << ")";
return out;
}
int main() {
entt11::registry registry;
auto entity1 = registry.create();
auto entity2 = registry.create();
auto entity3 = registry.create();
auto& pose = registry.assign<Pose>(entity1, 1.0f, 2.0f, 3.0f);
registry.assign<Pose>(entity2);
registry.view<Pose>().each([&](entt11::entity entity, const Pose& pose) {
std::cout << entity << std::endl;
std::cout << pose.p << std::endl;
});
}
And here's the implementation.
entt11.hpp
#pragma once
#include <iostream> // std::cout
#include <cstdint> // std::uint32_t
#include <vector> // std::vector
#include <unordered_map> // std::unordered_map
#include <functional> // std::function<>
namespace entt11 {
using entity = std::uint32_t;
static std::vector<entity> entities;
template<typename T>
std::unordered_map<entity, T>& pool() {
static std::unordered_map<entity, T> pool{};
return pool;
}
template<typename T>
struct View {
void each(std::function<void(entity, T)> func) {
for (auto kv : pool<T>()) {
func(kv.first, kv.second);
}
}
};
struct registry {
entity create() {
entity e = entities.size();
entities.emplace_back(e);
return e;
}
template<typename T, typename... Args>
T& assign(entity e, Args ... args) {
return pool<T>()[e] = T{ args... };
};
template<typename T>
View<T> view() { return View<T>{}; }
};
} // end entt11
Next we'll learn about what working with an ECS would look like if you didn't have templates, such as when working in C or some other language.
...
EnTT - Fast and Reliable ECS (Entity Component System)
Table of contents
Examples
Blog
- RAII
- Polymorphism
- Shared Components
- Intent System
- Input Handling
- Undo
- Operator Stack
- State
- Resources
- Interpolation
Resources
Extras