Skip to content

Commit

Permalink
fix networking and data saving
Browse files Browse the repository at this point in the history
  • Loading branch information
Thepigcat76 committed Jul 18, 2024
1 parent 75325e6 commit cb1e33d
Show file tree
Hide file tree
Showing 9 changed files with 166 additions and 105 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,15 @@
import com.leclowndu93150.modular_angelring.utils.FlightSpeedPercentage;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.Level;
import net.neoforged.neoforge.common.NeoForgeMod;
import org.jetbrains.annotations.NotNull;
import top.theillusivec4.curios.api.CuriosApi;
Expand All @@ -21,6 +26,7 @@
import java.util.Optional;

import static com.leclowndu93150.modular_angelring.common.AngelRingModules.getSpeedModifier;
import static com.leclowndu93150.modular_angelring.common.AngelRingModules.setSpeedModifier;

public class AngelRingItem extends Item {

Expand All @@ -38,6 +44,39 @@ public boolean isFoil(@NotNull ItemStack pStack) {
return true;
}

@Override
public InteractionResultHolder<ItemStack> use(Level pLevel, Player player, InteractionHand pUsedHand) {

final float MAX_FLY_SPEED = 0.15F;
final float MIN_FLY_SPEED = 0.0F;
final float SPEED_INCREMENT = 0.005F;
ItemStack item = player.getItemInHand(pUsedHand);

if (item.is(this) && item.has(DataComponentRegistry.SPEED_MODIFIER)) {
float currentFlySpeed = getSpeedModifier(item);

if (player.isShiftKeyDown()) {
currentFlySpeed = Math.max(currentFlySpeed - SPEED_INCREMENT, MIN_FLY_SPEED); // Ensure it doesn't go below the min
} else if (currentFlySpeed < MAX_FLY_SPEED) {
currentFlySpeed = Math.min(currentFlySpeed + SPEED_INCREMENT, MAX_FLY_SPEED); // Ensure it doesn't exceed the max
}

setSpeedModifier(item, currentFlySpeed);

int percentage = FlightSpeedPercentage.speedToPercentage(currentFlySpeed);
player.displayClientMessage(Component.literal("Speed: ")
.append(String.valueOf(percentage))
.append("%")
.withStyle(ChatFormatting.WHITE), true);

player.level().playSound(player, player.getX(), player.getY(), player.getZ(),
SoundEvents.NOTE_BLOCK_BELL.value(), SoundSource.PLAYERS, 0.4f, 0.01f);
return InteractionResultHolder.success(item);
}

return InteractionResultHolder.fail(item);
}

private static void startFlight(Player player) {
if (!player.isCreative() && !player.isSpectator()) {
player.getAttribute(NeoForgeMod.CREATIVE_FLIGHT).setBaseValue(1);
Expand All @@ -52,29 +91,33 @@ private static void stopFlight(Player player) {

public static void tickRing(ItemStack stack, Player player) {
Optional<SlotResult> slotResult = CuriosApi.getCuriosInventory(player).flatMap(handler -> handler.findFirstCurio(ItemRegistry.ANGEL_RING.get()));
if(slotResult.isEmpty()){
if (slotResult.isEmpty()) {
player.getAbilities().setFlyingSpeed(0.05F);
return;
}

if (player.getAttribute(NeoForgeMod.CREATIVE_FLIGHT).getBaseValue() != 1) {
startFlight(player);
}
startFlight(player);
}

ItemStack angelRingStack = slotResult.get().stack();
if(angelRingStack.has(DataComponentRegistry.SPEED_MODIFIER) && ((player.getAbilities().getFlyingSpeed() != getSpeedModifier(angelRingStack)) || !PayloadActions.speedEnabled)){
if(PayloadActions.speedEnabled){
EnabledModifiersComponent data = stack.getOrDefault(DataComponentRegistry.MODIFIERS_ENABLED, EnabledModifiersComponent.EMPTY);

if (angelRingStack.has(DataComponentRegistry.SPEED_MODIFIER) && ((player.getAbilities().getFlyingSpeed() != getSpeedModifier(angelRingStack)) || !data.speedModifierEnabled())) {
if (data.speedModifierEnabled()) {
player.getAbilities().setFlyingSpeed(getSpeedModifier(angelRingStack));
} else player.getAbilities().setFlyingSpeed(0.05F);
} else {
player.getAbilities().setFlyingSpeed(0.05F);
}
}
}

public static void tickPlayer(Player player) {
Optional<SlotResult> slotResult = CuriosApi.getCuriosInventory(player).flatMap(handler -> handler.findFirstCurio(ItemRegistry.ANGEL_RING.get()));
if (slotResult.isPresent()) {
ItemStack angelRingStack = slotResult.get().stack();
tickRing(angelRingStack, player);
}
tickRing(angelRingStack, player);
}
if (slotResult.isEmpty()) {
stopFlight(player);
player.getAbilities().setFlyingSpeed(0.05F);
Expand All @@ -83,19 +126,21 @@ public static void tickPlayer(Player player) {

@Override
public void appendHoverText(@NotNull ItemStack stack, @NotNull TooltipContext pContext, @NotNull List<Component> pTooltipComponents, @NotNull TooltipFlag pTooltipFlag) {
EnabledModifiersComponent data = stack.getOrDefault(DataComponentRegistry.MODIFIERS_ENABLED, EnabledModifiersComponent.EMPTY);

if (AngelRingModules.getMiningSpeedModifier(stack) /* && KeyBindRegistry.miningEnabled */) {
pTooltipComponents.add(Component.literal("Mining Module")/*.append("Enabled")*/.withStyle(ChatFormatting.GRAY));
}
if (AngelRingModules.getInertiaModifier(stack) && PayloadActions.inertiaEnabled){
if (AngelRingModules.getInertiaModifier(stack) && data.inertiaEnabled()) {
pTooltipComponents.add(Component.literal("Inertia Module: ").append("Enabled").withStyle(ChatFormatting.GREEN));
}
if (AngelRingModules.getInertiaModifier(stack) && !PayloadActions.inertiaEnabled){
if (AngelRingModules.getInertiaModifier(stack) && !data.inertiaEnabled()) {
pTooltipComponents.add(Component.literal("Inertia Module: ").append("Disabled").withStyle(ChatFormatting.RED));
}
if (stack.has(DataComponentRegistry.SPEED_MODIFIER) && PayloadActions.speedEnabled){
if (stack.has(DataComponentRegistry.SPEED_MODIFIER) && data.speedModifierEnabled()) {
pTooltipComponents.add(Component.literal("Speed Module: ").append(String.valueOf(FlightSpeedPercentage.speedToPercentage(AngelRingModules.getSpeedModifier(stack)))).append("%").withStyle(ChatFormatting.GREEN));
}
if (stack.has(DataComponentRegistry.SPEED_MODIFIER) && !PayloadActions.speedEnabled){
if (stack.has(DataComponentRegistry.SPEED_MODIFIER) && !data.speedModifierEnabled()) {
pTooltipComponents.add(Component.literal("Speed Module: ").append(String.valueOf(FlightSpeedPercentage.speedToPercentage(AngelRingModules.getSpeedModifier(stack)))).append("%").withStyle(ChatFormatting.RED));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.leclowndu93150.modular_angelring.common;

import com.mojang.serialization.Codec;
import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;

import java.util.Objects;

public record EnabledModifiersComponent(boolean inertiaEnabled, boolean speedModifierEnabled, boolean miningEnabled) {
public static final EnabledModifiersComponent EMPTY = new EnabledModifiersComponent(false, false, false);

public static final MapCodec<EnabledModifiersComponent> CODEC = RecordCodecBuilder.mapCodec(builder -> builder.group(
Codec.BOOL.fieldOf("inertia_enabled").forGetter(EnabledModifiersComponent::inertiaEnabled),
Codec.BOOL.fieldOf("speed_enabled").forGetter(EnabledModifiersComponent::speedModifierEnabled),
Codec.BOOL.fieldOf("mining_enabled").forGetter(EnabledModifiersComponent::miningEnabled)
).apply(builder, EnabledModifiersComponent::new));
public static final StreamCodec<RegistryFriendlyByteBuf, EnabledModifiersComponent> STREAM_CODEC = StreamCodec.composite(
ByteBufCodecs.BOOL,
EnabledModifiersComponent::inertiaEnabled,
ByteBufCodecs.BOOL,
EnabledModifiersComponent::speedModifierEnabled,
ByteBufCodecs.BOOL,
EnabledModifiersComponent::miningEnabled,
EnabledModifiersComponent::new
);

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EnabledModifiersComponent that)) return false;
return miningEnabled == that.miningEnabled && inertiaEnabled == that.inertiaEnabled && speedModifierEnabled == that.speedModifierEnabled;
}

@Override
public int hashCode() {
return Objects.hash(inertiaEnabled, speedModifierEnabled, miningEnabled);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,23 @@

import com.leclowndu93150.modular_angelring.AngelRingMain;
import com.leclowndu93150.modular_angelring.common.AngelRingItem;
import com.leclowndu93150.modular_angelring.common.EnabledModifiersComponent;
import com.leclowndu93150.modular_angelring.networking.PayloadActions;
import com.leclowndu93150.modular_angelring.networking.noKeyPressedPayload;
import com.leclowndu93150.modular_angelring.registry.DataComponentRegistry;
import com.leclowndu93150.modular_angelring.registry.ItemRegistry;
import com.leclowndu93150.modular_angelring.registry.KeyBindRegistry;
import com.leclowndu93150.modular_angelring.utils.FlightSpeedPercentage;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.Options;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.entity.EntityEvent;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.Vec3;
import net.neoforged.bus.api.EventPriority;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.event.entity.living.LivingBreatheEvent;
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
import net.neoforged.neoforge.event.tick.EntityTickEvent;
import net.neoforged.neoforge.event.tick.PlayerTickEvent;
import top.theillusivec4.curios.api.CuriosApi;
import top.theillusivec4.curios.api.SlotResult;
Expand Down Expand Up @@ -60,8 +52,9 @@ public static void stopDrift(PlayerTickEvent.Pre event) {
if (slotResult.isPresent()) {
ItemStack angelRingStack = slotResult.get().stack();
Vec3 motion = player.getDeltaMovement();
if (player.getAbilities().flying && getInertiaModifier(angelRingStack) && PayloadActions.inertiaEnabled) {
if (PayloadActions.isNoKeysPressed) {
EnabledModifiersComponent data = angelRingStack.getOrDefault(DataComponentRegistry.MODIFIERS_ENABLED, EnabledModifiersComponent.EMPTY);
if (player.getAbilities().flying && getInertiaModifier(angelRingStack) && data.inertiaEnabled()) {
if (player.getPersistentData().getBoolean(PayloadActions.NO_KEYS_PRESSED)) {
if (motion.x != 0 || motion.z != 0) {
player.setDeltaMovement(0, motion.y, 0);
}
Expand All @@ -70,36 +63,6 @@ public static void stopDrift(PlayerTickEvent.Pre event) {
}
}

@SubscribeEvent(priority = EventPriority.LOW)
public static void newFlightSpeed(PlayerInteractEvent.RightClickItem event) {
final float MAX_FLY_SPEED = 0.15F;
final float MIN_FLY_SPEED = 0.0F;
final float SPEED_INCREMENT = 0.005F;
Player player = event.getEntity();
ItemStack item = player.getMainHandItem();

if (item.is(ItemRegistry.ANGEL_RING) && item.has(DataComponentRegistry.SPEED_MODIFIER)) {
float currentFlySpeed = getSpeedModifier(item);

if (player.isCrouching()) {
currentFlySpeed = Math.max(currentFlySpeed - SPEED_INCREMENT, MIN_FLY_SPEED); // Ensure it doesn't go below the min
} else if (currentFlySpeed < MAX_FLY_SPEED) {
currentFlySpeed = Math.min(currentFlySpeed + SPEED_INCREMENT, MAX_FLY_SPEED); // Ensure it doesn't exceed the max
}

setSpeedModifier(item, currentFlySpeed);

int percentage = FlightSpeedPercentage.speedToPercentage(currentFlySpeed);
player.displayClientMessage(Component.literal("Speed: ")
.append(String.valueOf(percentage))
.append("%")
.withStyle(ChatFormatting.WHITE), true);

player.level().playSound(player, player.getX(), player.getY(), player.getZ(),
SoundEvents.NOTE_BLOCK_BELL.value(), SoundSource.PLAYERS, 0.4f, 0.01f);
}
}

@SubscribeEvent(priority = EventPriority.LOW)
public static void onPlayerTick(PlayerTickEvent.Pre event) {
AngelRingItem.tickPlayer(event.getEntity());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ public final class NetworkingEvents {
public static void registerPayloads(RegisterPayloadHandlersEvent event) {
PayloadRegistrar registrar = event.registrar(AngelRingMain.MODID);
registrar.playToServer(KeyPressedPayload.TYPE, KeyPressedPayload.STREAM_CODEC, PayloadActions::keyPressedAction);
registrar.playToServer(noKeyPressedPayload.TYPE, noKeyPressedPayload.STREAM_CODEC, PayloadActions::noKeyPressedAction);
registrar.playBidirectional(NoKeyPressedPayload.TYPE, NoKeyPressedPayload.STREAM_CODEC, PayloadActions::noKeyPressedAction);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@
import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;

public record noKeyPressedPayload(boolean pressed) implements CustomPacketPayload {
public static final Type<noKeyPressedPayload> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(AngelRingMain.MODID, "no_keypressed_payload"));
public static final StreamCodec<RegistryFriendlyByteBuf, noKeyPressedPayload> STREAM_CODEC = StreamCodec.composite(
public record NoKeyPressedPayload(boolean pressed) implements CustomPacketPayload {
public static final Type<NoKeyPressedPayload> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(AngelRingMain.MODID, "no_keypressed_payload"));
public static final StreamCodec<RegistryFriendlyByteBuf, NoKeyPressedPayload> STREAM_CODEC = StreamCodec.composite(
ByteBufCodecs.BOOL,
noKeyPressedPayload::pressed,
noKeyPressedPayload::new
NoKeyPressedPayload::pressed,
NoKeyPressedPayload::new
);

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,31 +1,45 @@
package com.leclowndu93150.modular_angelring.networking;

import com.leclowndu93150.modular_angelring.common.EnabledModifiersComponent;
import com.leclowndu93150.modular_angelring.registry.DataComponentRegistry;
import com.leclowndu93150.modular_angelring.registry.ItemRegistry;
import com.leclowndu93150.modular_angelring.registry.KeyBindRegistry;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.neoforged.neoforge.network.PacketDistributor;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import top.theillusivec4.curios.api.CuriosApi;
import top.theillusivec4.curios.api.SlotResult;

import java.util.Optional;

public final class PayloadActions {
public static boolean inertiaEnabled = true;
public static boolean speedEnabled = true;
public static boolean isNoKeysPressed = false;

public static final String NO_KEYS_PRESSED = "no_keys_pressed";

public static void keyPressedAction(KeyPressedPayload payload, IPayloadContext ctx) {
// SERVER-SIDE
Player player = ctx.player();
Level level = player.level();
int key = payload.key();
if (key == KeyBindRegistry.INERTIA_MODULE.get().getKey().getValue()) {
inertiaEnabled = !inertiaEnabled;
}

if (key == KeyBindRegistry.SPEED_MODULE.get().getKey().getValue()) {
speedEnabled = !speedEnabled;
Optional<SlotResult> slotResult = CuriosApi.getCuriosInventory(player).flatMap(handler -> handler.findFirstCurio(ItemRegistry.ANGEL_RING.get()));
if (slotResult.isPresent()) {
ItemStack itemStack = slotResult.get().stack();
EnabledModifiersComponent data = itemStack.getOrDefault(DataComponentRegistry.MODIFIERS_ENABLED, EnabledModifiersComponent.EMPTY);
if (key == KeyBindRegistry.INERTIA_MODULE.get().getKey().getValue()) {
itemStack.set(DataComponentRegistry.MODIFIERS_ENABLED,
new EnabledModifiersComponent(!data.inertiaEnabled(), data.speedModifierEnabled(), data.miningEnabled()));
} else if (key == KeyBindRegistry.SPEED_MODULE.get().getKey().getValue()) {
itemStack.set(DataComponentRegistry.MODIFIERS_ENABLED,
new EnabledModifiersComponent(data.inertiaEnabled(), !data.speedModifierEnabled(), data.miningEnabled()));
}
}
}

public static void noKeyPressedAction(noKeyPressedPayload payload, IPayloadContext ctx) {
public static void noKeyPressedAction(NoKeyPressedPayload payload, IPayloadContext ctx) {
// SERVER-SIDE
isNoKeysPressed = payload.pressed();
Player player = ctx.player();
player.getPersistentData().putBoolean(NO_KEYS_PRESSED, payload.pressed());
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.leclowndu93150.modular_angelring.registry;

import com.leclowndu93150.modular_angelring.common.EnabledModifiersComponent;
import com.mojang.serialization.Codec;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.network.codec.ByteBufCodecs;
Expand All @@ -21,4 +22,7 @@ public class DataComponentRegistry {

public static final Supplier<DataComponentType<Float>> SPEED_MODIFIER = COMPONENTS.registerComponentType("speed_modifier",
builder -> builder.persistent(Codec.FLOAT).networkSynchronized(ByteBufCodecs.FLOAT));

public static final Supplier<DataComponentType<EnabledModifiersComponent>> MODIFIERS_ENABLED = COMPONENTS.registerComponentType("modifiers_enabled",
builder -> builder.persistent(EnabledModifiersComponent.CODEC.codec()).networkSynchronized(EnabledModifiersComponent.STREAM_CODEC));
}
Loading

0 comments on commit cb1e33d

Please sign in to comment.