using System;
using System.Collections.Generic;
using System.Reflection;
namespace Konis.Testbed
{
///
/// The sprite defs a tuning panel lets an emitter take.
///
public static class SpriteChoices
{
private const BindingFlags Declared = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly;
// The static classes whose sprite fields the testbed offers.
private static readonly Type[] Libraries = { typeof(TestbedSprites), typeof(SoftDisc) };
///
/// Every choice the testbed offers.
///
public static readonly IReadOnlyList All = BuildAll();
private static int IndexOf(List choices, SpriteDef def)
{
for (int i = 0; i < choices.Count; i++)
{
if (ReferenceEquals(choices[i].Def, def))
{
return i;
}
}
return -1;
}
private static string LabelFor(SpriteDef def)
{
return string.IsNullOrEmpty(def.Name) ? def.GetType().Name : def.Name;
}
///
/// Returns a choice for each sprite def held in a public static field of , in
/// declaration order, and then one for each of that no field holds. Each is labeled
/// for its def, and one a field holds takes Library.Field as its source. A def appears once, under the
/// first field that holds it, and a null in is left out.
///
public static IReadOnlyList Build(IEnumerable libraries, IEnumerable inUse)
{
if (libraries == null)
{
throw new ArgumentNullException(nameof(libraries));
}
if (inUse == null)
{
throw new ArgumentNullException(nameof(inUse));
}
var returnMe = new List();
foreach (Type library in libraries)
{
FieldInfo[] fields = library.GetFields(Declared);
Array.Sort(fields, (left, right) => left.MetadataToken.CompareTo(right.MetadataToken));
foreach (FieldInfo field in fields)
{
var def = typeof(SpriteDef).IsAssignableFrom(field.FieldType)
? (SpriteDef)field.GetValue(null) : null;
if (def != null && IndexOf(returnMe, def) < 0)
{
returnMe.Add(new SpriteChoice(def, LabelFor(def), library.Name + "." + field.Name));
}
}
}
foreach (SpriteDef def in inUse)
{
if (def != null && IndexOf(returnMe, def) < 0)
{
returnMe.Add(new SpriteChoice(def, LabelFor(def), source: null));
}
}
return returnMe;
}
// Every effect's own sprite is in the list, so a def bound to the tuning panel always finds its current one.
private static IReadOnlyList BuildAll()
{
var inUse = new List();
foreach (Effect effect in Effects.All)
{
inUse.Add(effect.Def.Sprite);
}
return Build(Libraries, inUse);
}
///
/// Returns the choice that holds , or null when there is none, as for a null def.
///
public static SpriteChoice Find(SpriteDef def)
{
foreach (SpriteChoice choice in All)
{
if (ReferenceEquals(choice.Def, def))
{
return choice;
}
}
return null;
}
}
}