diff --git a/src/main/java/ru/bclib/util/BonemealUtil.java b/src/main/java/ru/bclib/util/BonemealUtil.java new file mode 100644 index 00000000..18baa32e --- /dev/null +++ b/src/main/java/ru/bclib/util/BonemealUtil.java @@ -0,0 +1,60 @@ +package ru.bclib.util; + +import java.util.Map; +import java.util.Random; + +import com.google.common.collect.Maps; + +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.block.Block; + +public class BonemealUtil { + private static final Map>> GRASS_BIOMES = Maps.newHashMap(); + private static final Map> GRASS_TYPES = Maps.newHashMap(); + + public static void addBonemealGrass(Block terrain, Block plant) { + addBonemealGrass(terrain, plant, 1F); + } + + public static void addBonemealGrass(Block terrain, Block plant, float chance) { + WeightedList list = GRASS_TYPES.get(terrain); + if (list == null) { + list = new WeightedList(); + GRASS_TYPES.put(terrain, list); + } + list.add(plant, chance); + } + + public static void addBonemealGrass(ResourceLocation biome, Block terrain, Block plant) { + addBonemealGrass(biome, terrain, plant, 1F); + } + + public static void addBonemealGrass(ResourceLocation biome, Block terrain, Block plant, float chance) { + Map> map = GRASS_BIOMES.get(biome); + if (map == null) { + map = Maps.newHashMap(); + GRASS_BIOMES.put(biome, map); + } + WeightedList list = map.get(terrain); + if (list == null) { + list = new WeightedList(); + map.put(terrain, list); + } + list.add(plant, chance); + } + + public static Block getGrass(ResourceLocation biomeID, Block terrain, Random random) { + Map> map = GRASS_BIOMES.get(biomeID); + WeightedList list = null; + if (map != null) { + list = map.get(terrain); + if (list == null) { + list = GRASS_TYPES.get(terrain); + } + } + else { + list = GRASS_TYPES.get(terrain); + } + return list == null ? null : list.get(random); + } +} diff --git a/src/main/java/ru/bclib/util/WeightedList.java b/src/main/java/ru/bclib/util/WeightedList.java new file mode 100644 index 00000000..eeb856a9 --- /dev/null +++ b/src/main/java/ru/bclib/util/WeightedList.java @@ -0,0 +1,34 @@ +package ru.bclib.util; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class WeightedList { + private final List weights = new ArrayList(); + private final List values = new ArrayList(); + private float maxWeight; + + public void add(T value, float weight) { + maxWeight += weight; + weights.add(maxWeight); + values.add(value); + } + + public T get(Random random) { + if (maxWeight < 1) { + return null; + } + float weight = random.nextFloat() * maxWeight; + for (int i = 0; i < weights.size(); i++) { + if (weight <= weights.get(i)) { + return values.get(i); + } + } + return null; + } + + public boolean isEmpty() { + return maxWeight == 0; + } +}