Minecraft 1.21.5

Co-authored-by: Ven <[email protected]>
Co-authored-by: Jonathing <[email protected]>
This commit is contained in:
committed 2025-03-26 16:34:26 -07:00
1 parent 88904a1d09
commit d50a3b5ab7
548 files changed
+5432 -7867

No files matched your search

@@ -6,17 +6,17 @@
package net.minecraftforge.common;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import net.minecraft.util.RandomSource;
import net.minecraft.util.random.WeightedEntry;
import net.minecraft.util.random.WeightedRandom;
import net.minecraft.util.random.WeightedList;
import net.minecraft.world.entity.EntityType;
public class DungeonHooks
{
private static ArrayList<DungeonMob> dungeonMobs = new ArrayList<DungeonMob>();
public class DungeonHooks {
private static WeightedList<EntityType<?>> dungeonMobs = WeightedList.<EntityType<?>>builder()
.add(EntityType.SKELETON, 100)
.add(EntityType.ZOMBIE, 200)
.add(EntityType.SPIDER, 100)
.build();
/**
* Adds a mob to the possible list of creatures the spawner will create.
@@ -35,23 +35,20 @@ public class DungeonHooks
public static float addDungeonMob(EntityType<?> type, int rarity)
{
if (rarity <= 0)
{
throw new IllegalArgumentException("Rarity must be greater then zero");
}
Iterator<DungeonMob> itr = dungeonMobs.iterator();
while (itr.hasNext())
{
DungeonMob mob = itr.next();
if (type == mob.type)
{
var list = new ArrayList<>(dungeonMobs.unwrap());
var itr = list.iterator();
while (itr.hasNext()) {
var mob = itr.next();
if (type == mob.value()) {
itr.remove();
rarity = mob.getWeight().asInt() + rarity;
rarity = mob.weight() + rarity;
break;
}
}
dungeonMobs.add(new DungeonMob(rarity, type));
dungeonMobs = WeightedList.<EntityType<?>>builder().addAll(list).add(type, rarity).build();
return rarity;
}
@@ -61,16 +58,16 @@ public class DungeonHooks
* @param name The name of the mob to remove
* @return The rarity of the removed mob, prior to being removed.
*/
public static int removeDungeonMob(EntityType<?> name)
{
for (DungeonMob mob : dungeonMobs)
{
if (name == mob.type)
{
dungeonMobs.remove(mob);
return mob.getWeight().asInt();
}
public static int removeDungeonMob(EntityType<?> name) {
var list = new ArrayList<>(dungeonMobs.unwrap());
for (var mob : list) {
if (mob.value() != name) continue;
list.remove(mob);
dungeonMobs = WeightedList.<EntityType<?>>builder().addAll(list).build();
return mob.weight();
}
return 0;
}
@@ -79,33 +76,7 @@ public class DungeonHooks
* @param rand World generation random number generator
* @return The mob name
*/
public static EntityType<?> getRandomDungeonMob(RandomSource rand)
{
DungeonMob mob = WeightedRandom.getRandomItem(rand, dungeonMobs).orElseThrow();
return mob.type;
}
public static class DungeonMob extends WeightedEntry.IntrusiveBase
{
public final EntityType<?> type;
public DungeonMob(int weight, EntityType<?> type)
{
super(weight);
this.type = type;
}
@Override
public boolean equals(Object target)
{
return target instanceof DungeonMob && type.equals(((DungeonMob)target).type);
}
}
static
{
addDungeonMob(EntityType.SKELETON, 100);
addDungeonMob(EntityType.ZOMBIE, 200);
addDungeonMob(EntityType.SPIDER, 100);
public static EntityType<?> getRandomDungeonMob(RandomSource rand) {
return dungeonMobs.getRandomOrThrow(rand);
}
}
@@ -94,8 +94,6 @@ public class ForgeConfig {
* Client specific configuration - only loaded clientside from forge-client.toml
*/
public static class Client {
public final BooleanValue experimentalForgeLightPipelineEnabled;
public final BooleanValue showLoadWarnings;
public final BooleanValue allowMipmapLowering;
@@ -104,11 +102,6 @@ public class ForgeConfig {
builder.comment("Client only settings, mostly things related to rendering")
.push("client");
experimentalForgeLightPipelineEnabled = builder
.comment("EXPERIMENTAL: Enable the Forge block rendering pipeline - fixes the lighting of custom models.")
.translation("forge.configgui.forgeLightPipelineEnabled")
.define("experimentalForgeLightPipelineEnabled", false);
showLoadWarnings = builder
.comment("When enabled, Forge will show any warnings that occurred during loading.")
.translation("forge.configgui.showLoadWarnings")
@@ -10,7 +10,6 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
@@ -675,6 +674,7 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfi
public void clearComment() { comment.clear(); }
public boolean hasComment() { return !this.comment.isEmpty(); }
@SuppressWarnings("unused")
public String buildComment() { return buildComment(List.of("unknown", "unknown")); }
public String buildComment(final List<String> path) {
if (comment.stream().allMatch(String::isBlank)) {
@@ -356,10 +356,12 @@ public final class ForgeHooks {
lastEnd = end;
String url = string.substring(start, end);
MutableComponent link = Component.literal(url);
URI uri = null;
try {
// Add schema so client doesn't crash.
if ((new URI(url)).getScheme() == null) {
uri = new URI(url);
if (uri.getScheme() == null) {
if (!allowMissingHeader) {
if (ichat == null)
ichat = Component.literal(url);
@@ -368,6 +370,7 @@ public final class ForgeHooks {
continue;
}
url = "http://" + url;
uri = new URI(url);
}
} catch (URISyntaxException e) {
// Bad syntax bail out!
@@ -377,7 +380,7 @@ public final class ForgeHooks {
}
// Set the click event and append the link.
ClickEvent click = new ClickEvent(ClickEvent.Action.OPEN_URL, url);
ClickEvent click = new ClickEvent.OpenUrl(uri);
link.setStyle(link.getStyle().withClickEvent(click).withUnderlined(true).withColor(TextColor.fromLegacyFormat(ChatFormatting.BLUE)));
if (ichat == null)
ichat = Component.literal("");
@@ -406,7 +409,7 @@ public final class ForgeHooks {
// Logic from tryHarvestBlock for pre-canceling the event
boolean preCancelEvent = false;
ItemStack itemstack = entityPlayer.getMainHandItem();
if (!itemstack.isEmpty() && !itemstack.getItem().canAttackBlock(level.getBlockState(pos), level, pos, entityPlayer)) {
if (!itemstack.isEmpty() && !itemstack.canDestroyBlock(level.getBlockState(pos), level, pos, entityPlayer)) {
preCancelEvent = true;
}
@@ -693,7 +696,7 @@ public final class ForgeHooks {
return modId;
}
public static boolean onFarmlandTrample(ServerLevel level, BlockPos pos, BlockState state, float fallDistance, Entity entity) {
public static boolean onFarmlandTrample(ServerLevel level, BlockPos pos, BlockState state, double fallDistance, Entity entity) {
if (entity.canTrample(level, state, pos, fallDistance))
return !ForgeEventFactory.fireFarmlandTrampleEvent(level, pos, state, fallDistance, entity);
return false;
@@ -742,7 +745,7 @@ public final class ForgeHooks {
*
* <p>All loot-table generated loot should be passed to this function.</p>
*
* @param lootTableId The ID of the loot table currently being queried
* @param table The loot table currently being queried
* @param generatedLoot The loot generated by the loot table
* @param context The loot context that generated the loot, unmodified
* @return The modified list of drops
@@ -816,27 +819,27 @@ public final class ForgeHooks {
CompoundTag tag = null;
try {
CompoundTag rootTag = access.getDataTagRaw(false);
tag = rootTag.getCompound("fml");
tag = rootTag.getCompoundOrEmpty("fml");
} catch (IOException e) {
try {
CompoundTag rootTag = access.getDataTagRaw(true);
tag = rootTag.getCompound("fml");
tag = rootTag.getCompoundOrEmpty("fml");
} catch (IOException e2) {
LOGGER.error(WORLDPERSISTENCE, "Failed to read level data.. ", e2);
return;
}
}
if (tag.contains("LoadingModList")) {
ListTag modList = tag.getList("LoadingModList", net.minecraft.nbt.Tag.TAG_COMPOUND);
ListTag modList = tag.getListOrEmpty("LoadingModList");
Map<String, ArtifactVersion> mismatchedVersions = new HashMap<>(modList.size());
Map<String, ArtifactVersion> missingVersions = new HashMap<>(modList.size());
for (int i = 0; i < modList.size(); i++) {
CompoundTag mod = modList.getCompound(i);
String modId = mod.getString("ModId");
CompoundTag mod = modList.getCompoundOrEmpty(i);
String modId = mod.getStringOr("ModId", null);
if (Objects.equals("minecraft", modId))
continue;
String modVersion = mod.getString("ModVersion");
String modVersion = mod.getStringOr("ModVersion", null);
final var previousVersion = new DefaultArtifactVersion(modVersion);
ModList.get().getModContainerById(modId).ifPresentOrElse(container -> {
final var loadingVersion = container.getModInfo().getVersion();
@@ -899,9 +902,9 @@ public final class ForgeHooks {
if (tag.contains("Registries")) {
Map<ResourceLocation, ForgeRegistry.Snapshot> snapshot = new HashMap<>();
CompoundTag regs = tag.getCompound("Registries");
for (String key : regs.getAllKeys())
snapshot.put(ResourceLocation.parse(key), ForgeRegistry.Snapshot.read(regs.getCompound(key)));
CompoundTag regs = tag.getCompoundOrEmpty("Registries");
for (String key : regs.keySet())
snapshot.put(ResourceLocation.parse(key), ForgeRegistry.Snapshot.read(regs.getCompoundOrEmpty(key)));
failedElements = GameData.injectSnapshot(snapshot, true, true);
}
@@ -993,7 +996,7 @@ public final class ForgeHooks {
/**
* Handles living entities being under water. This fires the {@link LivingBreatheEvent} and if the entity's air supply
* is less than or equal to zero also the {@link LivingDrownEvent}. Additionally when the entity is under water it will
* dismount if {@link IForgeEntity#canBeRiddenUnderFluidType(FluidType, Entity)} returns false.
* dismount if {@link net.minecraftforge.common.extensions.IForgeEntity#canBeRiddenUnderFluidType(FluidType, Entity)} returns false.
*
* @param entity The living entity which is currently updated
* @param consumeAirAmount The amount of air to consume when the entity is unable to breathe
@@ -8,6 +8,7 @@ package net.minecraftforge.common;
import com.google.common.collect.Sets;
import net.minecraftforge.common.extensions.IForgeBlock;
import net.minecraftforge.common.extensions.IForgeItem;
import org.jetbrains.annotations.ApiStatus;
import java.util.Set;
import java.util.stream.Collectors;
@@ -97,7 +98,10 @@ public class ToolActions
/**
* A tool action corresponding to the 'block' action of shields.
*
* @deprecated Completely overshadowed by {@link net.minecraft.core.component.DataComponents#BLOCKS_ATTACKS}
*/
@Deprecated(forRemoval = true, since = "1.21.5")
public static final ToolAction SHIELD_BLOCK = ToolAction.get("shield_block");
/**
@@ -109,9 +113,15 @@ public class ToolActions
public static final Set<ToolAction> DEFAULT_AXE_ACTIONS = of(AXE_DIG, AXE_STRIP, AXE_SCRAPE, AXE_WAX_OFF);
public static final Set<ToolAction> DEFAULT_HOE_ACTIONS = of(HOE_DIG, HOE_TILL);
public static final Set<ToolAction> DEFAULT_SHOVEL_ACTIONS = of(SHOVEL_DIG, SHOVEL_FLATTEN);
/** @deprecated See {@link #PICKAXE_DIG} for details */
@Deprecated(forRemoval = true, since = "1.21.5")
public static final Set<ToolAction> DEFAULT_PICKAXE_ACTIONS = of(PICKAXE_DIG);
/** @deprecated See {@link #SWORD_DIG} and {@link #SWORD_SWEEP} for details */
@Deprecated(forRemoval = true, since = "1.21.5")
public static final Set<ToolAction> DEFAULT_SWORD_ACTIONS = of(SWORD_DIG, SWORD_SWEEP);
public static final Set<ToolAction> DEFAULT_SHEARS_ACTIONS = of(SHEARS_DIG, SHEARS_HARVEST, SHEARS_CARVE, SHEARS_DISARM);
/** @deprecated See {@link #SHIELD_BLOCK} for details */
@Deprecated(forRemoval = true, since = "1.21.5")
public static final Set<ToolAction> DEFAULT_SHIELD_ACTIONS = of(SHIELD_BLOCK);
public static final Set<ToolAction> DEFAULT_FISHING_ROD_ACTIONS = of(FISHING_ROD_CAST);
@@ -5,6 +5,7 @@
package net.minecraftforge.common;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
@@ -12,6 +13,7 @@ import java.util.Map;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.entity.npc.VillagerProfession;
import net.minecraft.world.entity.npc.VillagerTrades;
import net.minecraft.world.entity.npc.VillagerTrades.ItemListing;
@@ -20,15 +22,13 @@ import net.minecraftforge.event.village.VillagerTradesEvent;
import net.minecraftforge.event.village.WandererTradesEvent;
import net.minecraftforge.event.server.ServerAboutToStartEvent;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.commons.lang3.tuple.Pair;
public class VillagerTradingManager
{
public class VillagerTradingManager {
private static final Map<ResourceKey<VillagerProfession>, Int2ObjectMap<ItemListing[]>> VANILLA_TRADES = new HashMap<>();
private static final List<Pair<ItemListing[], Integer>> WANDERER_TRADES = new ArrayList<>();
private static final Map<VillagerProfession, Int2ObjectMap<ItemListing[]>> VANILLA_TRADES = new HashMap<>();
private static final Int2ObjectMap<ItemListing[]> WANDERER_TRADES = new Int2ObjectOpenHashMap<>();
static
{
static {
VillagerTrades.TRADES.forEach((key, value) -> {
Int2ObjectMap<ItemListing[]> copy = new Int2ObjectOpenHashMap<>();
for (var ent : value.int2ObjectEntrySet()) {
@@ -36,50 +36,40 @@ public class VillagerTradingManager
}
VANILLA_TRADES.put(key, copy);
});
VillagerTrades.WANDERING_TRADER_TRADES.int2ObjectEntrySet().forEach(e -> WANDERER_TRADES.put(e.getIntKey(), Arrays.copyOf(e.getValue(), e.getValue().length)));
WANDERER_TRADES.addAll(VillagerTrades.WANDERING_TRADER_TRADES);
}
static void loadTrades(ServerAboutToStartEvent e)
{
static void loadTrades(ServerAboutToStartEvent e) {
postWandererEvent();
postVillagerEvents();
}
/**
* Posts the WandererTradesEvent.
*/
private static void postWandererEvent()
{
List<ItemListing> generic = NonNullList.create();
List<ItemListing> rare = NonNullList.create();
Arrays.stream(WANDERER_TRADES.get(1)).forEach(generic::add);
Arrays.stream(WANDERER_TRADES.get(2)).forEach(rare::add);
MinecraftForge.EVENT_BUS.post(new WandererTradesEvent(generic, rare));
VillagerTrades.WANDERING_TRADER_TRADES.put(1, generic.toArray(new ItemListing[0]));
VillagerTrades.WANDERING_TRADER_TRADES.put(2, rare.toArray(new ItemListing[0]));
/** Posts the WandererTradesEvent. */
private static void postWandererEvent() {
var event = MinecraftForge.EVENT_BUS.fire(new WandererTradesEvent(WANDERER_TRADES));
VillagerTrades.WANDERING_TRADER_TRADES.clear();
for (var pool : event.getPools())
VillagerTrades.WANDERING_TRADER_TRADES.add(Pair.of(pool.getEntries().toArray(ItemListing[]::new), pool.getRolls()));
}
/**
* Posts a VillagerTradesEvent for each registered profession.
*/
private static void postVillagerEvents()
{
for (VillagerProfession prof : ForgeRegistries.VILLAGER_PROFESSIONS)
{
/** Posts a VillagerTradesEvent for each registered profession. */
private static void postVillagerEvents() {
// TODO [VillagerType][1.21.5] Villager Professions are stored as keys in vanilla now? Re-evaluate this.
for (VillagerProfession value : ForgeRegistries.VILLAGER_PROFESSIONS) {
var prof = ForgeRegistries.VILLAGER_PROFESSIONS.getResourceKey(value).orElseThrow();
Int2ObjectMap<ItemListing[]> trades = VANILLA_TRADES.getOrDefault(prof, new Int2ObjectOpenHashMap<>());
Int2ObjectMap<List<ItemListing>> mutableTrades = new Int2ObjectOpenHashMap<>();
for (int i = 1; i < 6; i++)
{
mutableTrades.put(i, NonNullList.create());
}
for (var entry : trades.int2ObjectEntrySet()) {
for (var entry : trades.int2ObjectEntrySet())
Arrays.stream(entry.getValue()).forEach(mutableTrades.get(entry.getIntKey())::add);
}
MinecraftForge.EVENT_BUS.post(new VillagerTradesEvent(mutableTrades, prof));
Int2ObjectMap<ItemListing[]> newTrades = new Int2ObjectOpenHashMap<>();
for (var entry : mutableTrades.int2ObjectEntrySet()) {
for (var entry : mutableTrades.int2ObjectEntrySet())
newTrades.put(entry.getIntKey(), entry.getValue().toArray(new ItemListing[0]));
}
VillagerTrades.TRADES.put(prof, newTrades);
}
}
@@ -5,6 +5,7 @@
package net.minecraftforge.common.brewing;
/*
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -12,7 +13,6 @@ import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.core.NonNullList;
/*
public class BrewingRecipeRegistry {
/**
@@ -11,10 +11,8 @@ import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.commands.arguments.selector.EntitySelector;
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Allows modders to register custom entity selectors by assigning an {@link IEntitySelectorType} to a String token. <br>
@@ -9,14 +9,12 @@ import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.serialization.JsonOps;
import net.minecraft.advancements.Advancement;
import net.minecraft.advancements.AdvancementHolder;
import net.minecraft.core.HolderLookup;
import net.minecraft.resources.RegistryOps;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.common.crafting.conditions.ICondition;
@@ -92,7 +92,7 @@ public class PartialNBTIngredient extends AbstractIngredient {
public static final MapCodec<PartialNBTIngredient> CODEC = RecordCodecBuilder.mapCodec(builder ->
builder.group(
Ingredient.NON_AIR_HOLDER_SET_CODEC.fieldOf("items").forGetter(i -> i.values),
TagParser.AS_CODEC.fieldOf("nbt").forGetter(i -> i.nbt)
TagParser.FLATTENED_CODEC.fieldOf("nbt").forGetter(i -> i.nbt)
).apply(builder, PartialNBTIngredient::new)
);
@@ -8,9 +8,7 @@ package net.minecraftforge.common.data;
import net.minecraft.core.HolderLookup;
import net.minecraft.data.PackOutput;
import net.minecraft.data.tags.FluidTagsProvider;
import net.minecraft.data.tags.IntrinsicHolderTagsProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.BlockTags;
import net.minecraft.tags.FluidTags;
import net.minecraft.tags.TagKey;
import net.minecraft.world.level.material.Fluid;
@@ -18,8 +16,6 @@ import net.minecraftforge.common.ForgeMod;
import org.jetbrains.annotations.ApiStatus;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import static net.minecraftforge.common.Tags.Fluids.*;
@ApiStatus.Internal
@@ -587,8 +587,11 @@ public interface IForgeBlock {
* @param pos Block position in level
* @param direction The direction that the fire is coming from
* @param igniter The entity that lit the fire
* @return {@code true} if the block <strong>SHOULD BE REMOVED</strong>
*/
default void onCaughtFire(BlockState state, Level level, BlockPos pos, @Nullable Direction direction, @Nullable LivingEntity igniter) {}
default boolean onCaughtFire(BlockState state, Level level, BlockPos pos, @Nullable Direction direction, @Nullable LivingEntity igniter) {
return false;
}
/**
* Called when fire is updating on a neighbor block.
@@ -5,7 +5,6 @@
package net.minecraftforge.common.extensions;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
import net.minecraft.world.entity.player.Player;
@@ -31,19 +30,16 @@ public interface IForgeBlockEntity extends ICapabilityProvider {
}
/**
* Called when you receive a TileEntityData packet for the location this
* TileEntity is currently in. On the client, the NetworkManager will always
* be the remote server. On the server, it will be whomever is responsible for
* Called when you receive a TileEntityData packet for the location this TileEntity is currently in. On the client,
* the NetworkManager will always be the remote server. On the server, it will be whomever is responsible for
* sending the packet.
*
* @param net The NetworkManager the packet originated from
* @param pkt The data packet
* @param connection The Connection the packet originated from
* @param pkt The data packet
* @param lookup The holder lookup provider
*/
default void onDataPacket(Connection connection, ClientboundBlockEntityDataPacket pkt, HolderLookup.Provider lookup) {
CompoundTag compoundtag = pkt.getTag();
if (compoundtag != null) {
self().loadWithComponents(compoundtag, lookup);
}
this.self().loadWithComponents(pkt.getTag(), lookup);
}
/**
@@ -460,9 +460,10 @@ public interface IForgeBlockState {
* @param pos Block position in level
* @param face The face that the fire is coming from
* @param igniter The entity that lit the fire
* @return {@code true} if the block <strong>SHOULD BE REMOVED</strong>
*/
default void onCaughtFire(Level level, BlockPos pos, @Nullable Direction face, @Nullable LivingEntity igniter) {
self().getBlock().onCaughtFire(self(), level, pos, face, igniter);
default boolean onCaughtFire(Level level, BlockPos pos, @Nullable Direction face, @Nullable LivingEntity igniter) {
return self().getBlock().onCaughtFire(self(), level, pos, face, igniter);
}
/**
@@ -98,7 +98,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag> {
* @param fallDistance The fall distance
* @return {@code true} if this entity can trample, {@code false} otherwise
*/
boolean canTrample(ServerLevel level, BlockState state, BlockPos pos, float fallDistance);
boolean canTrample(ServerLevel level, BlockState state, BlockPos pos, double fallDistance);
/**
* Returns The classification of this entity
@@ -9,6 +9,7 @@ import java.util.Arrays;
import java.util.Objects;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import net.minecraft.core.Registry;
@@ -49,6 +50,12 @@ public interface IForgeGameTestHelper {
return (GameTestHelper) this;
}
int getTickAsInt();
default GameTestAssertException throwing(String message) {
return new GameTestAssertException(Component.literal(message), this.getTickAsInt());
}
default void say(String message) {
this.say(message, Style.EMPTY);
}
@@ -73,14 +80,22 @@ public interface IForgeGameTestHelper {
return ForgeI18n.getPattern(message) != null ? Component.translatable(message) : Component.literal(message);
}
default void assertTrue(boolean value, String message) {
this.assertTrue(value, () -> message);
}
default void assertTrue(boolean value, Supplier<String> message) {
if (!value)
throw new GameTestAssertException(message.get());
throw new GameTestAssertException(Component.literal(message.get()), this.getTickAsInt());
}
default void assertFalse(boolean value, String message) {
this.assertFalse(value, () -> message);
}
default void assertFalse(boolean value, Supplier<String> message) {
if (value)
throw new GameTestAssertException(message.get());
throw new GameTestAssertException(Component.literal(message.get()), this.getTickAsInt());
}
default <N> void assertValueEqual(N expected, N actual, String name, String message) {
@@ -89,7 +104,7 @@ public interface IForgeGameTestHelper {
default <N> void assertValueEqual(N expected, N actual, String name, Supplier<String> message) {
if (!Objects.equals(expected, actual))
throw new GameTestAssertException("%s -- Expected %s to be %s, but was %s".formatted(message.get(), name, expected, actual));
throw this.throwing("%s -- Expected %s to be %s, but was %s".formatted(message.get(), name, expected, actual));
}
default <N> void assertValueEqual(N[] expected, N[] actual, String name, String message) {
@@ -98,7 +113,7 @@ public interface IForgeGameTestHelper {
default <N> void assertValueEqual(N[] expected, N[] actual, String name, Supplier<String> message) {
if (!Objects.deepEquals(expected, actual))
throw new GameTestAssertException("%s -- Expected %s to be %s, but was %s".formatted(message.get(), name, Arrays.toString(expected), Arrays.toString(actual)));
throw this.throwing("%s -- Expected %s to be %s, but was %s".formatted(message.get(), name, Arrays.toString(expected), Arrays.toString(actual)));
}
default <N> void assertValueNotEqual(N expected, N actual, String name, String message) {
@@ -107,7 +122,7 @@ public interface IForgeGameTestHelper {
default <N> void assertValueNotEqual(N expected, N actual, String name, Supplier<String> message) {
if (Objects.equals(expected, actual))
throw new GameTestAssertException("%s -- Expected %s to NOT be %s, but was".formatted(message.get(), name, expected));
throw this.throwing("%s -- Expected %s to NOT be %s, but was".formatted(message.get(), name, expected));
}
default <N> void assertValueNotEqual(N[] expected, N[] actual, String name, String message) {
@@ -116,7 +131,7 @@ public interface IForgeGameTestHelper {
default <N> void assertValueNotEqual(N[] expected, N[] actual, String name, Supplier<String> message) {
if (!Objects.deepEquals(expected, actual))
throw new GameTestAssertException("%s -- Expected %s to NOT be %s, but was".formatted(message.get(), name, Arrays.toString(expected)));
throw this.throwing("%s -- Expected %s to NOT be %s, but was".formatted(message.get(), name, Arrays.toString(expected)));
}
default <E> Registry<E> registryLookup(ResourceKey<? extends Registry<? extends E>> registryKey) {
@@ -145,7 +160,7 @@ public interface IForgeGameTestHelper {
var server = level.getServer();
var listener = new ServerGamePacketListenerImpl(server, connection, player, cookie);
var info = GameProtocols.SERVERBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(server.registryAccess()));
var info = GameProtocols.SERVERBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(server.registryAccess()), listener);
connection.setupInboundProtocol(info, listener);
return player;
}
@@ -258,13 +273,26 @@ public interface IForgeGameTestHelper {
return new BoolFlag(name);
}
default void fail(String message) {
self().fail(Component.literal(message));
}
public static class Flag<T> {
private final String name;
@Nullable
protected T value = null;
private final Function<String, ? extends RuntimeException> thrower;
protected @Nullable T value = null;
public Flag(String name) {
this(name, RuntimeException::new);
}
public Flag(String name, Function<String, ? extends RuntimeException> thrower) {
this.name = name;
this.thrower = thrower;
}
protected final RuntimeException throwing(String message) {
return this.thrower.apply(message);
}
public void set(T value) {
@@ -287,7 +315,7 @@ public interface IForgeGameTestHelper {
public void assertUnset(Supplier<String> message) {
if (this.value != null) {
String s = message != null ? message.get() + " -- " : "";
throw new GameTestAssertException(s + "Expected " + name + " to be null, but was " + this.value);
throw this.throwing(s + "Expected " + name + " to be null, but was " + this.value);
}
}
@@ -302,7 +330,7 @@ public interface IForgeGameTestHelper {
public void assertSet(Supplier<String> message) {
if (this.value == null) {
String s = message != null ? message.get() + " -- " : "";
throw new GameTestAssertException(s + "Flag " + name + " was never set");
throw this.throwing(s + "Flag " + name + " was never set");
}
}
@@ -318,7 +346,7 @@ public interface IForgeGameTestHelper {
assertSet(message);
if (expected != null && !expected.equals(this.value)) {
String s = message != null ? message.get() + " -- " : "";
throw new GameTestAssertException(s + "Expected " + name + " to be " + expected + ", but was " + this.value);
throw this.throwing(s + "Expected " + name + " to be " + expected + ", but was " + this.value);
}
}
}
@@ -228,18 +228,11 @@ public interface IForgeItem {
}
/**
* Called to tick this items in a players inventory, the indexes are the global slot index.
* Called to tick this items in a entitie's inventory, the slotIndex may be -1 for non player entities as they may not have a slot index.
* See {@link EntityEquipment#tick(Entity)}
*/
default void onInventoryTick(ItemStack stack, Level level, Player player, int slotIndex, int selectedIndex) {
// For compatibility reasons we have to use non-local index values, I think this is a vanilla bug but lets maintain compatibility
var inv = player.getInventory();
int vanillaIndex = slotIndex;
if (slotIndex >= inv.items.size()) {
vanillaIndex -= inv.items.size();
if (vanillaIndex >= inv.armor.size())
vanillaIndex -= inv.armor.size();
}
stack.inventoryTick(level, player, vanillaIndex, selectedIndex == vanillaIndex);
default void inventoryTick(ItemStack stack, Level level, Entity entity, @Nullable EquipmentSlot slot, int slotIndex) {
stack.inventoryTick(level, entity, slot);
}
/**
@@ -460,9 +453,11 @@ public interface IForgeItem {
* @param entity The LivingEntity holding the shield
* @param attacker The LivingEntity holding the ItemStack
* @return True if this ItemStack can disable the shield in question.
* @deprecated Overriding this does nothing! Use {@link net.minecraft.core.component.DataComponents#WEAPON}.
*/
@Deprecated(forRemoval = true, since = "1.21.5")
default boolean canDisableShield(ItemStack stack, ItemStack shield, LivingEntity entity, LivingEntity attacker) {
return attacker.canDisableShield();
return attacker.getSecondsToDisableBlocking() > 0.0F;
}
/**
@@ -223,13 +223,13 @@ public interface IForgeItemStack {
}
/**
* Called to tick this items in a players inventory, the indexes are the global slot index.
* Called to tick this items in a entitie's inventory, the slotIndex may be -1 for non player entities as they may not have a slot index.
* See {@link EntityEquipment#tick(Entity)}
*/
default void onInventoryTick(Level level, Player player, int slotIndex, int selectedIndex) {
self().getItem().onInventoryTick(self(), level, player, slotIndex, selectedIndex);
default void inventoryTick(Level level, Entity entity, @Nullable EquipmentSlot slot, int slotIndex) {
self().getItem().inventoryTick(self(), level, entity, slot, slotIndex);
}
/**
* Called every tick from {@code Horse#playGallopSound(SoundEvent)} on the item in the
* armor slot.
@@ -91,7 +91,7 @@ public interface IForgeTransformation {
Transformation transform = self();
if (transform.isIdentity()) return Transformation.identity();
Matrix4f ret = transform.getMatrix();
Matrix4f ret = transform.getMatrixCopy();
Matrix4f tmp = new Matrix4f().translation(origin.x(), origin.y(), origin.z());
tmp.mul(ret, ret);
tmp.translation(-origin.x(), -origin.y(), -origin.z());
@@ -0,0 +1,89 @@
package net.minecraftforge.common.extensions;
import net.minecraft.util.random.Weighted;
import net.minecraft.util.random.WeightedList;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.function.Predicate;
public interface IForgeWeightedList<E> {
private WeightedList<E> self() {
return (WeightedList<E>) this;
}
/**
* Removes any existing elements from this list. If removal takes place, this will create a new list.
* <p>To check if the builder elements have changed, simply check if the old and new lists are equal.</p>
* {@snippet :
* private static void test() {
* var list = WeightedList.<String>builder().add("Hello, World!", 1).build();
*
* // if builder has no removals
* assert list == list.removeIf(String::isEmpty);
*
* // if builder has removals
* assert list != list.removeIf(s -> s.equals("Hello, World!"));
* }
*}
*
* @param predicate The predicate to remove elements with
* @return The builder
* @apiNote This is an <strong>expensive operation</strong> and primarily exists to help port legacy systems that
* used older list-based systems from 1.21.4 and older.
* @see java.util.List#removeIf(Predicate)
*/
default WeightedList<E> removeIf(Predicate<E> predicate) {
var list = new ArrayList<>(this.self().unwrap());
return list.removeIf(w -> predicate.test(w.value()))
? WeightedList.<E>builder().addAll(list).build()
: this.self();
}
interface Builder<E> {
private WeightedList.Builder<E> self() {
return (WeightedList.Builder<E>) this;
}
/** @see com.google.common.collect.ImmutableList.Builder#addAll(Iterable) */
default WeightedList.Builder<E> addAll(Iterable<Weighted<E>> iterable) {
for (var w : iterable) this.self().add(w.value(), w.weight());
return this.self();
}
/** @see com.google.common.collect.ImmutableList.Builder#addAll(Iterator) */
default WeightedList.Builder<E> addAll(Iterator<Weighted<E>> iterator) {
return this.addAll(() -> iterator);
}
/**
* Removes any existing elements from the builder. If removal takes place, this will create a new builder.
* <p>To check if the builder elements have changed, simply check if the old and new builders are equal.</p>
* {@snippet :
* private static void test() {
* var builder = WeightedList.<String>builder();
* builder.add("Hello, World!", 1);
*
* // if builder has no removals
* assert builder == builder.removeIf(String::isEmpty);
*
* // if builder has removals
* assert builder != builder.removeIf(s -> s.equals("Hello, World!"));
* }
*}
*
* @param predicate The predicate to remove elements with
* @return The builder
* @apiNote This is an <strong>expensive operation</strong> and primarily exists to help port legacy systems
* that used the older arraylist-based building from 1.21.4 and older.
* @see IForgeWeightedList#removeIf(Predicate)
* @see java.util.List#removeIf(Predicate)
*/
default WeightedList.Builder<E> removeIf(Predicate<E> predicate) {
var list = new ArrayList<>(this.self().build().unwrap());
return list.removeIf(w -> predicate.test(w.value()))
? WeightedList.<E>builder().addAll(list)
: this.self();
}
}
}
@@ -8,7 +8,9 @@ package net.minecraftforge.common.util;
import java.util.List;
import java.util.UUID;
import net.minecraft.core.UUIDUtil;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.nbt.Tag;
public interface INBTBuilder {
@@ -63,9 +65,14 @@ public interface INBTBuilder {
return this;
}
/** @deprecated Use {@link #putByteArray(String, byte...)} */
@Deprecated(forRemoval = true, since = "1.21.5")
public Builder putByteArray(String key, List<Byte> value) {
tag.putByteArray(key, value);
return this;
var array = new byte[value.size()];
for (var i = 0; i < value.size(); i++)
array[i] = value.get(i);
return this.putByteArray(key, array);
}
public Builder putIntArray(String key, int... value) {
@@ -73,9 +80,14 @@ public interface INBTBuilder {
return this;
}
/** @deprecated Use {@link #putIntArray(String, int...)} */
@Deprecated(forRemoval = true, since = "1.21.5")
public Builder putIntArray(String key, List<Integer> value) {
tag.putIntArray(key, value);
return this;
var array = new int[value.size()];
for (var i = 0; i < value.size(); i++)
array[i] = value.get(i);
return this.putIntArray(key, array);
}
public Builder putLongArray(String key, long... value) {
@@ -83,9 +95,14 @@ public interface INBTBuilder {
return this;
}
/** @deprecated Use {@link #putLongArray(String, long...)} */
@Deprecated(forRemoval = true, since = "1.21.5")
public Builder putLongArray(String key, List<Long> value) {
tag.putLongArray(key, value);
return this;
var array = new long[value.size()];
for (var i = 0; i < value.size(); i++)
array[i] = value.get(i);
return this.putLongArray(key, array);
}
public Builder put(String key, boolean value) {
@@ -99,7 +116,7 @@ public interface INBTBuilder {
}
public Builder put(String key, UUID value) {
tag.putUUID(key, value);
tag.putIntArray(key, UUIDUtil.uuidToIntArray(value));
return this;
}
}
@@ -24,20 +24,19 @@ import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.serialization.JsonOps;
import net.minecraft.nbt.TagParser;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.util.GsonHelper;
import org.jetbrains.annotations.Nullable;
public class JsonUtils
{
public class JsonUtils {
// http://stackoverflow.com/questions/7706772/deserializing-immutablelist-using-gson/21677349#21677349
public enum ImmutableListTypeAdapter implements JsonDeserializer<ImmutableList<?>>, JsonSerializer<ImmutableList<?>>
{
public enum ImmutableListTypeAdapter implements JsonDeserializer<ImmutableList<?>>, JsonSerializer<ImmutableList<?>> {
INSTANCE;
@Override
public ImmutableList<?> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException
{
public ImmutableList<?> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
final Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments();
final Type parametrizedType = listOf(typeArguments[0]).getType();
final List<?> list = context.deserialize(json, parametrizedType);
@@ -45,8 +44,7 @@ public class JsonUtils
}
@Override
public JsonElement serialize(ImmutableList<?> src, Type type, JsonSerializationContext context)
{
public JsonElement serialize(ImmutableList<?> src, Type type, JsonSerializationContext context) {
final Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments();
final Type parametrizedType = listOf(typeArguments[0]).getType();
return context.serialize(src, parametrizedType);
@@ -54,18 +52,15 @@ public class JsonUtils
}
@SuppressWarnings({ "serial", "unchecked" })
private static <E> TypeToken<List<E>> listOf(final Type arg)
{
private static <E> TypeToken<List<E>> listOf(final Type arg) {
return new TypeToken<List<E>>() {}.where(new TypeParameter<E>() {}, (TypeToken<E>) TypeToken.of(arg));
}
public enum ImmutableMapTypeAdapter implements JsonDeserializer<ImmutableMap<String, ?>>, JsonSerializer<ImmutableMap<String, ?>>
{
public enum ImmutableMapTypeAdapter implements JsonDeserializer<ImmutableMap<String, ?>>, JsonSerializer<ImmutableMap<String, ?>> {
INSTANCE;
@Override
public ImmutableMap<String, ?> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException
{
public ImmutableMap<String, ?> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
final Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments();
final Type parameterizedType = mapOf(typeArguments[1]).getType();
final Map<String, ?> map = context.deserialize(json, parameterizedType);
@@ -73,8 +68,7 @@ public class JsonUtils
}
@Override
public JsonElement serialize(ImmutableMap<String, ?> src, Type type, JsonSerializationContext context)
{
public JsonElement serialize(ImmutableMap<String, ?> src, Type type, JsonSerializationContext context) {
final Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments();
final Type parameterizedType = mapOf(typeArguments[1]).getType();
return context.serialize(src, parameterizedType);
@@ -82,20 +76,14 @@ public class JsonUtils
}
@Nullable
public static CompoundTag readNBT(JsonObject json, String key)
{
if (net.minecraft.util.GsonHelper.isValidNode(json, key))
{
try
{
return TagParser.parseTag(net.minecraft.util.GsonHelper.getAsString(json, key));
} catch (CommandSyntaxException e)
{
throw new JsonSyntaxException("Malformed NBT tag", e);
}
} else
{
public static CompoundTag readNBT(JsonObject json, String key) {
if (!net.minecraft.util.GsonHelper.isValidNode(json, key))
return null;
try {
return TagParser.parseCompoundFully(GsonHelper.getAsString(json, key));
} catch (CommandSyntaxException e) {
throw new JsonSyntaxException("Malformed NBT tag", e);
}
}
@@ -0,0 +1,105 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.util;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.function.Function;
/**
* Proxy object for a value that is calculated on first access
* @param <T> The type of the value
*/
public sealed interface LazyFunction<T, R> extends Function<T, R> permits LazyFunction.Fast, LazyFunction.Concurrent {
/**
* Constructs a lazy-initialized object
* @param function The function for the value, to be called the first time the value is needed.
*/
static <T, R> LazyFunction<T, R> of(@NotNull Function<T, R> function) {
return new LazyFunction.Fast<>(function);
}
/**
* Constructs a thread-safe lazy-initialized object
* @param function The function for the value, to be called the first time the value is needed.
*/
static <T, R> LazyFunction<T, R> concurrentOf(@NotNull Function<T, R> function) {
return new LazyFunction.Concurrent<>(function);
}
R get() throws IllegalStateException;
/** Non-thread-safe implementation. */
final class Fast<T, R> implements LazyFunction<T, R> {
private Function<T, R> function;
private R instance;
private Fast(Function<T, R> function) {
this.function = function;
}
@Override
public @Nullable R apply(T t) {
if (function != null) {
instance = function.apply(t);
function = null;
}
return instance;
}
@Override
public R get() throws IllegalStateException {
if (function != null)
throw new IllegalStateException("Cannot call get() before apply()");
return instance;
}
}
/** Thread-safe implementation. */
final class Concurrent<T, R> implements LazyFunction<T, R> {
private volatile Object lock = new Object();
private volatile Function<T, R> function;
private volatile R instance;
private Concurrent(Function<T, R> function)
{
this.function = function;
}
@Override
public @Nullable R apply(T t) {
// Copy the lock to a local variable to prevent NPEs if the lock field is set to null between the
// null-check and the synchronization
Object localLock = this.lock;
if (function != null)
{
// localLock is not null here because supplier was non-null after we copied the lock and both of them
// are volatile
synchronized (localLock)
{
if (function != null)
{
instance = function.apply(t);
function = null;
this.lock = null;
}
}
}
return instance;
}
@Override
public R get() throws IllegalStateException {
if (function != null)
throw new IllegalStateException("Cannot call get() before apply()");
return instance;
}
}
}
@@ -5,47 +5,47 @@
package net.minecraftforge.common.util;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.level.saveddata.SavedData;
import net.minecraft.world.level.storage.DimensionDataStorage;
import net.minecraft.world.level.saveddata.SavedDataType;
import org.jetbrains.annotations.Nullable;
import com.mojang.serialization.codecs.RecordCodecBuilder;
@SuppressWarnings("deprecation")
public class LevelCapabilityData extends SavedData {
public static final String ID = "capabilities";
public static final SavedDataType<LevelCapabilityData> TYPE = new SavedDataType<LevelCapabilityData>(
"capabilities",
LevelCapabilityData::new,
ctx ->
RecordCodecBuilder.create(b ->
b.group(
CompoundTag.CODEC.fieldOf("data").forGetter(i -> {
if (i.serializable == null)
return new CompoundTag();
return i.serializable.serializeNBT(ctx.levelOrThrow().registryAccess());
})
).apply(b, nbt -> new LevelCapabilityData(ctx, nbt))
),
null
);
@Nullable
private final INBTSerializable<CompoundTag> serializable;
private CompoundTag capNBT = null;
public LevelCapabilityData(@Nullable INBTSerializable<CompoundTag> serializable) {
this.serializable = serializable;
private LevelCapabilityData(SavedData.Context ctx) {
this.serializable = ctx.levelOrThrow().getCapabilityDispatcher();
}
@Override
public CompoundTag save(CompoundTag nbt, HolderLookup.Provider provider) {
if (serializable != null)
nbt = serializable.serializeNBT(provider);
return nbt;
private LevelCapabilityData(SavedData.Context ctx, CompoundTag data) {
this(ctx);
if (this.serializable != null)
this.serializable.deserializeNBT(ctx.levelOrThrow().registryAccess(), data);
}
@Override
public boolean isDirty() {
return true;
}
public static LevelCapabilityData compute(DimensionDataStorage data, @Nullable INBTSerializable<CompoundTag> caps) {
var factory = new Factory<>(
() -> new LevelCapabilityData(caps),
(tag, lookup) -> {
var ret = new LevelCapabilityData(caps);
if (caps != null)
caps.deserializeNBT(lookup, tag);
return ret;
},
null
);
return data.computeIfAbsent(factory, ID);
}
}
@@ -10,7 +10,7 @@ import java.util.Optional;
import net.minecraft.core.Holder;
import net.minecraft.sounds.Music;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.util.random.SimpleWeightedRandomList;
import net.minecraft.util.random.WeightedList;
import net.minecraft.world.level.biome.AmbientAdditionsSettings;
import net.minecraft.world.level.biome.AmbientMoodSettings;
import net.minecraft.world.level.biome.AmbientParticleSettings;
@@ -90,7 +90,7 @@ public class BiomeSpecialEffectsBuilder extends BiomeSpecialEffects.Builder {
return this.ambientAdditionsSettings;
}
public Optional<SimpleWeightedRandomList<Music>> getBackgroundMusic() {
public Optional<WeightedList<Music>> getBackgroundMusic() {
return this.backgroundMusic;
}
}
@@ -13,11 +13,15 @@ import java.util.function.Function;
import com.mojang.datafixers.util.Either;
import com.mojang.serialization.Codec;
import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.ListCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.Util;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet;
import net.minecraft.core.RegistryCodecs;
import net.minecraft.util.random.Weighted;
import net.minecraft.util.random.WeightedList;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.level.biome.Biome;
@@ -155,15 +159,12 @@ public final class ForgeBiomeModifiers {
* @param biomes Biomes to add mob spawns to.
* @param spawners List of SpawnerDatas specifying EntityType, weight, and pack size.
*/
public record AddSpawnsBiomeModifier(HolderSet<Biome> biomes, List<SpawnerData> spawners) implements BiomeModifier {
public record AddSpawnsBiomeModifier(HolderSet<Biome> biomes, WeightedList<SpawnerData> spawners) implements BiomeModifier {
public static final MapCodec<AddSpawnsBiomeModifier> CODEC = RecordCodecBuilder.mapCodec(builder ->
builder.group(
Biome.LIST_CODEC.fieldOf("biomes").forGetter(AddSpawnsBiomeModifier::biomes),
// Allow either a list or single spawner, attempting to decode the list format first.
Codec.either(SpawnerData.CODEC.listOf(), SpawnerData.CODEC).xmap(
either -> either.map(Function.identity(), List::of), // convert list/singleton to list when decoding
list -> list.size() == 1 ? Either.right(list.get(0)) : Either.left(list) // convert list to singleton/list when encoding
).fieldOf("spawners").forGetter(AddSpawnsBiomeModifier::spawners)
WeightedList.codec(SpawnerData.CODEC).fieldOf("spawners").forGetter(AddSpawnsBiomeModifier::spawners)
).apply(builder, AddSpawnsBiomeModifier::new));
/**
@@ -172,16 +173,18 @@ public final class ForgeBiomeModifiers {
* @param spawner SpawnerData specifying EntityTYpe, weight, and pack size.
* @return AddSpawnsBiomeModifier that adds a single spawn entry to the specified biomes.
*/
public static AddSpawnsBiomeModifier singleSpawn(HolderSet<Biome> biomes, SpawnerData spawner) {
return new AddSpawnsBiomeModifier(biomes, List.of(spawner));
public static AddSpawnsBiomeModifier singleSpawn(HolderSet<Biome> biomes, int weight, SpawnerData spawner) {
return new AddSpawnsBiomeModifier(biomes, WeightedList.of(List.of(new Weighted<>(spawner, weight))));
}
@Override
public void modify(Holder<Biome> biome, Phase phase, Builder builder) {
if (phase == Phase.ADD && this.biomes.contains(biome)) {
var spawns = builder.getMobSpawnSettings();
for (var spawner : this.spawners)
spawns.addSpawn(spawner.type.getCategory(), spawner);
for (var weighted : this.spawners.unwrap()) {
var spawner = weighted.value();
spawns.addSpawn(spawner.type().getCategory(), weighted.weight(), spawner);
}
}
}
@@ -216,7 +219,7 @@ public final class ForgeBiomeModifiers {
if (phase == Phase.REMOVE && this.biomes.contains(biome)) {
var spawns = builder.getMobSpawnSettings();
for (var category : MobCategory.values())
spawns.getSpawner(category).removeIf(data -> this.entityTypes.contains(ForgeRegistries.ENTITY_TYPES.getHolder(data.type).get()));
spawns.getSpawner(category).removeIf(data -> this.entityTypes.contains(ForgeRegistries.ENTITY_TYPES.getHolder(data.type()).orElseThrow()));
}
}
@@ -6,563 +6,73 @@
package net.minecraftforge.common.world;
import com.mojang.datafixers.util.Pair;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import it.unimi.dsi.fastutil.longs.LongSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Function;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.world.entity.Entity;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.ForcedChunksSavedData;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.TicketType;
import net.minecraftforge.fml.ModList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.Unmodifiable;
@ParametersAreNonnullByDefault
public class ForgeChunkManager
{
private static final Logger LOGGER = LogManager.getLogger();
private static final TicketType<TicketOwner<BlockPos>> BLOCK = TicketType.create("forge:block", Comparator.comparing(info -> info));
private static final TicketType<TicketOwner<BlockPos>> BLOCK_TICKING = TicketType.create("forge:block_ticking", Comparator.comparing(info -> info));
private static final TicketType<TicketOwner<UUID>> ENTITY = TicketType.create("forge:entity", Comparator.comparing(info -> info));
private static final TicketType<TicketOwner<UUID>> ENTITY_TICKING = TicketType.create("forge:entity_ticking", Comparator.comparing(info -> info));
private static final Map<String, LoadingValidationCallback> callbacks = new HashMap<>();
/**
* Sets the forced chunk loading validation callback for the given mod. This allows for validating and removing no longer valid tickets on level load.
*
* @apiNote This method should be called from a {@link net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent} using one of the {@link
* net.minecraftforge.fml.event.lifecycle.ParallelDispatchEvent} enqueueWork methods.
*/
public static void setForcedChunkLoadingCallback(String modId, LoadingValidationCallback callback)
{
if (ModList.get().isLoaded(modId))
callbacks.put(modId, callback);
else
LOGGER.warn("A mod attempted to set the forced chunk validation loading callback for an unloaded mod of id: {}", modId);
/** @deprecated Vanilla now handles all forced chunks using its new {@link TicketType} system. */
@Deprecated(forRemoval = true, since = "1.21.5")
public class ForgeChunkManager {
private static <T> T error() {
throw new UnsupportedOperationException("Mod used ForgeChnkManager when they should use vanilla's TicketType system, see Level.getChunkSource().addTicketWithRadius");
}
/**
* Checks if a level has any forced chunks. Mainly used for seeing if a level should continue ticking with no players in it.
*/
public static boolean hasForcedChunks(ServerLevel level)
{
ForcedChunksSavedData data = level.getDataStorage().get(ForcedChunksSavedData.factory(), "chunks");
if (data == null) return false;
return !data.getChunks().isEmpty() || !data.getBlockForcedChunks().isEmpty() || !data.getEntityForcedChunks().isEmpty();
}
/** @deprecated Use Vanilla's {@link TicketType} system */
public static void setForcedChunkLoadingCallback(String modId, LoadingValidationCallback callback) { error(); }
/**
* Forces a chunk to be loaded for the given mod with the "owner" of the ticket being a given block position.
*
* @param add {@code true} to force the chunk, {@code false} to unforce the chunk.
* @param ticking {@code true} to make the chunk receive full chunk ticks even if there is no player nearby.
*/
public static boolean forceChunk(ServerLevel level, String modId, BlockPos owner, int chunkX, int chunkZ, boolean add, boolean ticking)
{
return forceChunk(level, modId, owner, chunkX, chunkZ, add, ticking, ticking ? BLOCK_TICKING : BLOCK, ForcedChunksSavedData::getBlockForcedChunks);
}
/** @deprecated Use Vanilla's {@link TicketType} system */
public static boolean hasForcedChunks(ServerLevel level) { return error(); }
/**
* Forces a chunk to be loaded for the given mod with the "owner" of the ticket being the UUID of the given entity.
*
* @param add {@code true} to force the chunk, {@code false} to unforce the chunk.
* @param ticking {@code true} to make the chunk receive full chunk ticks even if there is no player nearby.
*/
public static boolean forceChunk(ServerLevel level, String modId, Entity owner, int chunkX, int chunkZ, boolean add, boolean ticking)
{
return forceChunk(level, modId, owner.getUUID(), chunkX, chunkZ, add, ticking);
}
/** @deprecated Use Vanilla's {@link TicketType} system */
public static boolean forceChunk(ServerLevel level, String modId, BlockPos owner, int chunkX, int chunkZ, boolean add, boolean ticking) { return error(); }
/**
* Forces a chunk to be loaded for the given mod with the "owner" of the ticket being a given UUID.
*
* @param add {@code true} to force the chunk, {@code false} to unforce the chunk.
* @param ticking {@code true} to make the chunk receive full chunk ticks even if there is no player nearby.
*/
public static boolean forceChunk(ServerLevel level, String modId, UUID owner, int chunkX, int chunkZ, boolean add, boolean ticking)
{
return forceChunk(level, modId, owner, chunkX, chunkZ, add, ticking, ticking ? ENTITY_TICKING : ENTITY, ForcedChunksSavedData::getEntityForcedChunks);
}
/** @deprecated Use Vanilla's {@link TicketType} system */
public static boolean forceChunk(ServerLevel level, String modId, Entity owner, int chunkX, int chunkZ, boolean add, boolean ticking) { return error(); }
/**
* Forces a chunk to be loaded for the given mod with the given "owner".
*
* @param add {@code true} to force the chunk, {@code false} to unforce the chunk.
*
* @implNote Based on {@link ServerLevel#setChunkForced(int, int, boolean)}
*/
private static <T extends Comparable<? super T>> boolean forceChunk(ServerLevel level, String modId, T owner, int chunkX, int chunkZ, boolean add, boolean ticking,
TicketType<TicketOwner<T>> type, Function<ForcedChunksSavedData, TicketTracker<T>> ticketGetter)
{
if (!ModList.get().isLoaded(modId))
{
LOGGER.warn("A mod attempted to force a chunk for an unloaded mod of id: {}", modId);
return false;
}
ForcedChunksSavedData saveData = level.getDataStorage().computeIfAbsent(ForcedChunksSavedData.factory(), "chunks");
ChunkPos pos = new ChunkPos(chunkX, chunkZ);
long chunk = pos.toLong();
TicketTracker<T> tickets = ticketGetter.apply(saveData);
TicketOwner<T> ticketOwner = new TicketOwner<>(modId, owner);
boolean success;
if (add)
{
success = tickets.add(ticketOwner, chunk, ticking);
if (success)
level.getChunk(chunkX, chunkZ);
}
else
{
success = tickets.remove(ticketOwner, chunk, ticking);
}
if (success)
{
saveData.setDirty(true);
forceChunk(level, pos, type, ticketOwner, add, ticking);
}
return success;
}
/**
* Adds/Removes a ticket from the level's chunk provider with the proper levels to match the forced chunks.
*
* @param add {@code true} to force the chunk, {@code false} to unforce the chunk.
* @param ticking {@code true} to make the chunk receive full chunk ticks even if there is no player nearby.
*
* @implNote We use distance 2 for what we pass, as when using register/releaseTicket the ticket's level is set to 33 - distance and the level that forced chunks use
* is 31.
*/
private static <T extends Comparable<? super T>> void forceChunk(ServerLevel level, ChunkPos pos, TicketType<TicketOwner<T>> type, TicketOwner<T> owner, boolean add,
boolean ticking)
{
if (add)
level.getChunkSource().addRegionTicket(type, pos, 2, owner, ticking);
else
level.getChunkSource().removeRegionTicket(type, pos, 2, owner, ticking);
}
/**
* Reinstates forge's forced chunks when vanilla initially loads a level and reinstates their forced chunks. This method also will validate all of forge's forced
* chunks using and registered {@link LoadingValidationCallback}.
*
* @apiNote Internal
*/
public static void reinstatePersistentChunks(ServerLevel level, ForcedChunksSavedData saveData)
{
if (!callbacks.isEmpty())
{
//If we have any callbacks, gather all owned tickets by modid for both blocks and entities
Map<String, Map<BlockPos, Pair<LongSet, LongSet>>> blockTickets = gatherTicketsByModId(saveData.getBlockForcedChunks());
Map<String, Map<UUID, Pair<LongSet, LongSet>>> entityTickets = gatherTicketsByModId(saveData.getEntityForcedChunks());
//Fire the callbacks allowing them to remove any tickets they don't want anymore
for (Map.Entry<String, LoadingValidationCallback> entry : callbacks.entrySet())
{
String modId = entry.getKey();
boolean hasBlockTicket = blockTickets.containsKey(modId);
boolean hasEntityTicket = entityTickets.containsKey(modId);
if (hasBlockTicket || hasEntityTicket)
{
Map<BlockPos, Pair<LongSet, LongSet>> ownedBlockTickets = hasBlockTicket ? Collections.unmodifiableMap(blockTickets.get(modId)) : Collections.emptyMap();
Map<UUID, Pair<LongSet, LongSet>> ownedEntityTickets = hasEntityTicket ? Collections.unmodifiableMap(entityTickets.get(modId)) : Collections.emptyMap();
entry.getValue().validateTickets(level, new TicketHelper(saveData, modId, ownedBlockTickets, ownedEntityTickets));
}
}
}
//Reinstate the chunks that we want to load
reinstatePersistentChunks(level, BLOCK, saveData.getBlockForcedChunks().chunks, false);
reinstatePersistentChunks(level, BLOCK_TICKING, saveData.getBlockForcedChunks().tickingChunks, true);
reinstatePersistentChunks(level, ENTITY, saveData.getEntityForcedChunks().chunks, false);
reinstatePersistentChunks(level, ENTITY_TICKING, saveData.getEntityForcedChunks().tickingChunks, true);
}
/**
* Gathers tickets into a mod filtered map for use in providing all tickets a mod has registered to its {@link LoadingValidationCallback}.
*/
private static <T extends Comparable<? super T>> Map<String, Map<T, Pair<LongSet, LongSet>>> gatherTicketsByModId(TicketTracker<T> tickets)
{
Map<String, Map<T, Pair<LongSet, LongSet>>> modSortedOwnedChunks = new HashMap<>();
gatherTicketsByModId(tickets.chunks, Pair::getFirst, modSortedOwnedChunks);
gatherTicketsByModId(tickets.tickingChunks, Pair::getSecond, modSortedOwnedChunks);
return modSortedOwnedChunks;
}
/**
* Gathers tickets into a mod filtered map for use in providing all tickets a mod has registered to its {@link LoadingValidationCallback}.
*/
private static <T extends Comparable<? super T>> void gatherTicketsByModId(Map<TicketOwner<T>, LongSet> tickets, Function<Pair<LongSet, LongSet>, LongSet> typeGetter,
Map<String, Map<T, Pair<LongSet, LongSet>>> modSortedOwnedChunks)
{
for (Map.Entry<TicketOwner<T>, LongSet> entry : tickets.entrySet())
{
Pair<LongSet, LongSet> pair = modSortedOwnedChunks.computeIfAbsent(entry.getKey().modId, modId -> new HashMap<>())
.computeIfAbsent(entry.getKey().owner, owner -> new Pair<>(new LongOpenHashSet(), new LongOpenHashSet()));
typeGetter.apply(pair).addAll(entry.getValue());
}
}
/**
* Adds back any persistent forced chunks to the level's chunk provider.
*/
private static <T extends Comparable<? super T>> void reinstatePersistentChunks(ServerLevel level, TicketType<TicketOwner<T>> type,
Map<TicketOwner<T>, LongSet> tickets, boolean ticking)
{
for (Map.Entry<TicketOwner<T>, LongSet> entry : tickets.entrySet())
{
for (long chunk : entry.getValue())
{
forceChunk(level, new ChunkPos(chunk), type, entry.getKey(), true, ticking);
}
}
}
/**
* Writes the forge forced chunks into the NBT compound. Format is List{modid, List{ChunkPos, List{BlockPos}, List{UUID}}}
*
* @apiNote Internal
*/
public static void writeForgeForcedChunks(CompoundTag nbt, TicketTracker<BlockPos> blockForcedChunks, TicketTracker<UUID> entityForcedChunks)
{
if (!blockForcedChunks.isEmpty() || !entityForcedChunks.isEmpty())
{
Map<String, Long2ObjectMap<CompoundTag>> forcedEntries = new HashMap<>();
writeForcedChunkOwners(forcedEntries, blockForcedChunks, "Blocks", Tag.TAG_COMPOUND, (pos, forcedBlocks) -> forcedBlocks.add(NbtUtils.writeBlockPos(pos)));
writeForcedChunkOwners(forcedEntries, entityForcedChunks, "Entities", Tag.TAG_INT_ARRAY, (uuid, forcedEntities) -> forcedEntities.add(NbtUtils.createUUID(uuid)));
ListTag forcedChunks = new ListTag();
for (Map.Entry<String, Long2ObjectMap<CompoundTag>> entry : forcedEntries.entrySet())
{
CompoundTag forcedEntry = new CompoundTag();
forcedEntry.putString("Mod", entry.getKey());
ListTag modForced = new ListTag();
modForced.addAll(entry.getValue().values());
forcedEntry.put("ModForced", modForced);
forcedChunks.add(forcedEntry);
}
nbt.put("ForgeForced", forcedChunks);
}
}
private static <T extends Comparable<? super T>> void writeForcedChunkOwners(Map<String, Long2ObjectMap<CompoundTag>> forcedEntries, TicketTracker<T> tracker,
String listKey, int listType, BiConsumer<T, ListTag> ownerWriter)
{
writeForcedChunkOwners(forcedEntries, tracker.chunks, listKey,listType, ownerWriter);
writeForcedChunkOwners(forcedEntries, tracker.tickingChunks, "Ticking" + listKey, listType, ownerWriter);
}
private static <T extends Comparable<? super T>> void writeForcedChunkOwners(Map<String, Long2ObjectMap<CompoundTag>> forcedEntries,
Map<TicketOwner<T>, LongSet> forcedChunks, String listKey, int listType, BiConsumer<T, ListTag> ownerWriter)
{
for (Map.Entry<TicketOwner<T>, LongSet> entry : forcedChunks.entrySet())
{
Long2ObjectMap<CompoundTag> modForced = forcedEntries.computeIfAbsent(entry.getKey().modId, modId -> new Long2ObjectOpenHashMap<>());
for (long chunk : entry.getValue())
{
CompoundTag modEntry = modForced.computeIfAbsent(chunk, chunkPos -> {
CompoundTag baseEntry = new CompoundTag();
baseEntry.putLong("Chunk", chunkPos);
return baseEntry;
});
ListTag ownerList = modEntry.getList(listKey, listType);
ownerWriter.accept(entry.getKey().owner, ownerList);
//Note: As getList returns a new list in the case the data is of the wrong type,
// we need to mimic was vanilla does in various places and put our list back in
// the CompoundNBT regardless.
modEntry.put(listKey, ownerList);
}
}
}
/**
* Reads the forge forced chunks from the NBT compound. Format is List{modid, List{ChunkPos, List{BlockPos}, List{UUID}}}
*
* @apiNote Internal
*/
public static void readForgeForcedChunks(CompoundTag nbt, TicketTracker<BlockPos> blockForcedChunks, TicketTracker<UUID> entityForcedChunks)
{
ListTag forcedChunks = nbt.getList("ForgeForced", Tag.TAG_COMPOUND);
for (int i = 0; i < forcedChunks.size(); i++)
{
CompoundTag forcedEntry = forcedChunks.getCompound(i);
String modId = forcedEntry.getString("Mod");
if (ModList.get().isLoaded(modId))
{
ListTag modForced = forcedEntry.getList("ModForced", Tag.TAG_COMPOUND);
for (int j = 0; j < modForced.size(); j++)
{
CompoundTag modEntry = modForced.getCompound(j);
long chunkPos = modEntry.getLong("Chunk");
readBlockForcedChunks(modId, chunkPos, modEntry, "Blocks", blockForcedChunks.chunks);
readBlockForcedChunks(modId, chunkPos, modEntry, "TickingBlocks", blockForcedChunks.tickingChunks);
readEntityForcedChunks(modId, chunkPos, modEntry, "Entities", entityForcedChunks.chunks);
readEntityForcedChunks(modId, chunkPos, modEntry, "TickingEntities", entityForcedChunks.tickingChunks);
}
}
else
{
LOGGER.warn("Found chunk loading data for mod {} which is currently not available or active - it will be removed from the level save.", modId);
}
}
}
/**
* Reads the forge block forced chunks.
*/
private static void readBlockForcedChunks(String modId, long chunkPos, CompoundTag modEntry, String key, Map<TicketOwner<BlockPos>, LongSet> blockForcedChunks)
{
ListTag forcedBlocks = modEntry.getList(key, Tag.TAG_INT_ARRAY);
for (int k = 0; k < forcedBlocks.size(); k++)
{
var aint = forcedBlocks.getIntArray(k);
var pos = aint.length == 3 ? new BlockPos(aint[0], aint[1], aint[2]) : BlockPos.ZERO;
blockForcedChunks.computeIfAbsent(new TicketOwner<>(modId, pos), owner -> new LongOpenHashSet()).add(chunkPos);
}
}
/**
* Reads the forge entity forced chunks.
*/
private static void readEntityForcedChunks(String modId, long chunkPos, CompoundTag modEntry, String key, Map<TicketOwner<UUID>, LongSet> entityForcedChunks)
{
ListTag forcedEntities = modEntry.getList(key, Tag.TAG_INT_ARRAY);
for (Tag uuid : forcedEntities)
{
entityForcedChunks.computeIfAbsent(new TicketOwner<>(modId, NbtUtils.loadUUID(uuid)), owner -> new LongOpenHashSet()).add(chunkPos);
}
}
/** @deprecated Use Vanilla's {@link TicketType} system */
public static boolean forceChunk(ServerLevel level, String modId, UUID owner, int chunkX, int chunkZ, boolean add, boolean ticking) { return error(); }
/** @deprecated Use Vanilla's {@link TicketType} system */
@FunctionalInterface
@Deprecated(forRemoval = true, since = "1.21.5")
public interface LoadingValidationCallback {
/**
* Called back when tickets are about to be loaded and reinstated to allow mods to invalidate and remove specific tickets that may no longer be valid.
*
* @param level The level
* @param ticketHelper Ticket helper to remove any invalid tickets.
*/
void validateTickets(ServerLevel level, TicketHelper ticketHelper);
}
/**
* Class to help mods remove no longer valid tickets.
*/
public static class TicketHelper
{
private final Map<BlockPos, Pair<LongSet, LongSet>> blockTickets;
private final Map<UUID, Pair<LongSet, LongSet>> entityTickets;
private final ForcedChunksSavedData saveData;
private final String modId;
private TicketHelper(ForcedChunksSavedData saveData, String modId, Map<BlockPos, Pair<LongSet, LongSet>> blockTickets, Map<UUID, Pair<LongSet, LongSet>> entityTickets)
{
this.saveData = saveData;
this.modId = modId;
this.blockTickets = blockTickets;
this.entityTickets = entityTickets;
}
/**
* Gets all "BLOCK" tickets this mod had registered and which block positions are forcing which chunks. First element of the pair is the non-fully ticking
* tickets, second element is the fully ticking tickets.
*
* @apiNote This map is unmodifiable and does not update to reflect removed tickets so it is safe to call the remove methods while iterating it.
*/
public Map<BlockPos, Pair<LongSet, LongSet>> getBlockTickets()
{
return blockTickets;
}
/**
* Gets all "ENTITY" tickets this mod had registered and which entity (UUID) is forcing which chunks. First element of the pair is the non-fully ticking
* tickets, second element is the fully ticking tickets.
*
* @apiNote This map is unmodifiable and does not update to reflect removed tickets so it is safe to call the remove methods while iterating it.
*/
public Map<UUID, Pair<LongSet, LongSet>> getEntityTickets()
{
return entityTickets;
}
/**
* Removes all tickets that a given block was responsible for; both ticking and not ticking.
*
* @param owner Block that was responsible.
*/
public void removeAllTickets(BlockPos owner)
{
removeAllTickets(saveData.getBlockForcedChunks(), owner);
}
/**
* Removes all tickets that a given entity (UUID) was responsible for; both ticking and not ticking.
*
* @param owner Entity (UUID) that was responsible.
*/
public void removeAllTickets(UUID owner)
{
removeAllTickets(saveData.getEntityForcedChunks(), owner);
}
/**
* Removes all tickets that a given owner was responsible for; both ticking and not ticking.
*/
private <T extends Comparable<? super T>> void removeAllTickets(TicketTracker<T> tickets, T owner)
{
TicketOwner<T> ticketOwner = new TicketOwner<>(modId, owner);
if (tickets.chunks.containsKey(ticketOwner) || tickets.tickingChunks.containsKey(ticketOwner))
{
tickets.chunks.remove(ticketOwner);
tickets.tickingChunks.remove(ticketOwner);
saveData.setDirty(true);
}
}
/**
* Removes the ticket for the given chunk that a given block was responsible for.
*
* @param owner Block that was responsible.
* @param chunk Chunk to remove ticket of.
* @param ticking Whether or not the ticket to remove represents a ticking set of tickets or not.
*/
public void removeTicket(BlockPos owner, long chunk, boolean ticking)
{
removeTicket(saveData.getBlockForcedChunks(), owner, chunk, ticking);
}
/**
* Removes the ticket for the given chunk that a given entity (UUID) was responsible for.
*
* @param owner Entity (UUID) that was responsible.
* @param chunk Chunk to remove ticket of.
* @param ticking Whether or not the ticket to remove represents a ticking set of tickets or not.
*/
public void removeTicket(UUID owner, long chunk, boolean ticking)
{
removeTicket(saveData.getEntityForcedChunks(), owner, chunk, ticking);
}
private <T extends Comparable<? super T>> void removeTicket(TicketTracker<T> tickets, T owner, long chunk, boolean ticking)
{
if (tickets.remove(new TicketOwner<>(modId, owner), chunk, ticking))
saveData.setDirty(true);
}
/** @deprecated Use Vanilla's {@link TicketType} system */
@Deprecated(forRemoval = true, since = "1.21.5")
public static class TicketHelper {
private TicketHelper() { }
/** @deprecated Use Vanilla's {@link TicketType} system */
public @Unmodifiable Map<BlockPos, Pair<LongSet, LongSet>> getBlockTickets() { return error(); }
/** @deprecated Use Vanilla's {@link TicketType} system */
public @Unmodifiable Map<UUID, Pair<LongSet, LongSet>> getEntityTickets() { return error(); }
/** @deprecated Use Vanilla's {@link TicketType} system */
public void removeAllTickets(BlockPos owner) { error(); }
/** @deprecated Use Vanilla's {@link TicketType} system */
public void removeAllTickets(UUID owner) { error(); }
/** @deprecated Use Vanilla's {@link TicketType} system */
public void removeTicket(BlockPos owner, long chunk, boolean ticking) { error(); }
/** @deprecated Use Vanilla's {@link TicketType} system */
public void removeTicket(UUID owner, long chunk, boolean ticking) { error(); }
}
/**
* Helper class to keep track of a ticket owner by modid and owner object
*/
public static class TicketOwner<T extends Comparable<? super T>> implements Comparable<TicketOwner<T>>
{
private final String modId;
private final T owner;
private TicketOwner(String modId, T owner)
{
this.modId = modId;
this.owner = owner;
}
@Override
public int compareTo(TicketOwner<T> other)
{
int res = modId.compareTo(other.modId);
return res == 0 ? owner.compareTo(other.owner) : res;
}
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TicketOwner<?> that = (TicketOwner<?>) o;
return Objects.equals(modId, that.modId) && Objects.equals(owner, that.owner);
}
@Override
public int hashCode()
{
return Objects.hash(modId, owner);
}
/** @deprecated Use Vanilla's {@link TicketType} system */
@Deprecated(forRemoval = true, since = "1.21.5")
public static class TicketOwner implements Comparable<TicketOwner> {
private TicketOwner() { }
@Override public int compareTo(TicketOwner o) { return error(); }
}
/**
* Helper class to manage tracking and handling loaded tickets.
*/
public static class TicketTracker<T extends Comparable<? super T>>
{
private final Map<TicketOwner<T>, LongSet> chunks = new HashMap<>();
private final Map<TicketOwner<T>, LongSet> tickingChunks = new HashMap<>();
/**
* Gets an unmodifiable view of the tracked chunks.
*/
public Map<TicketOwner<T>, LongSet> getChunks()
{
return Collections.unmodifiableMap(chunks);
}
/**
* Gets an unmodifiable view of the tracked fully ticking chunks.
*/
public Map<TicketOwner<T>, LongSet> getTickingChunks()
{
return Collections.unmodifiableMap(tickingChunks);
}
/**
* Checks if this tracker is empty.
*
* @return {@code true} if there are no chunks or ticking chunks being tracked.
*/
public boolean isEmpty()
{
return chunks.isEmpty() && tickingChunks.isEmpty();
}
private Map<TicketOwner<T>, LongSet> getTickets(boolean ticking)
{
return ticking ? tickingChunks : chunks;
}
/**
* @return {@code true} if the state changed.
*/
private boolean remove(TicketOwner<T> owner, long chunk, boolean ticking)
{
Map<TicketOwner<T>, LongSet> tickets = getTickets(ticking);
if (tickets.containsKey(owner))
{
LongSet ticketChunks = tickets.get(owner);
if (ticketChunks.remove(chunk))
{
if (ticketChunks.isEmpty())
tickets.remove(owner);
return true;
}
}
return false;
}
/**
* @return {@code true} if the state changed.
*/
private boolean add(TicketOwner<T> owner, long chunk, boolean ticking)
{
return getTickets(ticking).computeIfAbsent(owner, o -> new LongOpenHashSet()).add(chunk);
}
/** @deprecated Use Vanilla's {@link TicketType} system */
@Deprecated(forRemoval = true, since = "1.21.5")
public static class TicketTracker {
public Map<TicketOwner, LongSet> getChunks() { return error(); }
public boolean isEmpty() { return error(); }
}
}
@@ -9,54 +9,48 @@ import java.util.Collections;
import java.util.List;
import java.util.Set;
import net.minecraft.Util;
import net.minecraft.util.random.WeightedList;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.level.biome.MobSpawnSettings;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Unmodifiable;
public class MobSpawnSettingsBuilder extends MobSpawnSettings.Builder
{
public class MobSpawnSettingsBuilder extends MobSpawnSettings.Builder {
private final Set<MobCategory> typesView = Collections.unmodifiableSet(this.spawners.keySet());
private final Set<EntityType<?>> costView = Collections.unmodifiableSet(this.mobSpawnCosts.keySet());
public MobSpawnSettingsBuilder(MobSpawnSettings orig)
{
orig.getSpawnerTypes().forEach(k -> {
spawners.get(k).clear();
spawners.get(k).addAll(orig.getMobs(k).unwrap());
});
public MobSpawnSettingsBuilder(MobSpawnSettings orig) {
orig.getSpawnerTypes().forEach(k ->
spawners.put(k, WeightedList.<MobSpawnSettings.SpawnerData>builder().addAll(orig.getMobs(k).unwrap()))
);
orig.getEntityTypes().forEach(k -> mobSpawnCosts.put(k, orig.getMobSpawnCost(k)));
creatureGenerationProbability = orig.getCreatureProbability();
}
public Set<MobCategory> getSpawnerTypes()
{
public Set<MobCategory> getSpawnerTypes() {
return this.typesView;
}
public List<MobSpawnSettings.SpawnerData> getSpawner(MobCategory type)
{
public WeightedList.Builder<MobSpawnSettings.SpawnerData> getSpawner(MobCategory type) {
return this.spawners.get(type);
}
public Set<EntityType<?>> getEntityTypes()
{
public Set<EntityType<?>> getEntityTypes() {
return this.costView;
}
@Nullable
public MobSpawnSettings.MobSpawnCost getCost(EntityType<?> type)
{
public MobSpawnSettings.MobSpawnCost getCost(EntityType<?> type) {
return this.mobSpawnCosts.get(type);
}
public float getProbability()
{
public float getProbability() {
return this.creatureGenerationProbability;
}
public MobSpawnSettingsBuilder disablePlayerSpawn()
{
public MobSpawnSettingsBuilder disablePlayerSpawn() {
return this;
}
}
@@ -9,9 +9,11 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import net.minecraft.core.HolderSet;
import net.minecraft.util.random.WeightedRandomList;
import net.minecraft.util.random.Weighted;
import net.minecraft.util.random.WeightedList;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.MobSpawnSettings;
@@ -20,9 +22,9 @@ import net.minecraft.world.level.levelgen.structure.Structure.StructureSettings;
import net.minecraft.world.level.levelgen.structure.StructureSpawnOverride;
import net.minecraft.world.level.levelgen.structure.TerrainAdjustment;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.UnmodifiableView;
public class StructureSettingsBuilder
{
public class StructureSettingsBuilder {
private HolderSet<Biome> biomes;
private final Map<MobCategory, StructureSpawnOverrideBuilder> spawnOverrides;
private GenerationStep.Decoration step;
@@ -32,13 +34,11 @@ public class StructureSettingsBuilder
* @param settings Existing StructureSettings.
* @return A new builder with a copy of that StructureSettings's values.
*/
public static StructureSettingsBuilder copyOf(StructureSettings settings)
{
public static StructureSettingsBuilder copyOf(StructureSettings settings) {
return new StructureSettingsBuilder(settings.biomes(), settings.spawnOverrides(), settings.step(), settings.terrainAdaptation());
}
private StructureSettingsBuilder(HolderSet<Biome> biomes, Map<MobCategory, StructureSpawnOverride> spawnOverrides, GenerationStep.Decoration step, TerrainAdjustment terrainAdaptation)
{
private StructureSettingsBuilder(HolderSet<Biome> biomes, Map<MobCategory, StructureSpawnOverride> spawnOverrides, GenerationStep.Decoration step, TerrainAdjustment terrainAdaptation) {
this.biomes = biomes;
this.spawnOverrides = spawnOverrides.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> StructureSpawnOverrideBuilder.copyOf(entry.getValue())));
this.step = step;
@@ -48,21 +48,18 @@ public class StructureSettingsBuilder
/**
* @return A new StructureSettings with the finalized values.
*/
public StructureSettings build()
{
public StructureSettings build() {
Map<MobCategory, StructureSpawnOverride> overrides = Collections.unmodifiableMap(
this.spawnOverrides.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().build()))
);
return new StructureSettings(this.biomes, overrides, this.step, this.terrainAdaptation);
}
public HolderSet<Biome> getBiomes()
{
public HolderSet<Biome> getBiomes() {
return biomes;
}
public void setBiomes(HolderSet<Biome> biomes)
{
public void setBiomes(HolderSet<Biome> biomes) {
this.biomes = biomes;
}
@@ -70,9 +67,7 @@ public class StructureSettingsBuilder
* Gets a mutable builder for the spawn overrides of a given mob category or {@code null} if no overrides are defined for that category.
* @param category Mob category
*/
@Nullable
public StructureSpawnOverrideBuilder getSpawnOverrides(MobCategory category)
{
public @Nullable StructureSpawnOverrideBuilder getSpawnOverrides(MobCategory category) {
return spawnOverrides.get(category);
}
@@ -80,8 +75,7 @@ public class StructureSettingsBuilder
* Gets or creates a mutable builder for the spawn overrides of a given mob category. If the override needed to be created it will default to piece bounding.
* @param category Mob category
*/
public StructureSpawnOverrideBuilder getOrAddSpawnOverrides(MobCategory category)
{
public StructureSpawnOverrideBuilder getOrAddSpawnOverrides(MobCategory category) {
return spawnOverrides.computeIfAbsent(category, c -> new StructureSpawnOverrideBuilder(StructureSpawnOverride.BoundingBoxType.PIECE, Collections.emptyList()));
}
@@ -89,32 +83,28 @@ public class StructureSettingsBuilder
* Removes the spawn overrides for the given mob category.
* @param category Mob category
*/
public void removeSpawnOverrides(MobCategory category)
{
public void removeSpawnOverrides(MobCategory category) {
this.spawnOverrides.remove(category);
}
/**
* Gets the world generation decoration step the structure spawns during.
*/
public GenerationStep.Decoration getDecorationStep()
{
public GenerationStep.Decoration getDecorationStep() {
return step;
}
/**
* Sets the world generation decoration step the structure spawns during.
*/
public void setDecorationStep(GenerationStep.Decoration step)
{
public void setDecorationStep(GenerationStep.Decoration step) {
this.step = step;
}
/**
* Gets the way the structure adapts to the terrain during generation.
*/
public TerrainAdjustment getTerrainAdaptation()
{
public TerrainAdjustment getTerrainAdaptation() {
return terrainAdaptation;
}
@@ -122,28 +112,24 @@ public class StructureSettingsBuilder
* Sets the way the structure adapts to the terrain during generation.
* @param terrainAdaptation New terrain adjustment
*/
public void setTerrainAdaptation(TerrainAdjustment terrainAdaptation)
{
public void setTerrainAdaptation(TerrainAdjustment terrainAdaptation) {
this.terrainAdaptation = terrainAdaptation;
}
public static class StructureSpawnOverrideBuilder
{
public static class StructureSpawnOverrideBuilder {
private StructureSpawnOverride.BoundingBoxType boundingBox;
private final List<MobSpawnSettings.SpawnerData> spawns;
private final List<MobSpawnSettings.SpawnerData> spawnsView;
private final List<Weighted<MobSpawnSettings.SpawnerData>> spawns;
private final List<Weighted<MobSpawnSettings.SpawnerData>> spawnsView;
/**
* @param override Existing spawn override data.
* @return A new builder with a copy of that StructureSpawnOverride's values.
*/
public static StructureSpawnOverrideBuilder copyOf(StructureSpawnOverride override)
{
public static StructureSpawnOverrideBuilder copyOf(StructureSpawnOverride override) {
return new StructureSpawnOverrideBuilder(override.boundingBox(), override.spawns().unwrap());
}
private StructureSpawnOverrideBuilder(StructureSpawnOverride.BoundingBoxType boundingBox, List<MobSpawnSettings.SpawnerData> spawns)
{
private StructureSpawnOverrideBuilder(StructureSpawnOverride.BoundingBoxType boundingBox, List<Weighted<MobSpawnSettings.SpawnerData>> spawns) {
this.boundingBox = boundingBox;
this.spawns = new ArrayList<>(spawns);
this.spawnsView = Collections.unmodifiableList(this.spawns);
@@ -152,49 +138,45 @@ public class StructureSettingsBuilder
/**
* Gets the type of bounding box for this structures spawn overrides.
*/
public StructureSpawnOverride.BoundingBoxType getBoundingBox()
{
return boundingBox;
public StructureSpawnOverride.BoundingBoxType getBoundingBox() {
return this.boundingBox;
}
/**
* Sets the way the structure checks for spawn overrides. Whether it is on a piece by piece basis or within the bounds of the overall structure.
* Sets the way the structure checks for spawn overrides. Whether it is on a piece by piece basis or within the
* bounds of the overall structure.
*/
public void setBoundingBox(StructureSpawnOverride.BoundingBoxType boundingBox)
{
public void setBoundingBox(StructureSpawnOverride.BoundingBoxType boundingBox) {
this.boundingBox = boundingBox;
}
/**
* Unmodifiable view of the possible spawns.
*/
public List<MobSpawnSettings.SpawnerData> getSpawns()
{
return spawnsView;
/** @return An {@linkplain Collections#unmodifiableList(List) Unmodifiable view} of the possible spawns. */
@UnmodifiableView
public List<Weighted<MobSpawnSettings.SpawnerData>> getSpawns() {
return this.spawnsView;
}
/** Adds a spawn to the overrides with a default weight of {@code 1}. */
public void addSpawn(MobSpawnSettings.SpawnerData spawn) {
this.addSpawn(spawn, 1);
}
/** Adds a spawn to the overrides. */
public void addSpawn(MobSpawnSettings.SpawnerData spawn, int weight) {
this.spawns.add(new Weighted<>(Objects.requireNonNull(spawn), weight));
}
/**
* Adds a spawn to the overrides.
* Removes all instances of a given spawn from the list of overrides. Use {@link #getSpawns()} to get instances
* of spawn data to remove.
*/
public void addSpawn(MobSpawnSettings.SpawnerData spawn)
{
this.spawns.add(spawn);
public void removeSpawn(MobSpawnSettings.SpawnerData spawn) {
this.spawns.removeIf(s -> s.value().equals(spawn));
}
/**
* Removes a given spawn from the list of overrides. Use {@link #getSpawns()} to get instances of spawn data to remove.
*/
public void removeSpawn(MobSpawnSettings.SpawnerData spawn)
{
this.spawns.remove(spawn);
}
/**
* @return A new StructureSpawnOverride with the finalized values.
*/
public StructureSpawnOverride build()
{
return new StructureSpawnOverride(boundingBox, WeightedRandomList.create(spawns));
/** @return A new StructureSpawnOverride with the finalized values. */
public StructureSpawnOverride build() {
return new StructureSpawnOverride(this.boundingBox, WeightedList.of(this.spawns));
}
}
}