-
Notifications
You must be signed in to change notification settings - Fork 211
Expand file tree
/
Copy pathMetaTileEntityItemBus.java
More file actions
458 lines (410 loc) · 19.9 KB
/
Copy pathMetaTileEntityItemBus.java
File metadata and controls
458 lines (410 loc) · 19.9 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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package gregtech.common.metatileentities.multi.multiblockpart;
import gregtech.api.GTValues;
import gregtech.api.capability.*;
import gregtech.api.capability.impl.GhostCircuitItemStackHandler;
import gregtech.api.capability.impl.ItemHandlerList;
import gregtech.api.capability.impl.NotifiableItemStackHandler;
import gregtech.api.items.itemhandlers.GTItemStackHandler;
import gregtech.api.metatileentity.MetaTileEntity;
import gregtech.api.metatileentity.interfaces.IGregTechTileEntity;
import gregtech.api.metatileentity.multiblock.AbilityInstances;
import gregtech.api.metatileentity.multiblock.IMultiblockAbilityPart;
import gregtech.api.metatileentity.multiblock.MultiblockAbility;
import gregtech.api.metatileentity.multiblock.MultiblockControllerBase;
import gregtech.api.mui.GTGuiTextures;
import gregtech.api.mui.GTGuis;
import gregtech.api.mui.widget.GhostCircuitSlotWidget;
import gregtech.api.util.GTHashMaps;
import gregtech.client.renderer.texture.Textures;
import gregtech.client.renderer.texture.cube.SimpleOverlayRenderer;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.IItemHandlerModifiable;
import codechicken.lib.raytracer.CuboidRayTraceResult;
import codechicken.lib.render.CCRenderState;
import codechicken.lib.render.pipeline.IVertexOperation;
import codechicken.lib.vec.Matrix4;
import com.cleanroommc.modularui.api.drawable.IKey;
import com.cleanroommc.modularui.api.widget.IWidget;
import com.cleanroommc.modularui.factory.PosGuiData;
import com.cleanroommc.modularui.screen.ModularPanel;
import com.cleanroommc.modularui.value.BoolValue;
import com.cleanroommc.modularui.value.sync.BooleanSyncValue;
import com.cleanroommc.modularui.value.sync.PanelSyncManager;
import com.cleanroommc.modularui.value.sync.SyncHandlers;
import com.cleanroommc.modularui.widget.Widget;
import com.cleanroommc.modularui.widgets.ItemSlot;
import com.cleanroommc.modularui.widgets.SlotGroupWidget;
import com.cleanroommc.modularui.widgets.ToggleButton;
import com.cleanroommc.modularui.widgets.layout.Flow;
import com.cleanroommc.modularui.widgets.layout.Grid;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MetaTileEntityItemBus extends MetaTileEntityMultiblockNotifiablePart
implements IMultiblockAbilityPart<IItemHandlerModifiable>, IControllable,
IGhostSlotConfigurable {
@Nullable
protected GhostCircuitItemStackHandler circuitInventory;
private IItemHandlerModifiable actualImportItems;
private boolean workingEnabled;
private boolean autoCollapse;
public MetaTileEntityItemBus(ResourceLocation metaTileEntityId, int tier, boolean isExportHatch) {
super(metaTileEntityId, tier, isExportHatch);
this.workingEnabled = true;
initializeInventory();
}
@Override
public MetaTileEntity createMetaTileEntity(IGregTechTileEntity tileEntity) {
return new MetaTileEntityItemBus(metaTileEntityId, getTier(), isExportHatch);
}
@Override
protected void initializeInventory() {
super.initializeInventory();
if (this.hasGhostCircuitInventory()) {
this.circuitInventory = new GhostCircuitItemStackHandler(this);
this.circuitInventory.addNotifiableMetaTileEntity(this);
this.actualImportItems = new ItemHandlerList(Arrays.asList(super.getImportItems(), this.circuitInventory));
} else {
this.actualImportItems = null;
}
}
@Override
public IItemHandlerModifiable getImportItems() {
return this.actualImportItems == null ? super.getImportItems() : this.actualImportItems;
}
@Override
public void addToMultiBlock(MultiblockControllerBase controllerBase) {
super.addToMultiBlock(controllerBase);
if (hasGhostCircuitInventory() && this.actualImportItems instanceof ItemHandlerList) {
for (IItemHandler handler : ((ItemHandlerList) this.actualImportItems).getBackingHandlers()) {
if (handler instanceof INotifiableHandler notifiable) {
notifiable.addNotifiableMetaTileEntity(controllerBase);
notifiable.addToNotifiedList(this, handler, isExportHatch);
}
}
}
}
@Override
public void removeFromMultiBlock(MultiblockControllerBase controllerBase) {
super.removeFromMultiBlock(controllerBase);
if (hasGhostCircuitInventory() && this.actualImportItems instanceof ItemHandlerList) {
for (IItemHandler handler : ((ItemHandlerList) this.actualImportItems).getBackingHandlers()) {
if (handler instanceof INotifiableHandler notifiable) {
notifiable.removeNotifiableMetaTileEntity(controllerBase);
}
}
}
}
@Override
public void update() {
super.update();
if (!getWorld().isRemote && getOffsetTimer() % 5 == 0) {
if (workingEnabled) {
if (isExportHatch) {
pushItemsIntoNearbyHandlers(getFrontFacing());
} else {
pullItemsFromNearbyHandlers(getFrontFacing());
}
}
// Only attempt to auto collapse the inventory contents once the bus has been notified
if (isAutoCollapse()) {
// Exclude the ghost circuit inventory from the auto collapse, so it does not extract any ghost circuits
// from the slot
IItemHandlerModifiable inventory = (isExportHatch ? this.getExportItems() : super.getImportItems());
if (!isAttachedToMultiBlock() || (isExportHatch ? this.getNotifiedItemOutputList().contains(inventory) :
this.getNotifiedItemInputList().contains(inventory))) {
collapseInventorySlotContents(inventory);
}
}
}
}
@Override
public void setWorkingEnabled(boolean workingEnabled) {
this.workingEnabled = workingEnabled;
World world = getWorld();
if (world != null && !world.isRemote) {
writeCustomData(GregtechDataCodes.WORKING_ENABLED, buf -> buf.writeBoolean(workingEnabled));
}
}
@Override
public boolean isWorkingEnabled() {
return workingEnabled;
}
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing side) {
if (capability == GregtechTileCapabilities.CAPABILITY_CONTROLLABLE) {
return GregtechTileCapabilities.CAPABILITY_CONTROLLABLE.cast(this);
}
return super.getCapability(capability, side);
}
@Override
public void renderMetaTileEntity(CCRenderState renderState, Matrix4 translation, IVertexOperation[] pipeline) {
super.renderMetaTileEntity(renderState, translation, pipeline);
if (shouldRenderOverlay()) {
SimpleOverlayRenderer renderer = isExportHatch ? Textures.PIPE_OUT_OVERLAY : Textures.PIPE_IN_OVERLAY;
renderer.renderSided(getFrontFacing(), renderState, translation, pipeline);
SimpleOverlayRenderer overlay = isExportHatch ? Textures.ITEM_HATCH_OUTPUT_OVERLAY :
Textures.ITEM_HATCH_INPUT_OVERLAY;
overlay.renderSided(getFrontFacing(), renderState, translation, pipeline);
}
}
private int getInventorySize() {
int sizeRoot = 1 + Math.min(GTValues.UHV, getTier());
return sizeRoot * sizeRoot;
}
@Override
protected IItemHandlerModifiable createExportItemHandler() {
return isExportHatch ? new NotifiableItemStackHandler(this, getInventorySize(), getController(), true) :
new GTItemStackHandler(this, 0);
}
@Override
protected IItemHandlerModifiable createImportItemHandler() {
return isExportHatch ? new GTItemStackHandler(this, 0) :
new NotifiableItemStackHandler(this, getInventorySize(), getController(), false);
}
@Override
public MultiblockAbility<IItemHandlerModifiable> getAbility() {
return isExportHatch ? MultiblockAbility.EXPORT_ITEMS : MultiblockAbility.IMPORT_ITEMS;
}
@Override
public void writeInitialSyncData(PacketBuffer buf) {
super.writeInitialSyncData(buf);
buf.writeBoolean(workingEnabled);
buf.writeBoolean(autoCollapse);
}
@Override
public void receiveInitialSyncData(PacketBuffer buf) {
super.receiveInitialSyncData(buf);
this.workingEnabled = buf.readBoolean();
this.autoCollapse = buf.readBoolean();
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound data) {
super.writeToNBT(data);
data.setBoolean("workingEnabled", workingEnabled);
data.setBoolean("autoCollapse", autoCollapse);
if (this.circuitInventory != null && !this.isExportHatch) {
this.circuitInventory.write(data);
}
return data;
}
@Override
public void readFromNBT(NBTTagCompound data) {
super.readFromNBT(data);
if (data.hasKey("workingEnabled")) {
this.workingEnabled = data.getBoolean("workingEnabled");
}
if (data.hasKey("autoCollapse")) {
this.autoCollapse = data.getBoolean("autoCollapse");
}
if (this.circuitInventory != null && !this.isExportHatch) {
this.circuitInventory.read(data);
}
}
@Override
public void receiveCustomData(int dataId, PacketBuffer buf) {
super.receiveCustomData(dataId, buf);
if (dataId == GregtechDataCodes.TOGGLE_COLLAPSE_ITEMS) {
this.autoCollapse = buf.readBoolean();
} else if (dataId == GregtechDataCodes.WORKING_ENABLED) {
this.workingEnabled = buf.readBoolean();
}
}
@Override
public void registerAbilities(@NotNull AbilityInstances abilityInstances) {
if (this.hasGhostCircuitInventory() && this.actualImportItems != null) {
abilityInstances.add(isExportHatch ? this.exportItems : this.actualImportItems);
} else {
abilityInstances.add(isExportHatch ? this.exportItems : this.importItems);
}
}
@Override
public boolean usesMui2() {
return true;
}
@Override
public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager guiSyncManager) {
int rowSize = (int) Math.sqrt(getInventorySize());
guiSyncManager.registerSlotGroup("item_inv", rowSize);
int backgroundWidth = Math.max(
9 * 18 + 18 + 14 + 5, // Player Inv width
rowSize * 18 + 14); // Bus Inv width
int backgroundHeight = 18 + 18 * rowSize + 94;
List<List<IWidget>> widgets = new ArrayList<>();
for (int i = 0; i < rowSize; i++) {
widgets.add(new ArrayList<>());
for (int j = 0; j < rowSize; j++) {
int index = i * rowSize + j;
IItemHandlerModifiable handler = isExportHatch ? exportItems : importItems;
widgets.get(i)
.add(new ItemSlot()
.slot(SyncHandlers.itemSlot(handler, index)
.slotGroup("item_inv")
.changeListener((newItem, onlyAmountChanged, client, init) -> {
if (onlyAmountChanged &&
handler instanceof GTItemStackHandler gtHandler) {
gtHandler.onContentsChanged(index);
}
})
.accessibility(!isExportHatch, true)));
}
}
BooleanSyncValue workingStateValue = new BooleanSyncValue(() -> workingEnabled, val -> workingEnabled = val);
guiSyncManager.syncValue("working_state", workingStateValue);
BooleanSyncValue collapseStateValue = new BooleanSyncValue(() -> autoCollapse, val -> autoCollapse = val);
guiSyncManager.syncValue("collapse_state", collapseStateValue);
boolean hasGhostCircuit = hasGhostCircuitInventory() && this.circuitInventory != null;
return GTGuis.createPanel(this, backgroundWidth, backgroundHeight)
.child(IKey.lang(getMetaFullName()).asWidget().pos(5, 5))
.child(SlotGroupWidget.playerInventory().left(7).bottom(7))
.child(new Grid()
.top(18).height(rowSize * 18)
.minElementMargin(0, 0)
.minColWidth(18).minRowHeight(18)
.alignX(0.5f)
.matrix(widgets))
.child(Flow.column()
.pos(backgroundWidth - 7 - 18, backgroundHeight - 18 * 4 - 7 - 5)
.width(18).height(18 * 4 + 5)
.child(GTGuiTextures.getLogo(getUITheme()).asWidget().size(17).top(18 * 3 + 5))
.child(new ToggleButton()
.top(18 * 2)
.value(new BoolValue.Dynamic(workingStateValue::getBoolValue,
workingStateValue::setBoolValue))
.overlay(GTGuiTextures.BUTTON_ITEM_OUTPUT)
.tooltipBuilder(t -> t.setAutoUpdate(true)
.addLine(isExportHatch ?
(workingStateValue.getBoolValue() ?
IKey.lang("gregtech.gui.item_auto_output.tooltip.enabled") :
IKey.lang("gregtech.gui.item_auto_output.tooltip.disabled")) :
(workingStateValue.getBoolValue() ?
IKey.lang("gregtech.gui.item_auto_input.tooltip.enabled") :
IKey.lang("gregtech.gui.item_auto_input.tooltip.disabled")))))
.child(new ToggleButton()
.top(18)
.value(new BoolValue.Dynamic(collapseStateValue::getBoolValue,
collapseStateValue::setBoolValue))
.overlay(GTGuiTextures.BUTTON_AUTO_COLLAPSE)
.tooltipBuilder(t -> t.setAutoUpdate(true)
.addLine(collapseStateValue.getBoolValue() ?
IKey.lang("gregtech.gui.item_auto_collapse.tooltip.enabled") :
IKey.lang("gregtech.gui.item_auto_collapse.tooltip.disabled"))))
.childIf(hasGhostCircuit, new GhostCircuitSlotWidget()
.slot(SyncHandlers.itemSlot(circuitInventory, 0))
.background(GTGuiTextures.SLOT, GTGuiTextures.INT_CIRCUIT_OVERLAY))
.childIf(!hasGhostCircuit, new Widget<>()
.background(GTGuiTextures.SLOT, GTGuiTextures.BUTTON_X)
.tooltip(t -> t.addLine(
IKey.lang("gregtech.gui.configurator_slot.unavailable.tooltip")))));
}
@Override
public boolean hasGhostCircuitInventory() {
return !this.isExportHatch;
}
private static void collapseInventorySlotContents(IItemHandlerModifiable inventory) {
// Gather a snapshot of the provided inventory
Object2IntMap<ItemStack> inventoryContents = GTHashMaps.fromItemHandler(inventory, true);
List<ItemStack> inventoryItemContents = new ArrayList<>();
// Populate the list of item stacks in the inventory with apportioned item stacks, for easy replacement
for (Object2IntMap.Entry<ItemStack> e : inventoryContents.object2IntEntrySet()) {
ItemStack stack = e.getKey();
int count = e.getIntValue();
int maxStackSize = stack.getMaxStackSize();
while (count >= maxStackSize) {
ItemStack copy = stack.copy();
copy.setCount(maxStackSize);
inventoryItemContents.add(copy);
count -= maxStackSize;
}
if (count > 0) {
ItemStack copy = stack.copy();
copy.setCount(count);
inventoryItemContents.add(copy);
}
}
for (int i = 0; i < inventory.getSlots(); i++) {
ItemStack stackToMove;
// Ensure that we are not exceeding the List size when attempting to populate items
if (i >= inventoryItemContents.size()) {
stackToMove = ItemStack.EMPTY;
} else {
stackToMove = inventoryItemContents.get(i);
}
// Populate the slots
inventory.setStackInSlot(i, stackToMove);
}
}
@Override
public boolean onScrewdriverClick(EntityPlayer playerIn, EnumHand hand, EnumFacing facing,
CuboidRayTraceResult hitResult) {
setAutoCollapse(!this.autoCollapse);
if (!getWorld().isRemote) {
if (this.autoCollapse) {
playerIn.sendStatusMessage(new TextComponentTranslation("gregtech.bus.collapse_true"), true);
} else {
playerIn.sendStatusMessage(new TextComponentTranslation("gregtech.bus.collapse_false"), true);
}
}
return true;
}
public boolean isAutoCollapse() {
return autoCollapse;
}
public void setAutoCollapse(boolean inverted) {
autoCollapse = inverted;
if (!getWorld().isRemote) {
if (autoCollapse) {
if (isExportHatch) {
addNotifiedOutput(this.getExportItems());
} else {
addNotifiedInput(super.getImportItems());
}
}
writeCustomData(GregtechDataCodes.TOGGLE_COLLAPSE_ITEMS,
packetBuffer -> packetBuffer.writeBoolean(autoCollapse));
notifyBlockUpdate();
markDirty();
}
}
@Override
public void setGhostCircuitConfig(int config) {
if (this.circuitInventory == null || this.circuitInventory.getCircuitValue() == config) {
return;
}
this.circuitInventory.setCircuitValue(config);
if (!getWorld().isRemote) {
markDirty();
}
}
@Override
public void addInformation(ItemStack stack, @Nullable World player, @NotNull List<String> tooltip,
boolean advanced) {
if (this.isExportHatch)
tooltip.add(I18n.format("gregtech.machine.item_bus.export.tooltip"));
else
tooltip.add(I18n.format("gregtech.machine.item_bus.import.tooltip"));
tooltip.add(I18n.format("gregtech.universal.tooltip.item_storage_capacity", getInventorySize()));
tooltip.add(I18n.format("gregtech.universal.enabled"));
}
@Override
public void addToolUsages(ItemStack stack, @Nullable World world, List<String> tooltip, boolean advanced) {
tooltip.add(I18n.format("gregtech.tool_action.screwdriver.access_covers"));
tooltip.add(I18n.format("gregtech.tool_action.screwdriver.auto_collapse"));
tooltip.add(I18n.format("gregtech.tool_action.wrench.set_facing"));
super.addToolUsages(stack, world, tooltip, advanced);
}
}