PotionContents .java

net.minecraft.world.item.alchemy.PotionContents (record): members: potion, customColor, customEffects, customName, isPotionWithoutCustomEffects, NO_EFFECT.

net.minecraft.world.item.alchemyrecord250 linescommon10.1 KB

Implements

API Surface (19)

ItemStack createItemStack(final Item item, final Holder<Potion> potion)
boolean is(final Holder<Potion> potion)
boolean is(final TagKey<Potion> potion)
boolean isPotionWithoutCustomEffects()
Iterable<MobEffectInstance> getAllEffects()
void forEachEffect(final Consumer<MobEffectInstance> consumer, final float durationScale)
PotionContents withPotion(final Holder<Potion> potion)
PotionContents withEffectAdded(final MobEffectInstance effect)
int getColor()
int getColorOr(final int defaultColor)
Component getName(final String prefix)
OptionalInt getColorOptional(final Iterable<MobEffectInstance> effects)
boolean hasEffects()
List<MobEffectInstance> customEffects()
void applyToLivingEntity(final LivingEntity entity, final float durationScale)
void addPotionTooltip(final Iterable<MobEffectInstance> effects, final Consumer<Component> lines, final float durationScale, final float tickrate)
MutableComponent getPotionDescription(final Holder<MobEffect> mobEffect, final int amplifier)
void onConsume(final Level level, final LivingEntity user, final ItemStack stack, final Consumable consumable)
void addToTooltip(final Item.TooltipContext context, final Consumer<Component> consumer, final TooltipFlag flag, final DataComponentGetter components)

Fields & Constants (7)

EMPTY
NO_EFFECT
BASE_POTION_COLOR
FULL_CODEC
CODEC
STREAM_CODEC
durationScale

String literals (12)

"effect.none"
"potion"
"custom_color"
"custom_effects"
"custom_name"
"empty"
"potion.withDuration"
"potion.whenDrank"
"attribute.modifier.plus."
"attribute.modifier.take."
"potion.withAmplifier"
"potion.potency."

Full Source

PotionContents.java250 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.item.alchemy;
2
3
import com.google.common.collect.Iterables;
4
import com.google.common.collect.Lists;
5
import com.mojang.datafixers.util.Pair;
6
import com.mojang.serialization.Codec;
7
import com.mojang.serialization.codecs.RecordCodecBuilder;
8
import java.util.List;
9
import java.util.Optional;
10
import java.util.OptionalInt;
11
import java.util.function.Consumer;
12
import net.minecraft.ChatFormatting;
13
import net.minecraft.core.Holder;
14
import net.minecraft.core.component.DataComponentGetter;
15
import net.minecraft.core.component.DataComponents;
16
import net.minecraft.network.RegistryFriendlyByteBuf;
17
import net.minecraft.network.chat.CommonComponents;
18
import net.minecraft.network.chat.Component;
19
import net.minecraft.network.chat.MutableComponent;
20
import net.minecraft.network.codec.ByteBufCodecs;
21
import net.minecraft.network.codec.StreamCodec;
22
import net.minecraft.server.level.ServerLevel;
23
import net.minecraft.tags.TagKey;
24
import net.minecraft.util.ARGB;
25
import net.minecraft.util.Util;
26
import net.minecraft.world.effect.MobEffect;
27
import net.minecraft.world.effect.MobEffectInstance;
28
import net.minecraft.world.effect.MobEffectUtil;
29
import net.minecraft.world.entity.LivingEntity;
30
import net.minecraft.world.entity.ai.attributes.Attribute;
31
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
32
import net.minecraft.world.entity.player.Player;
33
import net.minecraft.world.item.Item;
34
import net.minecraft.world.item.ItemStack;
35
import net.minecraft.world.item.TooltipFlag;
36
import net.minecraft.world.item.component.Consumable;
37
import net.minecraft.world.item.component.ConsumableListener;
38
import net.minecraft.world.item.component.ItemAttributeModifiers;
39
import net.minecraft.world.item.component.TooltipProvider;
40
import net.minecraft.world.level.Level;
41
42
public record PotionContents(Optional<Holder<Potion>> potion, Optional<Integer> customColor, List<MobEffectInstance> customEffects, Optional<String> customName)
43
	implements ConsumableListener,
