Forge 1.19.3

Created a CreativeModeTabEvent to register creative mode tabs and populate entries per tab
Moved datapack registries to DataPackRegistryEvent.NewRegistry event instead of tying them to ForgeRegistry
Made it easier for mods to datagen datapack builtin entries with DatapackBuiltinEntriesProvider
Provided access to lookupProvider for datagen
Updated dependencies to match versions used by vanilla and update JarJar to 0.3.18
Added a test mod for the new CreativeModeTabEvent
Throws better error message for Forge registries in tag datagen
Deleted ForgeRegistryTagsProvider
Updated ClientChatReceivedEvent and ServerChatEvent for Mojang changes
Added patches for both sign related methods in ModelLayers
Changed RegisterShadersEvent to use ResourceProvider
Migrated old Mojang math types to JOML

Co-authored-by: Marc Hermans <[email protected]>
Co-authored-by: LexManos <[email protected]>
Co-authored-by: sciwhiz12 <[email protected]>
Co-authored-by: coehlrich <[email protected]>
This commit is contained in:
committed 2022-12-08 01:45:22 -06:00
1 parent 617ecb7ad3
commit 8255d7aed3
726 files changed
+7615 -6653

No files matched your search

@@ -0,0 +1,282 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.graph.ElementOrder;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.MutableGraph;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.logging.LogUtils;
import it.unimi.dsi.fastutil.booleans.BooleanConsumer;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.packs.resources.PreparableReloadListener;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.SimplePreparableReloadListener;
import net.minecraft.util.GsonHelper;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.CreativeModeTabs;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.CreativeModeTabSearchRegistry;
import net.minecraftforge.event.CreativeModeTabEvent;
import net.minecraftforge.fml.ModLoader;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.fml.loading.FMLLoader;
import net.minecraftforge.fml.loading.toposort.TopologicalSort;
import net.minecraftforge.server.ServerLifecycleHooks;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
public final class CreativeModeTabRegistry
{
private static final Logger LOGGER = LogUtils.getLogger();
private static final ResourceLocation CREATIVE_MODE_TAB_ORDERING_JSON = new ResourceLocation("forge", "creative_mode_tab_ordering.json");
private static final List<CreativeModeTab> SORTED_TABS = new ArrayList<>();
private static final List<CreativeModeTab> SORTED_TABS_VIEW = Collections.unmodifiableList(SORTED_TABS);
/**
* {@return an unmodifiable view of the sorted list of creative mode tabs in ascending order}
*/
public static List<CreativeModeTab> getSortedCreativeModeTabs()
{
return SORTED_TABS_VIEW;
}
/**
* {@return the {@linkplain CreativeModeTab} with the given name, or null}
*
* @param name the name to look up
*/
@Nullable
public static CreativeModeTab getTab(ResourceLocation name)
{
return creativeModeTabs.get(name);
}
/**
* {@return the name of the given {@linkplain CreativeModeTab}, or null}
*
* @param tab the tab to look up
*/
@Nullable
public static ResourceLocation getName(CreativeModeTab tab)
{
return creativeModeTabs.inverse().get(tab);
}
private static void processCreativeModeTab(CreativeModeTab creativeModeTab, ResourceLocation name, List<Object> afterEntries, List<Object> beforeEntries)
{
creativeModeTabs.put(name, creativeModeTab);
for (Object after : afterEntries)
{
ResourceLocation other = getCreativeModeTabName(after);
edges.put(other, name);
}
for (Object before : beforeEntries)
{
ResourceLocation other = getCreativeModeTabName(before);
edges.put(name, other);
}
}
private static ResourceLocation getCreativeModeTabName(Object entry)
{
if (entry instanceof String s)
return new ResourceLocation(s);
if (entry instanceof ResourceLocation rl)
return rl;
if (entry instanceof CreativeModeTab t)
return Objects.requireNonNull(getName(t), "Can't have sorting dependencies for creative mode tabs not registered in the CreativeModeTabSortingRegistry");
throw new IllegalStateException("Invalid object type passed into the CreativeModeTab dependencies " + entry.getClass());
}
private static final BiMap<ResourceLocation, CreativeModeTab> creativeModeTabs = HashBiMap.create();
private static final BiMap<ResourceLocation, CreativeModeTab> vanillaCreativeModeTabs = HashBiMap.create();
private static final Multimap<ResourceLocation, ResourceLocation> edges = HashMultimap.create();
private static final Multimap<ResourceLocation, ResourceLocation> vanillaEdges = HashMultimap.create();
static
{
final ResourceLocation buildingBlocks = new ResourceLocation("building_blocks");
final ResourceLocation coloredBlocks = new ResourceLocation("colored_blocks");
final ResourceLocation naturalBlocks = new ResourceLocation("natural_blocks");
final ResourceLocation functionalBlocks = new ResourceLocation("functional_blocks");
final ResourceLocation redstoneBlocks = new ResourceLocation("redstone_blocks");
final ResourceLocation toolsAndUtilities = new ResourceLocation("tools_and_utilities");
final ResourceLocation combat = new ResourceLocation("combat");
final ResourceLocation foodAndDrinks = new ResourceLocation("food_and_drinks");
final ResourceLocation ingredients = new ResourceLocation("ingredients");
final ResourceLocation spawnEggs = new ResourceLocation("spawn_eggs");
processCreativeModeTab(CreativeModeTabs.BUILDING_BLOCKS, buildingBlocks, List.of(), List.of());
processCreativeModeTab(CreativeModeTabs.COLORED_BLOCKS, coloredBlocks, List.of(buildingBlocks), List.of(naturalBlocks));
processCreativeModeTab(CreativeModeTabs.NATURAL_BLOCKS, naturalBlocks, List.of(coloredBlocks), List.of(functionalBlocks));
processCreativeModeTab(CreativeModeTabs.FUNCTIONAL_BLOCKS, functionalBlocks, List.of(naturalBlocks), List.of(redstoneBlocks));
processCreativeModeTab(CreativeModeTabs.REDSTONE_BLOCKS, redstoneBlocks, List.of(functionalBlocks), List.of(toolsAndUtilities));
processCreativeModeTab(CreativeModeTabs.TOOLS_AND_UTILITIES, toolsAndUtilities, List.of(redstoneBlocks), List.of(combat));
processCreativeModeTab(CreativeModeTabs.COMBAT, combat, List.of(toolsAndUtilities), List.of(foodAndDrinks));
processCreativeModeTab(CreativeModeTabs.FOOD_AND_DRINKS, foodAndDrinks, List.of(combat), List.of(ingredients));
processCreativeModeTab(CreativeModeTabs.INGREDIENTS, ingredients, List.of(foodAndDrinks), List.of(spawnEggs));
processCreativeModeTab(CreativeModeTabs.SPAWN_EGGS, spawnEggs, List.of(ingredients), List.of());
vanillaEdges.putAll(edges);
vanillaCreativeModeTabs.putAll(creativeModeTabs);
}
static PreparableReloadListener getReloadListener()
{
return new SimplePreparableReloadListener<JsonObject>()
{
final Gson gson = new GsonBuilder().create();
@NotNull
@Override
protected JsonObject prepare(@NotNull ResourceManager resourceManager, ProfilerFiller profiler)
{
Optional<Resource> res = resourceManager.getResource(CREATIVE_MODE_TAB_ORDERING_JSON);
if (res.isEmpty())
return new JsonObject();
try (Reader reader = res.get().openAsReader())
{
return this.gson.fromJson(reader, JsonObject.class);
}
catch (IOException e)
{
LOGGER.error("Could not read CreativeModeTab sorting file " + CREATIVE_MODE_TAB_ORDERING_JSON, e);
return new JsonObject();
}
}
@Override
protected void apply(@NotNull JsonObject data, @NotNull ResourceManager resourceManager, ProfilerFiller p)
{
try
{
if (data.size() > 0)
{
JsonArray order = GsonHelper.getAsJsonArray(data, "order");
List<CreativeModeTab> customOrder = new ArrayList<>();
for (JsonElement entry : order)
{
ResourceLocation id = new ResourceLocation(entry.getAsString());
CreativeModeTab CreativeModeTab = getTab(id);
if (CreativeModeTab == null)
throw new IllegalStateException("CreativeModeTab not found with name " + id);
customOrder.add(CreativeModeTab);
}
List<CreativeModeTab> missingCreativeModeTabs = creativeModeTabs.values().stream().filter(CreativeModeTab -> !customOrder.contains(CreativeModeTab)).toList();
if (!missingCreativeModeTabs.isEmpty())
throw new IllegalStateException("CreativeModeTabs missing from the ordered list: " + missingCreativeModeTabs.stream()
.map(CreativeModeTab -> Objects.toString(CreativeModeTabRegistry.getName(CreativeModeTab))).collect(Collectors.joining(", ")));
setCreativeModeTabOrder(customOrder);
return;
}
}
catch (Exception e)
{
LOGGER.error("Error parsing CreativeModeTab sorting file " + CREATIVE_MODE_TAB_ORDERING_JSON, e);
}
recalculateItemCreativeModeTabs();
}
};
}
@SuppressWarnings("UnstableApiUsage")
private static void recalculateItemCreativeModeTabs()
{
final MutableGraph<CreativeModeTab> graph = GraphBuilder.directed().nodeOrder(ElementOrder.<CreativeModeTab>insertion()).build();
for (CreativeModeTab CreativeModeTab : creativeModeTabs.values())
{
graph.addNode(CreativeModeTab);
}
edges.forEach((key, value) -> {
if (creativeModeTabs.containsKey(key) && creativeModeTabs.containsKey(value))
graph.putEdge(creativeModeTabs.get(key), creativeModeTabs.get(value));
});
List<CreativeModeTab> tierList = TopologicalSort.topologicalSort(graph, null);
setCreativeModeTabOrder(tierList);
}
private static void setCreativeModeTabOrder(List<CreativeModeTab> tierList)
{
runInServerThreadIfPossible(hasServer -> {
SORTED_TABS.clear();
SORTED_TABS.addAll(tierList);
});
}
private static void runInServerThreadIfPossible(BooleanConsumer runnable)
{
MinecraftServer server = ServerLifecycleHooks.getCurrentServer();
if (server != null)
server.execute(() -> runnable.accept(true));
else
runnable.accept(false);
}
@ApiStatus.Internal
public static void fireCollectionEvent()
{
edges.clear();
edges.putAll(vanillaEdges);
creativeModeTabs.clear();
creativeModeTabs.putAll(vanillaCreativeModeTabs);
ModLoader.get().postEvent(new CreativeModeTabEvent.Register(CreativeModeTabRegistry::registerCreativeModeTab));
recalculateItemCreativeModeTabs();
if (FMLEnvironment.dist == Dist.CLIENT && !FMLLoader.getLaunchHandler().isData())
CreativeModeTabSearchRegistry.createSearchTrees();
}
@ApiStatus.Internal
private static CreativeModeTab registerCreativeModeTab(Consumer<CreativeModeTab.Builder> configurator, ResourceLocation name, List<Object> afterEntries, List<Object> beforeEntries)
{
if (creativeModeTabs.containsKey(name))
throw new IllegalStateException("Duplicate creative mode tab with name: " + name);
// The initial values for the builder do not matter
CreativeModeTab.Builder builder = new CreativeModeTab.Builder(CreativeModeTab.Row.TOP, 0);
configurator.accept(builder);
CreativeModeTab creativeModeTab = builder.build();
if (creativeModeTab.isAlignedRight())
throw new IllegalStateException("CreativeModeTab " + name + " is aligned right, this is not supported!");
processCreativeModeTab(creativeModeTab, name, afterEntries, beforeEntries);
return creativeModeTab;
}
}
@@ -7,17 +7,25 @@ package net.minecraftforge.common;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.Map.Entry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Strings;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
@@ -27,8 +35,6 @@ import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JsonOps;
import com.mojang.serialization.Lifecycle;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
@@ -37,14 +43,24 @@ import net.minecraft.advancements.Advancement;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.core.*;
import net.minecraft.network.chat.*;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Holder;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.ChatDecorator;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.TextColor;
import net.minecraft.network.chat.contents.LiteralContents;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.packs.PackType;
import net.minecraft.tags.BlockTags;
import net.minecraft.tags.TagEntry;
import net.minecraft.tags.TagKey;
import net.minecraft.util.CrudeIncrementalIntIdentityHashBiMap;
import net.minecraft.util.GsonHelper;
import net.minecraft.util.Mth;
import net.minecraft.util.datafix.fixes.StructuresBecomeConfiguredFix;
import net.minecraft.world.Difficulty;
import net.minecraft.world.InteractionHand;
@@ -77,15 +93,11 @@ import net.minecraft.world.level.storage.WorldData;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.storage.loot.LootTables;
import net.minecraft.util.*;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.inventory.AnvilMenu;
import net.minecraft.world.Container;
import net.minecraft.world.item.context.UseOnContext;
@@ -104,12 +116,10 @@ import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSpecialEffects;
import net.minecraft.world.level.biome.BiomeGenerationSettings;
import net.minecraft.world.level.biome.MobSpawnSettings;
import net.minecraftforge.common.crafting.conditions.ICondition;
import net.minecraftforge.common.loot.IGlobalLootModifier;
import net.minecraftforge.common.loot.LootModifierManager;
import net.minecraftforge.common.loot.LootTableIdCondition;
@@ -174,16 +184,13 @@ import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import net.minecraft.ChatFormatting;
import net.minecraft.resources.RegistryResourceAccess;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.RegistryResourceAccess.EntryThunk;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.material.Fluid;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
@@ -215,66 +222,6 @@ public class ForgeHooks
return player.hasCorrectToolForDrops(state);
}
/**
* Called when a player uses 'pick block', calls new Entity and Block hooks.
*/
@SuppressWarnings("resource")
@Deprecated(forRemoval = true, since = "1.19")
public static boolean onPickBlock(HitResult target, Player player, Level level)
{
ItemStack result = ItemStack.EMPTY;
boolean isCreative = player.getAbilities().instabuild;
BlockEntity te = null;
if (target.getType() == HitResult.Type.BLOCK)
{
BlockPos pos = ((BlockHitResult)target).getBlockPos();
BlockState state = level.getBlockState(pos);
if (state.isAir())
return false;
if (isCreative && Screen.hasControlDown() && state.hasBlockEntity())
te = level.getBlockEntity(pos);
result = state.getCloneItemStack(target, level, pos, player);
if (result.isEmpty())
LOGGER.warn("Picking on: [{}] {} gave null item", target.getType(), ForgeRegistries.BLOCKS.getKey(state.getBlock()));
}
else if (target.getType() == HitResult.Type.ENTITY)
{
Entity entity = ((EntityHitResult)target).getEntity();
result = entity.getPickedResult(target);
if (result.isEmpty())
LOGGER.warn("Picking on: [{}] {} gave null item", target.getType(), ForgeRegistries.ENTITY_TYPES.getKey(entity.getType()));
}
if (result.isEmpty())
return false;
if (te != null)
Minecraft.getInstance().addCustomNbtData(result, te);
if (isCreative)
{
player.getInventory().setPickedItem(result);
Minecraft.getInstance().gameMode.handleCreativeModeItemAdd(player.getItemInHand(InteractionHand.MAIN_HAND), 36 + player.getInventory().selected);
return true;
}
int slot = player.getInventory().findSlotMatchingItem(result);
if (slot != -1)
{
if (Inventory.isHotbarSlot(slot))
player.getInventory().selected = slot;
else
Minecraft.getInstance().gameMode.handlePickItem(slot);
return true;
}
return false;
}
public static boolean onItemStackedOn(ItemStack carriedItem, ItemStack stackedOnItem, Slot slot, ClickAction action, Player player, SlotAccess carriedSlotAccess)
{
return MinecraftForge.EVENT_BUS.post(new ItemStackedOnOtherEvent(carriedItem, stackedOnItem, slot, action, player, carriedSlotAccess));
@@ -301,12 +248,12 @@ public class ForgeHooks
{
MinecraftForge.EVENT_BUS.post(new LivingSetAttackTargetEvent(entity, target, targetType));
}
public static LivingChangeTargetEvent onLivingChangeTarget(LivingEntity entity, LivingEntity originalTarget, ILivingTargetType targetType)
{
LivingChangeTargetEvent event = new LivingChangeTargetEvent(entity, originalTarget, targetType);
MinecraftForge.EVENT_BUS.post(event);
return event;
}
@@ -457,71 +404,23 @@ public class ForgeHooks
}
@Nullable
public static Component onServerChatSubmittedEvent(ServerPlayer player, String plain, Component decorated, boolean canChangeMessage)
public static Component onServerChatSubmittedEvent(ServerPlayer player, String plain, Component decorated)
{
ServerChatEvent.Submitted event = new ServerChatEvent.Submitted(player, plain, decorated, canChangeMessage);
ServerChatEvent event = new ServerChatEvent(player, plain, decorated);
return MinecraftForge.EVENT_BUS.post(event) ? null : event.getMessage();
}
private static final ChatDecorator SERVER_CHAT_SUBMITTED_DECORATOR = new ChatDecorator()
{
@NotNull
@Override
public CompletableFuture<Component> decorate(@Nullable ServerPlayer sender, Component message)
{
return CompletableFuture.supplyAsync(() -> {
if (sender == null)
return message; // Vanilla should never get here with the patches we use, but let's be safe with dumb mods
return onServerChatSubmittedEvent(sender, getRawText(message), message, true);
});
}
@NotNull
@Override
public CompletableFuture<PlayerChatMessage> decorate(@Nullable ServerPlayer sender, PlayerChatMessage message)
{
if (message.signedContent().isDecorated())
{
return CompletableFuture.supplyAsync(() -> {
if (sender != null)
return onServerChatSubmittedEvent(sender, message.signedContent().plain(), message.signedContent().decorated(), false) == null;
return false;
}).thenApply(canceled -> canceled == Boolean.TRUE ? null : message);
}
return this.decorate(sender, message.serverContent()).thenApply(component -> component == null ? null : message.withUnsignedContent(component));
}
};
@NotNull
public static ChatDecorator getServerChatSubmittedDecorator()
{
return SERVER_CHAT_SUBMITTED_DECORATOR;
}
@Nullable
public static Component onServerChatPreviewEvent(@NotNull ServerPlayer player, @NotNull Component message)
{
ServerChatEvent.Preview event = new ServerChatEvent.Preview(player, getRawText(message), message);
return MinecraftForge.EVENT_BUS.post(event) ? null : event.getMessage();
}
@NotNull
public static ChatDecorator getServerChatPreviewDecorator()
{
return (player, message) -> CompletableFuture.supplyAsync(() -> {
if (player == null)
return (sender, message) -> CompletableFuture.supplyAsync(() -> {
if (sender == null)
return message; // Vanilla should never get here with the patches we use, but let's be safe with dumb mods
Component preview = onServerChatPreviewEvent(player, message);
// Send the input message back to the client if the event was cancelled
return preview == null ? message : preview;
return onServerChatSubmittedEvent(sender, getRawText(message), message);
});
}
static final Pattern URL_PATTERN = Pattern.compile(
// schema ipv4 OR namespace port path ends
// |-----------------| |-------------------------| |-------------------------| |---------| |--| |---------------|
@@ -615,7 +514,7 @@ public class ForgeHooks
if (!entityPlayer.mayBuild())
{
if (itemstack.isEmpty() || !itemstack.hasAdventureModeBreakTagForBlock(level.registryAccess().registryOrThrow(Registry.BLOCK_REGISTRY), new BlockInWorld(level, pos, false)))
if (itemstack.isEmpty() || !itemstack.hasAdventureModeBreakTagForBlock(level.registryAccess().registryOrThrow(Registries.BLOCK), new BlockInWorld(level, pos, false)))
preCancelEvent = true;
}
}
@@ -658,7 +557,7 @@ public class ForgeHooks
Level level = context.getLevel();
Player player = context.getPlayer();
if (player != null && !player.getAbilities().mayBuild && !itemstack.hasAdventureModePlaceTagForBlock(level.registryAccess().registryOrThrow(Registry.BLOCK_REGISTRY), new BlockInWorld(level, context.getClickedPos(), false)))
if (player != null && !player.getAbilities().mayBuild && !itemstack.hasAdventureModePlaceTagForBlock(level.registryAccess().registryOrThrow(Registries.BLOCK), new BlockInWorld(level, context.getClickedPos(), false)))
return InteractionResult.PASS;
// handle all placement events here
@@ -978,6 +877,11 @@ public class ForgeHooks
};
}
public static Collection<CreativeModeTab> onCheckCreativeTabs(CreativeModeTab... vanillaTabs) {
final List<CreativeModeTab> tabs = new ArrayList<>(Arrays.asList(vanillaTabs));
return tabs;
}
@FunctionalInterface
public interface BiomeCallbackFunction
{
@@ -1340,8 +1244,6 @@ public class ForgeHooks
private static final Set<String> VANILLA_DIMS = Sets.newHashSet("minecraft:overworld", "minecraft:the_nether", "minecraft:the_end");
private static final String DIMENSIONS_KEY = "dimensions";
private static final String SEED_KEY = "seed";
//No to static init!
private static final Supplier<Codec<Registry<LevelStem>>> CODEC = Suppliers.memoize(() -> RegistryCodecs.dataPackAwareCodec(Registry.LEVEL_STEM_REGISTRY, Lifecycle.stable(), LevelStem.CODEC).xmap(LevelStem::sortMap, Function.identity()));
private static final Map<EntityType<? extends LivingEntity>, AttributeSupplier> FORGE_ATTRIBUTES = new HashMap<>();
/** FOR INTERNAL USE ONLY, DO NOT CALL DIRECTLY */
@@ -1665,12 +1567,4 @@ public class ForgeHooks
}
return false;
}
@SuppressWarnings("unchecked")
public static <E> Collection<Entry<ResourceKey<E>, EntryThunk<E>>> filterThunks(Map<ResourceKey<E>, RegistryResourceAccess.EntryThunk<E>> map)
{
return map.entrySet().stream().filter(e ->
((EntryThunk<Boolean>)e.getValue()).parseElement(JsonOps.INSTANCE, ICondition.DECODER)
.get().left().get().value()).toList(); // Validity of this .get() call is enforced by the above Decoder object, which only returns DataResult.success.
}
}
@@ -133,6 +133,7 @@ public class ForgeInternalHandler
public void resourceReloadListeners(AddReloadListenerEvent event)
{
event.addListener(TierSortingRegistry.getReloadListener());
event.addListener(CreativeModeTabRegistry.getReloadListener());
}
}
@@ -11,6 +11,9 @@ import net.minecraft.commands.synchronization.ArgumentTypeInfo;
import net.minecraft.commands.synchronization.ArgumentTypeInfos;
import net.minecraft.commands.synchronization.SingletonArgumentInfo;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.registries.Registries;
import net.minecraft.data.PackOutput;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.Mob;
@@ -29,13 +32,11 @@ import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.item.Items;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.util.ExtraCodecs;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryCodecs;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.pathfinder.BlockPathTypes;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions;
import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent;
import net.minecraftforge.common.crafting.PartialNBTIngredient;
import net.minecraftforge.common.crafting.DifferenceIngredient;
import net.minecraftforge.common.crafting.IntersectionIngredient;
@@ -54,7 +55,6 @@ import net.minecraftforge.common.world.ForgeBiomeModifiers.RemoveSpawnsBiomeModi
import net.minecraftforge.common.world.NoneBiomeModifier;
import net.minecraftforge.common.world.NoneStructureModifier;
import net.minecraftforge.common.world.StructureModifier;
import net.minecraftforge.event.ServerChatEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fluids.FluidType;
import net.minecraftforge.fluids.ForgeFlowingFluid;
@@ -103,9 +103,6 @@ import net.minecraftforge.common.data.ForgeEntityTypeTagsProvider;
import net.minecraftforge.common.data.ForgeItemTagsProvider;
import net.minecraftforge.common.data.ForgeLootTableProvider;
import net.minecraftforge.common.data.ForgeRecipeProvider;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.fml.common.Mod;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
@@ -116,6 +113,7 @@ import com.mojang.serialization.codecs.RecordCodecBuilder;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;
@@ -127,7 +125,7 @@ public class ForgeMod
private static final Marker FORGEMOD = MarkerManager.getMarker("FORGEMOD");
private static final DeferredRegister<Attribute> ATTRIBUTES = DeferredRegister.create(ForgeRegistries.Keys.ATTRIBUTES, "forge");
private static final DeferredRegister<ArgumentTypeInfo<?, ?>> COMMAND_ARGUMENT_TYPES = DeferredRegister.create(Registry.COMMAND_ARGUMENT_TYPE_REGISTRY, "forge");
private static final DeferredRegister<ArgumentTypeInfo<?, ?>> COMMAND_ARGUMENT_TYPES = DeferredRegister.create(Registries.COMMAND_ARGUMENT_TYPE, "forge");
private static final DeferredRegister<Codec<? extends BiomeModifier>> BIOME_MODIFIER_SERIALIZERS = DeferredRegister.create(ForgeRegistries.Keys.BIOME_MODIFIER_SERIALIZERS, "forge");
private static final DeferredRegister<Codec<? extends StructureModifier>> STRUCTURE_MODIFIER_SERIALIZERS = DeferredRegister.create(ForgeRegistries.Keys.STRUCTURE_MODIFIER_SERIALIZERS, "forge");
private static final DeferredRegister<HolderSetType> HOLDER_SET_TYPES = DeferredRegister.create(ForgeRegistries.Keys.HOLDER_SET_TYPES, "forge");
@@ -384,7 +382,6 @@ public class ForgeMod
});
private static boolean enableMilkFluid = false;
private static boolean serverChatPreviewEnabled = false;
public static final RegistryObject<FluidType> MILK_TYPE = RegistryObject.createOptional(new ResourceLocation("milk"), ForgeRegistries.Keys.FLUID_TYPES.location(), "minecraft");
public static final RegistryObject<Fluid> MILK = RegistryObject.create(new ResourceLocation("milk"), ForgeRegistries.FLUIDS);
public static final RegistryObject<Fluid> FLOWING_MILK = RegistryObject.create(new ResourceLocation("flowing_milk"), ForgeRegistries.FLUIDS);
@@ -403,25 +400,6 @@ public class ForgeMod
enableMilkFluid = true;
}
/**
* Run this method during mod constructor to enable chat previews for the server.
* Recommended for mods which modify the chat message in {@link ServerChatEvent}.
*
* @see ServerChatEvent
*/
public static void enableServerChatPreview()
{
serverChatPreviewEnabled = true;
}
/**
* @return {@code true} if server chat previews are enabled
*/
public static boolean isServerChatPreviewEnabled()
{
return serverChatPreviewEnabled;
}
public ForgeMod()
{
LOGGER.info(FORGEMOD,"Forge mod loading, version {}, for MC {} with MCP {}", ForgeVersion.getVersion(), MCPVersion.getMCVersion(), MCPVersion.getMCPVersion());
@@ -438,6 +416,11 @@ public class ForgeMod
CrashReportCallables.registerCrashCallable("Forge", ()->ForgeVersion.getGroup()+":"+ForgeVersion.getVersion());
final IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
// Forge-provided datapack registries
modEventBus.addListener((DataPackRegistryEvent.NewRegistry event) -> {
event.dataPackRegistry(ForgeRegistries.Keys.BIOME_MODIFIERS, BiomeModifier.DIRECT_CODEC);
event.dataPackRegistry(ForgeRegistries.Keys.STRUCTURE_MODIFIERS, StructureModifier.DIRECT_CODEC);
});
modEventBus.addListener(this::preInit);
modEventBus.addListener(this::gatherData);
modEventBus.addListener(this::loadComplete);
@@ -493,16 +476,18 @@ public class ForgeMod
public void gatherData(GatherDataEvent event)
{
DataGenerator gen = event.getGenerator();
PackOutput packOutput = gen.getPackOutput();
CompletableFuture<HolderLookup.Provider> lookupProvider = event.getLookupProvider();
ExistingFileHelper existingFileHelper = event.getExistingFileHelper();
ForgeBlockTagsProvider blockTags = new ForgeBlockTagsProvider(gen, existingFileHelper);
ForgeBlockTagsProvider blockTags = new ForgeBlockTagsProvider(packOutput, lookupProvider, existingFileHelper);
gen.addProvider(event.includeServer(), blockTags);
gen.addProvider(event.includeServer(), new ForgeItemTagsProvider(gen, blockTags, existingFileHelper));
gen.addProvider(event.includeServer(), new ForgeEntityTypeTagsProvider(gen, existingFileHelper));
gen.addProvider(event.includeServer(), new ForgeFluidTagsProvider(gen, existingFileHelper));
gen.addProvider(event.includeServer(), new ForgeRecipeProvider(gen));
gen.addProvider(event.includeServer(), new ForgeLootTableProvider(gen));
gen.addProvider(event.includeServer(), new ForgeBiomeTagsProvider(gen, existingFileHelper));
gen.addProvider(event.includeServer(), new ForgeItemTagsProvider(packOutput, lookupProvider, blockTags, existingFileHelper));
gen.addProvider(event.includeServer(), new ForgeEntityTypeTagsProvider(packOutput, lookupProvider, existingFileHelper));
gen.addProvider(event.includeServer(), new ForgeFluidTagsProvider(packOutput, lookupProvider, existingFileHelper));
gen.addProvider(event.includeServer(), new ForgeRecipeProvider(packOutput));
gen.addProvider(event.includeServer(), new ForgeLootTableProvider(packOutput));
gen.addProvider(event.includeServer(), new ForgeBiomeTagsProvider(packOutput, lookupProvider, existingFileHelper));
}
public void missingSoundMapping(MissingMappingsEvent event)
@@ -595,11 +580,11 @@ public class ForgeMod
public void registerLootData(RegisterEvent event)
{
if (!event.getRegistryKey().equals(Registry.LOOT_ITEM_REGISTRY))
if (!event.getRegistryKey().equals(Registries.LOOT_CONDITION_TYPE))
return;
event.register(Registry.LOOT_ITEM_REGISTRY, new ResourceLocation("forge:loot_table_id"), () -> LootTableIdCondition.LOOT_TABLE_ID);
event.register(Registry.LOOT_ITEM_REGISTRY, new ResourceLocation("forge:can_tool_perform_action"), () -> CanToolPerformAction.LOOT_CONDITION_TYPE);
event.register(Registries.LOOT_CONDITION_TYPE, new ResourceLocation("forge:loot_table_id"), () -> LootTableIdCondition.LOOT_TABLE_ID);
event.register(Registries.LOOT_CONDITION_TYPE, new ResourceLocation("forge:can_tool_perform_action"), () -> CanToolPerformAction.LOOT_CONDITION_TYPE);
}
public static final PermissionNode<Boolean> USE_SELECTORS_PERMISSION = new PermissionNode<>("forge", "use_entity_selectors",
@@ -63,7 +63,10 @@ public class ForgeSpawnEggItem extends SpawnEggItem
return ret != null ? ret : SpawnEggItem.byId(type);
}
@Override
protected EntityType<?> getDefaultType() {
return this.typeSupplier.get();
}
private static final DispenseItemBehavior DEFAULT_DISPENSE_BEHAVIOR = (source, stack) ->
{
@@ -6,6 +6,7 @@
package net.minecraftforge.common;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.BiomeTags;
import net.minecraft.tags.BlockTags;
@@ -191,7 +192,7 @@ public class Tags
private static TagKey<EntityType<?>> tag(String name)
{
return TagKey.create(Registry.ENTITY_TYPE_REGISTRY, new ResourceLocation("forge", name));
return TagKey.create(Registries.ENTITY_TYPE, new ResourceLocation("forge", name));
}
}
@@ -614,7 +615,7 @@ public class Tags
private static TagKey<Biome> tag(String name)
{
return TagKey.create(Registry.BIOME_REGISTRY, new ResourceLocation("forge", name));
return TagKey.create(Registries.BIOME, new ResourceLocation("forge", name));
}
}
}
@@ -5,11 +5,8 @@
package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.DataResult;
import com.mojang.serialization.Decoder;
import com.mojang.serialization.DynamicOps;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceKey;
@@ -24,27 +21,13 @@ import java.util.Set;
public interface ICondition
{
static boolean shouldRegisterEntry(JsonElement json)
{
if (!(json instanceof JsonObject obj) || !obj.has("forge:conditions"))
return true;
Decoder<Boolean> DECODER = new Decoder<>() {
@Override
public <T> DataResult<Pair<Boolean, T>> decode(DynamicOps<T> ops, T input)
{
if(input instanceof JsonObject obj && obj.has("forge:conditions"))
{
try
{
boolean result = CraftingHelper.processConditions(obj, "forge:conditions", IContext.TAGS_INVALID);
return DataResult.success(Pair.of(result, input));
}
catch(Exception ex)
{
ex.printStackTrace();
return DataResult.success(Pair.of(false, input)); // Print stacktrace and do not load errored conditions.
}
}
return DataResult.success(Pair.of(true, input));
}
};
return CraftingHelper.processConditions(obj, "forge:conditions", IContext.TAGS_INVALID);
}
ResourceLocation getID();
@@ -8,6 +8,7 @@ package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonObject;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
import net.minecraft.util.GsonHelper;
@@ -30,7 +31,7 @@ public class TagEmptyCondition implements ICondition
public TagEmptyCondition(ResourceLocation tag)
{
this.tag = TagKey.create(Registry.ITEM_REGISTRY, tag);
this.tag = TagKey.create(Registries.ITEM, tag);
}
@Override
@@ -0,0 +1,23 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.data;
import java.util.concurrent.CompletableFuture;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.registries.Registries;
import net.minecraft.data.PackOutput;
import net.minecraft.data.tags.IntrinsicHolderTagsProvider;
import net.minecraft.world.level.block.Block;
import org.jetbrains.annotations.Nullable;
public abstract class BlockTagsProvider extends IntrinsicHolderTagsProvider<Block>
{
@SuppressWarnings("deprecation")
public BlockTagsProvider(PackOutput output, CompletableFuture<HolderLookup.Provider> lookupProvider, String modId, @Nullable ExistingFileHelper existingFileHelper)
{
super(output, Registries.BLOCK, lookupProvider, block -> block.builtInRegistryHolder().key(), modId, existingFileHelper);
}
}
@@ -0,0 +1,28 @@
package net.minecraftforge.common.data;
import net.minecraft.Util;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.RegistrySetBuilder;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.data.PackOutput;
import net.minecraft.data.registries.RegistriesDatapackGenerator;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
public class DatapackBuiltinEntriesProvider extends RegistriesDatapackGenerator
{
public DatapackBuiltinEntriesProvider(PackOutput output, Supplier<HolderLookup.Provider> registriesSupplier)
{
super(output, CompletableFuture.supplyAsync(registriesSupplier, Util.backgroundExecutor()));
}
public DatapackBuiltinEntriesProvider(PackOutput output, RegistrySetBuilder datapackEntriesBuilder)
{
this(output, () -> createLookup(datapackEntriesBuilder));
}
public static HolderLookup.Provider createLookup(RegistrySetBuilder datapackEntriesBuilder) {
return datapackEntriesBuilder.build(RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY));
}
}
@@ -18,12 +18,10 @@ import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import net.minecraft.client.resources.ClientPackSource;
import net.minecraft.client.resources.AssetIndex;
import net.minecraft.client.resources.DefaultClientPackResources;
import net.minecraft.client.resources.IndexedAssetSource;
import net.minecraft.data.DataProvider;
import net.minecraft.data.HashCache;
import net.minecraft.server.packs.FilePackResources;
import net.minecraft.server.packs.FolderPackResources;
import net.minecraft.server.packs.PathPackResources;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.server.packs.resources.Resource;
@@ -98,15 +96,14 @@ public class ExistingFileHelper {
List<PackResources> candidateClientResources = new ArrayList<>();
List<PackResources> candidateServerResources = new ArrayList<>();
candidateClientResources.add(new VanillaPackResources(ClientPackSource.BUILT_IN, "minecraft", "realms"));
if (assetIndex != null && assetsDir != null)
if (assetIndex != null && assetsDir != null && assetsDir.exists())
{
candidateClientResources.add(new DefaultClientPackResources(ClientPackSource.BUILT_IN, new AssetIndex(assetsDir, assetIndex)));
candidateClientResources.add(ClientPackSource.createVanillaPackSource(IndexedAssetSource.createIndexFs(assetsDir.toPath(), assetIndex)));
}
candidateServerResources.add(new VanillaPackResources(ServerPacksSource.BUILT_IN_METADATA, "minecraft"));
candidateServerResources.add(ServerPacksSource.createVanillaPackSource());
for (Path existing : existingPacks) {
File file = existing.toFile();
PackResources pack = file.isDirectory() ? new FolderPackResources(file) : new FilePackResources(file);
PackResources pack = file.isDirectory() ? new PathPackResources(file.getName(), file.toPath(), false) : new FilePackResources(file.getName(), file, false);
candidateClientResources.add(pack);
candidateServerResources.add(pack);
}
@@ -5,7 +5,8 @@
package net.minecraftforge.common.data;
import net.minecraft.data.DataGenerator;
import net.minecraft.core.HolderLookup;
import net.minecraft.data.PackOutput;
import net.minecraft.data.tags.BiomeTagsProvider;
import net.minecraft.resources.ResourceKey;
import net.minecraft.tags.BiomeTags;
@@ -14,16 +15,18 @@ import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biomes;
import net.minecraftforge.common.Tags;
import java.util.concurrent.CompletableFuture;
public final class ForgeBiomeTagsProvider extends BiomeTagsProvider
{
public ForgeBiomeTagsProvider(DataGenerator arg, ExistingFileHelper existingFileHelper)
public ForgeBiomeTagsProvider(PackOutput output, CompletableFuture<HolderLookup.Provider> lookupProvider, ExistingFileHelper existingFileHelper)
{
super(arg, "forge", existingFileHelper);
super(output, lookupProvider, "forge", existingFileHelper);
}
@Override
protected void addTags()
protected void addTags(HolderLookup.Provider lookupProvider)
{
tag(Biomes.PLAINS, Tags.Biomes.IS_PLAINS);
tag(Biomes.DESERT, Tags.Biomes.IS_HOT_OVERWORLD, Tags.Biomes.IS_DRY_OVERWORLD, Tags.Biomes.IS_SANDY, Tags.Biomes.IS_DESERT);
@@ -5,8 +5,10 @@
package net.minecraftforge.common.data;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.tags.BlockTagsProvider;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.registries.Registries;
import net.minecraft.data.PackOutput;
import net.minecraft.data.tags.IntrinsicHolderTagsProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.BlockTags;
import net.minecraft.tags.TagKey;
@@ -15,22 +17,24 @@ import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraftforge.common.Tags;
import net.minecraftforge.registries.ForgeRegistries;
import org.jetbrains.annotations.Nullable;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import static net.minecraftforge.common.Tags.Blocks.*;
public final class ForgeBlockTagsProvider extends BlockTagsProvider
{
public ForgeBlockTagsProvider(DataGenerator gen, ExistingFileHelper existingFileHelper)
public ForgeBlockTagsProvider(PackOutput output, CompletableFuture<HolderLookup.Provider> lookupProvider, @Nullable ExistingFileHelper existingFileHelper)
{
super(gen, "forge", existingFileHelper);
super(output, lookupProvider, "forge", existingFileHelper);
}
@SuppressWarnings("unchecked")
@Override
public void addTags()
public void addTags(HolderLookup.Provider p_256380_)
{
tag(BARRELS).addTag(BARRELS_WOODEN);
tag(BARRELS_WOODEN).add(Blocks.BARREL);
@@ -5,21 +5,24 @@
package net.minecraftforge.common.data;
import net.minecraft.data.DataGenerator;
import net.minecraft.core.HolderLookup;
import net.minecraft.data.PackOutput;
import net.minecraft.data.tags.EntityTypeTagsProvider;
import net.minecraft.world.entity.EntityType;
import net.minecraftforge.common.Tags;
import java.util.concurrent.CompletableFuture;
public class ForgeEntityTypeTagsProvider extends EntityTypeTagsProvider
{
public ForgeEntityTypeTagsProvider(DataGenerator generator, ExistingFileHelper existingFileHelper)
public ForgeEntityTypeTagsProvider(PackOutput output, CompletableFuture<HolderLookup.Provider> lookupProvider, ExistingFileHelper existingFileHelper)
{
super(generator, "forge", existingFileHelper);
super(output, lookupProvider, "forge", existingFileHelper);
}
@Override
public void addTags()
public void addTags(HolderLookup.Provider lookupProvider)
{
tag(Tags.EntityTypes.BOSSES).add(EntityType.ENDER_DRAGON, EntityType.WITHER);
}
@@ -5,21 +5,24 @@
package net.minecraftforge.common.data;
import net.minecraft.data.DataGenerator;
import net.minecraft.core.HolderLookup;
import net.minecraft.data.PackOutput;
import net.minecraft.data.tags.FluidTagsProvider;
import net.minecraftforge.common.ForgeMod;
import java.util.concurrent.CompletableFuture;
import static net.minecraftforge.common.Tags.Fluids.MILK;
public final class ForgeFluidTagsProvider extends FluidTagsProvider
{
public ForgeFluidTagsProvider(DataGenerator gen, ExistingFileHelper existingFileHelper)
public ForgeFluidTagsProvider(PackOutput output, CompletableFuture<HolderLookup.Provider> lookupProvider, ExistingFileHelper existingFileHelper)
{
super(gen, "forge", existingFileHelper);
super(output, lookupProvider, "forge", existingFileHelper);
}
@Override
public void addTags()
public void addTags(HolderLookup.Provider lookupProvider)
{
tag(MILK).addOptional(ForgeMod.MILK.getId()).addOptional(ForgeMod.FLOWING_MILK.getId());
}
@@ -5,9 +5,10 @@
package net.minecraftforge.common.data;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.tags.BlockTagsProvider;
import net.minecraft.core.HolderLookup;
import net.minecraft.data.PackOutput;
import net.minecraft.data.tags.ItemTagsProvider;
import net.minecraft.data.tags.TagsProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.DyeColor;
@@ -18,18 +19,19 @@ import net.minecraftforge.common.Tags;
import net.minecraftforge.registries.ForgeRegistries;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
public final class ForgeItemTagsProvider extends ItemTagsProvider
{
public ForgeItemTagsProvider(DataGenerator gen, BlockTagsProvider blockTagProvider, ExistingFileHelper existingFileHelper)
public ForgeItemTagsProvider(PackOutput output, CompletableFuture<HolderLookup.Provider> lookupProvider, TagsProvider<Block> blockTagProvider, ExistingFileHelper existingFileHelper)
{
super(gen, blockTagProvider, "forge", existingFileHelper);
super(output, lookupProvider, blockTagProvider, "forge", existingFileHelper);
}
@SuppressWarnings("unchecked")
@Override
public void addTags()
public void addTags(HolderLookup.Provider lookupProvider)
{
copy(Tags.Blocks.BARRELS, Tags.Items.BARRELS);
copy(Tags.Blocks.BARRELS_WOODEN, Tags.Items.BARRELS_WOODEN);
@@ -5,10 +5,11 @@
package net.minecraftforge.common.data;
import com.mojang.datafixers.util.Pair;
import net.minecraft.advancements.critereon.ItemPredicate;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.PackOutput;
import net.minecraft.data.loot.LootTableProvider;
import net.minecraft.data.loot.LootTableSubProvider;
import net.minecraft.data.loot.packs.VanillaLootTableProvider;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.Items;
import net.minecraft.resources.ResourceLocation;
@@ -24,9 +25,6 @@ import net.minecraftforge.fml.util.ObfuscationReflectionHelper;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import net.minecraft.world.level.storage.loot.LootPool;
@@ -34,32 +32,30 @@ import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.storage.loot.ValidationContext;
import net.minecraft.world.level.storage.loot.entries.CompositeEntryBase;
import net.minecraft.world.level.storage.loot.entries.LootPoolEntryContainer;
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSet;
/**
* Currently used only for replacing shears item to shears_dig tool action
*/
public final class ForgeLootTableProvider extends LootTableProvider {
public ForgeLootTableProvider(DataGenerator gen) {
super(gen);
public ForgeLootTableProvider(PackOutput packOutput) {
super(packOutput, Set.of(), VanillaLootTableProvider.create(packOutput).getTables());
}
@Override
protected void validate(Map<ResourceLocation, LootTable> map, ValidationContext validationtracker) {
// do not validate against all registered loot tables
protected void validate(Map<ResourceLocation, LootTable> map, ValidationContext validationcontext) {
// Do not validate against all registered loot tables
}
@Override
protected List<Pair<Supplier<Consumer<BiConsumer<ResourceLocation, LootTable.Builder>>>, LootContextParamSet>> getTables() {
return super.getTables().stream().map(pair -> {
// provides new consumer with filtering only changed loot tables and replacing condition item to condition tag
return new Pair<Supplier<Consumer<BiConsumer<ResourceLocation, LootTable.Builder>>>, LootContextParamSet>(() -> replaceAndFilterChangesOnly(pair.getFirst().get()), pair.getSecond());
public List<LootTableProvider.SubProviderEntry> getTables() {
return super.getTables().stream().map(entry -> {
// Provides new sub provider with filtering only changed loot tables and replacing condition item to condition tag
return new LootTableProvider.SubProviderEntry(() -> replaceAndFilterChangesOnly(entry.provider().get()), entry.paramSet());
}).collect(Collectors.toList());
}
private Consumer<BiConsumer<ResourceLocation, LootTable.Builder>> replaceAndFilterChangesOnly(Consumer<BiConsumer<ResourceLocation, LootTable.Builder>> consumer) {
return (newConsumer) -> consumer.accept((resourceLocation, builder) -> {
private LootTableSubProvider replaceAndFilterChangesOnly(LootTableSubProvider subProvider) {
return newConsumer -> subProvider.generate((resourceLocation, builder) -> {
if (findAndReplaceInLootTableBuilder(builder, Items.SHEARS, ToolActions.SHEARS_DIG)) {
newConsumer.accept(resourceLocation, builder);
}
@@ -6,12 +6,13 @@
package net.minecraftforge.common.data;
import com.google.gson.JsonObject;
import net.minecraft.advancements.Advancement;
import net.minecraft.data.CachedOutput;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.PackOutput;
import net.minecraft.data.recipes.FinishedRecipe;
import net.minecraft.data.recipes.RecipeProvider;
import net.minecraft.data.recipes.ShapedRecipeBuilder;
import net.minecraft.data.recipes.ShapelessRecipeBuilder;
import net.minecraft.data.recipes.packs.VanillaRecipeProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
@@ -30,16 +31,17 @@ import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
public final class ForgeRecipeProvider extends RecipeProvider
public final class ForgeRecipeProvider extends VanillaRecipeProvider
{
private final Map<Item, TagKey<Item>> replacements = new HashMap<>();
private final Set<ResourceLocation> excludes = new HashSet<>();
public ForgeRecipeProvider(DataGenerator generatorIn)
public ForgeRecipeProvider(PackOutput packOutput)
{
super(generatorIn);
super(packOutput);
}
private void exclude(ItemLike item)
@@ -53,7 +55,7 @@ public final class ForgeRecipeProvider extends RecipeProvider
}
@Override
protected void buildCraftingRecipes(Consumer<FinishedRecipe> consumer)
protected void buildRecipes(Consumer<FinishedRecipe> consumer)
{
replace(Items.STICK, Tags.Items.RODS_WOODEN);
replace(Items.GOLD_INGOT, Tags.Items.INGOTS_GOLD);
@@ -84,7 +86,7 @@ public final class ForgeRecipeProvider extends RecipeProvider
exclude(Blocks.COBBLED_DEEPSLATE_SLAB);
exclude(Blocks.COBBLED_DEEPSLATE_WALL);
super.buildCraftingRecipes(vanilla -> {
super.buildRecipes(vanilla -> {
FinishedRecipe modified = enhance(vanilla);
if (modified != null)
consumer.accept(modified);
@@ -118,10 +120,19 @@ public final class ForgeRecipeProvider extends RecipeProvider
return modified ? vanilla : null;
}
@Nullable
@Override
protected void saveAdvancement(CachedOutput output, JsonObject advancementJson, Path pathIn)
protected CompletableFuture<?> saveAdvancement(CachedOutput output, FinishedRecipe finishedRecipe, JsonObject advancementJson)
{
//NOOP - We dont replace any of the advancement things yet...
// NOOP - We don't replace any of the advancement things yet...
return null;
}
@Override
protected CompletableFuture<?> buildAdvancement(CachedOutput p_253674_, ResourceLocation p_254102_, Advancement.Builder p_253712_)
{
// NOOP - We don't replace any of the advancement things yet...
return CompletableFuture.allOf();
}
@Nullable
@@ -1,31 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.data;
import com.mojang.serialization.Lifecycle;
import net.minecraft.core.Registry;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.tags.TagsProvider;
import net.minecraftforge.registries.GameData;
import net.minecraftforge.registries.IForgeRegistry;
import org.jetbrains.annotations.Nullable;
public abstract class ForgeRegistryTagsProvider<T> extends TagsProvider<T>
{
private static <T> Registry<T> wrapRegistry(IForgeRegistry<T> forgeRegistry)
{
if (forgeRegistry.tags() == null)
throw new IllegalArgumentException("Forge registry " + forgeRegistry.getRegistryName() + " does not have support for tags");
if (forgeRegistry.getDefaultKey() == null)
return GameData.getWrapper(forgeRegistry.getRegistryKey(), Lifecycle.experimental());
return GameData.getWrapper(forgeRegistry.getRegistryKey(), Lifecycle.experimental(), "default");
}
public ForgeRegistryTagsProvider(DataGenerator generator, IForgeRegistry<T> forgeRegistry, String modId, @Nullable ExistingFileHelper existingFileHelper)
{
super(generator, wrapRegistry(forgeRegistry), modId, existingFileHelper);
}
}
@@ -5,6 +5,7 @@
package net.minecraftforge.common.data;
import com.google.common.collect.ImmutableList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
@@ -14,6 +15,7 @@ import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
import net.minecraft.data.CachedOutput;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.DataProvider;
import net.minecraft.data.PackOutput;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.loot.IGlobalLootModifier;
import net.minecraftforge.common.loot.LootModifier;
@@ -24,6 +26,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
/**
@@ -59,26 +62,30 @@ public abstract class GlobalLootModifierProvider implements DataProvider
protected abstract void start();
@Override
public void run(CachedOutput cache) throws IOException
public CompletableFuture<?> run(CachedOutput cache)
{
start();
Path forgePath = gen.getOutputFolder().resolve("data/forge/loot_modifiers/global_loot_modifiers.json");
String modPath = "data/" + modid + "/loot_modifiers/";
Path forgePath = this.gen.getPackOutput().getOutputFolder(PackOutput.Target.DATA_PACK).resolve("forge").resolve("loot_modifiers").resolve("global_loot_modifiers.json");
Path modifierFolderPath = this.gen.getPackOutput().getOutputFolder(PackOutput.Target.DATA_PACK).resolve(this.modid).resolve("loot_modifiers");
List<ResourceLocation> entries = new ArrayList<>();
ImmutableList.Builder<CompletableFuture<?>> futuresBuilder = new ImmutableList.Builder<>();
toSerialize.forEach(LamdbaExceptionUtils.rethrowBiConsumer((name, json) ->
{
entries.add(new ResourceLocation(modid, name));
Path modifierPath = gen.getOutputFolder().resolve(modPath + name + ".json");
DataProvider.saveStable(cache, json, modifierPath);
Path modifierPath = modifierFolderPath.resolve(name + ".json");
futuresBuilder.add(DataProvider.saveStable(cache, json, modifierPath));
}));
JsonObject forgeJson = new JsonObject();
forgeJson.addProperty("replace", this.replace);
forgeJson.add("entries", GSON.toJsonTree(entries.stream().map(ResourceLocation::toString).collect(Collectors.toList())));
DataProvider.saveStable(cache, forgeJson, forgePath);
futuresBuilder.add(DataProvider.saveStable(cache, forgeJson, forgePath));
return CompletableFuture.allOf(futuresBuilder.build().toArray(CompletableFuture[]::new));
}
/**
@@ -5,25 +5,26 @@
package net.minecraftforge.common.data;
import com.mojang.logging.LogUtils;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Map;
import com.google.common.collect.ImmutableList;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.logging.LogUtils;
import com.mojang.serialization.Codec;
import com.mojang.serialization.DynamicOps;
import com.mojang.serialization.JsonOps;
import java.util.function.BiConsumer;
import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.data.CachedOutput;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.DataProvider;
import net.minecraft.data.PackOutput;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.resources.RegistryOps;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
@@ -31,6 +32,8 @@ import net.minecraft.server.packs.PackType;
import net.minecraftforge.common.crafting.CraftingHelper;
import net.minecraftforge.common.crafting.conditions.ICondition;
import net.minecraftforge.common.data.ExistingFileHelper.ResourceType;
import net.minecraftforge.data.event.GatherDataEvent;
import net.minecraftforge.registries.DataPackRegistriesHooks;
import org.slf4j.Logger;
/**
@@ -57,7 +60,7 @@ public class JsonCodecProvider<T> implements DataProvider
/**
* @param dataGenerator DataGenerator provided by {@link GatherDataEvent}.
* @param dynamicOps DynamicOps to encode values to jsons with using the provided Codec, e.g. {@link JsonOps.INSTANCE}.
* @param dynamicOps DynamicOps to encode values to jsons with using the provided Codec, e.g. {@link JsonOps#INSTANCE}.
* @param packType PackType specifying whether to generate entries in assets or data.
* @param directory String representing the directory to generate jsons in, e.g. "dimension" or "cheesemod/cheese".
* @param codec Codec to encode values to jsons with using the provided DynamicOps.
@@ -95,6 +98,7 @@ public class JsonCodecProvider<T> implements DataProvider
* @param registryKey ResourceKey identifying the registry and its directory.
* @param entries Map of entries to encode and their ResourceLocations. Paths for values are derived from the ResourceLocation's entryid:entrypath.
*/
@SuppressWarnings("unchecked")
public static <T> JsonCodecProvider<T> forDatapackRegistry(DataGenerator dataGenerator, ExistingFileHelper existingFileHelper, String modid,
RegistryOps<JsonElement> registryOps, ResourceKey<Registry<T>> registryKey, Map<ResourceLocation, T> entries)
{
@@ -104,21 +108,25 @@ public class JsonCodecProvider<T> implements DataProvider
final String registryFolder = registryId.getNamespace().equals("minecraft")
? registryId.getPath()
: registryId.getNamespace() + "/" + registryId.getPath();
final Codec<T> codec = (Codec<T>) RegistryAccess.REGISTRIES.get(registryKey).codec();
RegistryDataLoader.RegistryData<?> registryData = DataPackRegistriesHooks.getDataPackRegistries().stream().filter(data -> data.key() == registryKey).findAny().orElseThrow();
final Codec<T> codec = (Codec<T>) registryData.elementCodec();
return new JsonCodecProvider<>(dataGenerator, existingFileHelper, modid, registryOps, PackType.SERVER_DATA, registryFolder, codec, entries);
}
@Override
public void run(final CachedOutput cache) throws IOException
public CompletableFuture<?> run(final CachedOutput cache)
{
final Path outputFolder = this.dataGenerator.getOutputFolder();
final String dataFolder = this.packType.getDirectory();
final Path outputFolder = this.dataGenerator.getPackOutput().getOutputFolder(this.packType == PackType.CLIENT_RESOURCES
? PackOutput.Target.RESOURCE_PACK
: PackOutput.Target.DATA_PACK);
ImmutableList.Builder<CompletableFuture<?>> futuresBuilder = new ImmutableList.Builder<>();
gather(LamdbaExceptionUtils.rethrowBiConsumer((id, value) -> {
final Path path = outputFolder.resolve(String.join("/", dataFolder, id.getNamespace(), this.directory, id.getPath() + ".json"));
final Path path = outputFolder.resolve(id.getNamespace()).resolve(this.directory).resolve(id.getPath() + ".json");
JsonElement encoded = this.codec.encodeStart(this.dynamicOps, value)
.getOrThrow(false, msg -> LOGGER.error("Failed to encode {}: {}", path, msg));
ICondition[] conditions = this.conditions.get(id);
if (conditions != null && conditions.length > 0)
if (conditions != null && conditions.length > 0)
{
if(encoded instanceof JsonObject obj)
{
@@ -129,8 +137,10 @@ public class JsonCodecProvider<T> implements DataProvider
LOGGER.error("Attempted to apply conditions to a type that is not a JsonObject! - Path: {}", path);
}
}
DataProvider.saveStable(cache, encoded, path);
futuresBuilder.add(DataProvider.saveStable(cache, encoded, path));
}));
return CompletableFuture.allOf(futuresBuilder.build().toArray(CompletableFuture[]::new));
}
protected void gather(BiConsumer<ResourceLocation, T> consumer)
@@ -5,36 +5,24 @@
package net.minecraftforge.common.data;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import com.google.gson.JsonObject;
import java.nio.file.Path;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import com.google.common.hash.Hashing;
import com.google.gson.JsonObject;
import net.minecraft.data.CachedOutput;
import org.apache.commons.lang3.text.translate.JavaUnicodeEscaper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minecraft.world.level.block.Block;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.HashCache;
import net.minecraft.data.DataProvider;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.data.PackOutput;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.level.block.Block;
@SuppressWarnings("deprecation")
public abstract class LanguageProvider implements DataProvider {
private static final Gson GSON = (new GsonBuilder()).setPrettyPrinting().disableHtmlEscaping().setLenient().create();
private final Map<String, String> data = new TreeMap<>();
private final DataGenerator gen;
private final String modid;
@@ -49,10 +37,13 @@ public abstract class LanguageProvider implements DataProvider {
protected abstract void addTranslations();
@Override
public void run(CachedOutput cache) throws IOException {
public CompletableFuture<?> run(CachedOutput cache) {
addTranslations();
if (!data.isEmpty())
save(cache, data, this.gen.getOutputFolder().resolve("assets/" + modid + "/lang/" + locale + ".json"));
return save(cache, this.gen.getPackOutput().getOutputFolder(PackOutput.Target.RESOURCE_PACK).resolve(this.modid).resolve("lang").resolve(this.locale + ".json"));
return CompletableFuture.allOf();
}
@Override
@@ -60,14 +51,12 @@ public abstract class LanguageProvider implements DataProvider {
return "Languages: " + locale;
}
private void save(CachedOutput cache, Object object, Path target) throws IOException {
private CompletableFuture<?> save(CachedOutput cache, Path target) {
// TODO: DataProvider.saveStable handles the caching and hashing already, but creating the JSON Object this way seems unreliable. -C
JsonObject json = new JsonObject();
for (Map.Entry<String, String> pair : data.entrySet()) {
json.addProperty(pair.getKey(), pair.getValue());
}
this.data.forEach(json::addProperty);
DataProvider.saveStable(cache, json, target);
return DataProvider.saveStable(cache, json, target);
}
public void addBlock(Supplier<? extends Block> key, String name) {
@@ -5,13 +5,17 @@
package net.minecraftforge.common.data;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import net.minecraft.data.CachedOutput;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.HashCache;
import net.minecraft.data.DataProvider;
import net.minecraft.data.PackOutput;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.PackType;
import net.minecraft.sounds.SoundEvent;
@@ -19,14 +23,6 @@ import net.minecraftforge.registries.ForgeRegistries;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* Data provider for the {@code sounds.json} file, which identifies sound definitions
* for the various sound events in Minecraft.
@@ -34,7 +30,6 @@ import java.util.stream.Collectors;
public abstract class SoundDefinitionsProvider implements DataProvider
{
private static final Logger LOGGER = LogManager.getLogger();
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
private final DataGenerator generator;
private final String modId;
private final ExistingFileHelper helper;
@@ -61,15 +56,17 @@ public abstract class SoundDefinitionsProvider implements DataProvider
public abstract void registerSounds();
@Override
public void run(CachedOutput cache) throws IOException
public CompletableFuture<?> run(CachedOutput cache)
{
this.sounds.clear();
this.registerSounds();
this.validate();
if (!this.sounds.isEmpty())
{
this.save(cache, this.generator.getOutputFolder().resolve("assets/" + this.modId + "/sounds.json"));
return this.save(cache, this.generator.getPackOutput().getOutputFolder(PackOutput.Target.RESOURCE_PACK).resolve(this.modId).resolve("sounds.json"));
}
return CompletableFuture.allOf();
}
@Override
@@ -208,7 +205,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
.filter(it -> !this.validate(it.getKey(), it.getValue()))
.map(Map.Entry::getKey)
.map(it -> this.modId + ":" + it)
.collect(Collectors.toList());
.toList();
if (!notValid.isEmpty())
{
throw new IllegalStateException("Found invalid sound events: " + notValid);
@@ -228,7 +225,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
case EVENT: return this.validateEvent(name, sound.name());
}
// Differently from all the other errors, this is not a 'missing sound' but rather something completely different
// that has broken the invariants of this sound definitions provider. In fact, a sound may only be either of
// that has broken the invariants of this sound definition's provider. In fact, a sound may only be either of
// SOUND or EVENT type. Any other values is somebody messing with the internals, reflectively adding something
// to an enum or passing `null` to a parameter annotated with `@NotNull`.
throw new IllegalArgumentException("The given sound '" + sound.name() + "' does not have a valid type: expected either SOUND or EVENT, but found " + sound.type());
@@ -255,9 +252,9 @@ public abstract class SoundDefinitionsProvider implements DataProvider
return valid;
}
private void save(final CachedOutput cache, final Path targetFile) throws IOException
private CompletableFuture<?> save(final CachedOutput cache, final Path targetFile)
{
DataProvider.saveStable(cache, this.mapToJson(this.sounds), targetFile);
return DataProvider.saveStable(cache, this.mapToJson(this.sounds), targetFile);
}
private JsonObject mapToJson(final Map<String, SoundDefinition> map)
@@ -205,7 +205,7 @@ public interface IForgeBlock
{
if (isBed(state, levelReader, pos, entity) && levelReader instanceof Level level && BedBlock.canSetSpawn(level))
{
return BedBlock.findStandUpPosition(type, levelReader, pos, orientation);
return BedBlock.findStandUpPosition(type, levelReader, pos, state.getValue(BedBlock.FACING), orientation);
}
return Optional.empty();
}
@@ -10,6 +10,8 @@ import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.EnchantmentCategory;
import java.util.Set;
public interface IForgeEnchantment
{
@@ -31,25 +33,15 @@ public interface IForgeEnchantment
return self().getDamageBonus(level, mobType);
}
/**
* Determines what creative tabs this enchantment's variant of an enchanted book or similar item should appear in.
* @param book The item being added to the creative tab
* @param tab The creative tab that items are being added to
* @return whether the given Item's variant for this enchantment should appear in the respective creative tab
*/
default boolean allowedInCreativeTab(Item book, CreativeModeTab tab)
{
if (!self().isAllowedOnBooks())
{
return false;
}
else if (tab == CreativeModeTab.TAB_SEARCH)
{
return self().category != null;
}
else
{
return tab.hasEnchantmentCategory(self().category);
}
}
/**
* Determines whether item variants of this enchantment can be added to a given creative tab with the allowed categories.
*
* @param book the item being added to the creative tab
* @param allowedCategories the enchantment categories allowed in the creative tab
* @return whether item variants of this enchantment can be added to a given creative tab with the allowed categories
*/
default boolean allowedInCreativeTab(Item book, Set<EnchantmentCategory> allowedCategories)
{
return self().isAllowedOnBooks() && allowedCategories.contains(self().category);
}
}
@@ -11,6 +11,7 @@ import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Fluid;
@@ -72,13 +73,13 @@ public interface IForgeFluid
* Returns whether the fluid can create a source.
*
* @param state the state of the fluid
* @param reader the reader that can get the fluid
* @param level the level that can get the fluid
* @param pos the location of the fluid
* @return {@code true} if the fluid can create a source, {@code false} otherwise
*/
default boolean canConvertToSource(FluidState state, LevelReader reader, BlockPos pos)
default boolean canConvertToSource(FluidState state, Level level, BlockPos pos)
{
return getFluidType().canConvertToSource(state, reader, pos);
return getFluidType().canConvertToSource(state, level, pos);
}
/**
@@ -11,6 +11,7 @@ import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.FluidState;
@@ -67,13 +68,13 @@ public interface IForgeFluidState
/**
* Returns whether the fluid can create a source.
*
* @param reader the reader that can get the fluid
* @param level the level that can get the fluid
* @param pos the location of the fluid
* @return {@code true} if the fluid can create a source, {@code false} otherwise
*/
default boolean canConvertToSource(LevelReader reader, BlockPos pos)
default boolean canConvertToSource(Level level, BlockPos pos)
{
return self().getType().canConvertToSource(self(), reader, pos);
return self().getType().canConvertToSource(self(), level, pos);
}
/**
@@ -0,0 +1,47 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.extensions;
import net.minecraft.data.tags.IntrinsicHolderTagsProvider;
import net.minecraft.data.tags.TagsProvider;
import net.minecraft.resources.ResourceKey;
public interface IForgeIntrinsicHolderTagAppender<T> extends IForgeTagAppender<T>
{
private IntrinsicHolderTagsProvider.IntrinsicTagAppender<T> self() {
return (IntrinsicHolderTagsProvider.IntrinsicTagAppender<T>) this;
}
ResourceKey<T> getKey(T value);
/**
* Adds a registry entry to the tag json's remove list. Callable during datageneration.
*
* @param entry The entry to remove
* @return The builder for chaining
*/
default TagsProvider.TagAppender<T> remove(final T entry)
{
return remove(this.getKey(entry));
}
/**
* Adds multiple registry entries to the tag json's remove list. Callable during datageneration.
*
* @param entries The entries to remove
* @return The builder for chaining
*/
@SuppressWarnings("unchecked")
default TagsProvider.TagAppender<T> remove(final T first, final T...entries)
{
this.remove(first);
for (T entry : entries)
{
this.remove(entry);
}
return self();
}
}
@@ -303,18 +303,6 @@ public interface IForgeItem
return false;
}
/**
* Gets a list of tabs that items belonging to this class can display on,
* combined properly with getSubItems allows for a single item to span many
* sub-items across many tabs.
*
* @return A list of all tabs that this item could possibly be one.
*/
default java.util.Collection<CreativeModeTab> getCreativeTabs()
{
return java.util.Collections.singletonList(self().getItemCategory());
}
/**
*
* Should this item, when held, allow sneak-clicks to pass through to the
@@ -616,7 +604,7 @@ public interface IForgeItem
*/
default boolean canContinueUsing(ItemStack oldStack, ItemStack newStack)
{
return ItemStack.isSameIgnoreDurability(oldStack, newStack);
return ItemStack.isSame(oldStack, newStack);
}
/**
@@ -6,6 +6,7 @@
package net.minecraftforge.common.extensions;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.monster.EnderMan;
import net.minecraft.world.entity.player.Inventory;
@@ -85,7 +86,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
Player entityplayer = context.getPlayer();
BlockPos blockpos = context.getClickedPos();
BlockInWorld blockworldstate = new BlockInWorld(context.getLevel(), blockpos, false);
Registry<Block> registry = entityplayer.level.registryAccess().registryOrThrow(Registry.BLOCK_REGISTRY);
Registry<Block> registry = entityplayer.level.registryAccess().registryOrThrow(Registries.BLOCK);
if (entityplayer != null && !entityplayer.getAbilities().mayBuild && !self().hasAdventureModePlaceTagForBlock(registry, blockworldstate)) {
return InteractionResult.PASS;
} else {
@@ -9,6 +9,9 @@ import net.minecraft.server.packs.PackType;
public interface IForgePackResources
{
/**
* {@return {@code true} if the pack should be hidden from any user interfaces}
*/
default boolean isHidden()
{
return false;
@@ -5,8 +5,6 @@
package net.minecraftforge.common.extensions;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.alchemy.Potion;
import net.minecraft.world.item.alchemy.PotionUtils;
@@ -18,18 +16,6 @@ public interface IForgePotion
return (Potion) this;
}
/**
* Determines what creative tabs this potion's variant of a potion-related item (e.g. bottles, tipped arrows) should appear in.
* @param item The item being added to a creative tab
* @param tab The creative tab that items are being added to
* @param isDefaultTab whether the tab is the default tab for this item (e.g. Brewing for bottles, Combat for tipped arrows)
* @return whether the given Item's variant for this enchantment should appear in the respective creative tab
*/
default boolean allowedInCreativeTab(Item item, CreativeModeTab tab, boolean isDefaultTab)
{
return isDefaultTab;
}
/**
* Determines whether the potion bottle item should be enchanted.
* Not called for tipped arrows or if the item is already enchanted.
@@ -6,6 +6,7 @@
package net.minecraftforge.common.extensions;
import net.minecraft.data.tags.TagsProvider;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
@@ -33,32 +34,6 @@ public interface IForgeTagAppender<T>
return self();
}
/**
* Adds a registry entry to the tag json's remove list. Callable during datageneration.
* @param entry The entry to remove
* @return The builder for chaining
*/
default TagsProvider.TagAppender<T> remove(final T entry)
{
return remove(this.self().registry.getKey(entry));
}
/**
* Adds multiple registry entries to the tag json's remove list. Callable during datageneration.
* @param entries The entries to remove
* @return The builder for chaining
*/
@SuppressWarnings("unchecked")
default TagsProvider.TagAppender<T> remove(final T first, final T...entries)
{
this.remove(first);
for (T entry : entries)
{
this.remove(entry);
}
return self();
}
/**
* Adds a single element's ID to the tag json's remove list. Callable during datageneration.
* @param location The ID of the element to remove
@@ -86,6 +61,34 @@ public interface IForgeTagAppender<T>
return self();
}
/**
* Adds a resource key to the tag json's remove list. Callable during datageneration.
*
* @param resourceKey The resource key of the element to remove
* @return The appender for chaining
*/
default TagsProvider.TagAppender<T> remove(final ResourceKey<T> resourceKey)
{
this.remove(resourceKey.location());
return self();
}
/**
* Adds multiple resource keys to the tag json's remove list. Callable during datageneration.
*
* @param resourceKeys The resource keys of the elements to remove
* @return The appender for chaining
*/
default TagsProvider.TagAppender<T> remove(final ResourceKey<T> firstResourceKey, final ResourceKey<T>... resourceKeys)
{
this.remove(firstResourceKey.location());
for (ResourceKey<T> resourceKey : resourceKeys)
{
this.remove(resourceKey.location());
}
return self();
}
/**
* Adds a tag to the tag json's remove list. Callable during datageneration.
* @param tag The ID of the tag to remove
@@ -20,6 +20,12 @@ import java.util.function.Supplier;
*/
public class ConcatenatedListView<T> implements List<T>
{
@SafeVarargs
public static <T> ConcatenatedListView<T> of(List<T>... lists)
{
return new ConcatenatedListView<>(List.of(lists));
}
public static <T> List<T> of(List<? extends List<? extends T>> members)
{
return switch (members.size()) {
@@ -8,17 +8,21 @@ package net.minecraftforge.common.util;
import com.mojang.authlib.GameProfile;
import java.util.Set;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.core.BlockPos;
import net.minecraft.network.Connection;
import net.minecraft.network.PacketSendListener;
import net.minecraft.network.chat.ChatType;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.PlayerChatMessage;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.PacketFlow;
import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket;
import net.minecraft.network.protocol.game.ServerboundAcceptTeleportationPacket;
import net.minecraft.network.protocol.game.ServerboundBlockEntityTagQuery;
import net.minecraft.network.protocol.game.ServerboundChangeDifficultyPacket;
import net.minecraft.network.protocol.game.ServerboundChatAckPacket;
import net.minecraft.network.protocol.game.ServerboundChatCommandPacket;
import net.minecraft.network.protocol.game.ServerboundChatPacket;
import net.minecraft.network.protocol.game.ServerboundChatSessionUpdatePacket;
import net.minecraft.network.protocol.game.ServerboundClientCommandPacket;
import net.minecraft.network.protocol.game.ServerboundClientInformationPacket;
import net.minecraft.network.protocol.game.ServerboundCommandSuggestionPacket;
@@ -66,7 +70,6 @@ import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.stats.Stat;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.server.ServerLifecycleHooks;
import org.jetbrains.annotations.Nullable;
@@ -77,7 +80,7 @@ public class FakePlayer extends ServerPlayer
{
public FakePlayer(ServerLevel level, GameProfile name)
{
super(level.getServer(), level, name, null);
super(level.getServer(), level, name);
this.connection = new FakePlayerNetHandler(level.getServer(), this);
}
@@ -150,5 +153,14 @@ public class FakePlayer extends ServerPlayer
@Override public void handleCustomPayload(ServerboundCustomPayloadPacket packet) { }
@Override public void handleChangeDifficulty(ServerboundChangeDifficultyPacket packet) { }
@Override public void handleLockDifficulty(ServerboundLockDifficultyPacket packet) { }
@Override public void dismount(double x, double y, double z, float yaw, float pitch) { }
@Override public void teleport(double x, double y, double z, float yaw, float pitch, Set<ClientboundPlayerPositionPacket.RelativeArgument> relativeSet, boolean dismountVehicle) { }
@Override public void ackBlockChangesUpTo(int sequence) { }
@Override public void handleChatCommand(ServerboundChatCommandPacket packet) { }
@Override public void handleChatAck(ServerboundChatAckPacket packet) { }
@Override public void addPendingMessage(PlayerChatMessage message) { }
@Override public void sendPlayerChatMessage(PlayerChatMessage message, ChatType.Bound boundChatType) { }
@Override public void sendDisguisedChatMessage(Component content, ChatType.Bound boundChatType) { }
@Override public void handleChatSessionUpdate(ServerboundChatSessionUpdatePacket packet) { }
}
}
@@ -0,0 +1,24 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.util;
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenCustomHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.ItemStackLinkedSet;
import java.util.Map;
public class ItemStackMap {
public static <V> Map<ItemStack, V> createTypeAndTagLinkedMap() {
return new Object2ObjectLinkedOpenCustomHashMap<>(ItemStackLinkedSet.TYPE_AND_TAG);
}
public static <V> Map<ItemStack, V> createTypeAndTagMap() {
return new Object2ObjectOpenCustomHashMap<>(ItemStackLinkedSet.TYPE_AND_TAG);
}
}
@@ -5,47 +5,58 @@
package net.minecraftforge.common.util;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.mojang.math.Axis;
import com.mojang.math.Transformation;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.google.gson.*;
import net.minecraft.util.Mth;
import com.mojang.math.Matrix4f;
import com.mojang.math.Quaternion;
import com.mojang.math.Transformation;
import com.mojang.math.Vector3f;
import com.mojang.math.Vector4f;
import net.minecraftforge.client.model.generators.BlockModelBuilder.RootTransformBuilder.TransformOrigin;
import org.joml.Matrix4f;
import org.joml.Quaternionf;
import org.joml.Quaternionfc;
import org.joml.Vector3f;
import org.joml.Vector4f;
public final class TransformationHelper
{
public static Quaternion quatFromXYZ(Vector3f xyz, boolean degrees)
public static Quaternionf quatFromXYZ(Vector3f xyz, boolean degrees)
{
return new Quaternion(xyz.x(), xyz.y(), xyz.z(), degrees);
return quatFromXYZ(xyz.x, xyz.y, xyz.z, degrees);
}
public static Quaternion quatFromXYZ(float[] xyz, boolean degrees)
public static Quaternionf quatFromXYZ(float[] xyz, boolean degrees)
{
return new Quaternion(xyz[0], xyz[1], xyz[2], degrees);
return quatFromXYZ(xyz[0], xyz[1], xyz[2], degrees);
}
public static Quaternion makeQuaternion(float[] values)
public static Quaternionf quatFromXYZ(float x, float y, float z, boolean degrees)
{
return new Quaternion(values[0], values[1], values[2], values[3]);
float conversionFactor = degrees ? (float) Math.PI / 180 : 1;
return new Quaternionf().rotationXYZ(x * conversionFactor, y * conversionFactor, z * conversionFactor);
}
public static Quaternionf makeQuaternion(float[] values)
{
return new Quaternionf(values[0], values[1], values[2], values[3]);
}
public static Vector3f lerp(Vector3f from, Vector3f to, float progress)
{
Vector3f res = from.copy();
Vector3f res = new Vector3f(from);
res.lerp(to, progress);
return res;
}
private static final double THRESHOLD = 0.9995;
public static Quaternion slerp(Quaternion v0, Quaternion v1, float t)
public static Quaternionf slerp(Quaternionfc v0, Quaternionfc v1, float t)
{
// From https://en.wikipedia.org/w/index.php?title=Slerp&oldid=928959428
// License: CC BY-SA 3.0 https://creativecommons.org/licenses/by-sa/3.0/
@@ -55,20 +66,20 @@ public final class TransformationHelper
// the shorter path. Note that v1 and -v1 are equivalent when
// the negation is applied to all four components. Fix by
// reversing one quaternion.
float dot = v0.i() * v1.i() + v0.j() * v1.j() + v0.k() * v1.k() + v0.r() * v1.r();
float dot = v0.x() * v1.x() + v0.y() * v1.y() + v0.z() * v1.z() + v0.w() * v1.w();
if (dot < 0.0f) {
v1 = new Quaternion(-v1.i(), -v1.j(), -v1.k(), -v1.r());
v1 = new Quaternionf(-v1.x(), -v1.y(), -v1.z(), -v1.w());
dot = -dot;
}
// If the inputs are too close for comfort, linearly interpolate
// and normalize the result.
if (dot > THRESHOLD) {
float x = Mth.lerp(t, v0.i(), v1.i());
float y = Mth.lerp(t, v0.j(), v1.j());
float z = Mth.lerp(t, v0.k(), v1.k());
float w = Mth.lerp(t, v0.r(), v1.r());
return new Quaternion(x,y,z,w);
float x = Mth.lerp(t, v0.x(), v1.x());
float y = Mth.lerp(t, v0.y(), v1.y());
float z = Mth.lerp(t, v0.z(), v1.z());
float w = Mth.lerp(t, v0.w(), v1.w());
return new Quaternionf(x,y,z,w);
}
// Since dot is in range [0, DOT_THRESHOLD], acos is safe
@@ -81,11 +92,11 @@ public final class TransformationHelper
float s1 = sin0t / sin01;
float s0 = sin1t / sin01;
return new Quaternion(
s0 * v0.i() + s1 * v1.i(),
s0 * v0.j() + s1 * v1.j(),
s0 * v0.k() + s1 * v1.k(),
s0 * v0.r() + s1 * v1.r()
return new Quaternionf(
s0 * v0.x() + s1 * v1.x(),
s0 * v0.y() + s1 * v1.y(),
s0 * v0.z() + s1 * v1.z(),
s0 * v0.w() + s1 * v1.w()
);
}
@@ -143,9 +154,9 @@ public final class TransformationHelper
return ret;
}
Vector3f translation = null;
Quaternion leftRot = null;
Quaternionf leftRot = null;
Vector3f scale = null;
Quaternion rightRot = null;
Quaternionf rightRot = null;
// TODO: Default origin is opposing corner, due to a mistake.
// This should probably be replaced with center in future versions.
Vector3f origin = TransformOrigin.OPPOSING_CORNER.getVector(); // TODO: Changing this to ORIGIN_CENTER breaks models, function content needs changing too -C
@@ -206,7 +217,7 @@ public final class TransformationHelper
// Use a different origin if needed.
if (!TransformOrigin.CENTER.getVector().equals(origin))
{
Vector3f originFromCenter = origin.copy();
Vector3f originFromCenter = new Vector3f(origin);
originFromCenter.sub(TransformOrigin.CENTER.getVector());
matrix = matrix.applyOrigin(originFromCenter);
}
@@ -244,25 +255,25 @@ public final class TransformationHelper
if (!e.isJsonArray()) throw new JsonParseException("Matrix: expected an array, got: " + e);
JsonArray m = e.getAsJsonArray();
if (m.size() != 3) throw new JsonParseException("Matrix: expected an array of length 3, got: " + m.size());
float[] values = new float[16];
for (int i = 0; i < 3; i++)
Matrix4f matrix = new Matrix4f().zero();
for (int rowIdx = 0; rowIdx < 3; rowIdx++)
{
if (!m.get(i).isJsonArray()) throw new JsonParseException("Matrix row: expected an array, got: " + m.get(i));
JsonArray r = m.get(i).getAsJsonArray();
if (!m.get(rowIdx).isJsonArray()) throw new JsonParseException("Matrix row: expected an array, got: " + m.get(rowIdx));
JsonArray r = m.get(rowIdx).getAsJsonArray();
if (r.size() != 4) throw new JsonParseException("Matrix row: expected an array of length 4, got: " + r.size());
for (int j = 0; j < 4; j++)
for (int columnIdx = 0; columnIdx < 4; columnIdx++)
{
try
{
values[j*4+i] = r.get(j).getAsNumber().floatValue();
matrix.set(columnIdx, rowIdx, r.get(columnIdx).getAsNumber().floatValue());
}
catch (ClassCastException ex)
{
throw new JsonParseException("Matrix element: expected number, got: " + r.get(j));
throw new JsonParseException("Matrix element: expected number, got: " + r.get(columnIdx));
}
}
}
return new Matrix4f(values);
return matrix;
}
public static float[] parseFloatArray(JsonElement e, int length, String prefix)
@@ -285,26 +296,26 @@ public final class TransformationHelper
return ret;
}
public static Quaternion parseAxisRotation(JsonElement e)
public static Quaternionf parseAxisRotation(JsonElement e)
{
if (!e.isJsonObject()) throw new JsonParseException("Axis rotation: object expected, got: " + e);
JsonObject obj = e.getAsJsonObject();
if (obj.entrySet().size() != 1) throw new JsonParseException("Axis rotation: expected single axis object, got: " + e);
Map.Entry<String, JsonElement> entry = obj.entrySet().iterator().next();
Quaternion ret;
Quaternionf ret;
try
{
if (entry.getKey().equals("x"))
{
ret = Vector3f.XP.rotationDegrees(entry.getValue().getAsNumber().floatValue());
ret = Axis.XP.rotationDegrees(entry.getValue().getAsNumber().floatValue());
}
else if (entry.getKey().equals("y"))
{
ret = Vector3f.YP.rotationDegrees(entry.getValue().getAsNumber().floatValue());
ret = Axis.YP.rotationDegrees(entry.getValue().getAsNumber().floatValue());
}
else if (entry.getKey().equals("z"))
{
ret = Vector3f.ZP.rotationDegrees(entry.getValue().getAsNumber().floatValue());
ret = Axis.ZP.rotationDegrees(entry.getValue().getAsNumber().floatValue());
}
else throw new JsonParseException("Axis rotation: expected single axis key, got: " + entry.getKey());
}
@@ -315,13 +326,13 @@ public final class TransformationHelper
return ret;
}
public static Quaternion parseRotation(JsonElement e)
public static Quaternionf parseRotation(JsonElement e)
{
if (e.isJsonArray())
{
if (e.getAsJsonArray().get(0).isJsonObject())
{
Quaternion ret = Quaternion.ONE.copy();
Quaternionf ret = new Quaternionf();
for (JsonElement a : e.getAsJsonArray())
{
ret.mul(parseAxisRotation(a));
@@ -5,18 +5,15 @@
package net.minecraftforge.common.world;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet;
import net.minecraft.world.level.biome.BiomeGenerationSettings;
import net.minecraft.world.level.levelgen.GenerationStep;
import net.minecraft.world.level.levelgen.carver.ConfiguredWorldCarver;
import net.minecraft.world.level.levelgen.placement.PlacedFeature;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
public class BiomeGenerationSettingsBuilder extends BiomeGenerationSettings.Builder
public class BiomeGenerationSettingsBuilder extends BiomeGenerationSettings.PlainBuilder
{
public BiomeGenerationSettingsBuilder(BiomeGenerationSettings orig)
{
@@ -7,6 +7,7 @@ package net.minecraftforge.common.world;
import java.util.Optional;
import net.minecraft.core.Holder;
import net.minecraft.sounds.Music;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.level.biome.AmbientAdditionsSettings;
@@ -33,12 +34,12 @@ public class BiomeSpecialEffectsBuilder extends BiomeSpecialEffects.Builder
baseEffects.getBackgroundMusic().ifPresent(builder::backgroundMusic);
return builder;
}
public static BiomeSpecialEffectsBuilder create(int fogColor, int waterColor, int waterFogColor, int skyColor)
{
return new BiomeSpecialEffectsBuilder(fogColor, waterColor, waterFogColor, skyColor);
}
protected BiomeSpecialEffectsBuilder(int fogColor, int waterColor, int waterFogColor, int skyColor)
{
super();
@@ -47,62 +48,62 @@ public class BiomeSpecialEffectsBuilder extends BiomeSpecialEffects.Builder
this.waterFogColor(waterFogColor);
this.skyColor(skyColor);
}
public int getFogColor()
{
return this.fogColor.getAsInt();
}
public int waterColor()
{
return this.waterColor.getAsInt();
}
public int getWaterFogColor()
{
return this.waterFogColor.getAsInt();
}
public int getSkyColor()
{
return this.skyColor.getAsInt();
}
public BiomeSpecialEffects.GrassColorModifier getGrassColorModifier()
{
return this.grassColorModifier;
}
public Optional<Integer> getFoliageColorOverride()
{
return this.foliageColorOverride;
}
public Optional<Integer> getGrassColorOverride()
{
return this.grassColorOverride;
}
public Optional<AmbientParticleSettings> getAmbientParticle()
{
return this.ambientParticle;
}
public Optional<SoundEvent> getAmbientLoopSound()
public Optional<Holder<SoundEvent>> getAmbientLoopSound()
{
return this.ambientLoopSoundEvent;
}
public Optional<AmbientMoodSettings> getAmbientMoodSound()
{
return this.ambientMoodSettings;
}
public Optional<AmbientAdditionsSettings> getAmbientAdditionsSound()
{
return this.ambientAdditionsSettings;
}
public Optional<Music> getBackgroundMusic()
{
return this.backgroundMusic;
@@ -26,7 +26,7 @@ import net.minecraftforge.registries.ForgeRegistries;
public final class ForgeBiomeModifiers
{
private ForgeBiomeModifiers() {} // Utility class.
/**
* <p>Stock biome modifier that adds features to biomes. Has the following json format:</p>
* <pre>
@@ -38,7 +38,7 @@ public final class ForgeBiomeModifiers
* }
* </pre>
* <p>Be wary of using this to add vanilla PlacedFeatures to biomes, as doing so may cause a feature cycle violation.</p>
*
*
* @param biomes Biomes to add features to.
* @param features PlacedFeatures to add to biomes.
* @param step Decoration step to run features in.
@@ -62,7 +62,6 @@ public final class ForgeBiomeModifiers
}
}
/**
* <p>Stock biome modifier that removes features from biomes. Has the following json format:</p>
* <pre>
@@ -73,7 +72,7 @@ public final class ForgeBiomeModifiers
* "steps": "underground_ores" OR ["underground_ores", "vegetal_decoration"] // one or more decoration steps; optional field, defaults to all steps if not specified
* }
* </pre>
*
*
* @param biomes Biomes to remove features from.
* @param features PlacedFeatures to remove from biomes.
* @param steps Decoration steps to remove features from.
@@ -89,7 +88,7 @@ public final class ForgeBiomeModifiers
{
return new RemoveFeaturesBiomeModifier(biomes, features, EnumSet.allOf(Decoration.class));
}
@Override
public void modify(Holder<Biome> biome, Phase phase, Builder builder)
{
@@ -109,7 +108,7 @@ public final class ForgeBiomeModifiers
return ForgeMod.REMOVE_FEATURES_BIOME_MODIFIER_TYPE.get();
}
}
/**
* <p>Stock biome modifier that adds a mob spawn to a biome. Has the following json format:</p>
* <pre>
@@ -144,7 +143,7 @@ public final class ForgeBiomeModifiers
* ]
* }
* </pre>
*
*
* @param biomes Biomes to add mob spawns to.
* @param spawners List of SpawnerDatas specifying EntityType, weight, and pack size.
*/
@@ -160,7 +159,7 @@ public final class ForgeBiomeModifiers
{
return new AddSpawnsBiomeModifier(biomes, List.of(spawner));
}
@Override
public void modify(Holder<Biome> biome, Phase phase, Builder builder)
{
@@ -191,7 +190,7 @@ public final class ForgeBiomeModifiers
* "entity_types": #namespace:entitytype_tag // Accepts an entity type, [list of entity types], or #namespace:entitytype_tag
* }
* </pre>
*
*
* @param biomes Biomes to add mob spawns to.
* @param entityTypes EntityTypes to remove from spawn lists.
*/