Skip to content

Commit

Permalink
More item components
Browse files Browse the repository at this point in the history
  • Loading branch information
Electro593 committed Jan 21, 2025
1 parent 07f7d37 commit 27387a5
Show file tree
Hide file tree
Showing 16 changed files with 135 additions and 146 deletions.
14 changes: 3 additions & 11 deletions src/main/java/de/dafuqs/spectrum/api/item/ActivatableItem.java
Original file line number Diff line number Diff line change
@@ -1,24 +1,16 @@
package de.dafuqs.spectrum.api.item;

import de.dafuqs.spectrum.registries.*;
import net.minecraft.item.*;
import net.minecraft.nbt.*;

public interface ActivatableItem {

String NBT_STRING = "activated";

static void setActivated(ItemStack stack, boolean activated) {
NbtCompound compound = stack.getOrCreateNbt();
compound.putBoolean(NBT_STRING, activated);
stack.setNbt(compound);
stack.set(SpectrumDataComponentTypes.ACTIVATED, activated);
}

static boolean isActivated(ItemStack stack) {
NbtCompound compound = stack.getNbt();
if (compound != null && compound.contains(NBT_STRING)) {
return compound.getBoolean(NBT_STRING);
}
return false;
return stack.getOrDefault(SpectrumDataComponentTypes.ACTIVATED, false);
}

}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package de.dafuqs.spectrum.api.item;

import de.dafuqs.spectrum.*;
import de.dafuqs.spectrum.helpers.*;
import de.dafuqs.spectrum.registries.*;
import net.minecraft.item.*;
import net.minecraft.nbt.*;
import net.minecraft.registry.*;
import net.minecraft.util.math.random.*;

