encompass-cs/encompass-cs/Engines/Detector.cs

60 lines
1.9 KiB
C#

using System;
using System.Reflection;
using System.Collections.Generic;
using Encompass.Exceptions;
namespace Encompass.Engines
{
public abstract class Detector : Engine, IEntityTracker
{
private readonly List<Type> componentTypes = new List<Type>();
private readonly EntityTracker entityTracker = new EntityTracker();
public IEnumerable<Type> ComponentTypes { get { return componentTypes; } }
protected Detector()
{
var detectsAttribute = GetType().GetCustomAttribute<Detects>(false);
if (detectsAttribute != null)
{
componentTypes = detectsAttribute.componentTypes;
}
else
{
throw new DetectorWithoutComponentTypesException("Detector {0} does not have any component types declared. Use the Detects attribute to declare component types", GetType().Name);
}
}
public override void Update(double dt)
{
foreach (var id in entityTracker.TrackedEntityIDs)
{
Detect(GetEntity(id), dt);
}
}
public abstract void Detect(Entity entity, double dt);
public bool CheckAndTrackEntity(Guid entityID)
{
var entity = GetEntity(entityID);
var shouldTrack = CheckEntity(entity);
if (shouldTrack) { entityTracker.TrackEntity(entityID); }
return shouldTrack;
}
public bool CheckAndUntrackEntity(Guid entityID)
{
var entity = GetEntity(entityID);
var shouldUntrack = !CheckEntity(entity);
if (shouldUntrack) { entityTracker.UntrackEntity(entityID); }
return shouldUntrack;
}
private bool CheckEntity(Entity entity)
{
return EntityChecker.CheckEntity(entity, componentTypes);
}
}
}