EntityData memento

Quick and dirty implementation. An observer extends EntityComponentListener and listen for all changes in the ObservableEntityData :

public class EntityDataObserver implements EntityComponentListener {
	public Map<EntityId, Map<Class<? extends EntityComponent>, EntityComponent>> entities = new HashMap<>();

	@Override
	public void componentChange(EntityChange change) {
		if(!entities.containsKey(change.getEntityId()))
			entities.put(change.getEntityId(), new HashMap<>());
		
		Map<Class<? extends EntityComponent>, EntityComponent> components = entities.get(change.getEntityId());
		if(change.getComponent() == null)
			components.remove(change.getComponentType());
		else
			components.put(change.getComponentType(), change.getComponent());
	}
}

At run, we remove the observer from the entity data. It stores the state juste before the logic start.

At stop, we ask the entity data to erase all its components (with an ugly trick) and to set all the components stored in the observer.

public void setState(Map<EntityId, Map<Class<? extends EntityComponent>, EntityComponent>> entities){
	// we remove all entities that we can find
	// this trick seems ugly...
	long l = createEntity().getId();
	for(long i = 0; i <= l; i++)
		removeEntity(new EntityId(i));
	
	// then we set all components that have been stored by the observer
	for(EntityId eid : entities.keySet()){
		Map<Class<? extends EntityComponent>, EntityComponent> components = entities.get(eid);
		for(EntityComponent comp : components.values())
			setComponent(eid, comp);
	}
	// will it work with a new instance of entity data, where the entity Ids havn't already been created??
	// it remains to be tested
}

It’s working pretty well, although it takes time to rebuild the entity data (maybe because of the node structure of my own that runs behind and refresh everything each time something happens)

Will it work in deserialisation situation, with a new instance of EntityData where the entity Ids have never been created? I can’t say for now since it’s hard to test in my current setup.

Thanks @pspeed to have indicated me the right direction.