public interface ExperienceStorageItem {
Expand All @@ -15,12 +15,7 @@ public interface ExperienceStorageItem {
* @return The amount of stored experience
*/
static int getStoredExperience(ItemStack itemStack) {
NbtCompound nbtCompound = itemStack.getNbt();
if (nbtCompound == null || !nbtCompound.contains("stored_experience", NbtElement.NUMBER_TYPE)) {
return 0;
} else {
return nbtCompound.getInt("stored_experience");
}
return itemStack.getOrDefault(SpectrumDataComponentTypes.STORED_EXPERIENCE, 0);
}

/**
Expand All @@ -32,10 +27,10 @@ static int getStoredExperience(ItemStack itemStack) {
* @param random A random
* @return The overflow amount that could not be stored
*/
static int addStoredExperience(ItemStack itemStack, float amount, Random random) {
static int addStoredExperience(RegistryWrapper.WrapperLookup lookup, ItemStack itemStack, float amount, Random random) {
if (amount > 0) {
int intAmount = Support.getIntFromDecimalWithChance(amount, random);
return addStoredExperience(itemStack, intAmount);
return addStoredExperience(lookup, itemStack, intAmount);
}
return 0;
}
Expand All @@ -48,38 +43,23 @@ static int addStoredExperience(ItemStack itemStack, float amount, Random random)
* @param amount The amount of experience to store
* @return The overflow amount that could not be stored
*/
static int addStoredExperience(ItemStack itemStack, int amount) {
if (amount <= 0) {
static int addStoredExperience(RegistryWrapper.WrapperLookup lookup, ItemStack itemStack, int amount) {
if (amount <= 0 || itemStack.isEmpty())
return 0;
}

if (itemStack.getItem() instanceof ExperienceStorageItem experienceStorageItem) {
int maxStorage = experienceStorageItem.getMaxStoredExperience(itemStack);

NbtCompound nbtCompound = itemStack.getOrCreateNbt();
if (!nbtCompound.contains("stored_experience", NbtElement.NUMBER_TYPE)) {
nbtCompound.putInt("stored_experience", amount);
itemStack.setNbt(nbtCompound);
return 0;
} else {
int existingStoredExperience = nbtCompound.getInt("stored_experience");
int experienceOverflow = maxStorage - amount - existingStoredExperience;

if (experienceOverflow < 0) {
nbtCompound.putInt("stored_experience", maxStorage);
itemStack.setNbt(nbtCompound);
return -experienceOverflow;
} else {
nbtCompound.putInt("stored_experience", existingStoredExperience + amount);
itemStack.setNbt(nbtCompound);
return 0;
}
}
} else if (!itemStack.isEmpty()) {
SpectrumCommon.logError("Tried to add stored Experience to a non-ExperienceStorageItem item: " + itemStack.getItem().getName().getString());
int maxStorage = experienceStorageItem.getMaxStoredExperience(lookup, itemStack);
int existing = itemStack.getOrDefault(SpectrumDataComponentTypes.STORED_EXPERIENCE, 0);
int toAdd = amount + existing;
int overflow = Math.max(toAdd - maxStorage, 0);
toAdd = Math.min(toAdd, maxStorage);
itemStack.set(SpectrumDataComponentTypes.STORED_EXPERIENCE, toAdd);
return overflow;
} else {
itemStack.apply(SpectrumDataComponentTypes.STORED_EXPERIENCE, 0, existing -> existing + amount);
return 0;
}

return 0;
}

/**
Expand All @@ -91,26 +71,17 @@ static int addStoredExperience(ItemStack itemStack, int amount) {
* @return If there was enough experience that could be removed
*/
static boolean removeStoredExperience(ItemStack itemStack, int amount) {
if (itemStack.getItem() instanceof ExperienceStorageItem) {
NbtCompound nbtCompound = itemStack.getNbt();
if (nbtCompound == null || !nbtCompound.contains("stored_experience", NbtElement.NUMBER_TYPE)) {
return false;
} else {
int existingStoredExperience = nbtCompound.getInt("stored_experience");
if (existingStoredExperience < amount) {
return false;
} else {
nbtCompound.putInt("stored_experience", existingStoredExperience - amount);
itemStack.setNbt(nbtCompound);
return true;
}
if (itemStack.contains(SpectrumDataComponentTypes.STORED_EXPERIENCE)) {
var existing = itemStack.getOrDefault(SpectrumDataComponentTypes.STORED_EXPERIENCE, 0);
var newAmount = existing - amount;
if (newAmount >= 0) {
itemStack.set(SpectrumDataComponentTypes.STORED_EXPERIENCE, newAmount);
return true;
}
} else {
SpectrumCommon.logError("Tried to remove stored Experience from a non-ExperienceStorageItem: " + itemStack.getItem().getName().getString());
return false;
}
return false;
}

int getMaxStoredExperience(ItemStack itemStack);
int getMaxStoredExperience(RegistryWrapper.WrapperLookup lookup, ItemStack itemStack);

}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
import java.util.*;
import java.util.stream.*;

public class BlackHoleChestBlockEntity extends SpectrumChestBlockEntity implements ExtendedScreenHandlerFactory<FilterConfigurable.ExtendedData>, SidedInventory, EventQueue.Callback<Object> {
public class BlackHoleChestBlockEntity extends SpectrumChestBlockEntity implements FilterConfigurable, ExtendedScreenHandlerFactory<FilterConfigurable.ExtendedData>, SidedInventory, EventQueue.Callback<Object> {

public static final int INVENTORY_SIZE = 28;
public static final int ITEM_FILTER_SLOT_COUNT = 5;
Expand Down Expand Up @@ -141,10 +141,10 @@ public boolean isFull() {
}
}

if (canStoreExperience()) {
if (canStoreExperience() && world != null) {
var experienceStack = inventory.get(EXPERIENCE_STORAGE_PROVIDER_ITEM_SLOT);
var experienceStorage = (ExperienceStorageItem) experienceStack.getItem();
return ExperienceStorageItem.getStoredExperience(experienceStack) >= experienceStorage.getMaxStoredExperience(experienceStack);
return ExperienceStorageItem.getStoredExperience(experienceStack) >= experienceStorage.getMaxStoredExperience(world.getRegistryManager(), experienceStack);
}

return true;
Expand Down Expand Up @@ -257,7 +257,7 @@ public void triggerEvent(World world, GameEventListener listener, Object entry)
if (entry instanceof ExperienceOrbEventQueue.EventEntry experienceEntry) {
ExperienceOrbEntity experienceOrbEntity = experienceEntry.experienceOrbEntity;
if (experienceOrbEntity != null && experienceOrbEntity.isAlive() && hasExperienceStorageItem()) {
ExperienceStorageItem.addStoredExperience(this.inventory.get(EXPERIENCE_STORAGE_PROVIDER_ITEM_SLOT), experienceOrbEntity.getExperienceAmount()); // overflow experience is void, to not lag the world on large farms
ExperienceStorageItem.addStoredExperience(world.getRegistryManager(), this.inventory.get(EXPERIENCE_STORAGE_PROVIDER_ITEM_SLOT), experienceOrbEntity.getExperienceAmount()); // overflow experience is void, to not lag the world on large farms

sendPlayExperienceOrbEntityAbsorbedParticle((ServerWorld) world, experienceOrbEntity);
world.playSound(null, experienceOrbEntity.getBlockPos(), SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, SoundCategory.BLOCKS, 0.9F + world.random.nextFloat() * 0.2F, 0.9F + world.random.nextFloat() * 0.2F);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,9 @@ public static void craftCinderhearthRecipe(World world, @NotNull CinderhearthBlo
}

private static void craftRecipe(@NotNull CinderhearthBlockEntity cinderhearth, ItemStack inputStack, List<ItemStack> outputs, float experience) {
var world = cinderhearth.world;
if (world == null) return;

DefaultedList<ItemStack> backupInventory = DefaultedList.ofSize(INVENTORY_SIZE, ItemStack.EMPTY);
for (int i = 0; i < cinderhearth.inventory.size(); i++) {
backupInventory.set(i, cinderhearth.inventory.get(i));
Expand Down Expand Up @@ -467,8 +470,8 @@ private static void craftRecipe(@NotNull CinderhearthBlockEntity cinderhearth, I

// grant experience & advancements
float experienceMod = cinderhearth.drainInkForUpgrades(cinderhearth, UpgradeType.EXPERIENCE, InkColors.PURPLE, cinderhearth.usesEfficiency);
int finalExperience = Support.getIntFromDecimalWithChance(experience * experienceMod, cinderhearth.world.random);
ExperienceStorageItem.addStoredExperience(cinderhearth.getStack(EXPERIENCE_STORAGE_ITEM_SLOT_ID), finalExperience);
int finalExperience = Support.getIntFromDecimalWithChance(experience * experienceMod, world.random);
ExperienceStorageItem.addStoredExperience(world.getRegistryManager(), cinderhearth.getStack(EXPERIENCE_STORAGE_ITEM_SLOT_ID), finalExperience);
cinderhearth.grantPlayerCinderhearthSmeltingAdvancement(inputStackCopy, outputs, finalExperience);
} else {
cinderhearth.inventory = backupInventory;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package de.dafuqs.spectrum.blocks.deeper_down.flora;

import com.mojang.serialization.*;
import com.mojang.serialization.codecs.*;
import de.dafuqs.spectrum.api.block.*;
import de.dafuqs.spectrum.helpers.*;
import de.dafuqs.spectrum.registries.*;
import net.fabricmc.fabric.api.tag.convention.v2.*;
import net.minecraft.block.*;
import net.minecraft.block.entity.*;
import net.minecraft.component.type.*;
import net.minecraft.enchantment.*;
import net.minecraft.entity.*;
import net.minecraft.entity.effect.*;
Expand All @@ -29,19 +32,27 @@

public class DoomBloomBlock extends FlowerBlock implements Fertilizable, ExplosionAware {

public static final MapCodec<DoomBloomBlock> CODEC = RecordCodecBuilder.mapCodec((i) -> i.group(
STEW_EFFECT_CODEC.forGetter(FlowerBlock::getStewEffects),
createSettingsCodec()
).apply(i, DoomBloomBlock::new));

public static final IntProperty AGE = Properties.AGE_4;
public static final int AGE_MAX = Properties.AGE_4_MAX;
protected static final VoxelShape SHAPE = Block.createCuboidShape(4.0, 0.0, 4.0, 12.0, 9.0, 12.0);
protected static final double GROW_CHANCE = 0.2;

public DoomBloomBlock(RegistryEntry<StatusEffect> suspiciousStewEffect, int effectDuration, Settings settings) {
super(suspiciousStewEffect, effectDuration, settings);
this(createStewEffectList(suspiciousStewEffect, effectDuration), settings);
}

public DoomBloomBlock(SuspiciousStewEffectsComponent stewEffects, Settings settings) {
super(stewEffects, settings);
}

@Override
public MapCodec<? extends DoomBloomBlock> getCodec() {
//TODO: Make the codec
return null;
return CODEC;
}

@Override
Expand Down Expand Up @@ -151,7 +162,7 @@ public void neighborUpdate(BlockState state, World world, BlockPos pos, Block bl
@Override
public void afterBreak(World world, PlayerEntity player, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, ItemStack stack) {
super.afterBreak(world, player, pos, state, blockEntity, stack);
if (EnchantmentHelper.getLevel(Enchantments.SILK_TOUCH, stack) == 0 && !stack.isIn(ConventionalItemTags.SHEAR_TOOLS)) {
if (SpectrumEnchantmentHelper.getLevel(world.getRegistryManager(), Enchantments.SILK_TOUCH, stack) == 0 && !stack.isIn(ConventionalItemTags.SHEAR_TOOLS)) {
explode(world, pos, state);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.*;
import net.minecraft.world.*;
import org.jetbrains.annotations.*;

import java.util.*;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package de.dafuqs.spectrum.items.magic_items;

import de.dafuqs.spectrum.*;
import de.dafuqs.spectrum.api.item.*;
import de.dafuqs.spectrum.helpers.*;
import de.dafuqs.spectrum.registries.*;
import net.minecraft.block.entity.*;
import net.minecraft.enchantment.*;
import net.minecraft.entity.*;
import net.minecraft.entity.player.*;
import net.minecraft.item.*;
import net.minecraft.item.tooltip.*;
import net.minecraft.nbt.*;
import net.minecraft.registry.*;
import net.minecraft.server.network.*;
import net.minecraft.sound.*;
Expand All @@ -34,18 +35,14 @@ public KnowledgeGemItem(Settings settings, int maxStorageBase) {

public static ItemStack getKnowledgeDropStackWithXP(int experience, boolean noStoreTooltip) {
ItemStack stack = new ItemStack(SpectrumItems.KNOWLEDGE_GEM);
NbtCompound compound = new NbtCompound();
compound.putInt("stored_experience", experience);
if (noStoreTooltip) {
compound.putBoolean("do_not_display_store_tooltip", true);
}
stack.setNbt(compound);
stack.set(SpectrumDataComponentTypes.STORED_EXPERIENCE, experience);
stack.set(SpectrumDataComponentTypes.HIDE_USAGE_TOOLTIP, noStoreTooltip);
return stack;
}

@Override
public int getMaxStoredExperience(ItemStack itemStack) {
int efficiencyLevel = EnchantmentHelper.getLevel(Enchantments.EFFICIENCY, itemStack);
public int getMaxStoredExperience(RegistryWrapper.WrapperLookup lookup, ItemStack itemStack) {
int efficiencyLevel = SpectrumEnchantmentHelper.getLevel(lookup, Enchantments.EFFICIENCY, itemStack);
return maxStorageBase * (int) Math.pow(10, Math.min(5, efficiencyLevel)); // to not exceed int max
}

Expand All @@ -54,8 +51,8 @@ public UseAction getUseAction(ItemStack stack) {
return UseAction.BOW;
}

public int getTransferableExperiencePerTick(ItemStack itemStack) {
int quickChargeLevel = EnchantmentHelper.getLevel(Enchantments.QUICK_CHARGE, itemStack);
public int getTransferableExperiencePerTick(RegistryWrapper.WrapperLookup lookup, ItemStack itemStack) {
int quickChargeLevel = SpectrumEnchantmentHelper.getLevel(lookup, Enchantments.QUICK_CHARGE, itemStack);
return (int) (2 * Math.pow(2, Math.min(10, quickChargeLevel)));
}

Expand All @@ -76,15 +73,15 @@ public void usageTick(World world, LivingEntity user, ItemStack stack, int remai

int playerExperience = serverPlayerEntity.totalExperience;
int itemExperience = ExperienceStorageItem.getStoredExperience(stack);
int transferableExperience = getTransferableExperiencePerTick(stack);
int transferableExperience = getTransferableExperiencePerTick(world.getRegistryManager(), stack);

if (serverPlayerEntity.isSneaking()) {
int maxStorage = getMaxStoredExperience(stack);
int maxStorage = getMaxStoredExperience(world.getRegistryManager(), stack);
int experienceToTransfer = serverPlayerEntity.isCreative() ? Math.min(transferableExperience, maxStorage - itemExperience) : Math.min(Math.min(transferableExperience, playerExperience), maxStorage - itemExperience);

// store experience in gem; drain from player
if (experienceToTransfer > 0 && itemExperience < maxStorage && removePlayerExperience(serverPlayerEntity, experienceToTransfer)) {
ExperienceStorageItem.addStoredExperience(stack, experienceToTransfer);
ExperienceStorageItem.addStoredExperience(world.getRegistryManager(), stack, experienceToTransfer);

if (remainingUseTicks % 4 == 0) {
world.playSound(null, user.getBlockPos(), SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, SoundCategory.PLAYERS, 0.3F, 0.8F + world.getRandom().nextFloat() * 0.4F);
Expand Down Expand Up @@ -114,22 +111,24 @@ public void usageTick(World world, LivingEntity user, ItemStack stack, int remai
public void appendTooltip(ItemStack stack, TooltipContext context, List<Text> tooltip, TooltipType type) {
super.appendTooltip(stack, context, tooltip, type);

int maxExperience = getMaxStoredExperience(stack);
int storedExperience = ExperienceStorageItem.getStoredExperience(stack);
if (storedExperience == 0) {
tooltip.add(Text.literal("0 ").formatted(Formatting.DARK_GRAY).append(Text.translatable("item.spectrum.knowledge_gem.tooltip.stored_experience", maxExperience).formatted(Formatting.GRAY)));
} else {
tooltip.add(Text.literal(storedExperience + " ").formatted(Formatting.GREEN).append(Text.translatable("item.spectrum.knowledge_gem.tooltip.stored_experience", maxExperience).formatted(Formatting.GRAY)));
}
if (shouldDisplayUsageTooltip(stack)) {
tooltip.add(Text.translatable("item.spectrum.knowledge_gem.tooltip.use", getTransferableExperiencePerTick(stack)).formatted(Formatting.GRAY));
addBannerPatternProviderTooltip(tooltip);
}
SpectrumCommon.getRegistryLookup().ifPresent(lookup -> {
int maxExperience = getMaxStoredExperience(lookup, stack);
int storedExperience = ExperienceStorageItem.getStoredExperience(stack);
if (storedExperience == 0) {
tooltip.add(Text.literal("0 ").formatted(Formatting.DARK_GRAY).append(Text.translatable("item.spectrum.knowledge_gem.tooltip.stored_experience", maxExperience).formatted(Formatting.GRAY)));
} else {
tooltip.add(Text.literal(storedExperience + " ").formatted(Formatting.GREEN).append(Text.translatable("item.spectrum.knowledge_gem.tooltip.stored_experience", maxExperience).formatted(Formatting.GRAY)));
}
if (shouldDisplayUsageTooltip(stack)) {
tooltip.add(Text.translatable("item.spectrum.knowledge_gem.tooltip.use", getTransferableExperiencePerTick(lookup, stack)).formatted(Formatting.GRAY));
addBannerPatternProviderTooltip(tooltip);
}
});

}

public boolean shouldDisplayUsageTooltip(ItemStack itemStack) {
NbtCompound nbtCompound = itemStack.getNbt();
return nbtCompound == null || !nbtCompound.getBoolean("do_not_display_store_tooltip");
return itemStack.getOrDefault(SpectrumDataComponentTypes.HIDE_USAGE_TOOLTIP, false);
}

public boolean removePlayerExperience(@NotNull PlayerEntity playerEntity, int experience) {
Expand Down
Loading

0 comments on commit 27387a5

Please sign in to comment.