44
	TooltipProvider {
45
	public static final PotionContents EMPTY = new PotionContents(Optional.empty(), Optional.empty(), List.of(), Optional.empty());
46
	private static final Component NO_EFFECT = Component.translatable("effect.none").withStyle(ChatFormatting.GRAY);
47
	public static final int BASE_POTION_COLOR = -13083194;
48
	private static final Codec<PotionContents> FULL_CODEC = RecordCodecBuilder.create(
49
		i -> i.group(
50
				Potion.CODEC.optionalFieldOf("potion").forGetter(PotionContents::potion),
51
				Codec.INT.optionalFieldOf("custom_color").forGetter(PotionContents::customColor),
52
				MobEffectInstance.CODEC.listOf().optionalFieldOf("custom_effects", List.of()).forGetter(PotionContents::customEffects),
53
				Codec.STRING.optionalFieldOf("custom_name").forGetter(PotionContents::customName)
54
			)
55
			.apply(i, PotionContents::new)
56
	);
57
	public static final Codec<PotionContents> CODEC = Codec.withAlternative(FULL_CODEC, Potion.CODEC, PotionContents::new);
58
	public static final StreamCodec<RegistryFriendlyByteBuf, PotionContents> STREAM_CODEC = StreamCodec.composite(
59
		Potion.STREAM_CODEC.apply(ByteBufCodecs::optional),
60
		PotionContents::potion,
61
		ByteBufCodecs.INT.apply(ByteBufCodecs::optional),
62
		PotionContents::customColor,
63
		MobEffectInstance.STREAM_CODEC.apply(ByteBufCodecs.list()),
64
		PotionContents::customEffects,
65
		ByteBufCodecs.STRING_UTF8.apply(ByteBufCodecs::optional),
66
		PotionContents::customName,
67
		PotionContents::new
68
	);
69
70
	public PotionContents(final Holder<Potion> potion) {
71
		this(Optional.of(potion), Optional.empty(), List.of(), Optional.empty());
72
	}
73
74
	public static ItemStack createItemStack(final Item item, final Holder<Potion> potion) {
75
		ItemStack itemStack = new ItemStack(item);
76
		itemStack.set(DataComponents.POTION_CONTENTS, new PotionContents(potion));
77
		return itemStack;
78
	}
79
80
	public boolean is(final Holder<Potion> potion) {
81
		return this.isPotionWithoutCustomEffects() && this.potion.get().is(potion);
82
	}
83
84
	public boolean is(final TagKey<Potion> potion) {
85
		return this.isPotionWithoutCustomEffects() && this.potion.get().is(potion);
86
	}
87
88
	public boolean isPotionWithoutCustomEffects() {
89
		return this.potion.isPresent() && this.customEffects.isEmpty();
90
	}
91
92
	public Iterable<MobEffectInstance> getAllEffects() {
93
		if (this.potion.isEmpty()) {
94
			return this.customEffects;
95
		} else {
96
			return this.customEffects.isEmpty() ? this.potion.get().value().getEffects() : Iterables.concat(this.potion.get().value().getEffects(), this.customEffects);
97
		}
98
	}
99
100
	public void forEachEffect(final Consumer<MobEffectInstance> consumer, final float durationScale) {
101
		if (this.potion.isPresent()) {
102
			for (MobEffectInstance effect : this.potion.get().value().getEffects()) {
103
				consumer.accept(effect.withScaledDuration(durationScale));
104
			}
105
		}
106
107
		for (MobEffectInstance effect : this.customEffects) {
108
			consumer.accept(effect.withScaledDuration(durationScale));
109
		}
110
	}
111
112
	public PotionContents withPotion(final Holder<Potion> potion) {
113
		return new PotionContents(Optional.of(potion), this.customColor, this.customEffects, this.customName);
114
	}
115
116
	public PotionContents withEffectAdded(final MobEffectInstance effect) {
117
		return new PotionContents(this.potion, this.customColor, Util.copyAndAdd(this.customEffects, effect), this.customName);
118
	}
119
120
	public int getColor() {
121
		return this.getColorOr(-13083194);
122
	}
123
124
	public int getColorOr(final int defaultColor) {
125
		return this.customColor.isPresent() ? this.customColor.get() : getColorOptional(this.getAllEffects()).orElse(defaultColor);
126
	}
127
128
	public Component getName(final String prefix) {
129
		String suffix = this.customName.or(() -> this.potion.map(p -> p.value().name())).orElse("empty");
130
		return Component.translatable(prefix + suffix);
131
	}
132
133
	public static OptionalInt getColorOptional(final Iterable<MobEffectInstance> effects) {
134
		int red = 0;
135
		int green = 0;
136
		int blue = 0;
137
		int totalWeight = 0;
138
139
		for (MobEffectInstance effect : effects) {
140
			if (effect.isVisible()) {
141
				int color = effect.getEffect().value().getColor();
142
				int amplifier = effect.getAmplifier() + 1;
143
				red += amplifier * ARGB.red(color);
144
				green += amplifier * ARGB.green(color);
145
				blue += amplifier * ARGB.blue(color);
146
				totalWeight += amplifier;
147
			}
148
		}
149
150
		return totalWeight == 0 ? OptionalInt.empty() : OptionalInt.of(ARGB.color(red / totalWeight, green / totalWeight, blue / totalWeight));
151
	}
152
153
	public boolean hasEffects() {
154
		return !this.customEffects.isEmpty() ? true : this.potion.isPresent() && !this.potion.get().value().getEffects().isEmpty();
155
	}
156
157
	public List<MobEffectInstance> customEffects() {
158
		return Lists.transform(this.customEffects, MobEffectInstance::new);
159
	}
160
161
	public void applyToLivingEntity(final LivingEntity entity, final float durationScale) {
162
		if (entity.level() instanceof ServerLevel serverLevel) {
163
			Player player = entity instanceof Player playerEntity ? playerEntity : null;
164
			this.forEachEffect(effect -> {
165
				if (effect.getEffect().value().isInstantaneous()) {
166
					effect.getEffect().value().applyInstantaneousEffect(serverLevel, player, player, entity, effect.getAmplifier(), 1.0);
167
				} else {
168
					entity.addEffect(effect);
169
				}
170
			}, durationScale);
171
		}
172
	}
173
174
	public static void addPotionTooltip(
175
		final Iterable<MobEffectInstance> effects, final Consumer<Component> lines, final float durationScale, final float tickrate
176
	) {
177
		List<Pair<Holder<Attribute>, AttributeModifier>> modifiers = Lists.newArrayList();
178
		boolean noEffects = true;
179
180
		for (MobEffectInstance effect : effects) {
181
			noEffects = false;
182
			Holder<MobEffect> mobEffect = effect.getEffect();
183
			int amplifier = effect.getAmplifier();
184
			mobEffect.value().createModifiers(amplifier, (attribute, modifierx) -> modifiers.add(new Pair<>(attribute, modifierx)));
185
			MutableComponent line = getPotionDescription(mobEffect, amplifier);
186
			if (!effect.endsWithin(20)) {
187
				line = Component.translatable("potion.withDuration", line, MobEffectUtil.formatDuration(effect, durationScale, tickrate));
188
			}
189
190
			lines.accept(line.withStyle(mobEffect.value().getCategory().getTooltipFormatting()));
191
		}
192
193
		if (noEffects) {
194
			lines.accept(NO_EFFECT);
195
		}
196
197
		if (!modifiers.isEmpty()) {
198
			lines.accept(CommonComponents.EMPTY);
199
			lines.accept(Component.translatable("potion.whenDrank").withStyle(ChatFormatting.DARK_PURPLE));
200
201
			for (Pair<Holder<Attribute>, AttributeModifier> entry : modifiers) {
202
				AttributeModifier modifier = entry.getSecond();
203
				double amount = modifier.amount();
204
				double displayAmount;
205
				if (modifier.operation() != AttributeModifier.Operation.ADD_MULTIPLIED_BASE && modifier.operation() != AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL) {
206
					displayAmount = modifier.amount();
207
				} else {
208
					displayAmount = modifier.amount() * 100.0;
209
				}
210
211
				if (amount > 0.0) {
212
					lines.accept(
213
						Component.translatable(
214
								"attribute.modifier.plus." + modifier.operation().id(),
215
								ItemAttributeModifiers.ATTRIBUTE_MODIFIER_FORMAT.format(displayAmount),
216
								Component.translatable(entry.getFirst().value().getDescriptionId())
217
							)
218
							.withStyle(ChatFormatting.BLUE)
219
					);
220
				} else if (amount < 0.0) {
221
					displayAmount *= -1.0;
222
					lines.accept(
223
						Component.translatable(
224
								"attribute.modifier.take." + modifier.operation().id(),
225
								ItemAttributeModifiers.ATTRIBUTE_MODIFIER_FORMAT.format(displayAmount),
226
								Component.translatable(entry.getFirst().value().getDescriptionId())
227
							)
228
							.withStyle(ChatFormatting.RED)
229
					);
230
				}
231
			}
232
		}
233
	}
234
235
	public static MutableComponent getPotionDescription(final Holder<MobEffect> mobEffect, final int amplifier) {
236
		MutableComponent line = Component.translatable(mobEffect.value().getDescriptionId());
237
		return amplifier > 0 ? Component.translatable("potion.withAmplifier", line, Component.translatable("potion.potency." + amplifier)) : line;
238
	}
239
240
	@Override
241
	public void onConsume(final Level level, final LivingEntity user, final ItemStack stack, final Consumable consumable) {
242
		this.applyToLivingEntity(user, stack.getOrDefault(DataComponents.POTION_DURATION_SCALE, 1.0F));
243
	}
244
245
	@Override
246
	public void addToTooltip(final Item.TooltipContext context, final Consumer<Component> consumer, final TooltipFlag flag, final DataComponentGetter components) {
247
		addPotionTooltip(this.getAllEffects(), consumer, components.getOrDefault(DataComponents.POTION_DURATION_SCALE, 1.0F), context.tickRate());
248
	}
249
}
250

Decompiled Minecraft 26.3 source of PotionContents (net/minecraft/world/item/alchemy/PotionContents.java) with Mojang official mappings, stored verbatim on the site.