| 1 | package net.minecraft.client.color.item;
|
| 2 |
|
| 3 | import com.mojang.serialization.MapCodec;
|
| 4 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 5 | import it.unimi.dsi.fastutil.ints.IntList;
|
| 6 | import net.fabricmc.api.EnvType;
|
| 7 | import net.fabricmc.api.Environment;
|
| 8 | import net.minecraft.client.multiplayer.ClientLevel;
|
| 9 | import net.minecraft.core.component.DataComponents;
|
| 10 | import net.minecraft.util.ARGB;
|
| 11 | import net.minecraft.util.ExtraCodecs;
|
| 12 | import net.minecraft.world.entity.LivingEntity;
|
| 13 | import net.minecraft.world.item.ItemStack;
|
| 14 | import net.minecraft.world.item.component.FireworkExplosion;
|
| 15 | import org.jspecify.annotations.Nullable;
|
| 16 |
|
| 17 | @Environment(EnvType.CLIENT)
|
| 18 | public record Firework(int defaultColor) implements ItemTintSource {
|
| 19 | public static final MapCodec<Firework> MAP_CODEC = RecordCodecBuilder.mapCodec(
|
| 20 | i -> i.group(ExtraCodecs.RGB_COLOR_CODEC.fieldOf("default").forGetter(Firework::defaultColor)).apply(i, Firework::new)
|
| 21 | );
|
| 22 |
|
| 23 | public Firework() {
|
| 24 | this(-7697782);
|
| 25 | }
|
| 26 |
|
| 27 | @Override
|
| 28 | public int calculate(final ItemStack itemStack, final @Nullable ClientLevel level, final @Nullable LivingEntity owner) {
|
| 29 | FireworkExplosion explosion = itemStack.get(DataComponents.FIREWORK_EXPLOSION);
|
| 30 | IntList explosionColors = explosion != null ? explosion.colors() : IntList.of();
|
| 31 | int colorCount = explosionColors.size();
|
| 32 | if (colorCount == 0) {
|
| 33 | return this.defaultColor;
|
| 34 | }
|
| 35 |
|
| 36 | if (colorCount == 1) {
|
| 37 | return ARGB.opaque(explosionColors.getInt(0));
|
| 38 | }
|
| 39 |
|
| 40 | int totalRed = 0;
|
| 41 | int totalGreen = 0;
|
| 42 | int totalBlue = 0;
|
| 43 |
|
| 44 | for (int i = 0; i < colorCount; i++) {
|
| 45 | int color = explosionColors.getInt(i);
|
| 46 | totalRed += ARGB.red(color);
|
| 47 | totalGreen += ARGB.green(color);
|
| 48 | totalBlue += ARGB.blue(color);
|
| 49 | }
|
| 50 |
|
| 51 | return ARGB.color(totalRed / colorCount, totalGreen / colorCount, totalBlue / colorCount);
|
| 52 | }
|
| 53 |
|
| 54 | @Override
|
| 55 | public MapCodec<Firework> type() {
|
| 56 | return MAP_CODEC;
|
| 57 | }
|
| 58 | }
|
| 59 |
|