-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathSimplePowerGrid.java
More file actions
286 lines (265 loc) · 10.6 KB
/
SimplePowerGrid.java
File metadata and controls
286 lines (265 loc) · 10.6 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package dev.dubhe.anvilcraft.api.power;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import dev.dubhe.anvilcraft.AnvilCraft;
import dev.dubhe.anvilcraft.client.support.PowerGridSupport;
import dev.dubhe.anvilcraft.util.ColorUtil;
import dev.dubhe.anvilcraft.util.Line;
import dev.dubhe.anvilcraft.util.ShapeUtil;
import dev.dubhe.anvilcraft.util.VirtualThreadFactoryImpl;
import lombok.Getter;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtOps;
import net.minecraft.nbt.Tag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.util.FastColor;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.BooleanOp;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@Getter
public class SimplePowerGrid {
private static ExecutorService EXECUTOR;
public static final Codec<SimplePowerGrid> CODEC = RecordCodecBuilder.create(ins -> ins.group(
Codec.INT.fieldOf("hash").forGetter(o -> o.id),
Codec.STRING.fieldOf("level").forGetter(o -> o.level),
BlockPos.CODEC.fieldOf("pos").forGetter(o -> o.pos),
PowerComponentInfo.CODEC.listOf().fieldOf("powerComponentInfoList").forGetter(it -> it.powerComponentInfoList),
Codec.INT.fieldOf("generate").forGetter(o -> o.generate),
Codec.INT.fieldOf("consume").forGetter(o -> o.consume)
).apply(ins, SimplePowerGrid::new));
static {
recreateExecutor();
}
private final Random random = new Random();
private final int[] EMPTY = {};
private final int id;
private final String level;
private final BlockPos pos;
private final List<BlockPos> blocks = new ArrayList<>();
private final List<PowerComponentInfo> powerComponentInfoList = new ArrayList<>();
private final List<Line> powerTransmitterLines = new ArrayList<>();
private final int generate; // 发电功率
private final int consume; // 耗电功率
private final int color;
private List<Line> powerGridBoundLines = new ArrayList<>();
private Future<?> shapeFuture;
/**
* 简单电网
*/
public SimplePowerGrid(int id, String level, BlockPos pos, List<PowerComponentInfo> powerComponentInfoList, int generate, int consume) {
this.pos = pos;
this.level = level;
this.id = id;
random.setSeed(id);
int[] colors = ColorUtil.hsvToRgb(random.nextInt(360), 80, 80);
this.color = FastColor.ARGB32.color((int) (0.4 * 255), colors[0], colors[1], colors[2]);
this.generate = generate;
this.consume = consume;
blocks.addAll(powerComponentInfoList.stream().map(PowerComponentInfo::pos).toList());
this.powerComponentInfoList.addAll(powerComponentInfoList);
createMergedOutlineShape();
createTransmitterVisualLines();
}
/**
* @param grid 电网
*/
public SimplePowerGrid(PowerGrid grid) {
this.id = grid.hashCode();
this.level = grid.getLevel().dimension().location().toString();
this.pos = grid.getPos();
Set<IPowerComponent> powerComponents = new HashSet<>();
powerComponents.addAll(grid.storages);
powerComponents.addAll(grid.producers);
powerComponents.addAll(grid.consumers);
powerComponents.addAll(grid.transmitters);
this.color = 0;
for (IPowerComponent component : powerComponents) {
switch (component.getComponentType()) {
case STORAGE -> {
IPowerStorage it = (IPowerStorage) component;
powerComponentInfoList.add(new PowerComponentInfo(
it.getPos(),
0,
0,
it.getPowerAmount(),
it.getCapacity(),
it.getRange(),
PowerComponentType.STORAGE
));
}
case CONSUMER -> {
IPowerConsumer it = (IPowerConsumer) component;
powerComponentInfoList.add(new PowerComponentInfo(
it.getPos(),
it.getInputPower(),
0,
0,
0,
it.getRange(),
PowerComponentType.CONSUMER
));
}
case PRODUCER -> {
IPowerProducer it = (IPowerProducer) component;
powerComponentInfoList.add(new PowerComponentInfo(
it.getPos(),
0,
it.getOutputPower(),
0,
0,
it.getRange(),
PowerComponentType.PRODUCER
));
}
case TRANSMITTER -> {
IPowerTransmitter it = (IPowerTransmitter) component;
powerComponentInfoList.add(new PowerComponentInfo(
it.getPos(),
0,
0,
0,
0,
it.getRange(),
PowerComponentType.TRANSMITTER
));
}
default -> powerComponentInfoList.add(new PowerComponentInfo(
component.getPos(),
0,
0,
0,
0,
component.getRange(),
PowerComponentType.INVALID
));
}
}
this.consume = grid.getConsume();
this.generate = grid.getGenerate();
}
/**
* 寻找电网
*/
public static Optional<SimplePowerGrid> findPowerGrid(BlockPos pos) {
for (SimplePowerGrid value : PowerGridSupport.getGridMap().values()) {
for (BlockPos block : value.blocks) {
if (block.equals(pos)) {
return Optional.of(value);
}
}
}
return Optional.empty();
}
public static void recreateExecutor() {
if (EXECUTOR != null) {
EXECUTOR.shutdownNow();
}
EXECUTOR = Executors.newThreadPerTaskExecutor(new VirtualThreadFactoryImpl());
}
/**
* @param buf 缓冲区
*/
public void encode(FriendlyByteBuf buf) {
Tag tag = CODEC.encodeStart(NbtOps.INSTANCE, this).getOrThrow();
CompoundTag data = new CompoundTag();
data.put("data", tag);
buf.writeNbt(data);
}
public boolean collideFast(AABB aabb) {
for (PowerComponentInfo it : this.powerComponentInfoList) {
if (new AABB(it.pos()).inflate(it.range()).intersects(aabb)) return true;
}
return false;
}
/**
* 获得指定坐标的电网元件信息
*/
public Optional<PowerComponentInfo> getInfoForPos(BlockPos pos) {
return powerComponentInfoList.stream().filter(it -> it.pos().equals(pos)).findFirst();
}
public boolean isOverloaded() {
return this.getConsume() > this.getGenerate();
}
public boolean shouldRender(Vec3 cameraPos) {
int renderDistance = Minecraft.getInstance().options.getEffectiveRenderDistance() * 16;
return powerComponentInfoList.stream().anyMatch(it -> it.pos().getCenter().distanceTo(cameraPos) < renderDistance);
}
private void createTransmitterVisualLines() {
List<Map.Entry<BlockPos, AABB>> shapes = this.powerComponentInfoList.stream()
.filter(it -> it.type() == PowerComponentType.TRANSMITTER)
.map(it -> Map.entry(
it.pos(), new AABB(
-it.range() + it.pos().getX(),
-it.range() + it.pos().getY(),
-it.range() + it.pos().getZ(),
it.range() + 1 + it.pos().getX(),
it.range() + 1 + it.pos().getY(),
it.range() + 1 + it.pos().getZ()
)
))
.toList();
for (int i = 0; i < shapes.size(); i++) {
Map.Entry<BlockPos, AABB> e1 = shapes.get(i);
for (int j = i + 1; j < shapes.size(); j++) {
Map.Entry<BlockPos, AABB> e2 = shapes.get(j);
AABB a = e1.getValue();
AABB b = e2.getValue();
if (a.intersects(b)) {
Vec3 start = e1.getKey().getCenter();
Vec3 end = e2.getKey().getCenter();
powerTransmitterLines.add(new Line(start, end));
}
}
}
}
private void createMergedOutlineShape() {
if (SimplePowerGrid.EXECUTOR.isShutdown()) SimplePowerGrid.recreateExecutor();
this.shapeFuture = SimplePowerGrid.EXECUTOR.submit(() -> {
List<VoxelShape> input = new ArrayList<>();
for (PowerComponentInfo it : powerComponentInfoList) {
Vec3 center = it.pos().getCenter();
float size = it.range() * 2 + 1;
input.add(Shapes.create(AABB.ofSize(center, size, size, size)));
}
//noinspection CatchMayIgnoreException
try {
Future<VoxelShape> future = ShapeUtil.threadedJoin(input, BooleanOp.OR, EXECUTOR);
VoxelShape shape = future.get();
List<Line> lines = new ArrayList<>();
shape.forAllEdges((minX, minY, minZ, maxX, maxY, maxZ) -> {
Vec3 min = new Vec3(minX, minY, minZ);
Vec3 max = new Vec3(maxX, maxY, maxZ);
lines.add(new Line(min, max));
});
this.powerGridBoundLines = lines;
} catch (Throwable e) {
if (e instanceof ExecutionException) {
AnvilCraft.LOGGER.error("Exception thrown while building power grid shape.", e);
}
}
});
}
private BlockPos offset(BlockPos pos) {
return pos.subtract(this.pos);
}
public void destroy() {
if (!shapeFuture.isDone()) {
shapeFuture.cancel(true);
}
}
}