Entitas  0.40.0
Entitas is a super fast Entity Component System (ECS) Framework specifically made for C# and Unity
MatcherStatic.cs
1 using System;
2 using System.Collections.Generic;
3 
4 namespace Entitas {
5 
6  public partial class Matcher<TEntity> {
7 
8  public static IAllOfMatcher<TEntity> AllOf(params int[] indices) {
9  var matcher = new Matcher<TEntity>();
10  matcher._allOfIndices = distinctIndices(indices);
11  return matcher;
12  }
13 
14  public static IAllOfMatcher<TEntity> AllOf(params IMatcher<TEntity>[] matchers) {
15  var allOfMatcher = (Matcher<TEntity>)Matcher<TEntity>.AllOf(mergeIndices(matchers));
16  setComponentNames(allOfMatcher, matchers);
17  return allOfMatcher;
18  }
19 
20  public static IAnyOfMatcher<TEntity> AnyOf(params int[] indices) {
21  var matcher = new Matcher<TEntity>();
22  matcher._anyOfIndices = distinctIndices(indices);
23  return matcher;
24  }
25 
26  public static IAnyOfMatcher<TEntity> AnyOf(params IMatcher<TEntity>[] matchers) {
27  var anyOfMatcher = (Matcher<TEntity>)Matcher<TEntity>.AnyOf(mergeIndices(matchers));
28  setComponentNames(anyOfMatcher, matchers);
29  return anyOfMatcher;
30  }
31 
32  static int[] mergeIndices(int[] allOfIndices, int[] anyOfIndices, int[] noneOfIndices) {
33  var indicesList = EntitasCache.GetIntList();
34 
35  if(allOfIndices != null) {
36  indicesList.AddRange(allOfIndices);
37  }
38  if(anyOfIndices != null) {
39  indicesList.AddRange(anyOfIndices);
40  }
41  if(noneOfIndices != null) {
42  indicesList.AddRange(noneOfIndices);
43  }
44 
45  var mergedIndices = distinctIndices(indicesList);
46 
47  EntitasCache.PushIntList(indicesList);
48 
49  return mergedIndices;
50  }
51 
52  static int[] mergeIndices(IMatcher<TEntity>[] matchers) {
53  var indices = new int[matchers.Length];
54  for (int i = 0; i < matchers.Length; i++) {
55  var matcher = matchers[i];
56  if(matcher.indices.Length != 1) {
57  throw new MatcherException(matcher.indices.Length);
58  }
59  indices[i] = matcher.indices[0];
60  }
61 
62  return indices;
63  }
64 
65  static string[] getComponentNames(IMatcher<TEntity>[] matchers) {
66  for (int i = 0; i < matchers.Length; i++) {
67  var matcher = matchers[i] as Matcher<TEntity>;
68  if(matcher != null && matcher.componentNames != null) {
69  return matcher.componentNames;
70  }
71  }
72 
73  return null;
74  }
75 
76  static void setComponentNames(Matcher<TEntity> matcher, IMatcher<TEntity>[] matchers) {
77  var componentNames = getComponentNames(matchers);
78  if(componentNames != null) {
79  matcher.componentNames = componentNames;
80  }
81  }
82 
83  static int[] distinctIndices(IList<int> indices) {
84  var indicesSet = EntitasCache.GetIntHashSet();
85 
86  foreach(var index in indices) {
87  indicesSet.Add(index);
88  }
89  var uniqueIndices = new int[indicesSet.Count];
90  indicesSet.CopyTo(uniqueIndices);
91  Array.Sort(uniqueIndices);
92 
93  EntitasCache.PushIntHashSet(indicesSet);
94 
95  return uniqueIndices;
96  }
97  }
98 }