Skip to content

Commit

Permalink
Make use of getExistingData for attachments
Browse files Browse the repository at this point in the history
  • Loading branch information
pupnewfster committed Feb 28, 2024
1 parent cc6445d commit becf60a
Show file tree
Hide file tree
Showing 15 changed files with 55 additions and 60 deletions.
Expand Up @@ -38,10 +38,9 @@ public static AttachedSideConfig create(IAttachmentHolder attachmentHolder) {

@Nullable
public static IPersistentConfigInfo getStoredConfigInfo(ItemStack stack, TransmissionType transmissionType) {
if (stack.hasData(MekanismAttachmentTypes.SIDE_CONFIG)) {
return stack.getData(MekanismAttachmentTypes.SIDE_CONFIG).getConfig(transmissionType);
}
return null;
return stack.getExistingData(MekanismAttachmentTypes.SIDE_CONFIG)
.map(config -> config.getConfig(transmissionType))
.orElse(null);
}

private final Map<TransmissionType, LightConfigInfo> configInfo;
Expand Down
Expand Up @@ -7,6 +7,7 @@
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
Expand Down Expand Up @@ -205,11 +206,12 @@ public List<CONTAINER> getAttachmentContainersIfPresent(IAttachmentHolder holder

@Nullable
public ATTACHMENT getAttachmentIfPresent(IAttachmentHolder holder) {
if (holder.hasData(attachment)) {
return holder.getData(attachment);
Optional<ATTACHMENT> existingData = holder.getExistingData(attachment);
if (existingData.isPresent()) {
return existingData.get();
}
if (holder instanceof ItemStack stack && hasLegacyData(stack)) {
//If the holder is an item that has legacy data then we want have the attachment get attached which will cause the legacy data to be removed
//If the holder is an item that has legacy data then we want to have the attachment get attached which will cause the legacy data to be removed
// and converted to the new format
return holder.getData(attachment);
}
Expand All @@ -218,8 +220,9 @@ public ATTACHMENT getAttachmentIfPresent(IAttachmentHolder holder) {

@Nullable
public ATTACHMENT getAttachment(IAttachmentHolder holder) {
if (holder.hasData(this.attachment)) {
return holder.getData(this.attachment);
Optional<ATTACHMENT> existingData = holder.getExistingData(attachment);
if (existingData.isPresent()) {
return existingData.get();
} else if (holder instanceof ItemStack stack) {
if (knownDefaultItemContainers.containsKey(stack.getItem())) {
return stack.getData(this.attachment);
Expand Down
Expand Up @@ -61,9 +61,10 @@ public String getOwnerName() {
@Override
public void setOwnerUUID(@Nullable UUID owner) {
if (!Objects.equals(this.ownerUUID, owner)) {
if (this.ownerUUID != null && attachmentHolder.hasData(MekanismAttachmentTypes.FREQUENCY_AWARE)) {
if (this.ownerUUID != null) {
//If the object happens to be a frequency aware object reset the frequency when the owner changes
attachmentHolder.getData(MekanismAttachmentTypes.FREQUENCY_AWARE).setFrequency(null);
attachmentHolder.getExistingData(MekanismAttachmentTypes.FREQUENCY_AWARE)
.ifPresent(frequencyAware -> frequencyAware.setFrequency(null));
}
this.ownerUUID = owner;
}
Expand Down
9 changes: 6 additions & 3 deletions src/main/java/mekanism/common/block/BlockCardboardBox.java
@@ -1,6 +1,8 @@
package mekanism.common.block;

import java.util.Optional;
import mekanism.common.advancements.MekanismCriteriaTriggers;
import mekanism.common.attachments.BlockData;
import mekanism.common.block.interfaces.IHasTileEntity;
import mekanism.common.block.states.BlockStateHelper;
import mekanism.common.block.states.IStateStorage;
Expand Down Expand Up @@ -43,9 +45,10 @@ public InteractionResult use(@NotNull BlockState state, @NotNull Level world, @N
return InteractionResult.FAIL;
}
if (!world.isClientSide) {
TileEntityCardboardBox box = WorldUtils.getTileEntity(TileEntityCardboardBox.class, world, pos);
if (box != null && box.hasData(MekanismAttachmentTypes.BLOCK_DATA)) {
box.getData(MekanismAttachmentTypes.BLOCK_DATA).placeIntoWorld(world, pos);
Optional<BlockData> blockData = Optional.ofNullable(WorldUtils.getTileEntity(TileEntityCardboardBox.class, world, pos))
.flatMap(box -> box.getExistingData(MekanismAttachmentTypes.BLOCK_DATA));
if (blockData.isPresent()) {
blockData.get().placeIntoWorld(world, pos);
//TODO: Do we need to call setPlacedBy or not bother given we are setting the blockstate to what it was AND setting any tile data
//adjustedState.getBlock().setPlacedBy(world, pos, data.blockState, player, new ItemStack(adjustedState.getBlock()));
popResource(world, pos, MekanismBlocks.CARDBOARD_BOX.getItemStack());
Expand Down
4 changes: 1 addition & 3 deletions src/main/java/mekanism/common/content/qio/QIODriveData.java
Expand Up @@ -25,9 +25,7 @@ public QIODriveData(QIODriveKey key) {
countCapacity = driveItem.getCountCapacity(driveStack);
typeCapacity = driveItem.getTypeCapacity(driveStack);
// load item map from drive stack
if (driveStack.hasData(MekanismAttachmentTypes.DRIVE_METADATA)) {
driveStack.getData(MekanismAttachmentTypes.DRIVE_METADATA).loadItemMap(this);
}
driveStack.getExistingData(MekanismAttachmentTypes.DRIVE_METADATA).ifPresent(driveData -> driveData.loadItemMap(this));
// update cached item count value
itemCount = itemMap.values().longStream().sum();

Expand Down
Expand Up @@ -38,8 +38,9 @@ public long recalculateEMC(@NotNull ItemInfo info, long currentEMC) throws Arith
ItemStack stack = info.createStack();
//Stored items
currentEMC = addEmc(emcProxy, currentEMC, ContainerType.ITEM.getAttachmentContainersIfPresent(stack));
if (stack.hasData(MekanismAttachmentTypes.UPGRADES)) {//Stored upgrades
UpgradeAware upgradeAware = stack.getData(MekanismAttachmentTypes.UPGRADES);
Optional<UpgradeAware> existingUpgrades = stack.getExistingData(MekanismAttachmentTypes.UPGRADES);
if (existingUpgrades.isPresent()) {//Stored upgrades
UpgradeAware upgradeAware = existingUpgrades.get();
for (Map.Entry<Upgrade, Integer> entry : upgradeAware.getUpgrades().entrySet()) {
currentEMC = addEmc(emcProxy, currentEMC, UpgradeUtils.getStack(entry.getKey(), entry.getValue()));
}
Expand Down
11 changes: 4 additions & 7 deletions src/main/java/mekanism/common/item/ItemConfigurationCard.java
Expand Up @@ -94,14 +94,11 @@ public InteractionResult useOn(UseOnContext context) {
return InteractionResult.PASS;
}

@Nullable
private CompoundTag getData(ItemStack stack) {
if (stack.hasData(MekanismAttachmentTypes.CONFIGURATION_DATA)) {
CompoundTag data = stack.getData(MekanismAttachmentTypes.CONFIGURATION_DATA);
if (!data.isEmpty()) {
return data;
}
}
return null;
return stack.getExistingData(MekanismAttachmentTypes.CONFIGURATION_DATA)
.filter(data -> !data.isEmpty())
.orElse(null);
}

@Nullable
Expand Down
5 changes: 4 additions & 1 deletion src/main/java/mekanism/common/item/ItemRobit.java
@@ -1,6 +1,7 @@
package mekanism.common.item;

import java.util.List;
import java.util.Optional;
import java.util.UUID;
import mekanism.api.energy.IEnergyContainer;
import mekanism.api.robit.RobitSkin;
Expand All @@ -25,6 +26,7 @@
import net.minecraft.advancements.CriteriaTriggers;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.damagesource.DamageSource;
Expand Down Expand Up @@ -117,7 +119,8 @@ public void attachCapabilities(RegisterCapabilitiesEvent event) {
public void inventoryTick(@NotNull ItemStack stack, @NotNull Level level, @NotNull Entity entity, int slot, boolean isSelected) {
super.inventoryTick(stack, level, entity, slot, isSelected);
if (!level.isClientSide && HolidayManager.hasRobitSkinsToday()) {
if (!stack.hasData(MekanismAttachmentTypes.ROBIT_SKIN) || stack.getData(MekanismAttachmentTypes.ROBIT_SKIN) == MekanismRobitSkins.BASE) {
Optional<ResourceKey<RobitSkin>> nonBaseSkin = stack.getExistingData(MekanismAttachmentTypes.ROBIT_SKIN).filter(skin -> skin != MekanismRobitSkins.BASE);
if (nonBaseSkin.isEmpty()) {
//Randomize the robit's skin
stack.setData(MekanismAttachmentTypes.ROBIT_SKIN, HolidayManager.getRandomBaseSkin(level.random));
}
Expand Down
Expand Up @@ -64,11 +64,9 @@ public ItemStack apply(ItemStack stack, LootContext lootContext) {
}

private <ATTACHMENT> void copyAttachment(IAttachmentHolder source, IAttachmentHolder target, AttachmentType<ATTACHMENT> attachmentType) {
if (source.hasData(attachmentType)) {
//TODO: Is this fine or do we need a better way of copying this as a new object? For BlockData it doesn't matter
// but it might for some types we add in the future?
target.setData(attachmentType, source.getData(attachmentType));
}
//TODO: Is this fine or do we need a better way of copying this as a new object? For BlockData it doesn't matter
// but it might for some types we add in the future?
source.getExistingData(attachmentType).ifPresent(attachment -> target.setData(attachmentType, attachment));
}

@Override
Expand Down
Expand Up @@ -98,8 +98,9 @@ public static void deleteInventory(ItemStack stack) {
@NotNull
private static UUID getInventoryId(ItemStack stack) {
convertLegacyToAttachment(stack);
if (stack.hasData(MekanismAttachmentTypes.PERSONAL_STORAGE_ID)) {
return stack.getData(MekanismAttachmentTypes.PERSONAL_STORAGE_ID);
Optional<UUID> existingData = stack.getExistingData(MekanismAttachmentTypes.PERSONAL_STORAGE_ID);
if (existingData.isPresent()) {
return existingData.get();
}
UUID invId = UUID.randomUUID();
stack.setData(MekanismAttachmentTypes.PERSONAL_STORAGE_ID, invId);
Expand Down
Expand Up @@ -4,6 +4,7 @@
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
Expand Down Expand Up @@ -145,8 +146,9 @@ static RecipeUpgradeData<?> getUpgradeData(@NotNull RecipeUpgradeType type, @Not
}
case SORTING -> stack.getData(MekanismAttachmentTypes.SORTING) ? SortingRecipeData.SORTING : null;
case UPGRADE -> {
if (stack.hasData(MekanismAttachmentTypes.UPGRADES)) {
UpgradeAware upgradeAware = stack.getData(MekanismAttachmentTypes.UPGRADES);
Optional<UpgradeAware> existingData = stack.getExistingData(MekanismAttachmentTypes.UPGRADES);
if (existingData.isPresent()) {
UpgradeAware upgradeAware = existingData.get();
Map<Upgrade, Integer> upgrades = upgradeAware.getUpgrades();
List<IInventorySlot> slots = upgradeAware.getInventorySlots(null);
if (!upgrades.isEmpty() || slots.stream().anyMatch(slot -> !slot.isEmpty())) {
Expand Down
Expand Up @@ -17,16 +17,12 @@ public TileEntityCardboardBox(BlockPos pos, BlockState state) {
@Override
public void readFromStack(ItemStack stack) {
super.readFromStack(stack);
if (stack.hasData(MekanismAttachmentTypes.BLOCK_DATA)) {
setData(MekanismAttachmentTypes.BLOCK_DATA, stack.getData(MekanismAttachmentTypes.BLOCK_DATA));
}
stack.getExistingData(MekanismAttachmentTypes.BLOCK_DATA).ifPresent(storedData -> setData(MekanismAttachmentTypes.BLOCK_DATA, storedData));
}

@Override
public void writeToStack(ItemStack stack) {
super.writeToStack(stack);
if (hasData(MekanismAttachmentTypes.BLOCK_DATA)) {
stack.setData(MekanismAttachmentTypes.BLOCK_DATA, getData(MekanismAttachmentTypes.BLOCK_DATA));
}
getExistingData(MekanismAttachmentTypes.BLOCK_DATA).ifPresent(storedData -> stack.setData(MekanismAttachmentTypes.BLOCK_DATA, storedData));
}
}
Expand Up @@ -750,17 +750,17 @@ public void readFromStack(ItemStack stack) {
setOwnerUUID(ownerUUID);
}
}
if (supportsUpgrades() && stack.hasData(MekanismAttachmentTypes.UPGRADES)) {
if (supportsUpgrades()) {
//The read method validates that data is stored
stack.getData(MekanismAttachmentTypes.UPGRADES).copyTo(getComponent());
stack.getExistingData(MekanismAttachmentTypes.UPGRADES).ifPresent(storedUpgrades -> storedUpgrades.copyTo(getComponent()));
}
for (ContainerType<?, ?, ?> type : ContainerType.TYPES) {
if (handles(type)) {
type.copyFrom(stack, this);
}
}
if (this instanceof ITileFilterHolder<?> filterHolder && stack.hasData(MekanismAttachmentTypes.FILTER_AWARE)) {
stack.getData(MekanismAttachmentTypes.FILTER_AWARE).copyTo(filterHolder.getFilterManager());
if (this instanceof ITileFilterHolder<?> filterHolder) {
stack.getExistingData(MekanismAttachmentTypes.FILTER_AWARE).ifPresent(storedFilters -> storedFilters.copyTo(filterHolder.getFilterManager()));
}
if (supportsRedstone()) {
setControlType(stack.getData(MekanismAttachmentTypes.REDSTONE_CONTROL));
Expand Down
Expand Up @@ -160,14 +160,9 @@ public CompoundTag getReducedUpdateTag() {
serializedAttachments = new CompoundTag();
}
//Serialize our subset of attachments that we know need to be sync'd
syncableAttachmentTypes.forEach((type, name) -> {
if (hasData(type)) {
Tag serialized = getData(type).serializeNBT();
if (serialized != null) {
serializedAttachments.put(name, serialized);
}
}
});
syncableAttachmentTypes.forEach((type, name) -> getExistingData(type)
.map(INBTSerializable::serializeNBT)
.ifPresent(serialized -> serializedAttachments.put(name, serialized)));
if (!serializedAttachments.isEmpty()) {
updateTag.put(ATTACHMENTS_NBT_KEY, serializedAttachments);
}
Expand Down
Expand Up @@ -123,12 +123,10 @@ public void writeToStack(ItemStack stack) {
@Override
public void readFromStack(ItemStack stack) {
super.readFromStack(stack);
if (stack.hasData(MekanismAttachmentTypes.ITEM_TARGET)) {
ItemStack type = stack.getData(MekanismAttachmentTypes.ITEM_TARGET);
itemType = type.isEmpty() ? null : HashedItem.create(type);
} else {
itemType = null;
}
itemType = stack.getExistingData(MekanismAttachmentTypes.ITEM_TARGET)
.filter(type -> !type.isEmpty())
.map(HashedItem::create)
.orElse(null);
count = stack.getData(MekanismAttachmentTypes.LONG_AMOUNT);
fuzzy = stack.getData(MekanismAttachmentTypes.FUZZY);
}
Expand Down

0 comments on commit becf60a

Please sign in to comment.