summary refs log blame commit diff stats
path: root/src/main/java/ganarchy/chewstuff/mixin/PotionMix.java
blob: 5ed97ab87dd9f770e1d0e60028a6c772ad117d99 (plain) (tree)


































































                                                                              
package ganarchy.chewstuff.mixin;

import ganarchy.chewstuff.ChewComponents;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.effect.StatusEffectInstance;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

/**
 * The mixin for status effect instances.
 */
@Mixin(StatusEffectInstance.class)
public class PotionMix {
    /**
     * Checks the apply effect and cancels it when we're force-ticking it.
     */
    @Inject(
        at = @At("HEAD"),
        method = "applyUpdateEffect(Lnet/minecraft/entity/LivingEntity;)V",
        cancellable = true
    )
    private void chewstuff_checkApplyEffect(
        LivingEntity entity, CallbackInfo cbinfo
    ) {
        StatusEffectInstance self = (StatusEffectInstance) (Object) this;
        var maybeInfo = ChewComponents.CHEW.maybeGet(entity);
        maybeInfo.ifPresent(info -> {
            var effect = self.getEffectType();
            if (info.effects.getOrDefault(effect, 0) <= 0) {
                return;
            }
            if (info.applied.contains(effect)) {
                info.applied.remove(effect);
                cbinfo.cancel();
            } else {
                info.applied.add(effect);
            }
        });
    }

    /**
     * Checks for effect ticks.
     */
    @Inject(
        at = @At("HEAD"),
        method =
            "update(Lnet/minecraft/entity/LivingEntity;Ljava/lang/Runnable;)Z"
    )
    private void chewstuff_checkUpdate(
        LivingEntity entity,
        Runnable runnable,
        CallbackInfoReturnable<Boolean> cbinfo
    ) {
        StatusEffectInstance self = (StatusEffectInstance) (Object) this;
        var maybeInfo = ChewComponents.CHEW.maybeGet(entity);
        maybeInfo.ifPresent(info -> {
            var effect = self.getEffectType();
            if (info.effects.getOrDefault(effect, 0) <= 0) {
                return;
            }
            info.effects.computeIfPresent(effect, (k, v) -> v - 1);
        });
    }
}