aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/java/coffee/liz/ecs/DAGWorld.java
blob: b5b54c2e1b83dfdcfae3c222b02d29f2548bde64 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package coffee.liz.ecs;

import coffee.liz.ecs.model.Component;
import coffee.liz.ecs.model.Entity;
import coffee.liz.ecs.model.System;
import coffee.liz.ecs.model.World;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/** World that updates in {@link System#getDependencies()} topological order. */
@Log4j2
@RequiredArgsConstructor
public class DAGWorld<T> implements World<T> {
	/** All entities in the world. */
	protected final Set<Entity> entities = Collections.synchronizedSet(new HashSet<>());

	/** Cache mapping component types to entities having that component. */
	private final Map<Class<? extends Component>, Set<Entity>> componentCache = Collections
			.synchronizedMap(new HashMap<>());

	/** Deterministic ID's for spawned entities. */
	private final AtomicInteger nextEntityId = new AtomicInteger(0);

	/** All registered systems. */
	protected final Map<Class<? extends System<T>>, System<T>> systems;

	/** Ordered list of systems for execution. */
	private final List<System<T>> systemExecutionOrder;

	public DAGWorld(final Map<Class<? extends System<T>>, System<T>> systems) {
		this.systems = systems;
		this.systemExecutionOrder = buildExecutionOrder(systems.values().stream().toList());
		log.debug("Executing in order: {}", systemExecutionOrder);
	}

	@Override
	public Entity createEntity() {
		final Entity entity = Entity.builder().id(nextEntityId.incrementAndGet()).build();
		entities.add(entity);
		return entity;
	}

	@Override
	public void removeEntity(final Entity entity) {
		entity.getComponentMap().keySet().forEach(componentType -> {
			final Set<Entity> cachedEntities = componentCache.get(componentType);
			if (cachedEntities != null) {
				cachedEntities.remove(entity);
			}
		});
		entities.remove(entity);
	}

	@Override
	public Set<Entity> query(final Collection<Class<? extends Component>> components) {
		if (components.isEmpty()) {
			return Set.copyOf(entities);
		}

		final Class<? extends Component> firstType = components.iterator().next();
		final Set<Entity> candidates = componentCache.get(firstType);
		if (candidates == null) {
			return Collections.emptySet();
		}

		return candidates.stream().filter(entity -> components.stream().allMatch(entity::has))
				.collect(Collectors.toSet());
	}

	@Override
	public void update(final T state, final Duration duration) {
		systemExecutionOrder.forEach(system -> {
			refreshComponentCache();
			system.update(this, state, duration);
		});
		refreshComponentCache();
	}

	@SuppressWarnings("unchecked")
	@Override
	public <S extends System<T>> S getSystem(final Class<S> system) {
		return (S) systems.get(system);
	}

	private void refreshComponentCache() {
		componentCache.clear();
		entities.forEach(entity -> entity.getComponentMap().keySet().forEach(
				componentType -> componentCache.computeIfAbsent(componentType, _ -> new HashSet<>()).add(entity)));
	}

	private List<System<T>> buildExecutionOrder(final Collection<System<T>> systems) {
		if (systems.isEmpty()) {
			return Collections.emptyList();
		}

		final Map<Class<?>, System<T>> systemMap = systems.stream()
				.collect(Collectors.toMap(System::getClass, system -> system));
		final Map<Class<?>, Integer> inDegree = new HashMap<>();
		final Map<Class<?>, Set<Class<?>>> adjacencyList = new HashMap<>();

		systems.forEach(system -> {
			final Class<?> systemClass = system.getClass();
			inDegree.put(systemClass, 0);
			adjacencyList.put(systemClass, new HashSet<>());
		});

		systems.forEach(system -> {
			system.getDependencies().forEach(dependency -> {
				if (systemMap.containsKey(dependency)) {
					adjacencyList.get(dependency).add(system.getClass());
					inDegree.merge(system.getClass(), 1, Integer::sum);
				}
			});
		});

		// Kahn's algorithm
		final List<System<T>> result = new ArrayList<>();

		final Queue<Class<?>> queue = new LinkedList<>(
				inDegree.entrySet().stream().filter(entry -> entry.getValue() == 0).map(Map.Entry::getKey).toList());

		while (!queue.isEmpty()) {
			final Class<?> currentClass = queue.poll();
			result.add(systemMap.get(currentClass));

			adjacencyList.getOrDefault(currentClass, Collections.emptySet()).forEach(dependent -> {
				final int newInDegree = inDegree.get(dependent) - 1;
				inDegree.put(dependent, newInDegree);
				if (newInDegree == 0) {
					queue.add(dependent);
				}
			});
		}

		if (result.size() != systems.size()) {
			throw new IllegalStateException("Circular dependency detected in systems");
		}

		return Collections.unmodifiableList(result);
	}

	@Override
	public void close() throws Exception {
		for (final System<T> system : systemExecutionOrder) {
			system.close();
		}
		componentCache.clear();
		entities.clear();
	}
}