This repository has been archived on 2023-02-02. You can view files and clone it, but cannot push or open issues or pull requests.
mfgames-nitride-cil/src/Nitride/Entities/LinkEntitySequence.cs
2022-07-08 23:52:10 -05:00

65 lines
1.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using FluentValidation;
using Gallium;
namespace Nitride.Entities;
/// <summary>
/// Links a series of entities together in some manner. This assumes that
/// the entities coming into the operation are already ordered.
/// </summary>
[WithProperties]
public partial class LinkEntitySequence : OperationBase, IResolvingOperation
{
private readonly IValidator<LinkEntitySequence> validator;
public LinkEntitySequence(IValidator<LinkEntitySequence> validator)
{
this.validator = validator;
this.CreateSequenceIndex = (
list,
index) => new EntitySequence(list, index);
this.AddSequenceIndex = (
entity,
sequence) => entity.Add(sequence);
}
/// <summary>
/// Gets or sets a callback to add a sequence into a given entity.
/// </summary>
public Func<Entity, EntitySequence, Entity> AddSequenceIndex { get; set; }
/// <summary>
/// Gets or sets the function used to create the sequence index.
/// </summary>
public Func<IReadOnlyList<Entity>, int, EntitySequence> CreateSequenceIndex { get; set; }
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
// Make sure everything is good.
this.validator.ValidateAndThrow(this);
// We pull all the entities into a list so we can walk through them
// more than once along with index access. We also don't reorder the
// list since we assumed it has been ordered already.
var list = input.ToList();
// Go through the list and assign each entity in order with a unique
// copy of the sequence.
for (int i = 0; i < list.Count; i++)
{
Entity entity = list[i];
EntitySequence index = this.CreateSequenceIndex(list.AsReadOnly(), i);
yield return this.AddSequenceIndex(entity, index);
}
}
}