| 1 | package net.minecraft.client.sounds;
|
| 2 |
|
| 3 | import com.google.common.collect.Lists;
|
| 4 | import java.util.List;
|
| 5 | import net.fabricmc.api.EnvType;
|
| 6 | import net.fabricmc.api.Environment;
|
| 7 | import net.minecraft.ChatFormatting;
|
| 8 | import net.minecraft.SharedConstants;
|
| 9 | import net.minecraft.client.resources.sounds.Sound;
|
| 10 | import net.minecraft.network.chat.Component;
|
| 11 | import net.minecraft.network.chat.MutableComponent;
|
| 12 | import net.minecraft.resources.Identifier;
|
| 13 | import net.minecraft.util.RandomSource;
|
| 14 | import org.jspecify.annotations.Nullable;
|
| 15 |
|
| 16 | @Environment(EnvType.CLIENT)
|
| 17 | public class WeighedSoundEvents implements Weighted<Sound> {
|
| 18 | private final List<Weighted<Sound>> list = Lists.newArrayList();
|
| 19 | private final @Nullable Component subtitle;
|
| 20 |
|
| 21 | public WeighedSoundEvents(final Identifier location, final @Nullable String subtitle) {
|
| 22 | if (SharedConstants.DEBUG_SUBTITLES) {
|
| 23 | MutableComponent components = Component.literal(location.getPath());
|
| 24 | if ("FOR THE DEBUG!".equals(subtitle)) {
|
| 25 | components = components.append(Component.literal(" missing").withStyle(ChatFormatting.RED));
|
| 26 | }
|
| 27 |
|
| 28 | this.subtitle = components;
|
| 29 | } else {
|
| 30 | this.subtitle = subtitle == null ? null : Component.translatable(subtitle);
|
| 31 | }
|
| 32 | }
|
| 33 |
|
| 34 | @Override
|
| 35 | public int getWeight() {
|
| 36 | int sum = 0;
|
| 37 |
|
| 38 | for (Weighted<Sound> sound : this.list) {
|
| 39 | sum += sound.getWeight();
|
| 40 | }
|
| 41 |
|
| 42 | return sum;
|
| 43 | }
|
| 44 |
|
| 45 | public Sound getSound(final RandomSource random) {
|
| 46 | int weight = this.getWeight();
|
| 47 | if (!this.list.isEmpty() && weight != 0) {
|
| 48 | int index = random.nextInt(weight);
|
| 49 |
|
| 50 | for (Weighted<Sound> weighted : this.list) {
|
| 51 | index -= weighted.getWeight();
|
| 52 | if (index < 0) {
|
| 53 | return weighted.getSound(random);
|
| 54 | }
|
| 55 | }
|
| 56 |
|
| 57 | return SoundManager.EMPTY_SOUND;
|
| 58 | } else {
|
| 59 | return SoundManager.EMPTY_SOUND;
|
| 60 | }
|
| 61 | }
|
| 62 |
|
| 63 | public void addSound(final Weighted<Sound> sound) {
|
| 64 | this.list.add(sound);
|
| 65 | }
|
| 66 |
|
| 67 | public @Nullable Component getSubtitle() {
|
| 68 | return this.subtitle;
|
| 69 | }
|
| 70 |
|
| 71 | @Override
|
| 72 | public void preloadIfRequired(final SoundEngine soundEngine) {
|
| 73 | for (Weighted<Sound> weighted : this.list) {
|
| 74 | weighted.preloadIfRequired(soundEngine);
|
| 75 | }
|
| 76 | }
|
| 77 | }
|
| 78 |
|