1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package com.lhkbob.entreri.impl;
28
29 import com.lhkbob.entreri.Component;
30 import com.lhkbob.entreri.ComponentIterator;
31
32 import java.util.Arrays;
33
34
35
36
37
38
39 public class ComponentIteratorImpl implements ComponentIterator {
40 private final EntitySystemImpl system;
41
42 private int index;
43
44 private AbstractComponent<?>[] required;
45 private AbstractComponent<?>[] optional;
46
47 private AbstractComponent<?> primary;
48
49
50
51
52
53
54
55
56
57
58 public ComponentIteratorImpl(EntitySystemImpl system) {
59 if (system == null) {
60 throw new NullPointerException("System cannot be null");
61 }
62 this.system = system;
63 required = new AbstractComponent<?>[0];
64 optional = new AbstractComponent<?>[0];
65 primary = null;
66 index = 0;
67 }
68
69 @Override
70 @SuppressWarnings("unchecked")
71 public <T extends Component> T addRequired(Class<T> type) {
72 if (type == null) {
73 throw new NullPointerException("Component type cannot be null");
74 }
75 AbstractComponent<T> data = system.getRepository(type).createDataInstance();
76
77
78 if (primary == null) {
79
80 primary = data;
81 } else {
82
83
84 required = Arrays.copyOf(required, required.length + 1);
85
86 if (data.owner.getMaxComponentIndex() <
87 primary.owner.getMaxComponentIndex()) {
88
89 required[required.length - 1] = primary;
90 primary = data;
91 } else {
92
93 required[required.length - 1] = data;
94 }
95 }
96
97 return (T) data;
98 }
99
100 @Override
101 @SuppressWarnings("unchecked")
102 public <T extends Component> T addOptional(Class<T> type) {
103 if (type == null) {
104 throw new NullPointerException("Component type cannot be null");
105 }
106
107 AbstractComponent<T> data = system.getRepository(type).createDataInstance();
108
109
110 optional = Arrays.copyOf(optional, optional.length + 1);
111 optional[optional.length - 1] = data;
112
113 return (T) data;
114 }
115
116 @Override
117 public boolean next() {
118 if (primary == null) {
119 return false;
120 }
121
122 boolean found;
123 int entity;
124 int component;
125 int count = primary.owner.getMaxComponentIndex();
126 while (index < count - 1) {
127 index++;
128
129 found = true;
130 entity = primary.owner.getEntityIndex(index);
131 if (entity != 0) {
132
133 primary.setIndex(index);
134 for (int i = 0; i < required.length; i++) {
135 component = required[i].owner.getComponentIndex(entity);
136 if (component == 0) {
137 found = false;
138 break;
139 } else {
140 required[i].setIndex(component);
141 }
142 }
143
144 if (found) {
145
146
147 for (int i = 0; i < optional.length; i++) {
148 component = optional[i].owner.getComponentIndex(entity);
149 optional[i].setIndex(component);
150 }
151
152 return true;
153 }
154 }
155 }
156
157 return false;
158 }
159
160 @Override
161 public void reset() {
162 index = 0;
163 }
164 }