aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorquou <quou@disroot.org>2023-04-28 22:24:08 +1000
committerquou <quou@disroot.org>2023-04-28 22:24:08 +1000
commit34ccbafa9221066cf0ebcad8596404bbc2048302 (patch)
tree2429c5aa8be1820c81a19f7f9231c633408cb051
parent3a6653f510f097bba84e6245577304f7e57f3706 (diff)
Improve the C++ ECS demo by making it respect alignment with the allocation.
-rw-r--r--ecs2.cpp34
1 files changed, 22 insertions, 12 deletions
diff --git a/ecs2.cpp b/ecs2.cpp
index 2b2ac66..28f88ae 100644
--- a/ecs2.cpp
+++ b/ecs2.cpp
@@ -2,15 +2,12 @@
#include <stdio.h>
#include <stdlib.h>
+#include <stdint.h>
+#include <stddef.h>
#include <assert.h>
/* So it's like the other ECS example with a bunch of academic masturbation
- * See https://git.quou.xyz/samples/tree/ecs.c
- *
- * Areas for improvement:
- * - Should really respect alignment.
- * - Entity destruction
- */
+ * See https://git.quou.xyz/samples/tree/ecs.c */
#define max_entities 256
/* If you want more than 32 component types then you'll have to
@@ -22,6 +19,20 @@ typedef int Entity;
unsigned get_new_component_id();
+void* aligned_malloc(size_t size, size_t alignment) {
+ size_t offset = alignment - 1 + sizeof(void*);
+ void* p1 = malloc(size + offset);
+ void** p2 = (void**)(((uintptr_t)(p1) + offset) & ~(alignment - 1));
+ p2[-1] = p1;
+ return p2;
+}
+
+void aligned_free(void* ptr) {
+ if (ptr) {
+ free(((void**)ptr)[-1]);
+ }
+}
+
/* DO NOT make either of these functions static. That will break stuff. */
template <typename T>
unsigned get_component_id() {
@@ -45,13 +56,13 @@ struct Component_Pool {
Component_Pool(): data(0) {}
- void init(int es) {
+ void init(int es, int alignment) {
element_size = es;
- data = malloc(element_size * max_entities);
+ data = aligned_malloc(element_size * max_entities, alignment);
}
void deinit() {
- free(data);
+ aligned_free(data);
}
bool isinit() {
@@ -61,10 +72,9 @@ struct Component_Pool {
struct World {
Component_Pool pools[max_component_types];
+ unsigned bitset[max_entities];
int entity_count;
- int bitset[max_entities];
-
World(): entity_count(0) {}
void deinit() {
@@ -77,7 +87,7 @@ struct World {
template <typename T>
void register_component_type() {
- pools[get_component_id<T>()].init(sizeof(T));
+ pools[get_component_id<T>()].init(sizeof(T), alignof(T));
}
Entity create_entity() {