-
Notifications
You must be signed in to change notification settings - Fork 365
Expand file tree
/
Copy pathMEStockingBusPartMachine.java
More file actions
439 lines (384 loc) · 17.4 KB
/
MEStockingBusPartMachine.java
File metadata and controls
439 lines (384 loc) · 17.4 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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
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.NotifiableItemStackHandler;
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.ExportOnlyAEItemList;
import com.gregtechceu.gtceu.integration.ae2.slot.ExportOnlyAEItemSlot;
import com.gregtechceu.gtceu.integration.ae2.slot.ExportOnlyAESlot;
import com.gregtechceu.gtceu.integration.ae2.slot.IConfigurableSlotList;
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.item.ItemStack;
import net.minecraft.world.phys.BlockHitResult;
import appeng.api.config.Actionable;
import appeng.api.networking.IGrid;
import appeng.api.stacks.AEItemKey;
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 MEStockingBusPartMachine extends MEInputBusPartMachine implements IMEStockingPart {
@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 MEStockingBusPartMachine(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 NotifiableItemStackHandler createInventory() {
this.aeItemHandler = new ExportOnlyAEStockingItemList(this, CONFIG_SIZE);
return this.aeItemHandler;
}
/////////////////////////////////
// ********** 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() {
// Update the visual display for the fake items. This also is important for the item handler's
// getStackInSlot() method, as it uses the cached items set here.
MEStorage networkInv = this.getMainNode().getGrid().getStorageService().getInventory();
for (ExportOnlyAEItemSlot slot : this.aeItemHandler.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 void setDistinct(boolean isDistinct) {
super.setDistinct(isDistinct);
if (!isRemote() && !isDistinct) {
// Ensure that our configured items won't match any other buses in the multiblock.
// Needed since we allow duplicates in distinct mode on, but not off
validateConfig();
}
}
@Override
public IConfigurableSlotList getSlotList() {
return aeItemHandler;
}
@Override
public boolean testConfiguredInOtherPart(@Nullable GenericStack config) {
if (config == null) return false;
// In distinct mode, we don't need to check other buses since only one bus can run a recipe at a time.
if (!isFormed() || isDistinct()) return false;
// Otherwise, we need to test for if the item is configured
// in any stocking bus in the multi (besides ourselves).
for (MultiblockControllerMachine controller : getControllers()) {
for (IMultiPart part : controller.getParts()) {
if (part instanceof MEStockingBusPartMachine bus) {
// We don't need to check for ourselves, as this case is handled elsewhere.
if (bus == this || bus.isDistinct()) continue;
if (bus.aeItemHandler.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.aeItemHandler.clearInventory(0);
} else if (updateMEStatus()) {
this.refreshList();
updateInventorySubscription();
}
}
}
/**
* Refresh the configuration list in auto-pull mode.
* Sets the config to the CONFIG_SIZE items with the highest amount in the ME system.
*/
private void refreshList() {
IGrid grid = this.getMainNode().getGrid();
if (grid == null) {
aeItemHandler.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>> topItems = 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 AEItemKey itemKey)) 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(itemKey, amount))) continue;
if (amount >= minStackSize) {
if (topItems.size() < CONFIG_SIZE) {
topItems.offer(entry);
} else if (amount > topItems.peek().getLongValue()) {
topItems.poll();
topItems.offer(entry);
}
}
}
// Now, topItems is a PQ with CONFIG_SIZE highest amount items in the system.
int index;
int itemAmount = topItems.size();
for (index = 0; index < CONFIG_SIZE; index++) {
if (topItems.isEmpty()) break;
Object2LongMap.Entry<AEKey> entry = topItems.poll();
AEKey what = entry.getKey();
long amount = entry.getLongValue();
// If we get here, the item has already been checked by the PQ.
long request = networkStorage.extract(what, amount, Actionable.SIMULATE, actionSource);
// Since we want our items to be displayed from highest to lowest, but poll() returns
// the lowest first, we fill in the slots starting at itemAmount-1
var slot = this.aeItemHandler.getInventory()[itemAmount - index - 1];
slot.setConfig(new GenericStack(what, 1));
slot.setStock(new GenericStack(what, request));
}
aeItemHandler.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"))));
}
@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 ExportOnlyAEStockingItemList extends ExportOnlyAEItemList {
public ExportOnlyAEStockingItemList(MetaMachine holder, int slots) {
super(holder, slots, ExportOnlyAEStockingItemSlot::new);
}
@Override
public boolean isAutoPull() {
return autoPull;
}
@Override
public boolean isStocking() {
return true;
}
@Override
public boolean hasStackInConfig(GenericStack stack, boolean checkExternal) {
boolean inThisBus = super.hasStackInConfig(stack, false);
if (inThisBus) return true;
if (checkExternal) {
return testConfiguredInOtherPart(stack);
}
return false;
}
}
private class ExportOnlyAEStockingItemSlot extends ExportOnlyAEItemSlot {
public ExportOnlyAEStockingItemSlot() {
super();
}
public ExportOnlyAEStockingItemSlot(@Nullable GenericStack config, @Nullable GenericStack stock) {
super(config, stock);
}
@Override
public ItemStack extractItem(int slot, int amount, boolean simulate) {
if (slot == 0 && this.stock != null) {
if (this.config != null) {
// Extract the items from the real net to either validate (simulate)
// or extract (modulate) when this is called
if (!isOnline()) return ItemStack.EMPTY;
MEStorage aeNetwork = getMainNode().getGrid().getStorageService().getInventory();
Actionable action = simulate ? Actionable.SIMULATE : Actionable.MODULATE;
var key = config.what();
long extracted = aeNetwork.extract(key, amount, action, actionSource);
if (extracted > 0) {
ItemStack resultStack = key instanceof AEItemKey itemKey ?
itemKey.toStack((int) extracted) : ItemStack.EMPTY;
if (!simulate) {
// 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 ItemStack.EMPTY;
}
@Override
public ExportOnlyAEStockingItemSlot copy() {
return new ExportOnlyAEStockingItemSlot(
this.config == null ? null : copy(this.config),
this.stock == null ? null : copy(this.stock));
}
}
}