/
ColumnTileEntity.java
543 lines (251 loc) · 10.2 KB
/
ColumnTileEntity.java
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
package drmdgg.marijuanacraft.init.blocks.tileentities;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import drmdgg.marijuanacraft.container.ColumnContainer;
import drmdgg.marijuanacraft.init.BlockInit;
import drmdgg.marijuanacraft.init.ModTileEntityTypes;
import drmdgg.marijuanacraft.recipes.PurgingRecipe;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.FurnaceTileEntity;
import net.minecraft.tileentity.ITickableTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fml.network.NetworkHooks;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.ItemStackHandler;
public class ColumnTileEntity extends TileEntity implements ITickableTileEntity, INamedContainerProvider {
public static final int FUEL_SLOT = 0;
public static final int INPUT_SLOT = 1;
public static final int OUTPUT_SLOT = 2;
private static final String INVENTORY_TAG = "inventory";
private static final String SMELT_TIME_LEFT_TAG = "smeltTimeLeft";
private static final String MAX_SMELT_TIME_TAG = "maxSmeltTime";
private static final String FUEL_BURN_TIME_LEFT_TAG = "fuelBurnTimeLeft";
private static final String MAX_FUEL_BURN_TIME_TAG = "maxFuelBurnTime";
public final ItemStackHandler inventory = new ItemStackHandler(3) {
@Override
public boolean isItemValid(final int slot, @Nonnull final ItemStack stack) {
switch (slot) {
case FUEL_SLOT:
return FurnaceTileEntity.isFuel(stack);
case INPUT_SLOT:
return isInput(stack);
case OUTPUT_SLOT:
return isOutput(stack);
default:
return false;
}
}
@Override
protected void onContentsChanged(final int slot) {
super.onContentsChanged(slot);
// Mark the tile entity as having changed whenever its inventory changes.
// "markDirty" tells vanilla that the chunk containing the tile entity has
// changed and means the game will save the chunk to disk later.
ColumnTileEntity.this.markDirty();
}
};
// Store the capability lazy optionals as fields to keep the amount of objects we use to a minimum
private final LazyOptional<ItemStackHandler> inventoryCapabilityExternal = LazyOptional.of(() -> this.inventory);
public short smeltTimeLeft = -1;
public short maxSmeltTime = -1;
public short fuelBurnTimeLeft = -1;
public short maxFuelBurnTime = -1;
public boolean lastBurning = false;
public ColumnTileEntity() {
super(ModTileEntityTypes.COLUMN.get());
}
private boolean isInput(final ItemStack stack) {
if (stack.isEmpty())
return false;
return getRecipe(stack).isPresent();
}
private boolean isOutput(final ItemStack stack) {
final Optional<ItemStack> result = getResult(inventory.getStackInSlot(INPUT_SLOT));
return result.isPresent() && ItemStack.areItemsEqual(result.get(), stack);
}
private Optional<PurgingRecipe> getRecipe(final ItemStack input) {
return getRecipe(new Inventory(input));
}
private Optional<PurgingRecipe> getRecipe(final Inventory inventory) {
return world.getRecipeManager().getRecipe(PurgingRecipe.purging, inventory, world);
}
private Optional<ItemStack> getResult(final ItemStack input) {
final Inventory dummyInventory = new Inventory(input);
return getRecipe(dummyInventory).map(recipe -> recipe.getCraftingResult(dummyInventory));
}
@Override
public void tick() {
if (world == null || world.isRemote)
return;
boolean hasFuel = false;
if (isBurning()) {
hasFuel = true;
--fuelBurnTimeLeft;
}
final ItemStack input = inventory.getStackInSlot(INPUT_SLOT);
final ItemStack result = getResult(input).orElse(ItemStack.EMPTY);
if (!result.isEmpty() && isInput(input)) {
final boolean canInsertResultIntoOutput = inventory.insertItem(OUTPUT_SLOT, result, true).isEmpty();
if (canInsertResultIntoOutput) {
if (!hasFuel)
if (burnFuel())
hasFuel = true;
if (hasFuel) {
if (smeltTimeLeft == -1) { // Item just got inserted
smeltTimeLeft = maxSmeltTime = getSmeltTime(input);
} else { // Item was already in here
--smeltTimeLeft;
if (smeltTimeLeft == 0) {
inventory.insertItem(OUTPUT_SLOT, result, false);
input.shrink(1);
inventory.setStackInSlot(INPUT_SLOT, input); // Update the data
if (input.hasContainerItem()) {
final ItemStack containerItem = input.getContainerItem();
final boolean canInsertContainerItemIntoInput = inventory.insertItem(INPUT_SLOT, containerItem, true).isEmpty();
if (canInsertContainerItemIntoInput)
inventory.insertItem(INPUT_SLOT, containerItem, false);
else // Drop the container item if we can't insert it
InventoryHelper.spawnItemStack(world, pos.getX(), pos.getY(), pos.getZ(), containerItem);
}
}
}
} else // No fuel -> add to smelt time to simulate cooling
if (smeltTimeLeft < maxSmeltTime)
++smeltTimeLeft;
}
} else // Invalid input (somehow)
smeltTimeLeft = maxSmeltTime = -1;
// If the burning state has changed.
if (lastBurning != this.isBurning()) {
// "markDirty" tells vanilla that the chunk containing the tile entity has
// changed and means the game will save the chunk to disk later.
this.markDirty();
// Notify clients of a block update.
// This will result in the packet from getUpdatePacket being sent to the client
// and our burning being synced.
final BlockState blockState = this.getBlockState();
final BlockState newState = BlockInit.COLUMNBLOCK.get().getDefaultState()
.with(ColumnBlock.BURNING, this.isBurning());
// Flag 2: Send the change to clients
world.notifyBlockUpdate(pos, blockState, newState, 2);
// Update the last synced burning state to the current burning state
lastBurning = this.isBurning();
}
}
private short getSmeltTime(final ItemStack input) {
final Optional<PurgingRecipe> recipe = getRecipe(input);
if (recipe.isPresent())
return (short) recipe.get().getProcessTime();
return 200;
}
/**
* @return If the fuel was burnt
*/
private boolean burnFuel() {
final ItemStack fuelStack = inventory.getStackInSlot(FUEL_SLOT);
if (!fuelStack.isEmpty()) {
final int burnTime = ForgeHooks.getBurnTime(fuelStack);
if (burnTime > 0) {
this.fuelBurnTimeLeft = this.maxFuelBurnTime = ((short) burnTime);
fuelStack.shrink(1);
return true;
}
}
return false;
}
public boolean isBurning() {
return this.fuelBurnTimeLeft > 0;
}
@Nonnull
@Override
public <T> LazyOptional<T> getCapability(@Nonnull final Capability<T> cap, @Nullable final Direction side) {
if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY)
return inventoryCapabilityExternal.cast();
return super.getCapability(cap, side);
}
@Override
public void onLoad() {
super.onLoad();
// We set this in onLoad instead of the constructor so that TileEntities
// constructed from NBT (saved tile entities) have this set to the proper value
if (world != null && !world.isRemote)
lastBurning = isBurning();
}
/**
* Read saved data from disk into the tile.
*/
public void read(final CompoundNBT compound) {
super.read(getBlockState(), compound);
this.inventory.deserializeNBT(compound.getCompound(INVENTORY_TAG));
this.smeltTimeLeft = compound.getShort(SMELT_TIME_LEFT_TAG);
this.maxSmeltTime = compound.getShort(MAX_SMELT_TIME_TAG);
this.fuelBurnTimeLeft = compound.getShort(FUEL_BURN_TIME_LEFT_TAG);
this.maxFuelBurnTime = compound.getShort(MAX_FUEL_BURN_TIME_TAG);
}
/**
* Write data from the tile into a compound tag for saving to disk.
*/
@Nonnull
@Override
public CompoundNBT write(final CompoundNBT compound) {
super.write(compound);
compound.put(INVENTORY_TAG, this.inventory.serializeNBT());
compound.putShort(SMELT_TIME_LEFT_TAG, this.smeltTimeLeft);
compound.putShort(MAX_SMELT_TIME_TAG, this.maxSmeltTime);
compound.putShort(FUEL_BURN_TIME_LEFT_TAG, this.fuelBurnTimeLeft);
compound.putShort(MAX_FUEL_BURN_TIME_TAG, this.maxFuelBurnTime);
return compound;
}
/**
* Get an NBT compound to sync to the client with SPacketChunkData, used for initial loading of the
* chunk or when many blocks change at once.
* This compound comes back to you client-side in {@link #handleUpdateTag}
* The default implementation ({@link TileEntity#handleUpdateTag}) calls {@link #writeInternal)}
* which doesn't save any of our extra data so we override it to call {@link #write} instead
*/
@Nonnull
public CompoundNBT getUpdateTag() {
return this.write(new CompoundNBT());
}
/**
* Invalidates our tile entity
*/
@Override
public void remove() {
super.remove();
// We need to invalidate our capability references so that any cached references (by other mods) don't
// continue to reference our capabilities and try to use them and/or prevent them from being garbage collected
inventoryCapabilityExternal.invalidate();
}
@Nonnull
@Override
public ITextComponent getDisplayName() {
return new TranslationTextComponent(BlockInit.COLUMNBLOCK.get().getTranslationKey());
}
/**
* Called from {@link NetworkHooks#openGui}
* (which is called from {@link ElectricFurnaceBlock#onBlockActivated} on the logical server)
*
* @return The logical-server-side Container for this TileEntity
*/
@Nonnull
@Override
public Container createMenu(final int windowId, final PlayerInventory inventory, final PlayerEntity player) {
return new ColumnContainer(windowId, inventory, this);
}
}