-
Notifications
You must be signed in to change notification settings - Fork 365
Expand file tree
/
Copy pathMEStockingHatchPartMachine.java
More file actions
424 lines (368 loc) · 16.5 KB
/
MEStockingHatchPartMachine.java
File metadata and controls
424 lines (368 loc) · 16.5 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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package com.gregtechceu.gtceu.integration.ae2.machine;
import com.gregtechceu.gtceu.api.blockentity.BlockEntityCreationInfo;
import com.gregtechceu.gtceu.api.machine.MetaMachine;
import com.gregtechceu.gtceu.api.machine.feature.multiblock.IMultiPart;
import com.gregtechceu.gtceu.api.machine.multiblock.MultiblockControllerMachine;
import com.gregtechceu.gtceu.api.machine.trait.NotifiableFluidTank;
import com.gregtechceu.gtceu.api.sync_system.annotations.SaveField;
import com.gregtechceu.gtceu.api.sync_system.annotations.SyncToClient;
import com.gregtechceu.gtceu.common.data.GTItems;
import com.gregtechceu.gtceu.common.item.behavior.IntCircuitBehaviour;
import com.gregtechceu.gtceu.common.mui.GTGuiTextures;
import com.gregtechceu.gtceu.common.mui.widgets.PopupPanel;
import com.gregtechceu.gtceu.config.ConfigHolder;
import com.gregtechceu.gtceu.integration.ae2.machine.feature.multiblock.IMEStockingPart;
import com.gregtechceu.gtceu.integration.ae2.slot.ExportOnlyAEFluidList;
import com.gregtechceu.gtceu.integration.ae2.slot.ExportOnlyAEFluidSlot;
import com.gregtechceu.gtceu.integration.ae2.slot.ExportOnlyAESlot;
import com.gregtechceu.gtceu.integration.ae2.slot.IConfigurableSlotList;
import com.gregtechceu.gtceu.integration.ae2.utils.AEUtil;
import net.minecraft.MethodsReturnNonnullByDefault;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraftforge.fluids.FluidStack;
import appeng.api.config.Actionable;
import appeng.api.networking.IGrid;
import appeng.api.stacks.AEFluidKey;
import appeng.api.stacks.AEKey;
import appeng.api.stacks.GenericStack;
import appeng.api.storage.MEStorage;
import brachy.modularui.api.IPanelHandler;
import brachy.modularui.api.drawable.IKey;
import brachy.modularui.drawable.ItemDrawable;
import brachy.modularui.drawable.UITexture;
import brachy.modularui.screen.ModularPanel;
import brachy.modularui.screen.RichTooltip;
import brachy.modularui.value.BoolValue;
import brachy.modularui.value.sync.PanelSyncManager;
import brachy.modularui.value.sync.SyncHandlers;
import brachy.modularui.widgets.ButtonWidget;
import brachy.modularui.widgets.ToggleButton;
import brachy.modularui.widgets.layout.Flow;
import brachy.modularui.widgets.textfield.TextFieldWidget;
import it.unimi.dsi.fastutil.objects.Object2LongMap;
import lombok.Getter;
import lombok.Setter;
import org.jetbrains.annotations.Nullable;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.function.Predicate;
import javax.annotation.ParametersAreNonnullByDefault;
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public class MEStockingHatchPartMachine extends MEInputHatchPartMachine implements IMEStockingPart {
private static final int CONFIG_SIZE = 16;
@SyncToClient
@SaveField
@Getter
private boolean autoPull;
@Getter
@Setter
@SaveField
private int minStackSize = 1;
@Getter
@Setter
@SaveField
private int ticksPerCycle = 40;
@Setter
private Predicate<GenericStack> autoPullTest;
public MEStockingHatchPartMachine(BlockEntityCreationInfo info) {
super(info);
this.autoPullTest = $ -> false;
}
/////////////////////////////////
// ***** Machine LifeCycle ****//
/////////////////////////////////
@Override
public void addedToController(MultiblockControllerMachine controller) {
super.addedToController(controller);
IMEStockingPart.super.addedToController(controller);
}
@Override
public void removedFromController(MultiblockControllerMachine controller) {
IMEStockingPart.super.removedFromController(controller);
super.removedFromController(controller);
}
@Override
protected NotifiableFluidTank createTank(int initialCapacity, int slots) {
this.aeFluidHandler = new ExportOnlyAEStockingFluidList(this, CONFIG_SIZE);
return this.aeFluidHandler;
}
/////////////////////////////////
// ********** Sync ME *********//
/////////////////////////////////
@Override
public void autoIO() {
super.autoIO();
if (ticksPerCycle == 0) ticksPerCycle = ConfigHolder.INSTANCE.compat.ae2.updateIntervals; // Emergency Check to
// Avoid Crash loops.
if (getOffsetTimer() % ticksPerCycle == 0) {
if (autoPull) {
refreshList();
}
syncME();
}
}
@Override
protected void syncME() {
MEStorage networkInv = this.getMainNode().getGrid().getStorageService().getInventory();
for (ExportOnlyAEFluidSlot slot : aeFluidHandler.getInventory()) {
var config = slot.getConfig();
if (config != null) {
// Try to fill the slot
var key = config.what();
long extracted = networkInv.extract(key, Long.MAX_VALUE, Actionable.SIMULATE, actionSource);
if (extracted >= minStackSize) {
slot.setStock(new GenericStack(key, extracted));
continue;
}
}
slot.setStock(null);
}
}
/*
* @Override
* public void attachSideTabs(TabsWidget sideTabs) {
* sideTabs.setMainTab(this); // removes the cover configurator, it's pointless and clashes with layout.
* }
*/
@Override
protected void flushInventory() {
// no-op, nothing to send back to the network
}
@Override
public IConfigurableSlotList getSlotList() {
return aeFluidHandler;
}
@Override
public boolean testConfiguredInOtherPart(@Nullable GenericStack config) {
if (config == null) return false;
if (!isFormed()) return false;
for (MultiblockControllerMachine controller : getControllers()) {
for (IMultiPart part : controller.getParts()) {
if (part instanceof MEStockingHatchPartMachine hatch) {
if (hatch == this) continue;
if (hatch.aeFluidHandler.hasStackInConfig(config, false)) {
return true;
}
}
}
}
return false;
}
@Override
public void setAutoPull(boolean autoPull) {
this.autoPull = autoPull;
if (!isRemote()) {
syncDataHolder.markClientSyncFieldDirty("autoPull");
if (!this.autoPull) {
this.aeFluidHandler.clearInventory(0);
} else if (updateMEStatus()) {
this.refreshList();
updateTankSubscription();
}
}
}
private void refreshList() {
IGrid grid = this.getMainNode().getGrid();
if (grid == null) {
aeFluidHandler.clearInventory(0);
return;
}
MEStorage networkStorage = grid.getStorageService().getInventory();
var counter = networkStorage.getAvailableStacks();
// Use a PriorityQueue to sort the stacks on size, take the first CONFIG_SIZE
// biggest stacks.
PriorityQueue<Object2LongMap.Entry<AEKey>> topFluids = new PriorityQueue<>(
Comparator.comparingLong(Object2LongMap.Entry<AEKey>::getLongValue));
for (Object2LongMap.Entry<AEKey> entry : counter) {
long amount = entry.getLongValue();
AEKey what = entry.getKey();
if (amount <= 0) continue;
if (!(what instanceof AEFluidKey fluidKey)) continue;
long request = networkStorage.extract(what, amount, Actionable.SIMULATE, actionSource);
if (request == 0) continue;
// Ensure that it is valid to configure with this stack
if (autoPullTest != null && !autoPullTest.test(new GenericStack(fluidKey, amount))) continue;
if (amount >= minStackSize) {
if (topFluids.size() < CONFIG_SIZE) {
topFluids.offer(entry);
} else if (amount > topFluids.peek().getLongValue()) {
topFluids.poll();
topFluids.offer(entry);
}
}
}
// Now, topFluids is a PQ with CONFIG_SIZE highest amount fluids in the system.
int index;
int fluidAmount = topFluids.size();
for (index = 0; index < CONFIG_SIZE; index++) {
if (topFluids.isEmpty()) break;
Object2LongMap.Entry<AEKey> entry = topFluids.poll();
AEKey what = entry.getKey();
long amount = entry.getLongValue();
// If we get here, the fluid has already been checked by the PQ.
long request = networkStorage.extract(what, amount, Actionable.SIMULATE, actionSource);
// Since we want our fluids to be displayed from highest to lowest, but poll() returns
// the lowest first, we fill in the slots starting at fluidAmount-1
var slot = this.aeFluidHandler.getInventory()[fluidAmount - index - 1];
slot.setConfig(new GenericStack(what, 1));
slot.setStock(new GenericStack(what, request));
}
aeFluidHandler.clearInventory(index);
}
///////////////////////////////
// ********** GUI ***********//
///////////////////////////////
@Override
protected Flow createButtonColumn(ModularPanel<?> panel, PanelSyncManager syncManager,
UITexture backgroundTexture) {
IPanelHandler settingsPanelHandler = syncManager.syncedPanel("stocking_settings", true,
(sm, sh) -> PopupPanel.createPopupPanel("stocking_settings_panel", 140, 70)
.child(Flow.col()
.coverChildren()
.child(IKey.lang("gtceu.gui.me_network.min_stack_size").asWidget())
.child(new TextFieldWidget()
.size(120, 18)
.value(SyncHandlers.intNumber(this::getMinStackSize, this::setMinStackSize))
.setNumbers(1, Integer.MAX_VALUE))
.child(IKey.lang("gtceu.gui.me_network.ticks_per_cycle").asWidget())
.child(new TextFieldWidget()
.size(120, 18)
.value(SyncHandlers.intNumber(this::getTicksPerCycle, this::setTicksPerCycle))
.setNumbers(1, 200))
.margin(5)));
return super.createButtonColumn(panel, syncManager, backgroundTexture)
.child(new ToggleButton()
.value(new BoolValue.Dynamic(this::isAutoPull, this::setAutoPull))
.stateOverlay(GTGuiTextures.BUTTON_AUTO_PULL)
.tooltipAutoUpdate(true)
.tooltipBuilder(r -> r
.addLine(IKey.lang("gtceu.gui.me_network.auto_pull_toggle"))))
.child(new ButtonWidget<>()
.size(18)
.onMousePressed((x, y, b) -> {
settingsPanelHandler.openPanel();
return true;
})
.overlay(new ItemDrawable(GTItems.TOOL_DATA_STICK.asItem()).asIcon().size(16))
.tooltip(new RichTooltip()
.addLine(IKey.lang("gtceu.gui.me_network.stocking_settings"))));
}
////////////////////////////////
// ******* Interaction *******//
////////////////////////////////
@Override
protected InteractionResult onScrewdriverClick(Player playerIn, InteractionHand hand, Direction gridSide,
BlockHitResult hitResult) {
if (!isRemote()) {
setAutoPull(!autoPull);
if (autoPull) {
playerIn.sendSystemMessage(
Component.translatable("gtceu.machine.me.stocking_auto_pull_enabled"));
} else {
playerIn.sendSystemMessage(
Component.translatable("gtceu.machine.me.stocking_auto_pull_disabled"));
}
}
return InteractionResult.sidedSuccess(isRemote());
}
////////////////////////////////
// ****** Configuration ******//
////////////////////////////////
@Override
protected CompoundTag writeConfigToTag() {
if (!autoPull) {
CompoundTag tag = super.writeConfigToTag();
tag.putBoolean("AutoPull", false);
return tag;
}
// if in auto-pull, no need to write actual configured slots, but still need to write the ghost circuit
CompoundTag tag = new CompoundTag();
tag.putBoolean("AutoPull", true);
tag.putByte("GhostCircuit",
(byte) IntCircuitBehaviour.getCircuitConfiguration(circuitInventory.getStackInSlot(0)));
return tag;
}
@Override
protected void readConfigFromTag(CompoundTag tag) {
if (tag.getBoolean("AutoPull")) {
// if being set to auto-pull, no need to read the configured slots
this.setAutoPull(true);
circuitInventory.setStackInSlot(0, IntCircuitBehaviour.stack(tag.getByte("GhostCircuit")));
return;
}
// set auto pull first to avoid issues with clearing the config after reading from the data stick
this.setAutoPull(false);
super.readConfigFromTag(tag);
}
private class ExportOnlyAEStockingFluidList extends ExportOnlyAEFluidList {
public ExportOnlyAEStockingFluidList(MetaMachine holder, int slots) {
super(holder, slots, ExportOnlyAEStockingFluidSlot::new);
}
@Override
public boolean isAutoPull() {
return autoPull;
}
@Override
public boolean isStocking() {
return true;
}
@Override
public boolean hasStackInConfig(GenericStack stack, boolean checkExternal) {
boolean inThisHatch = super.hasStackInConfig(stack, false);
if (inThisHatch) return true;
if (checkExternal) {
return testConfiguredInOtherPart(stack);
}
return false;
}
}
private class ExportOnlyAEStockingFluidSlot extends ExportOnlyAEFluidSlot {
public ExportOnlyAEStockingFluidSlot() {
super();
}
public ExportOnlyAEStockingFluidSlot(@Nullable GenericStack config, @Nullable GenericStack stock) {
super(config, stock);
}
@Override
public ExportOnlyAEFluidSlot copy() {
return new ExportOnlyAEStockingFluidSlot(
this.config == null ? null : copy(this.config),
this.stock == null ? null : copy(this.stock));
}
@Override
public FluidStack drain(int maxDrain, FluidAction action) {
if (this.stock != null && this.config != null) {
// Extract the items from the real net to either validate (simulate)
// or extract (modulate) when this is called
if (!isOnline()) return FluidStack.EMPTY;
MEStorage aeNetwork = getMainNode().getGrid().getStorageService().getInventory();
Actionable actionable = action.simulate() ? Actionable.SIMULATE : Actionable.MODULATE;
var key = config.what();
long extracted = aeNetwork.extract(key, maxDrain, actionable, actionSource);
if (extracted > 0) {
FluidStack resultStack = key instanceof AEFluidKey fluidKey ?
AEUtil.toFluidStack(fluidKey, extracted) : FluidStack.EMPTY;
if (action.execute()) {
// may as well update the display here
this.stock = ExportOnlyAESlot.copy(stock, stock.amount() - extracted);
if (this.stock.amount() == 0) {
this.stock = null;
}
if (this.onContentsChanged != null) {
this.onContentsChanged.run();
}
}
return resultStack;
}
}
return FluidStack.EMPTY;
}
}
}