namespace ChickenGameTest; using System; using System.Collections.Generic; using System.Numerics; // using System.Management; // public partial class StructuralInstance where TAttribute : class // { public sealed class StructuralBuilder where TAttribute : class { private readonly Dictionary _components = []; public StructuralBuilder() { } public StructuralBuilder(IStructuralInstance existing) { foreach (var (id, value) in existing.GetAttributes()) { _components[id] = value; } // for (int i = 0; i < existing.ComponentCount; i++) // { // var typeId = existing._attributesTypeIds[i]; // var component = existing.GetComponentAt(i); // _components[typeId] = component; // } } public StructuralBuilder Add(T component) where T : TAttribute { int id = ComponentTypeRegistry.GetId(); _components[id] = component; return this; } public StructuralBuilder Upsert(Func ifExists, Func none) where T : TAttribute { int id = ComponentTypeRegistry.GetId(); _components[id] = _components.TryGetValue(id, out var old) ? ifExists((T)old) : none(); return this; } public StructuralBuilder CombineWith(IStructuralInstance other, Action? configure = null) { var binder = new CombineBinder(); configure?.Invoke(binder); foreach (var (id, value) in other.GetAttributes()) { if (binder._ignores.Contains(id)) { continue; } if (_components.TryGetValue(id, out var existing) && binder._rules.TryGetValue(id, out var rule)) { _components[id] = rule.Invoke(existing, value); continue; } _components[id] = value; } return this; } public StructuralBuilder Remove() where T : TAttribute { int id = ComponentTypeRegistry.GetId(); _components.Remove(id); return this; } public bool Has() where T : TAttribute { int id = ComponentTypeRegistry.GetId(); return _components.ContainsKey(id); } public StructuralInstance Build() { int count = _components.Count; var typeIds = new int[count]; var components = new TAttribute[count]; int i = 0; foreach (var kv in _components) { typeIds[i] = kv.Key; components[i] = kv.Value; i++; } Array.Sort(typeIds, components); return new StructuralInstance(typeIds, components); } public MutableStructuralInstance BuildMutable() { // int count = _components.Count; var sortedList = new SortedList(_components); // var typeIds = new int[count]; // var components = new TAttribute[count]; // int i = 0; // foreach (var kv in _components) // { // typeIds[i] = kv.Key; // components[i] = kv.Value; // i++; // } // Array.Sort(typeIds, components); return new MutableStructuralInstance(sortedList); } public class CombineBinder { internal readonly Dictionary> _rules = []; internal readonly HashSet _ignores = []; public CombineBinder Bind(Func func) where T : TAttribute { _rules[ComponentType.Id] = (a, b) => func((T)a, (T)b); return this; } public CombineBinder Ignore() where T : TAttribute { _ignores.Add(ComponentType.Id); return this; } } } // }