mirror of
https://github.com/MinecraftForge/MinecraftForge.git
synced 2026-11-16 18:45:09 +00:00
1.21.3 update
This commit is contained in:
806 files changed
+6314
-10501
No files matched your search
@@ -18,6 +18,7 @@ import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.multiplayer.ClientPacketListener;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.CommandSource;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.commands.synchronization.SuggestionProviders;
|
||||
@@ -33,18 +34,15 @@ import org.jetbrains.annotations.ApiStatus;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class ClientCommandHandler
|
||||
{
|
||||
public class ClientCommandHandler {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static CommandDispatcher<CommandSourceStack> commands = null;
|
||||
|
||||
public static void init()
|
||||
{
|
||||
public static void init() {
|
||||
MinecraftForge.EVENT_BUS.addListener(ClientCommandHandler::handleClientPlayerLogin);
|
||||
}
|
||||
|
||||
private static void handleClientPlayerLogin(ClientPlayerNetworkEvent.LoggingIn event)
|
||||
{
|
||||
private static void handleClientPlayerLogin(ClientPlayerNetworkEvent.LoggingIn event) {
|
||||
final ClientPacketListener connection = event.getPlayer().connection;
|
||||
// Some custom server implementations do not send ClientboundCommandsPacket, so we provide a fallback:
|
||||
// Must set this, so that suggestions for client-only commands work, if server never sends commands packet
|
||||
@@ -58,8 +56,7 @@ public class ClientCommandHandler
|
||||
* with server commands in suggestions
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public static CommandDispatcher<SharedSuggestionProvider> mergeServerCommands(CommandDispatcher<SharedSuggestionProvider> serverCommands, CommandBuildContext buildContext)
|
||||
{
|
||||
public static CommandDispatcher<SharedSuggestionProvider> mergeServerCommands(CommandDispatcher<SharedSuggestionProvider> serverCommands, CommandBuildContext buildContext) {
|
||||
CommandDispatcher<CommandSourceStack> commandsTemp = new CommandDispatcher<>();
|
||||
MinecraftForge.EVENT_BUS.post(new RegisterClientCommandsEvent(commandsTemp, buildContext));
|
||||
|
||||
@@ -74,17 +71,15 @@ public class ClientCommandHandler
|
||||
|
||||
// Copies the client side commands into the server side commands to be used for suggestions
|
||||
CommandHelper.mergeCommandNode(commands.getRoot(), newServerCommands.getRoot(), new IdentityHashMap<>(), getSource(), (context) -> 0, (suggestions) -> {
|
||||
SuggestionProvider<SharedSuggestionProvider> suggestionProvider = SuggestionProviders
|
||||
.safelySwap((SuggestionProvider<SharedSuggestionProvider>) (SuggestionProvider<?>) suggestions);
|
||||
if (suggestionProvider == SuggestionProviders.ASK_SERVER)
|
||||
{
|
||||
@SuppressWarnings("unchecked")
|
||||
var shared = (SuggestionProvider<SharedSuggestionProvider>)(SuggestionProvider<?>)suggestions;
|
||||
var suggestionProvider = SuggestionProviders.safelySwap(shared);
|
||||
if (suggestionProvider == SuggestionProviders.ASK_SERVER) {
|
||||
suggestionProvider = (context, builder) -> {
|
||||
ClientCommandSourceStack source = getSource();
|
||||
StringReader reader = new StringReader(context.getInput());
|
||||
if (reader.canRead() && reader.peek() == '/')
|
||||
{
|
||||
reader.skip();
|
||||
}
|
||||
|
||||
ParseResults<CommandSourceStack> parse = commands.parse(reader, source);
|
||||
return commands.getCompletionSuggestions(parse);
|
||||
@@ -99,19 +94,45 @@ public class ClientCommandHandler
|
||||
/**
|
||||
* @return The command dispatcher for client side commands
|
||||
*/
|
||||
public static CommandDispatcher<CommandSourceStack> getDispatcher()
|
||||
{
|
||||
public static CommandDispatcher<CommandSourceStack> getDispatcher() {
|
||||
return commands;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A {@link ClientCommandSourceStack} for the player in the current client
|
||||
*/
|
||||
public static ClientCommandSourceStack getSource()
|
||||
{
|
||||
LocalPlayer player = Minecraft.getInstance().player;
|
||||
return new ClientCommandSourceStack(player, player.position(), player.getRotationVector(), player.getPermissionLevel(),
|
||||
player.getName().getString(), player.getDisplayName(), player);
|
||||
public static ClientCommandSourceStack getSource() {
|
||||
var mc = Minecraft.getInstance();
|
||||
LocalPlayer player = mc.player;
|
||||
return new ClientCommandSourceStack(
|
||||
new CommandSource() {
|
||||
@Override
|
||||
public void sendSystemMessage(Component message) {
|
||||
mc.gui.getChat().addMessage(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean acceptsSuccess() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean acceptsFailure() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldInformAdmins() {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
player.position(),
|
||||
player.getRotationVector(),
|
||||
player.getPermissionLevel(),
|
||||
player.getName().getString(),
|
||||
player.getDisplayName(),
|
||||
player
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -149,51 +170,49 @@ public class ClientCommandHandler
|
||||
* @param command the full command to execute, no preceding slash
|
||||
* @return {@code false} leaves the message to be sent to the server, while {@code true} means it should be caught before LocalPlayer#sendCommand
|
||||
*/
|
||||
public static boolean runCommand(String command)
|
||||
{
|
||||
public static boolean runCommand(String command) {
|
||||
StringReader reader = new StringReader(command);
|
||||
|
||||
ClientCommandSourceStack source = getSource();
|
||||
var mc = Minecraft.getInstance();
|
||||
|
||||
try {
|
||||
commands.execute(reader, source);
|
||||
//} catch (CommandRuntimeException execution) { // Probably thrown by the command
|
||||
// Minecraft.getInstance().player.sendSystemMessage(Component.literal("").append(execution.getComponent()).withStyle(ChatFormatting.RED));
|
||||
} catch (CommandSyntaxException syntax) {
|
||||
if (syntax.getType() == CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand() || syntax.getType() == CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument())
|
||||
{
|
||||
if (syntax.getType() == CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand() ||
|
||||
syntax.getType() == CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument()
|
||||
) {
|
||||
// in case of unknown command, let the server try and handle it
|
||||
return false;
|
||||
}
|
||||
Minecraft.getInstance().player.sendSystemMessage(
|
||||
Component.literal("").append(ComponentUtils.fromMessage(syntax.getRawMessage())).withStyle(ChatFormatting.RED));
|
||||
if (syntax.getInput() != null && syntax.getCursor() >= 0)
|
||||
{
|
||||
mc.gui.getChat().addMessage(
|
||||
Component.literal("").append(ComponentUtils.fromMessage(syntax.getRawMessage())).withStyle(ChatFormatting.RED)
|
||||
);
|
||||
if (syntax.getInput() != null && syntax.getCursor() >= 0) {
|
||||
int position = Math.min(syntax.getInput().length(), syntax.getCursor());
|
||||
MutableComponent details = Component.literal("")
|
||||
.withStyle(ChatFormatting.GRAY)
|
||||
.withStyle((style) -> style
|
||||
.withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, reader.getString())));
|
||||
if (position > 10)
|
||||
{
|
||||
details.append("...");
|
||||
}
|
||||
|
||||
details.append(syntax.getInput().substring(Math.max(0, position - 10), position));
|
||||
if (position < syntax.getInput().length())
|
||||
{
|
||||
details.append(Component.literal(syntax.getInput().substring(position)).withStyle(ChatFormatting.RED, ChatFormatting.UNDERLINE));
|
||||
}
|
||||
|
||||
details.append(Component.translatable("command.context.here").withStyle(ChatFormatting.RED, ChatFormatting.ITALIC));
|
||||
Minecraft.getInstance().player.sendSystemMessage(Component.literal("").append(details).withStyle(ChatFormatting.RED));
|
||||
mc.gui.getChat().addMessage(Component.literal("").append(details).withStyle(ChatFormatting.RED));
|
||||
}
|
||||
}
|
||||
catch (Exception generic)// Probably thrown by the command
|
||||
{
|
||||
} catch (Exception generic) { // Probably thrown by the command{
|
||||
MutableComponent message = Component.literal(generic.getMessage() == null ? generic.getClass().getName() : generic.getMessage());
|
||||
Minecraft.getInstance().player.sendSystemMessage(Component.translatable("command.failed")
|
||||
mc.gui.getChat().addMessage(
|
||||
Component.translatable("command.failed")
|
||||
.withStyle(ChatFormatting.RED)
|
||||
.withStyle((style) -> style
|
||||
.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, message))));
|
||||
.withStyle(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, message)))
|
||||
);
|
||||
LOGGER.error("Error executing client command \"{}\"", command, generic);
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -16,7 +16,6 @@ import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.item.crafting.RecipeManager;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.phys.Vec2;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
@@ -26,7 +25,6 @@ import java.util.Collection;
|
||||
import java.util.Set;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* overrides for {@link CommandSourceStack} so that the methods will run successfully client side
|
||||
@@ -42,7 +40,7 @@ public class ClientCommandSourceStack extends CommandSourceStack {
|
||||
@SuppressWarnings("resource")
|
||||
@Override
|
||||
public void sendSuccess(Supplier<Component> message, boolean sendToAdmins) {
|
||||
Minecraft.getInstance().player.sendSystemMessage(message.get());
|
||||
Minecraft.getInstance().gui.getChat().addMessage(message.get());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -62,14 +60,6 @@ public class ClientCommandSourceStack extends CommandSourceStack {
|
||||
return Minecraft.getInstance().getConnection().getOnlinePlayers().stream().map((player) -> player.getProfile().getName()).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return a {@link Stream} of recipe ids that are available on the client}
|
||||
*/
|
||||
@Override
|
||||
public Stream<ResourceLocation> getRecipeNames() {
|
||||
return Minecraft.getInstance().getConnection().getRecipeManager().getRecipeIds();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return a set of {@link ResourceKey} for levels from the client side}
|
||||
*/
|
||||
@@ -103,14 +93,6 @@ public class ClientCommandSourceStack extends CommandSourceStack {
|
||||
return Minecraft.getInstance().getConnection().getAdvancements().get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the {@link RecipeManager} from the client side}
|
||||
*/
|
||||
@Override
|
||||
public RecipeManager getRecipeManager() {
|
||||
return Minecraft.getInstance().getConnection().getRecipeManager();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the level from the client side}
|
||||
*/
|
||||
|
||||
@@ -21,11 +21,9 @@ import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
@Mod.EventBusSubscriber(value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD, modid = "forge")
|
||||
public class ClientForgeMod
|
||||
{
|
||||
public class ClientForgeMod {
|
||||
@SubscribeEvent
|
||||
public static void onRegisterGeometryLoaders(ModelEvent.RegisterGeometryLoaders event)
|
||||
{
|
||||
public static void onRegisterGeometryLoaders(ModelEvent.RegisterGeometryLoaders event) {
|
||||
event.register("empty", EmptyModel.LOADER);
|
||||
event.register("elements", ElementsModel.Loader.INSTANCE);
|
||||
event.register("obj", ObjLoader.INSTANCE);
|
||||
@@ -36,14 +34,12 @@ public class ClientForgeMod
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onRegisterReloadListeners(RegisterClientReloadListenersEvent event)
|
||||
{
|
||||
public static void onRegisterReloadListeners(RegisterClientReloadListenersEvent event) {
|
||||
event.registerReloadListener(ObjLoader.INSTANCE);
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onRegisterNamedRenderTypes(RegisterNamedRenderTypesEvent event)
|
||||
{
|
||||
public static void onRegisterNamedRenderTypes(RegisterNamedRenderTypesEvent event) {
|
||||
event.register("item_unlit", RenderType.translucent(), ForgeRenderTypes.ITEM_UNSORTED_UNLIT_TRANSLUCENT.get());
|
||||
}
|
||||
}
|
||||
@@ -21,22 +21,19 @@ import java.util.Map;
|
||||
* <p>
|
||||
* Provides a lookup by dimension type.
|
||||
*/
|
||||
public final class DimensionSpecialEffectsManager
|
||||
{
|
||||
public final class DimensionSpecialEffectsManager {
|
||||
private static ImmutableMap<ResourceLocation, DimensionSpecialEffects> EFFECTS;
|
||||
private static DimensionSpecialEffects DEFAULT_EFFECTS;
|
||||
|
||||
/**
|
||||
* Finds the {@link DimensionSpecialEffects} for a given dimension type, or the default if none is registered.
|
||||
*/
|
||||
public static DimensionSpecialEffects getForType(ResourceLocation type)
|
||||
{
|
||||
public static DimensionSpecialEffects getForType(ResourceLocation type) {
|
||||
return EFFECTS.getOrDefault(type, DEFAULT_EFFECTS);
|
||||
}
|
||||
|
||||
@ApiStatus.Internal
|
||||
public static void init()
|
||||
{
|
||||
public static void init() {
|
||||
var effects = new HashMap<ResourceLocation, DimensionSpecialEffects>();
|
||||
DEFAULT_EFFECTS = preRegisterVanillaEffects(effects);
|
||||
var event = new RegisterDimensionSpecialEffectsEvent(effects);
|
||||
@@ -49,8 +46,7 @@ public final class DimensionSpecialEffectsManager
|
||||
* <p>
|
||||
* Borrowed from {@link DimensionSpecialEffects#EFFECTS}.
|
||||
*/
|
||||
private static DimensionSpecialEffects preRegisterVanillaEffects(Map<ResourceLocation, DimensionSpecialEffects> effects)
|
||||
{
|
||||
private static DimensionSpecialEffects preRegisterVanillaEffects(Map<ResourceLocation, DimensionSpecialEffects> effects) {
|
||||
var overworldEffects = new DimensionSpecialEffects.OverworldEffects();
|
||||
effects.put(BuiltinDimensionTypes.OVERWORLD_EFFECTS, overworldEffects);
|
||||
effects.put(BuiltinDimensionTypes.NETHER_EFFECTS, new DimensionSpecialEffects.NetherEffects());
|
||||
@@ -58,7 +54,5 @@ public final class DimensionSpecialEffectsManager
|
||||
return overworldEffects;
|
||||
}
|
||||
|
||||
private DimensionSpecialEffectsManager()
|
||||
{
|
||||
}
|
||||
private DimensionSpecialEffectsManager() { }
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
package net.minecraftforge.client;
|
||||
|
||||
import com.google.common.base.Suppliers;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
@@ -19,7 +20,9 @@ import com.mojang.math.Constants;
|
||||
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.FileUtil;
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.client.Camera;
|
||||
import net.minecraft.client.ClientRecipeBook;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.Options;
|
||||
import net.minecraft.client.color.block.BlockColors;
|
||||
@@ -44,15 +47,18 @@ import net.minecraft.client.multiplayer.PlayerInfo;
|
||||
import net.minecraft.client.multiplayer.ServerData;
|
||||
import net.minecraft.client.particle.ParticleEngine;
|
||||
import net.minecraft.client.particle.ParticleRenderType;
|
||||
import net.minecraft.client.player.Input;
|
||||
import net.minecraft.client.player.ClientInput;
|
||||
import net.minecraft.client.renderer.FogParameters;
|
||||
import net.minecraft.client.renderer.FogRenderer;
|
||||
import net.minecraft.client.renderer.GameRenderer;
|
||||
import net.minecraft.client.renderer.LevelRenderer;
|
||||
import net.minecraft.client.renderer.MultiBufferSource;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.renderer.ShaderInstance;
|
||||
import net.minecraft.client.renderer.ShaderDefines;
|
||||
import net.minecraft.client.renderer.ShaderProgram;
|
||||
import net.minecraft.client.renderer.block.model.BakedQuad;
|
||||
import net.minecraft.client.renderer.culling.Frustum;
|
||||
import net.minecraft.client.renderer.entity.state.HumanoidRenderState;
|
||||
import net.minecraft.client.renderer.texture.SpriteContents;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlas;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
@@ -87,8 +93,8 @@ import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.inventory.InventoryMenu;
|
||||
import net.minecraft.world.inventory.tooltip.TooltipComponent;
|
||||
import net.minecraft.world.item.ArmorMaterial;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.RecipeManager;
|
||||
import net.minecraft.world.level.BlockAndTintGetter;
|
||||
@@ -118,11 +124,9 @@ import net.minecraftforge.client.event.RegisterClientReloadListenersEvent;
|
||||
import net.minecraftforge.client.event.RegisterColorHandlersEvent;
|
||||
import net.minecraftforge.client.event.RegisterKeyMappingsEvent;
|
||||
import net.minecraftforge.client.event.RegisterParticleProvidersEvent;
|
||||
import net.minecraftforge.client.event.RegisterShadersEvent;
|
||||
import net.minecraftforge.client.event.RenderBlockScreenEffectEvent;
|
||||
import net.minecraftforge.client.event.RenderHandEvent;
|
||||
import net.minecraftforge.client.event.RenderHighlightEvent;
|
||||
import net.minecraftforge.client.event.RenderLevelStageEvent;
|
||||
import net.minecraftforge.client.event.RenderTooltipEvent;
|
||||
import net.minecraftforge.client.event.ScreenEvent;
|
||||
import net.minecraftforge.client.event.TextureStitchEvent;
|
||||
@@ -245,10 +249,12 @@ public class ForgeHooksClient {
|
||||
MinecraftForge.EVENT_BUS.post(new ClientPauseChangeEvent.Post(pause));
|
||||
}
|
||||
|
||||
/*
|
||||
public static ResourceLocation getArmorTexture(Entity entity, ItemStack armor, EquipmentSlot slot, ArmorMaterial.Layer layer, boolean inner) {
|
||||
var result = armor.getItem().getArmorTexture(armor, entity, slot, layer, inner);
|
||||
return result != null ? result : layer.texture(inner);
|
||||
}
|
||||
*/
|
||||
|
||||
public static boolean onDrawHighlight(LevelRenderer context, Camera camera, HitResult target, float partialTick, PoseStack poseStack, MultiBufferSource bufferSource) {
|
||||
switch (target.getType()) {
|
||||
@@ -263,12 +269,6 @@ public class ForgeHooksClient {
|
||||
}
|
||||
}
|
||||
|
||||
public static void dispatchRenderStage(RenderType renderType, LevelRenderer levelRenderer, Matrix4f poseStack, Matrix4f projectionMatrix, int renderTick, Camera camera, Frustum frustum) {
|
||||
RenderLevelStageEvent.Stage stage = RenderLevelStageEvent.Stage.fromRenderType(renderType);
|
||||
if (stage != null)
|
||||
stage.dispatch(levelRenderer, poseStack, projectionMatrix, renderTick, camera, frustum);
|
||||
}
|
||||
|
||||
public static boolean renderSpecificFirstPersonHand(InteractionHand hand, PoseStack poseStack, MultiBufferSource bufferSource, int packedLight, float partialTick, float interpPitch, float swingProgress, float equipProgress, ItemStack stack) {
|
||||
return MinecraftForge.EVENT_BUS.post(new RenderHandEvent(hand, poseStack, bufferSource, packedLight, partialTick, interpPitch, swingProgress, equipProgress, stack));
|
||||
}
|
||||
@@ -285,13 +285,13 @@ public class ForgeHooksClient {
|
||||
ModLoader.get().postEvent(new RegisterColorHandlersEvent.Item(itemColors, blockColors));
|
||||
}
|
||||
|
||||
public static Model getArmorModel(LivingEntity entityLiving, ItemStack itemStack, EquipmentSlot slot, HumanoidModel<?> _default) {
|
||||
return IClientItemExtensions.of(itemStack).getGenericArmorModel(entityLiving, itemStack, slot, _default);
|
||||
public static Model getArmorModel(HumanoidRenderState state, ItemStack itemStack, EquipmentSlot slot, HumanoidModel<?> _default) {
|
||||
return IClientItemExtensions.of(itemStack).getGenericArmorModel(state, itemStack, slot, _default);
|
||||
}
|
||||
|
||||
/** Copies humanoid model properties from the original model to another, used for armor models */
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T extends LivingEntity> void copyModelProperties(HumanoidModel<T> original, HumanoidModel<?> replacement) {
|
||||
public static <T extends HumanoidRenderState> void copyModelProperties(HumanoidModel<T> original, HumanoidModel<?> replacement) {
|
||||
// this function does not make use of the <T> generic, so the unchecked cast should be safe
|
||||
original.copyPropertiesTo((HumanoidModel<T>)replacement);
|
||||
replacement.head.visible = original.head.visible;
|
||||
@@ -318,10 +318,6 @@ public class ForgeHooksClient {
|
||||
}
|
||||
}
|
||||
|
||||
public static float getFieldOfViewModifier(Player entity, float fovModifier) {
|
||||
return MinecraftForge.EVENT_BUS.fire(new ComputeFovModifierEvent(entity, fovModifier)).getNewFovModifier();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialization of Forge Renderers.
|
||||
*/
|
||||
@@ -400,18 +396,22 @@ public class ForgeHooksClient {
|
||||
return fluidFogColor;
|
||||
}
|
||||
|
||||
public static void onFogRender(FogRenderer.FogMode mode, FogType type, Camera camera, float partialTick, float renderDistance, float nearDistance, float farDistance, FogShape shape) {
|
||||
public static FogParameters getFogParameters(FogRenderer.FogMode mode, FogType type, Camera camera, float partialTick, float renderDistance, FogParameters original) {
|
||||
var ret = original;
|
||||
// Modify fog rendering depending on the fluid
|
||||
FluidState state = camera.getEntity().level().getFluidState(camera.getBlockPosition());
|
||||
if (camera.getPosition().y < (double)((float)camera.getBlockPosition().getY() + state.getHeight(camera.getEntity().level(), camera.getBlockPosition())))
|
||||
IClientFluidTypeExtensions.of(state).modifyFogRender(camera, mode, renderDistance, partialTick, nearDistance, farDistance, shape);
|
||||
ret = IClientFluidTypeExtensions.of(state).modifyFogRender(camera, mode, renderDistance, partialTick, ret);
|
||||
|
||||
ViewportEvent.RenderFog event = new ViewportEvent.RenderFog(mode, type, camera, partialTick, nearDistance, farDistance, shape);
|
||||
var event = new ViewportEvent.RenderFog(mode, type, camera, partialTick, ret.start(), ret.end(), ret.shape());
|
||||
if (MinecraftForge.EVENT_BUS.post(event)) {
|
||||
RenderSystem.setShaderFogStart(event.getNearPlaneDistance());
|
||||
RenderSystem.setShaderFogEnd(event.getFarPlaneDistance());
|
||||
RenderSystem.setShaderFogShape(event.getFogShape());
|
||||
return new FogParameters(
|
||||
event.getNearPlaneDistance(), event.getFarPlaneDistance(), event.getFogShape(),
|
||||
ret.red(), ret.green(), ret.blue(), ret.alpha()
|
||||
);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
public static void onModifyBakingResult(Map<ModelResourceLocation, BakedModel> models, ModelBakery modelBakery) {
|
||||
@@ -422,29 +422,28 @@ public class ForgeHooksClient {
|
||||
ModLoader.get().postEvent(new ModelEvent.BakingCompleted(modelManager, Collections.unmodifiableMap(models), modelBakery));
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static TextureAtlasSprite[] getFluidSprites(BlockAndTintGetter level, BlockPos pos, FluidState fluidStateIn) {
|
||||
IClientFluidTypeExtensions props = IClientFluidTypeExtensions.of(fluidStateIn);
|
||||
ResourceLocation overlayTexture = props.getOverlayTexture(fluidStateIn, level, pos);
|
||||
return new TextureAtlasSprite[] {
|
||||
Minecraft.getInstance().getTextureAtlas(TextureAtlas.LOCATION_BLOCKS).apply(props.getStillTexture(fluidStateIn, level, pos)),
|
||||
Minecraft.getInstance().getTextureAtlas(TextureAtlas.LOCATION_BLOCKS).apply(props.getFlowingTexture(fluidStateIn, level, pos)),
|
||||
overlayTexture == null ? null : Minecraft.getInstance().getTextureAtlas(TextureAtlas.LOCATION_BLOCKS).apply(overlayTexture),
|
||||
Minecraft.getInstance().getTextureAtlas(InventoryMenu.BLOCK_ATLAS).apply(props.getStillTexture(fluidStateIn, level, pos)),
|
||||
Minecraft.getInstance().getTextureAtlas(InventoryMenu.BLOCK_ATLAS).apply(props.getFlowingTexture(fluidStateIn, level, pos)),
|
||||
overlayTexture == null ? null : Minecraft.getInstance().getTextureAtlas(InventoryMenu.BLOCK_ATLAS).apply(overlayTexture),
|
||||
};
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static Material getBlockMaterial(ResourceLocation loc) {
|
||||
return new Material(TextureAtlas.LOCATION_BLOCKS, loc);
|
||||
return new Material(InventoryMenu.BLOCK_ATLAS, loc);
|
||||
}
|
||||
|
||||
/*
|
||||
public static void fillNormal(int[] faceData, Direction facing) {
|
||||
fillNormal(faceData, facing, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* internal, relies on fixed format of FaceBakery
|
||||
*/
|
||||
* /
|
||||
// TODO Do we need this?
|
||||
public static void fillNormal(int[] faceData, Direction facing, boolean calculateNormals) {
|
||||
Vector3f v2;
|
||||
@@ -468,6 +467,7 @@ public class ForgeHooksClient {
|
||||
for(int i = 0; i < 4; i++)
|
||||
faceData[i * 8 + 7] = normal;
|
||||
}
|
||||
*/
|
||||
|
||||
private static Vector3f getVertexPos(int[] data, int vertex) {
|
||||
int idx = vertex * 8;
|
||||
@@ -490,14 +490,6 @@ public class ForgeHooksClient {
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void loadEntityShader(Entity entity, GameRenderer entityRenderer) {
|
||||
if (entity != null) {
|
||||
ResourceLocation shader = EntitySpectatorShaderManager.get(entity.getType());
|
||||
if (shader != null)
|
||||
entityRenderer.loadEffect(shader);
|
||||
}
|
||||
}
|
||||
|
||||
private static int slotMainHand = 0;
|
||||
|
||||
public static boolean shouldCauseReequipAnimation(@NotNull ItemStack from, @NotNull ItemStack to, int slot) {
|
||||
@@ -517,22 +509,20 @@ public class ForgeHooksClient {
|
||||
|
||||
public static CustomizeGuiOverlayEvent.BossEventProgress onCustomizeBossEventProgress(GuiGraphics guiGraphics, Window window, LerpingBossEvent bossInfo, int x, int y, int increment) {
|
||||
var evt = new CustomizeGuiOverlayEvent.BossEventProgress(window, guiGraphics,
|
||||
Minecraft.getInstance().getTimer().getGameTimeDeltaPartialTick(false), bossInfo, x, y, increment);
|
||||
Minecraft.getInstance().getDeltaTracker().getGameTimeDeltaPartialTick(false), bossInfo, x, y, increment);
|
||||
MinecraftForge.EVENT_BUS.post(evt);
|
||||
return evt;
|
||||
}
|
||||
|
||||
public static void onCustomizeChatEvent(GuiGraphics guiGraphics, ChatComponent chat, Window window, int mouseX, int mouseY, int tickCount) {
|
||||
var minecraft = Minecraft.getInstance();
|
||||
minecraft.getProfiler().push("chat");
|
||||
var evt = new CustomizeGuiOverlayEvent.Chat(window, guiGraphics, minecraft.getTimer().getRealtimeDeltaTicks(), 0, chat.getHeight() - 40);
|
||||
var evt = new CustomizeGuiOverlayEvent.Chat(window, guiGraphics, minecraft.getDeltaTracker().getRealtimeDeltaTicks(), 0, chat.getHeight() - 40);
|
||||
MinecraftForge.EVENT_BUS.post(evt);
|
||||
guiGraphics.pose().pushPose();
|
||||
// We give the absolute Y position of the chat component in the event and account for the chat component's own offsetting here.
|
||||
guiGraphics.pose().translate(evt.getPosX(), (evt.getPosY() - chat.getHeight() + 40) / chat.getScale(), 0.0D);
|
||||
chat.render(guiGraphics, tickCount, mouseX, mouseY, false);
|
||||
guiGraphics.pose().popPose();
|
||||
minecraft.getProfiler().pop();
|
||||
}
|
||||
|
||||
public static void onCustomizeDebugEvent(GuiGraphics guiGraphics, Window window, float partialTick, List<String> text, boolean isLeft) {
|
||||
@@ -547,18 +537,18 @@ public class ForgeHooksClient {
|
||||
}
|
||||
}
|
||||
|
||||
public static void onMovementInputUpdate(Player player, Input movementInput) {
|
||||
public static void onMovementInputUpdate(Player player, ClientInput movementInput) {
|
||||
MinecraftForge.EVENT_BUS.post(new MovementInputUpdateEvent(player, movementInput));
|
||||
}
|
||||
|
||||
public static void onScreenKeyPressed(boolean[] state, Screen screen, int keyCode, int scanCode, int modifiers) {
|
||||
state[0] = ForgeEventFactoryClient.onScreenKeyPressedPre(screen, keyCode, scanCode, modifiers)
|
||||
public static boolean onScreenKeyPressed(Screen screen, int keyCode, int scanCode, int modifiers) {
|
||||
return ForgeEventFactoryClient.onScreenKeyPressedPre(screen, keyCode, scanCode, modifiers)
|
||||
|| screen.keyPressed(keyCode, scanCode, modifiers)
|
||||
|| ForgeEventFactoryClient.onScreenKeyPressedPost(screen, keyCode, scanCode, modifiers);
|
||||
}
|
||||
|
||||
public static void onScreenKeyReleased(boolean[] state, Screen screen, int keyCode, int scanCode, int modifiers) {
|
||||
state[0] = ForgeEventFactoryClient.onScreenKeyReleasedPre(screen, keyCode, scanCode, modifiers)
|
||||
public static boolean onScreenKeyReleased(Screen screen, int keyCode, int scanCode, int modifiers) {
|
||||
return ForgeEventFactoryClient.onScreenKeyReleasedPre(screen, keyCode, scanCode, modifiers)
|
||||
|| screen.keyReleased(keyCode, scanCode, modifiers)
|
||||
|| ForgeEventFactoryClient.onScreenKeyReleasedPost(screen, keyCode, scanCode, modifiers);
|
||||
}
|
||||
@@ -569,10 +559,6 @@ public class ForgeHooksClient {
|
||||
|| ForgeEventFactoryClient.onScreenCharTypedPost(screen, codePoint, modifiers);
|
||||
}
|
||||
|
||||
public static void onRecipesUpdated(RecipeManager mgr) {
|
||||
MinecraftForge.EVENT_BUS.post(new RecipesUpdatedEvent(mgr));
|
||||
}
|
||||
|
||||
public static void onKeyInput(int key, int scanCode, int action, int modifiers) {
|
||||
MinecraftForge.EVENT_BUS.post(new InputEvent.Key(key, scanCode, action, modifiers));
|
||||
}
|
||||
@@ -713,7 +699,7 @@ public class ForgeHooksClient {
|
||||
tooltip = ForgeI18n.parseMessage("fml.menu.multiplayer.unknown", target.forgeData.type());
|
||||
}
|
||||
|
||||
guiGraphics.blit(ICON_SHEET, x + width - 18, y + 10, 16, 16, 0, idx, 16, 16, 256, 256);
|
||||
guiGraphics.blit(RenderType::guiTextured, ICON_SHEET, x + width - 18, y + 10, 16, 16, 0, idx, 16, 16, 256, 256);
|
||||
|
||||
if(relativeMouseX > width - 15 && relativeMouseX < width && relativeMouseY > 10 && relativeMouseY < 26) {
|
||||
//this is not the most proper way to do it,
|
||||
@@ -742,10 +728,6 @@ public class ForgeHooksClient {
|
||||
ModLoader.get().postEvent(new RegisterKeyMappingsEvent(options));
|
||||
}
|
||||
|
||||
public static void onRegisterAdditionalModels(Set<ModelResourceLocation> additionalModels) {
|
||||
ModLoader.get().postEvent(new ModelEvent.RegisterAdditional(additionalModels));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static Component onClientChat(ChatType.Bound boundChatType, Component message, UUID sender) {
|
||||
ClientChatReceivedEvent event = new ClientChatReceivedEvent(boundChatType, message, sender);
|
||||
@@ -771,31 +753,9 @@ public class ForgeHooksClient {
|
||||
return MinecraftForge.EVENT_BUS.post(event) ? "" : event.getMessage();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mimics the behavior of {@link net.minecraft.client.renderer.ItemBlockRenderTypes#getRenderType(BlockState, boolean)}
|
||||
* for the input {@link RenderType}.
|
||||
*/
|
||||
@NotNull
|
||||
public static RenderType getEntityRenderType(RenderType chunkRenderType, boolean cull) {
|
||||
return RenderTypeHelper.getEntityRenderType(chunkRenderType, cull);
|
||||
}
|
||||
|
||||
@Mod.EventBusSubscriber(value = Dist.CLIENT, modid="forge", bus= Mod.EventBusSubscriber.Bus.MOD)
|
||||
public static class ClientEvents {
|
||||
@Nullable
|
||||
private static ShaderInstance rendertypeEntityTranslucentUnlitShader;
|
||||
|
||||
public static ShaderInstance getEntityTranslucentUnlitShader() {
|
||||
return Objects.requireNonNull(rendertypeEntityTranslucentUnlitShader, "Attempted to call getEntityTranslucentUnlitShader before shaders have finished loading.");
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void registerShaders(RegisterShadersEvent event) throws IOException {
|
||||
event.registerShader(new ShaderInstance(event.getResourceProvider(), ResourceLocation.fromNamespaceAndPath("forge", "rendertype_entity_unlit_translucent"), DefaultVertexFormat.NEW_ENTITY), (p_172645_) -> {
|
||||
rendertypeEntityTranslucentUnlitShader = p_172645_;
|
||||
});
|
||||
}
|
||||
}
|
||||
public static final Supplier<ShaderProgram> SHADER_UNLIT_TRANSLUCENT = Suppliers.memoize(() ->
|
||||
new ShaderProgram(ResourceLocation.fromNamespaceAndPath("forge", "rendertype_entity_unlit_translucent"), DefaultVertexFormat.NEW_ENTITY, ShaderDefines.EMPTY)
|
||||
);
|
||||
|
||||
public static Font getTooltipFont(@NotNull ItemStack stack, Font fallbackFont) {
|
||||
Font stackFont = IClientItemExtensions.of(stack).getFont(stack, IClientItemExtensions.FontContext.TOOLTIP);
|
||||
@@ -808,12 +768,6 @@ public class ForgeHooksClient {
|
||||
return preEvent;
|
||||
}
|
||||
|
||||
public static RenderTooltipEvent.Color onRenderTooltipColor(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, @NotNull Font font, @NotNull List<ClientTooltipComponent> components) {
|
||||
var colorEvent = new RenderTooltipEvent.Color(stack, graphics, x, y, font, 0xf0100010, 0x505000FF, 0x5028007f, components);
|
||||
MinecraftForge.EVENT_BUS.post(colorEvent);
|
||||
return colorEvent;
|
||||
}
|
||||
|
||||
public static List<ClientTooltipComponent> gatherTooltipComponents(ItemStack stack, List<? extends FormattedText> textElements, int mouseX, int screenWidth, int screenHeight, Font fallbackFont) {
|
||||
return gatherTooltipComponents(stack, textElements, Optional.empty(), mouseX, screenWidth, screenHeight, fallbackFont);
|
||||
}
|
||||
@@ -894,14 +848,6 @@ public class ForgeHooksClient {
|
||||
};
|
||||
}
|
||||
|
||||
public static ScreenEvent.RenderInventoryMobEffects onScreenPotionSize(Screen screen, int availableSpace, boolean compact, int horizontalOffset) {
|
||||
return MinecraftForge.EVENT_BUS.fire(new ScreenEvent.RenderInventoryMobEffects(screen, availableSpace, compact, horizontalOffset));
|
||||
}
|
||||
|
||||
public static boolean onToastAdd(Toast toast) {
|
||||
return MinecraftForge.EVENT_BUS.post(new ToastAddEvent(toast));
|
||||
}
|
||||
|
||||
public static boolean isBlockInSolidLayer(BlockState state) {
|
||||
var model = Minecraft.getInstance().getBlockRenderer().getBlockModel(state);
|
||||
return model.getRenderTypes(state, RandomSource.create(), ModelData.EMPTY).contains(RenderType.solid());
|
||||
@@ -949,37 +895,6 @@ public class ForgeHooksClient {
|
||||
return loc.withPath(normalised);
|
||||
}
|
||||
|
||||
/**
|
||||
* This function is a clone of {@link Direction#getNearest(float, float, float)} designed to return a consistent
|
||||
* direction when the normal is at an inflection point (ie 45 degrees) rounding errors
|
||||
* from associated matrix multiplication (such as during {@link SheetedDecalTextureGenerator#endVertex()}
|
||||
* can cause the direction chosen to be unstable.
|
||||
*
|
||||
* The function will only take effect if the Forge Client config option "stabilizeDirectionGetNearest" is enabled.
|
||||
*
|
||||
* This is a port of the downstream changes from https://github.com/neoforged/NeoForge PR #26
|
||||
*
|
||||
* @param nX X component of the normal
|
||||
* @param nY Y component of the normal
|
||||
* @param nZ Z component of the normal
|
||||
* @return the nearest Direction to the passed in normal, biased slightly in favor of the order of declaration
|
||||
*/
|
||||
public static Direction getNearestStable(float nX, float nY, float nZ) {
|
||||
if (ForgeConfig.CLIENT.stabilizeDirectionGetNearest.get()) {
|
||||
Direction ret = Direction.NORTH;
|
||||
float sum = Float.MIN_VALUE;
|
||||
for(Direction dir : Direction.values()) {
|
||||
float newSum = nX * (float)dir.getNormal().getX() + nY * (float)dir.getNormal().getY() + nZ * (float)dir.getNormal().getZ();
|
||||
if (newSum > sum + Constants.EPSILON) {
|
||||
sum = newSum;
|
||||
ret = dir;
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
} else
|
||||
return Direction.getNearest(nX, nY, nZ);
|
||||
}
|
||||
|
||||
// Make sure the below method is only ever called once (by forge).
|
||||
private static boolean initializedClientHooks = false;
|
||||
// Runs during Minecraft construction, before initial resource loading.
|
||||
@@ -997,7 +912,6 @@ public class ForgeHooksClient {
|
||||
ClientTooltipComponentManager.init();
|
||||
EntitySpectatorShaderManager.init();
|
||||
ForgeHooksClient.onRegisterKeyMappings(mc.options);
|
||||
RecipeBookManager.init();
|
||||
//GuiOverlayManager.init();
|
||||
DimensionSpecialEffectsManager.init();
|
||||
NamedRenderTypeManager.init();
|
||||
@@ -1014,11 +928,9 @@ public class ForgeHooksClient {
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void onScreenMouseDrag(Screen screen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY) {
|
||||
if (ForgeEventFactoryClient.onScreenMouseDragPre(screen, mouseX, mouseY, mouseButton, dragX, dragY))
|
||||
return;
|
||||
if (screen.mouseDragged(mouseX, mouseY, mouseButton, dragX, dragY))
|
||||
return;
|
||||
ForgeEventFactoryClient.onScreenMouseDragPost(screen, mouseX, mouseY, mouseButton, dragX, dragY);
|
||||
public static boolean onScreenMouseDrag(Screen screen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY) {
|
||||
return ForgeEventFactoryClient.onScreenMouseDragPre(screen, mouseX, mouseY, mouseButton, dragX, dragY)
|
||||
|| screen.mouseDragged(mouseX, mouseY, mouseButton, dragX, dragY)
|
||||
|| ForgeEventFactoryClient.onScreenMouseDragPost(screen, mouseX, mouseY, mouseButton, dragX, dragY);
|
||||
}
|
||||
}
|
||||
@@ -8,72 +8,64 @@ package net.minecraftforge.client;
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.RenderStateShard;
|
||||
import net.minecraft.client.renderer.RenderStateShard.TextureStateShard;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlas;
|
||||
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
|
||||
import com.mojang.blaze3d.vertex.VertexFormat;
|
||||
import net.minecraft.client.renderer.texture.TextureManager;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.util.TriState;
|
||||
import net.minecraft.world.inventory.InventoryMenu;
|
||||
import net.minecraftforge.common.util.NonNullLazy;
|
||||
import net.minecraftforge.common.util.NonNullSupplier;
|
||||
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public enum ForgeRenderTypes
|
||||
{
|
||||
ITEM_LAYERED_SOLID(()-> getItemLayeredSolid(TextureAtlas.LOCATION_BLOCKS)),
|
||||
ITEM_LAYERED_CUTOUT(()-> getItemLayeredCutout(TextureAtlas.LOCATION_BLOCKS)),
|
||||
ITEM_LAYERED_CUTOUT_MIPPED(()-> getItemLayeredCutoutMipped(TextureAtlas.LOCATION_BLOCKS)),
|
||||
ITEM_LAYERED_TRANSLUCENT(()-> getItemLayeredTranslucent(TextureAtlas.LOCATION_BLOCKS)),
|
||||
ITEM_UNSORTED_TRANSLUCENT(()-> getUnsortedTranslucent(TextureAtlas.LOCATION_BLOCKS)),
|
||||
ITEM_UNLIT_TRANSLUCENT(()-> getUnlitTranslucent(TextureAtlas.LOCATION_BLOCKS)),
|
||||
ITEM_UNSORTED_UNLIT_TRANSLUCENT(()-> getUnlitTranslucent(TextureAtlas.LOCATION_BLOCKS, false)),
|
||||
TRANSLUCENT_ON_PARTICLES_TARGET(() -> getTranslucentParticlesTarget(TextureAtlas.LOCATION_BLOCKS));
|
||||
public enum ForgeRenderTypes {
|
||||
ITEM_LAYERED_SOLID(()-> getItemLayeredSolid(InventoryMenu.BLOCK_ATLAS)),
|
||||
ITEM_LAYERED_CUTOUT(()-> getItemLayeredCutout(InventoryMenu.BLOCK_ATLAS)),
|
||||
ITEM_LAYERED_CUTOUT_MIPPED(()-> getItemLayeredCutoutMipped(InventoryMenu.BLOCK_ATLAS)),
|
||||
ITEM_LAYERED_TRANSLUCENT(()-> getItemLayeredTranslucent(InventoryMenu.BLOCK_ATLAS)),
|
||||
ITEM_UNSORTED_TRANSLUCENT(()-> getUnsortedTranslucent(InventoryMenu.BLOCK_ATLAS)),
|
||||
ITEM_UNLIT_TRANSLUCENT(()-> getUnlitTranslucent(InventoryMenu.BLOCK_ATLAS)),
|
||||
ITEM_UNSORTED_UNLIT_TRANSLUCENT(()-> getUnlitTranslucent(InventoryMenu.BLOCK_ATLAS, false)),
|
||||
TRANSLUCENT_ON_PARTICLES_TARGET(() -> getTranslucentParticlesTarget(InventoryMenu.BLOCK_ATLAS));
|
||||
|
||||
public static boolean enableTextTextureLinearFiltering = false;
|
||||
public static TriState enableTextTextureLinearFiltering = TriState.FALSE;
|
||||
|
||||
/**
|
||||
* @return A RenderType fit for multi-layer solid item rendering.
|
||||
*/
|
||||
public static RenderType getItemLayeredSolid(ResourceLocation textureLocation)
|
||||
{
|
||||
public static RenderType getItemLayeredSolid(ResourceLocation textureLocation) {
|
||||
return Internal.LAYERED_ITEM_SOLID.apply(textureLocation);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A RenderType fit for multi-layer cutout item item rendering.
|
||||
*/
|
||||
public static RenderType getItemLayeredCutout(ResourceLocation textureLocation)
|
||||
{
|
||||
public static RenderType getItemLayeredCutout(ResourceLocation textureLocation) {
|
||||
return Internal.LAYERED_ITEM_CUTOUT.apply(textureLocation);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A RenderType fit for multi-layer cutout-mipped item rendering.
|
||||
*/
|
||||
public static RenderType getItemLayeredCutoutMipped(ResourceLocation textureLocation)
|
||||
{
|
||||
public static RenderType getItemLayeredCutoutMipped(ResourceLocation textureLocation) {
|
||||
return Internal.LAYERED_ITEM_CUTOUT_MIPPED.apply(textureLocation);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A RenderType fit for multi-layer translucent item rendering.
|
||||
*/
|
||||
public static RenderType getItemLayeredTranslucent(ResourceLocation textureLocation)
|
||||
{
|
||||
public static RenderType getItemLayeredTranslucent(ResourceLocation textureLocation) {
|
||||
return Internal.LAYERED_ITEM_TRANSLUCENT.apply(textureLocation);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A RenderType fit for translucent item/entity rendering, but with depth sorting disabled.
|
||||
*/
|
||||
public static RenderType getUnsortedTranslucent(ResourceLocation textureLocation)
|
||||
{
|
||||
public static RenderType getUnsortedTranslucent(ResourceLocation textureLocation) {
|
||||
return Internal.UNSORTED_TRANSLUCENT.apply(textureLocation);
|
||||
}
|
||||
|
||||
@@ -81,8 +73,7 @@ public enum ForgeRenderTypes
|
||||
* @return A RenderType fit for translucent item/entity rendering, but with diffuse lighting disabled
|
||||
* so that fullbright quads look correct.
|
||||
*/
|
||||
public static RenderType getUnlitTranslucent(ResourceLocation textureLocation)
|
||||
{
|
||||
public static RenderType getUnlitTranslucent(ResourceLocation textureLocation) {
|
||||
return Internal.UNLIT_TRANSLUCENT_SORTED.apply(textureLocation);
|
||||
}
|
||||
|
||||
@@ -91,72 +82,63 @@ public enum ForgeRenderTypes
|
||||
* so that fullbright quads look correct.
|
||||
* @param sortingEnabled If false, depth sorting will not be performed.
|
||||
*/
|
||||
public static RenderType getUnlitTranslucent(ResourceLocation textureLocation, boolean sortingEnabled)
|
||||
{
|
||||
public static RenderType getUnlitTranslucent(ResourceLocation textureLocation, boolean sortingEnabled) {
|
||||
return (sortingEnabled ? Internal.UNLIT_TRANSLUCENT_SORTED : Internal.UNLIT_TRANSLUCENT_UNSORTED).apply(textureLocation);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Same as {@link RenderType#entityCutout(ResourceLocation)}, but with mipmapping enabled.
|
||||
*/
|
||||
public static RenderType getEntityCutoutMipped(ResourceLocation textureLocation)
|
||||
{
|
||||
public static RenderType getEntityCutoutMipped(ResourceLocation textureLocation) {
|
||||
return Internal.LAYERED_ITEM_CUTOUT_MIPPED.apply(textureLocation);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Replacement of {@link RenderType#text(ResourceLocation)}, but with optional linear texture filtering.
|
||||
*/
|
||||
public static RenderType getText(ResourceLocation locationIn)
|
||||
{
|
||||
public static RenderType getText(ResourceLocation locationIn) {
|
||||
return Internal.TEXT.apply(locationIn);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Replacement of {@link RenderType#textIntensity(ResourceLocation)}, but with optional linear texture filtering.
|
||||
*/
|
||||
public static RenderType getTextIntensity(ResourceLocation locationIn)
|
||||
{
|
||||
public static RenderType getTextIntensity(ResourceLocation locationIn) {
|
||||
return Internal.TEXT_INTENSITY.apply(locationIn);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Replacement of {@link RenderType#textPolygonOffset(ResourceLocation)}, but with optional linear texture filtering.
|
||||
*/
|
||||
public static RenderType getTextPolygonOffset(ResourceLocation locationIn)
|
||||
{
|
||||
public static RenderType getTextPolygonOffset(ResourceLocation locationIn) {
|
||||
return Internal.TEXT_POLYGON_OFFSET.apply(locationIn);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Replacement of {@link RenderType#textIntensityPolygonOffset(ResourceLocation)}, but with optional linear texture filtering.
|
||||
*/
|
||||
public static RenderType getTextIntensityPolygonOffset(ResourceLocation locationIn)
|
||||
{
|
||||
public static RenderType getTextIntensityPolygonOffset(ResourceLocation locationIn) {
|
||||
return Internal.TEXT_INTENSITY_POLYGON_OFFSET.apply(locationIn);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Replacement of {@link RenderType#textSeeThrough(ResourceLocation)}, but with optional linear texture filtering.
|
||||
*/
|
||||
public static RenderType getTextSeeThrough(ResourceLocation locationIn)
|
||||
{
|
||||
public static RenderType getTextSeeThrough(ResourceLocation locationIn) {
|
||||
return Internal.TEXT_SEETHROUGH.apply(locationIn);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Replacement of {@link RenderType#textIntensitySeeThrough(ResourceLocation)}, but with optional linear texture filtering.
|
||||
*/
|
||||
public static RenderType getTextIntensitySeeThrough(ResourceLocation locationIn)
|
||||
{
|
||||
public static RenderType getTextIntensitySeeThrough(ResourceLocation locationIn) {
|
||||
return Internal.TEXT_INTENSITY_SEETHROUGH.apply(locationIn);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A variation of {@link RenderType#translucent()} that uses {@link OutputStateShard#PARTICLES_TARGET} to allow fabulous transparency sorting when using {@link RenderLevelStageEvent}
|
||||
* @return A variation of {@link RenderType#translucent()} that uses {@link OutputStateShard#PARTICLES_TARGET}
|
||||
*/
|
||||
public static RenderType getTranslucentParticlesTarget(ResourceLocation locationIn)
|
||||
{
|
||||
public static RenderType getTranslucentParticlesTarget(ResourceLocation locationIn) {
|
||||
return Internal.TRANSLUCENT_PARTICLES_TARGET.apply(locationIn);
|
||||
}
|
||||
|
||||
@@ -166,35 +148,29 @@ public enum ForgeRenderTypes
|
||||
|
||||
private final NonNullSupplier<RenderType> renderTypeSupplier;
|
||||
|
||||
ForgeRenderTypes(NonNullSupplier<RenderType> renderTypeSupplier)
|
||||
{
|
||||
ForgeRenderTypes(NonNullSupplier<RenderType> renderTypeSupplier) {
|
||||
// Wrap in a Lazy<> to avoid running the supplier more than once.
|
||||
this.renderTypeSupplier = NonNullLazy.of(renderTypeSupplier);
|
||||
}
|
||||
|
||||
public RenderType get()
|
||||
{
|
||||
public RenderType get() {
|
||||
return renderTypeSupplier.get();
|
||||
}
|
||||
|
||||
private static class Internal extends RenderType {
|
||||
private static final ShaderStateShard RENDERTYPE_ENTITY_TRANSLUCENT_UNLIT_SHADER = new ShaderStateShard(ForgeHooksClient.SHADER_UNLIT_TRANSLUCENT.get());
|
||||
|
||||
private static class Internal extends RenderType
|
||||
{
|
||||
private static final ShaderStateShard RENDERTYPE_ENTITY_TRANSLUCENT_UNLIT_SHADER = new ShaderStateShard(ForgeHooksClient.ClientEvents::getEntityTranslucentUnlitShader);
|
||||
|
||||
private Internal(String name, VertexFormat fmt, VertexFormat.Mode glMode, int size, boolean doCrumbling, boolean depthSorting, Runnable onEnable, Runnable onDisable)
|
||||
{
|
||||
private Internal(String name, VertexFormat fmt, VertexFormat.Mode glMode, int size, boolean doCrumbling, boolean depthSorting, Runnable onEnable, Runnable onDisable) {
|
||||
super(name, fmt, glMode, size, doCrumbling, depthSorting, onEnable, onDisable);
|
||||
throw new IllegalStateException("This class must not be instantiated");
|
||||
}
|
||||
|
||||
public static Function<ResourceLocation, RenderType> UNSORTED_TRANSLUCENT = Util.memoize(Internal::unsortedTranslucent);
|
||||
private static RenderType unsortedTranslucent(ResourceLocation textureLocation)
|
||||
{
|
||||
private static RenderType unsortedTranslucent(ResourceLocation textureLocation) {
|
||||
final boolean sortingEnabled = false;
|
||||
CompositeState renderState = CompositeState.builder()
|
||||
.setShaderState(RenderType.RENDERTYPE_ENTITY_TRANSLUCENT_SHADER)
|
||||
.setTextureState(new TextureStateShard(textureLocation, false, false))
|
||||
.setTextureState(new TextureStateShard(textureLocation, TriState.FALSE, false))
|
||||
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
|
||||
.setCullState(NO_CULL)
|
||||
.setLightmapState(LIGHTMAP)
|
||||
@@ -203,25 +179,26 @@ public enum ForgeRenderTypes
|
||||
return create("forge_entity_unsorted_translucent", DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.QUADS, 256, true, sortingEnabled, renderState);
|
||||
}
|
||||
|
||||
private static final BiFunction<ResourceLocation, Boolean, RenderType> ENTITY_TRANSLUCENT = Util.memoize((p_173227_, p_173228_) -> {
|
||||
/*
|
||||
private static final BiFunction<ResourceLocation, Boolean, RenderType> ENTITY_TRANSLUCENT = Util.memoize((textureLocation, composite) -> {
|
||||
RenderType.CompositeState rendertype$compositestate = RenderType.CompositeState.builder()
|
||||
.setShaderState(RENDERTYPE_ENTITY_TRANSLUCENT_SHADER)
|
||||
.setTextureState(new RenderStateShard.TextureStateShard(p_173227_, false, false))
|
||||
.setTextureState(new TextureStateShard(textureLocation, TriState.FALSE, false))
|
||||
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
|
||||
.setCullState(NO_CULL)
|
||||
.setLightmapState(LIGHTMAP)
|
||||
.setOverlayState(OVERLAY)
|
||||
.createCompositeState(p_173228_);
|
||||
.createCompositeState(composite);
|
||||
return create("entity_translucent", DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.QUADS, 256, true, true, rendertype$compositestate);
|
||||
});
|
||||
*/
|
||||
|
||||
public static Function<ResourceLocation, RenderType> UNLIT_TRANSLUCENT_SORTED = Util.memoize(tex -> Internal.unlitTranslucent(tex, true));
|
||||
public static Function<ResourceLocation, RenderType> UNLIT_TRANSLUCENT_UNSORTED = Util.memoize(tex -> Internal.unlitTranslucent(tex, false));
|
||||
private static RenderType unlitTranslucent(ResourceLocation textureLocation, boolean sortingEnabled)
|
||||
{
|
||||
private static RenderType unlitTranslucent(ResourceLocation textureLocation, boolean sortingEnabled) {
|
||||
CompositeState renderState = CompositeState.builder()
|
||||
.setShaderState(RENDERTYPE_ENTITY_TRANSLUCENT_UNLIT_SHADER)
|
||||
.setTextureState(new TextureStateShard(textureLocation, false, false))
|
||||
.setTextureState(new TextureStateShard(textureLocation, TriState.FALSE, false))
|
||||
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
|
||||
.setCullState(NO_CULL)
|
||||
.setLightmapState(LIGHTMAP)
|
||||
@@ -234,7 +211,7 @@ public enum ForgeRenderTypes
|
||||
private static RenderType layeredItemSolid(ResourceLocation locationIn) {
|
||||
RenderType.CompositeState rendertype$state = RenderType.CompositeState.builder()
|
||||
.setShaderState(RenderType.RENDERTYPE_ENTITY_SOLID_SHADER)
|
||||
.setTextureState(new RenderStateShard.TextureStateShard(locationIn, false, false))
|
||||
.setTextureState(new TextureStateShard(locationIn, TriState.FALSE, false))
|
||||
.setTransparencyState(NO_TRANSPARENCY)
|
||||
.setLightmapState(LIGHTMAP)
|
||||
.setOverlayState(OVERLAY)
|
||||
@@ -246,7 +223,7 @@ public enum ForgeRenderTypes
|
||||
private static RenderType layeredItemCutout(ResourceLocation locationIn) {
|
||||
RenderType.CompositeState rendertype$state = RenderType.CompositeState.builder()
|
||||
.setShaderState(RenderType.RENDERTYPE_ENTITY_CUTOUT_SHADER)
|
||||
.setTextureState(new RenderStateShard.TextureStateShard(locationIn, false, false))
|
||||
.setTextureState(new TextureStateShard(locationIn, TriState.FALSE, false))
|
||||
.setTransparencyState(NO_TRANSPARENCY)
|
||||
.setLightmapState(LIGHTMAP)
|
||||
.setOverlayState(OVERLAY)
|
||||
@@ -258,7 +235,7 @@ public enum ForgeRenderTypes
|
||||
private static RenderType layeredItemCutoutMipped(ResourceLocation locationIn) {
|
||||
RenderType.CompositeState rendertype$state = RenderType.CompositeState.builder()
|
||||
.setShaderState(RenderType.RENDERTYPE_ENTITY_SMOOTH_CUTOUT_SHADER)
|
||||
.setTextureState(new RenderStateShard.TextureStateShard(locationIn, false, true))
|
||||
.setTextureState(new TextureStateShard(locationIn, TriState.FALSE, true))
|
||||
.setTransparencyState(NO_TRANSPARENCY)
|
||||
.setLightmapState(LIGHTMAP)
|
||||
.setOverlayState(OVERLAY)
|
||||
@@ -270,7 +247,7 @@ public enum ForgeRenderTypes
|
||||
private static RenderType layeredItemTranslucent(ResourceLocation locationIn) {
|
||||
RenderType.CompositeState rendertype$state = RenderType.CompositeState.builder()
|
||||
.setShaderState(RenderType.RENDERTYPE_ENTITY_TRANSLUCENT_SHADER)
|
||||
.setTextureState(new RenderStateShard.TextureStateShard(locationIn, false, false))
|
||||
.setTextureState(new TextureStateShard(locationIn, TriState.FALSE, false))
|
||||
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
|
||||
.setLightmapState(LIGHTMAP)
|
||||
.setOverlayState(OVERLAY)
|
||||
@@ -354,7 +331,7 @@ public enum ForgeRenderTypes
|
||||
private static RenderType getTranslucentParticlesTarget(ResourceLocation locationIn) {
|
||||
RenderType.CompositeState rendertype$state = RenderType.CompositeState.builder()
|
||||
.setShaderState(RENDERTYPE_TRANSLUCENT_SHADER)
|
||||
.setTextureState(new RenderStateShard.TextureStateShard(locationIn, false, true))
|
||||
.setTextureState(new TextureStateShard(locationIn, TriState.FALSE, true))
|
||||
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
|
||||
.setLightmapState(LIGHTMAP)
|
||||
.setOutputState(PARTICLES_TARGET)
|
||||
@@ -363,16 +340,15 @@ public enum ForgeRenderTypes
|
||||
}
|
||||
}
|
||||
|
||||
private static class CustomizableTextureState extends TextureStateShard
|
||||
{
|
||||
private CustomizableTextureState(ResourceLocation resLoc, Supplier<Boolean> blur, Supplier<Boolean> mipmap)
|
||||
{
|
||||
private static class CustomizableTextureState extends TextureStateShard {
|
||||
private CustomizableTextureState(ResourceLocation resLoc, Supplier<TriState> blur, Supplier<Boolean> mipmap) {
|
||||
super(resLoc, blur.get(), mipmap.get());
|
||||
this.setupState = () -> {
|
||||
this.blur = blur.get();
|
||||
this.mipmap = mipmap.get();
|
||||
TextureManager texturemanager = Minecraft.getInstance().getTextureManager();
|
||||
texturemanager.getTexture(resLoc).setFilter(this.blur, this.mipmap);
|
||||
TextureManager manager = Minecraft.getInstance().getTextureManager();
|
||||
var texture = manager.getTexture(resLoc);
|
||||
texture.setFilter(this.blur.toBoolean(texture.getDefaultBlur()), this.mipmap);
|
||||
RenderSystem.setShaderTexture(0, resLoc);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
package net.minecraftforge.client;
|
||||
|
||||
import net.minecraft.client.model.HumanoidModel;
|
||||
import net.minecraft.client.renderer.entity.state.HumanoidRenderState;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.entity.HumanoidArm;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
@@ -18,17 +19,16 @@ import net.minecraftforge.client.extensions.common.IClientItemExtensions;
|
||||
* and returning it in {@link IClientItemExtensions#getArmPose(LivingEntity, InteractionHand, ItemStack)}.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface IArmPoseTransformer
|
||||
{
|
||||
public interface IArmPoseTransformer {
|
||||
|
||||
/**
|
||||
* This method should be used to apply all wanted transformations to the player when the ArmPose is active.
|
||||
* You can use {@link LivingEntity#getTicksUsingItem()} and {@link LivingEntity#getUseItemRemainingTicks()} for moving animations.
|
||||
*
|
||||
* @param model The humanoid model
|
||||
* @param entity The humanoid entity
|
||||
* @param state The humanoid state
|
||||
* @param arm Arm to pose
|
||||
*/
|
||||
void applyTransform(HumanoidModel<?> model, LivingEntity entity, HumanoidArm arm);
|
||||
void applyTransform(HumanoidModel<? extends HumanoidRenderState> model, HumanoidRenderState state, HumanoidArm arm);
|
||||
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.client;
|
||||
|
||||
import net.minecraft.client.RecipeBookCategories;
|
||||
import net.minecraft.world.inventory.RecipeBookType;
|
||||
import net.minecraft.world.item.crafting.Recipe;
|
||||
import net.minecraft.world.item.crafting.RecipeHolder;
|
||||
import net.minecraft.world.item.crafting.RecipeType;
|
||||
import net.minecraftforge.client.event.RegisterRecipeBookCategoriesEvent;
|
||||
import net.minecraftforge.fml.ModLoader;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Manager for {@link RecipeBookType recipe book types} and {@link RecipeBookCategories categories}.
|
||||
* <p>
|
||||
* Provides a recipe category lookup.
|
||||
*/
|
||||
public final class RecipeBookManager {
|
||||
// Not using ConcurrentHashMap here because it's slower for lookups, so we only use it during init
|
||||
private static final Map<RecipeBookCategories, List<RecipeBookCategories>> AGGREGATE_CATEGORIES = new HashMap<>();
|
||||
private static final Map<RecipeBookType, List<RecipeBookCategories>> TYPE_CATEGORIES = new HashMap<>();
|
||||
private static final Map<RecipeType<?>, Function<Recipe<?>, RecipeBookCategories>> RECIPE_CATEGORY_LOOKUPS = new HashMap<>();
|
||||
private static final Map<RecipeBookCategories, List<RecipeBookCategories>> AGGREGATE_CATEGORIES_VIEW = Collections.unmodifiableMap(AGGREGATE_CATEGORIES);
|
||||
|
||||
/**
|
||||
* Finds the category the specified recipe should display in, or null if none.
|
||||
*/
|
||||
@Nullable
|
||||
public static <T extends Recipe<?>> RecipeBookCategories findCategories(RecipeType<T> type, RecipeHolder<T> recipe) {
|
||||
var lookup = RECIPE_CATEGORY_LOOKUPS.get(type);
|
||||
return lookup != null ? lookup.apply(recipe.value()) : null;
|
||||
}
|
||||
|
||||
@ApiStatus.Internal
|
||||
public static Map<RecipeBookCategories, List<RecipeBookCategories>> getAggregateCategories(Map<RecipeBookCategories, List<RecipeBookCategories>> vanilla) {
|
||||
return AGGREGATE_CATEGORIES_VIEW;
|
||||
}
|
||||
|
||||
@ApiStatus.Internal
|
||||
public static List<RecipeBookCategories> getCustomCategoriesOrEmpty(RecipeBookType recipeBookType) {
|
||||
return TYPE_CATEGORIES.getOrDefault(recipeBookType, List.of());
|
||||
}
|
||||
|
||||
@ApiStatus.Internal
|
||||
public static void init() {
|
||||
// The ImmutableMap is the patched out value of AGGREGATE_CATEGORIES
|
||||
var aggregateCategories = new HashMap<>(Map.of(
|
||||
RecipeBookCategories.CRAFTING_SEARCH, List.of(RecipeBookCategories.CRAFTING_EQUIPMENT, RecipeBookCategories.CRAFTING_BUILDING_BLOCKS, RecipeBookCategories.CRAFTING_MISC, RecipeBookCategories.CRAFTING_REDSTONE),
|
||||
RecipeBookCategories.FURNACE_SEARCH, List.of(RecipeBookCategories.FURNACE_FOOD, RecipeBookCategories.FURNACE_BLOCKS, RecipeBookCategories.FURNACE_MISC),
|
||||
RecipeBookCategories.BLAST_FURNACE_SEARCH, List.of(RecipeBookCategories.BLAST_FURNACE_BLOCKS, RecipeBookCategories.BLAST_FURNACE_MISC),
|
||||
RecipeBookCategories.SMOKER_SEARCH, List.of(RecipeBookCategories.SMOKER_FOOD)
|
||||
));
|
||||
|
||||
var typeCategories = new HashMap<RecipeBookType, List<RecipeBookCategories>>();
|
||||
var recipeCategoryLookups = new HashMap<RecipeType<?>, Function<Recipe<?>, RecipeBookCategories>>();
|
||||
var event = new RegisterRecipeBookCategoriesEvent(aggregateCategories, typeCategories, recipeCategoryLookups);
|
||||
ModLoader.get().postEventWrapContainerInModOrder(event);
|
||||
AGGREGATE_CATEGORIES.putAll(aggregateCategories);
|
||||
TYPE_CATEGORIES.putAll(typeCategories);
|
||||
RECIPE_CATEGORY_LOOKUPS.putAll(recipeCategoryLookups);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@
|
||||
package net.minecraftforge.client;
|
||||
|
||||
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.ItemBlockRenderTypes;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.renderer.Sheets;
|
||||
@@ -26,13 +25,11 @@ public final class RenderTypeHelper {
|
||||
* Provides a {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY} for the given {@link DefaultVertexFormat#BLOCK} format.
|
||||
* This should be called for each {@link RenderType} returned by {@link BakedModel#getRenderTypes(BlockState, RandomSource, ModelData)}.
|
||||
* <p>
|
||||
* Mimics the behavior of vanilla's {@link ItemBlockRenderTypes#getRenderType(BlockState, boolean)}.
|
||||
* Mimics the behavior of vanilla's {@link ItemBlockRenderTypes#getRenderType(BlockState)}.
|
||||
*/
|
||||
@NotNull
|
||||
public static RenderType getEntityRenderType(RenderType chunkRenderType, boolean cull) {
|
||||
if (chunkRenderType != RenderType.translucent())
|
||||
return Sheets.cutoutBlockSheet();
|
||||
return cull || !Minecraft.useShaderTransparency() ? Sheets.translucentCullBlockSheet() : Sheets.translucentItemSheet();
|
||||
public static RenderType getEntityRenderType(RenderType chunkRenderType) {
|
||||
return chunkRenderType == RenderType.translucent() ? Sheets.translucentItemSheet() : Sheets.cutoutBlockSheet();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -55,14 +52,14 @@ public final class RenderTypeHelper {
|
||||
* but removes the need to query the model again if the item is a {@link BlockItem}.
|
||||
*/
|
||||
@NotNull
|
||||
public static RenderType getFallbackItemRenderType(ItemStack stack, BakedModel model, boolean cull) {
|
||||
public static RenderType getFallbackItemRenderType(ItemStack stack, BakedModel model) {
|
||||
if (stack.getItem() instanceof BlockItem blockItem) {
|
||||
var renderTypes = model.getRenderTypes(blockItem.getBlock().defaultBlockState(), RandomSource.create(42), ModelData.EMPTY);
|
||||
if (renderTypes.contains(RenderType.translucent()))
|
||||
return getEntityRenderType(RenderType.translucent(), cull);
|
||||
return getEntityRenderType(RenderType.translucent());
|
||||
return Sheets.cutoutBlockSheet();
|
||||
}
|
||||
return cull ? Sheets.translucentCullBlockSheet() : Sheets.translucentItemSheet();
|
||||
return Sheets.translucentItemSheet();
|
||||
}
|
||||
|
||||
private RenderTypeHelper() {}
|
||||
|
||||
@@ -24,41 +24,42 @@ import org.jetbrains.annotations.ApiStatus;
|
||||
*
|
||||
* @see ViewportEvent.ComputeFov
|
||||
*/
|
||||
public class ComputeFovModifierEvent extends Event
|
||||
{
|
||||
public class ComputeFovModifierEvent extends Event {
|
||||
private final Player player;
|
||||
private final float fovModifier;
|
||||
private final float scale;
|
||||
private float newFovModifier;
|
||||
|
||||
@ApiStatus.Internal
|
||||
public ComputeFovModifierEvent(Player player, float fovModifier)
|
||||
{
|
||||
public ComputeFovModifierEvent(Player player, float fovModifier, float scale) {
|
||||
this.player = player;
|
||||
this.fovModifier = fovModifier;
|
||||
this.setNewFovModifier((float) Mth.lerp(Minecraft.getInstance().options.fovEffectScale().get(), 1.0F, fovModifier));
|
||||
this.scale = scale;
|
||||
this.newFovModifier = Mth.lerp(scale, 1.0F, fovModifier);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the player affected by this event}
|
||||
*/
|
||||
public Player getPlayer()
|
||||
{
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the original field of vision (FOV) of the player, before any modifications or interpolation}
|
||||
*/
|
||||
public float getFovModifier()
|
||||
{
|
||||
public float getFovModifier() {
|
||||
return fovModifier;
|
||||
}
|
||||
|
||||
public float getScale() {
|
||||
return scale;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the current field of vision (FOV) of the player}
|
||||
*/
|
||||
public float getNewFovModifier()
|
||||
{
|
||||
public float getNewFovModifier() {
|
||||
return newFovModifier;
|
||||
}
|
||||
|
||||
@@ -67,8 +68,7 @@ public class ComputeFovModifierEvent extends Event
|
||||
*
|
||||
* @param newFovModifier the new field of vision (FOV)
|
||||
*/
|
||||
public void setNewFovModifier(float newFovModifier)
|
||||
{
|
||||
public void setNewFovModifier(float newFovModifier) {
|
||||
this.newFovModifier = newFovModifier;
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@
|
||||
package net.minecraftforge.client.event;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import net.minecraft.client.model.EntityModel;
|
||||
import net.minecraft.client.model.SkullModel;
|
||||
import net.minecraft.client.model.SkullModelBase;
|
||||
import net.minecraft.client.model.geom.EntityModelSet;
|
||||
@@ -18,8 +17,8 @@ import net.minecraft.client.renderer.blockentity.BlockEntityRenderers;
|
||||
import net.minecraft.client.renderer.entity.EntityRenderer;
|
||||
import net.minecraft.client.renderer.entity.EntityRendererProvider;
|
||||
import net.minecraft.client.renderer.entity.EntityRenderers;
|
||||
import net.minecraft.client.renderer.entity.LivingEntityRenderer;
|
||||
import net.minecraft.client.renderer.entity.player.PlayerRenderer;
|
||||
import net.minecraft.client.renderer.entity.state.EntityRenderState;
|
||||
import net.minecraft.client.resources.PlayerSkin;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
@@ -128,12 +127,12 @@ public abstract class EntityRenderersEvent extends Event implements IModBusEvent
|
||||
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
|
||||
*/
|
||||
public static class AddLayers extends EntityRenderersEvent {
|
||||
private final Map<EntityType<?>, EntityRenderer<?>> renderers;
|
||||
private final Map<PlayerSkin.Model, EntityRenderer<? extends Player>> skinMap;
|
||||
private final Map<EntityType<?>, EntityRenderer<?, ?>> renderers;
|
||||
private final Map<PlayerSkin.Model, EntityRenderer<? extends Player, ?>> skinMap;
|
||||
private final EntityRendererProvider.Context context;
|
||||
|
||||
@ApiStatus.Internal
|
||||
public AddLayers(Map<EntityType<?>, EntityRenderer<?>> renderers, Map<PlayerSkin.Model, EntityRenderer<? extends Player>> playerRenderers, EntityRendererProvider.Context context) {
|
||||
public AddLayers(Map<EntityType<?>, EntityRenderer<?, ?>> renderers, Map<PlayerSkin.Model, EntityRenderer<? extends Player, ?>> playerRenderers, EntityRendererProvider.Context context) {
|
||||
this.renderers = renderers;
|
||||
this.skinMap = playerRenderers;
|
||||
this.context = context;
|
||||
@@ -160,7 +159,7 @@ public abstract class EntityRenderersEvent extends Event implements IModBusEvent
|
||||
*/
|
||||
@Nullable
|
||||
@SuppressWarnings("unchecked")
|
||||
public <R extends EntityRenderer<? extends Player>> R getPlayerSkin(PlayerSkin.Model skinName) {
|
||||
public <R extends EntityRenderer<? extends Player, ?>> R getPlayerSkin(PlayerSkin.Model skinName) {
|
||||
return (R)skinMap.get(skinName);
|
||||
}
|
||||
|
||||
@@ -174,7 +173,7 @@ public abstract class EntityRenderersEvent extends Event implements IModBusEvent
|
||||
*/
|
||||
@Nullable
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T extends LivingEntity, R extends EntityRenderer<T>> R getEntityRenderer(EntityType<? extends T> entityType) {
|
||||
public <T extends LivingEntity, S extends EntityRenderState, R extends EntityRenderer<T, S>> R getEntityRenderer(EntityType<? extends T> entityType) {
|
||||
return (R)renderers.get(entityType);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,53 +8,55 @@ package net.minecraftforge.client.event;
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.TickEvent;
|
||||
import net.minecraftforge.eventbus.api.Cancelable;
|
||||
import net.minecraftforge.fml.ModLoader;
|
||||
import net.minecraftforge.fml.event.IModBusEvent;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import com.mojang.blaze3d.audio.Channel;
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import com.mojang.datafixers.util.Pair;
|
||||
|
||||
import net.minecraft.client.Camera;
|
||||
import net.minecraft.client.ClientRecipeBook;
|
||||
import net.minecraft.client.DeltaTracker;
|
||||
import net.minecraft.client.KeyMapping;
|
||||
import net.minecraft.client.MouseHandler;
|
||||
import net.minecraft.client.gui.Font;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.components.toasts.Toast;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
|
||||
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent;
|
||||
import net.minecraft.client.model.EntityModel;
|
||||
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
|
||||
import net.minecraft.client.player.AbstractClientPlayer;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.client.renderer.GameRenderer;
|
||||
import net.minecraft.client.renderer.MultiBufferSource;
|
||||
import net.minecraft.client.renderer.ShaderInstance;
|
||||
import net.minecraft.client.renderer.entity.EntityRenderer;
|
||||
import net.minecraft.client.renderer.entity.EntityRendererProvider.Context;
|
||||
import net.minecraft.client.renderer.entity.ItemFrameRenderer;
|
||||
import net.minecraft.client.renderer.entity.LivingEntityRenderer;
|
||||
import net.minecraft.client.renderer.entity.player.PlayerRenderer;
|
||||
import net.minecraft.client.renderer.entity.state.EntityRenderState;
|
||||
import net.minecraft.client.renderer.entity.state.ItemFrameRenderState;
|
||||
import net.minecraft.client.renderer.entity.state.LivingEntityRenderState;
|
||||
import net.minecraft.client.renderer.entity.state.PlayerRenderState;
|
||||
import net.minecraft.client.resources.PlayerSkin.Model;
|
||||
import net.minecraft.client.resources.sounds.SoundInstance;
|
||||
import net.minecraft.client.sounds.SoundEngine;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.packs.resources.ResourceProvider;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.HumanoidArm;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.decoration.ItemFrame;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraftforge.client.event.sound.PlaySoundSourceEvent;
|
||||
import net.minecraftforge.client.event.sound.PlayStreamingSourceEvent;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
@@ -88,33 +90,27 @@ public final class ForgeEventFactoryClient {
|
||||
ML.postEvent(e);
|
||||
}
|
||||
|
||||
public static void onGatherLayers(Map<EntityType<?>, EntityRenderer<?>> renderers, Map<Model, EntityRenderer<? extends Player>> playerRenderers, Context context) {
|
||||
public static void onGatherLayers(Map<EntityType<?>, EntityRenderer<?, ?>> renderers, Map<Model, EntityRenderer<? extends Player, ?>> playerRenderers, Context context) {
|
||||
// TODO: Why is this a ModLoader event...
|
||||
postModBus(new EntityRenderersEvent.AddLayers(renderers, playerRenderers, context));
|
||||
}
|
||||
|
||||
public static void onRegisterShaders(ResourceProvider resourceProvider, List<Pair<ShaderInstance, Consumer<ShaderInstance>>> shaderList) {
|
||||
// TODO: Why is this a ModLoader event...
|
||||
postModBus(new RegisterShadersEvent(resourceProvider, shaderList));
|
||||
public static boolean onScreenMouseReleased(Screen screen, double mouseX, double mouseY, int button) {
|
||||
if (post(new ScreenEvent.MouseButtonReleased.Pre(screen, mouseX, mouseY, button)))
|
||||
return true;
|
||||
|
||||
var ret = screen.mouseReleased(mouseX, mouseY, button);
|
||||
var result = fire(new ScreenEvent.MouseButtonReleased.Post(screen, mouseX, mouseY, button, ret)).getResult();
|
||||
return result == Event.Result.DEFAULT ? ret : result == Event.Result.ALLOW;
|
||||
}
|
||||
|
||||
public static void onScreenMouseReleased(boolean[] state, Screen screen, double mouseX, double mouseY, int button) {
|
||||
state[0] = post(new ScreenEvent.MouseButtonReleased.Pre(screen, mouseX, mouseY, button));
|
||||
if (!state[0]) {
|
||||
state[0] = screen.mouseReleased(mouseX, mouseY, button);
|
||||
var result = fire(new ScreenEvent.MouseButtonReleased.Post(screen, mouseX, mouseY, button, state[0])).getResult();
|
||||
state[0] = result == Event.Result.DEFAULT ? state[0] : result == Event.Result.ALLOW;
|
||||
}
|
||||
}
|
||||
public static boolean onScreenMouseClicked(Screen screen, double mouseX, double mouseY, int button) {
|
||||
var ret = post(new ScreenEvent.MouseButtonPressed.Pre(screen, mouseX, mouseY, button));
|
||||
if (!ret)
|
||||
ret = screen.mouseClicked(mouseX, mouseY, button);
|
||||
|
||||
public static void onScreenMouseClicked(boolean[] state, Screen screen, double mouseX, double mouseY, int button) {
|
||||
state[0] = post(new ScreenEvent.MouseButtonPressed.Pre(screen, mouseX, mouseY, button));
|
||||
if (!state[0]) {
|
||||
state[0] = screen.mouseClicked(mouseX, mouseY, button);
|
||||
}
|
||||
|
||||
var result = fire(new ScreenEvent.MouseButtonPressed.Post(screen, mouseX, mouseY, button, state[0])).getResult();
|
||||
state[0] = result == Event.Result.DEFAULT ? state[0] : result == Event.Result.ALLOW;
|
||||
var result = fire(new ScreenEvent.MouseButtonPressed.Post(screen, mouseX, mouseY, button, ret)).getResult();
|
||||
return result == Event.Result.DEFAULT ? ret : result == Event.Result.ALLOW;
|
||||
}
|
||||
|
||||
public static boolean onMouseButtonPre(int button, int action, int mods) {
|
||||
@@ -141,8 +137,8 @@ public final class ForgeEventFactoryClient {
|
||||
return post(new ScreenEvent.MouseDragged.Pre(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY));
|
||||
}
|
||||
|
||||
public static void onScreenMouseDragPost(Screen guiScreen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY) {
|
||||
post(new ScreenEvent.MouseDragged.Post(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY));
|
||||
public static boolean onScreenMouseDragPost(Screen guiScreen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY) {
|
||||
return post(new ScreenEvent.MouseDragged.Post(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY));
|
||||
}
|
||||
|
||||
public static @Nullable Screen onScreenOpening(Screen old, Screen screen) {
|
||||
@@ -216,7 +212,7 @@ public final class ForgeEventFactoryClient {
|
||||
post(new ClientPlayerNetworkEvent.Clone(pc, oldPlayer, newPlayer, networkManager));
|
||||
}
|
||||
|
||||
public static ViewportEvent.ComputeFov fireComputeFov(GameRenderer renderer, Camera camera, double partialTick, double fov, boolean usedConfiguredFov) {
|
||||
public static ViewportEvent.ComputeFov fireComputeFov(GameRenderer renderer, Camera camera, double partialTick, float fov, boolean usedConfiguredFov) {
|
||||
return fire(new ViewportEvent.ComputeFov(renderer, camera, partialTick, fov, usedConfiguredFov));
|
||||
}
|
||||
|
||||
@@ -224,32 +220,32 @@ public final class ForgeEventFactoryClient {
|
||||
return fire(new ViewportEvent.ComputeCameraAngles(renderer, camera, partial, camera.getYRot(), camera.getXRot(), 0));
|
||||
}
|
||||
|
||||
public static <T extends LivingEntity, M extends EntityModel<T>> boolean onRenderLivingPre(LivingEntity entity, LivingEntityRenderer<T, M> renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
return post(new RenderLivingEvent.Pre<T, M>(entity, renderer, partialTick, poseStack, multiBufferSource, packedLight));
|
||||
public static <T extends LivingEntity, S extends LivingEntityRenderState, M extends EntityModel<? super S>> boolean onRenderLivingPre(S state, LivingEntityRenderer<T, S, M> renderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
return post(new RenderLivingEvent.Pre<T, S, M>(state, renderer, poseStack, multiBufferSource, packedLight));
|
||||
}
|
||||
|
||||
public static <T extends LivingEntity, M extends EntityModel<T>> boolean onRenderLivingPost(LivingEntity entity, LivingEntityRenderer<T, M> renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
return post(new RenderLivingEvent.Post<T, M>(entity, renderer, partialTick, poseStack, multiBufferSource, packedLight));
|
||||
public static <T extends LivingEntity, S extends LivingEntityRenderState, M extends EntityModel<? super S>> boolean onRenderLivingPost(S state, LivingEntityRenderer<T, S, M> renderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
return post(new RenderLivingEvent.Post<T, S, M>(state, renderer, poseStack, multiBufferSource, packedLight));
|
||||
}
|
||||
|
||||
public static boolean onRenderPlayerPre(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
return post(new RenderPlayerEvent.Pre(player, renderer, partialTick, poseStack, multiBufferSource, packedLight));
|
||||
public static boolean onRenderPlayerPre(PlayerRenderState player, PlayerRenderer renderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
return post(new RenderPlayerEvent.Pre(player, renderer, poseStack, multiBufferSource, packedLight));
|
||||
}
|
||||
|
||||
public static boolean onRenderPlayerPost(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
return post(new RenderPlayerEvent.Post(player, renderer, partialTick, poseStack, multiBufferSource, packedLight));
|
||||
public static boolean onRenderPlayerPost(PlayerRenderState player, PlayerRenderer renderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
return post(new RenderPlayerEvent.Post(player, renderer, poseStack, multiBufferSource, packedLight));
|
||||
}
|
||||
|
||||
public static boolean onRenderArm(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, AbstractClientPlayer player, HumanoidArm arm) {
|
||||
return post(new RenderArmEvent(poseStack, multiBufferSource, packedLight, player, arm));
|
||||
public static boolean onRenderArm(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, HumanoidArm arm) {
|
||||
return post(new RenderArmEvent(poseStack, multiBufferSource, packedLight, arm));
|
||||
}
|
||||
|
||||
public static boolean onRenderItemInFrame(ItemFrame itemFrame, ItemFrameRenderer<?> renderItemFrame, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
return post(new RenderItemInFrameEvent(itemFrame, renderItemFrame, poseStack, multiBufferSource, packedLight));
|
||||
public static boolean onRenderItemInFrame(ItemFrameRenderState state, ItemFrameRenderer<?> renderItemFrame, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
return post(new RenderItemInFrameEvent(state, renderItemFrame, poseStack, multiBufferSource, packedLight));
|
||||
}
|
||||
|
||||
public static RenderNameTagEvent fireRenderNameTagEvent(Entity entity, Component content, EntityRenderer<?> entityRenderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, float partialTick) {
|
||||
return fire(new RenderNameTagEvent(entity, content, entityRenderer, poseStack, multiBufferSource, packedLight, partialTick));
|
||||
public static RenderNameTagEvent fireRenderNameTagEvent(EntityRenderState state, Component content, EntityRenderer<?, ?> entityRenderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
return fire(new RenderNameTagEvent(state, content, entityRenderer, poseStack, multiBufferSource, packedLight));
|
||||
}
|
||||
|
||||
public static void onRenderScreenBackground(Screen screen, GuiGraphics guiGraphics) {
|
||||
@@ -263,4 +259,24 @@ public final class ForgeEventFactoryClient {
|
||||
public static void onRenderTickEnd(DeltaTracker timer) {
|
||||
post(new TickEvent.RenderTickEvent.Post(timer));
|
||||
}
|
||||
|
||||
public static RenderTooltipEvent.Background onRenderTooltipBackground(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, @NotNull Font font, @NotNull List<ClientTooltipComponent> components, @Nullable ResourceLocation backgroundPrefix) {
|
||||
return fire(new RenderTooltipEvent.Background(stack, graphics, x, y, font, components, backgroundPrefix));
|
||||
}
|
||||
|
||||
public static boolean onToastAdd(Toast toast) {
|
||||
return post(new ToastAddEvent(toast));
|
||||
}
|
||||
|
||||
public static ScreenEvent.RenderInventoryMobEffects onScreenEffectSize(Screen screen, int availableSpace, boolean compact, int horizontalOffset) {
|
||||
return fire(new ScreenEvent.RenderInventoryMobEffects(screen, availableSpace, compact, horizontalOffset));
|
||||
}
|
||||
|
||||
public static void onRecipesUpdated(ClientRecipeBook book) {
|
||||
post(new RecipesUpdatedEvent(book));
|
||||
}
|
||||
|
||||
public static ComputeFovModifierEvent fireFovModifierEvent(Player entity, float modifier, float scale) {
|
||||
return fire(new ComputeFovModifierEvent(entity, modifier, scale));
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,6 @@ import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Houses events related to models.
|
||||
@@ -116,31 +115,6 @@ public abstract class ModelEvent extends Event {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fired when the {@link net.minecraft.client.resources.model.ModelBakery} is notified of the resource manager reloading.
|
||||
* Allows developers to register models to be loaded, along with their dependencies.
|
||||
*
|
||||
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.</p>
|
||||
*
|
||||
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
|
||||
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
|
||||
*/
|
||||
public static class RegisterAdditional extends ModelEvent implements IModBusEvent {
|
||||
private final Set<ModelResourceLocation> models;
|
||||
|
||||
@ApiStatus.Internal
|
||||
public RegisterAdditional(Set<ModelResourceLocation> models) {
|
||||
this.models = models;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a model to be loaded, along with its dependencies.
|
||||
*/
|
||||
public void register(ModelResourceLocation model) {
|
||||
models.add(model);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows users to register their own {@link IGeometryLoader geometry loaders} for use in block/item models.
|
||||
*
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
package net.minecraftforge.client.event;
|
||||
|
||||
import net.minecraft.client.player.Input;
|
||||
import net.minecraft.client.player.ClientInput;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.entity.player.PlayerEvent;
|
||||
@@ -21,13 +21,11 @@ import org.jetbrains.annotations.ApiStatus;
|
||||
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
|
||||
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
|
||||
*/
|
||||
public class MovementInputUpdateEvent extends PlayerEvent
|
||||
{
|
||||
private final Input input;
|
||||
public class MovementInputUpdateEvent extends PlayerEvent {
|
||||
private final ClientInput input;
|
||||
|
||||
@ApiStatus.Internal
|
||||
public MovementInputUpdateEvent(Player player, Input input)
|
||||
{
|
||||
public MovementInputUpdateEvent(Player player, ClientInput input) {
|
||||
super(player);
|
||||
this.input = input;
|
||||
}
|
||||
@@ -35,8 +33,7 @@ public class MovementInputUpdateEvent extends PlayerEvent
|
||||
/**
|
||||
* {@return the player's movement inputs}
|
||||
*/
|
||||
public Input getInput()
|
||||
{
|
||||
public ClientInput getInput() {
|
||||
return input;
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
package net.minecraftforge.client.event;
|
||||
|
||||
import net.minecraft.client.ClientRecipeBook;
|
||||
import net.minecraft.world.item.crafting.RecipeManager;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.eventbus.api.Cancelable;
|
||||
@@ -13,28 +14,25 @@ import net.minecraftforge.fml.LogicalSide;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
/**
|
||||
* Fired when the {@link RecipeManager} has received and synced the recipes from the server to the client.
|
||||
* Fired when the {@link ClientRecipeBook} has updated information about recipes from the server to the client.
|
||||
*
|
||||
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.</p>
|
||||
*
|
||||
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
|
||||
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
|
||||
*/
|
||||
public class RecipesUpdatedEvent extends Event
|
||||
{
|
||||
private final RecipeManager recipeManager;
|
||||
public class RecipesUpdatedEvent extends Event {
|
||||
private final ClientRecipeBook recipeBook;
|
||||
|
||||
@ApiStatus.Internal
|
||||
public RecipesUpdatedEvent(RecipeManager recipeManager)
|
||||
{
|
||||
this.recipeManager = recipeManager;
|
||||
public RecipesUpdatedEvent(ClientRecipeBook recipeBook) {
|
||||
this.recipeBook = recipeBook;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the recipe manager}
|
||||
*/
|
||||
public RecipeManager getRecipeManager()
|
||||
{
|
||||
return recipeManager;
|
||||
public ClientRecipeBook getRecipeBook() {
|
||||
return recipeBook;
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.client.event;
|
||||
|
||||
import net.minecraft.client.RecipeBookCategories;
|
||||
import net.minecraft.world.inventory.RecipeBookType;
|
||||
import net.minecraft.world.item.crafting.Recipe;
|
||||
import net.minecraft.world.item.crafting.RecipeType;
|
||||
import net.minecraftforge.eventbus.api.Cancelable;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.fml.LogicalSide;
|
||||
import net.minecraftforge.fml.event.IModBusEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Allows users to register custom categories for the vanilla recipe book, making it usable in modded GUIs.
|
||||
*
|
||||
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.
|
||||
*
|
||||
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
|
||||
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
|
||||
*/
|
||||
public class RegisterRecipeBookCategoriesEvent extends Event implements IModBusEvent
|
||||
{
|
||||
private final Map<RecipeBookCategories, List<RecipeBookCategories>> aggregateCategories;
|
||||
private final Map<RecipeBookType, List<RecipeBookCategories>> typeCategories;
|
||||
private final Map<RecipeType<?>, Function<Recipe<?>, RecipeBookCategories>> recipeCategoryLookups;
|
||||
|
||||
@ApiStatus.Internal
|
||||
public RegisterRecipeBookCategoriesEvent(
|
||||
Map<RecipeBookCategories, List<RecipeBookCategories>> aggregateCategories,
|
||||
Map<RecipeBookType, List<RecipeBookCategories>> typeCategories,
|
||||
Map<RecipeType<?>, Function<Recipe<?>, RecipeBookCategories>> recipeCategoryLookups)
|
||||
{
|
||||
this.aggregateCategories = aggregateCategories;
|
||||
this.typeCategories = typeCategories;
|
||||
this.recipeCategoryLookups = recipeCategoryLookups;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the list of categories that compose an aggregate category.
|
||||
*/
|
||||
public void registerAggregateCategory(RecipeBookCategories category, List<RecipeBookCategories> others)
|
||||
{
|
||||
aggregateCategories.put(category, List.copyOf(others));
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the list of categories that compose a recipe book.
|
||||
*/
|
||||
public void registerBookCategories(RecipeBookType type, List<RecipeBookCategories> categories)
|
||||
{
|
||||
typeCategories.put(type, List.copyOf(categories));
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a category lookup for a certain recipe type.
|
||||
*/
|
||||
public void registerRecipeCategoryFinder(RecipeType<?> type, Function<Recipe<?>, RecipeBookCategories> lookup)
|
||||
{
|
||||
recipeCategoryLookups.put(type, lookup);
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.client.event;
|
||||
|
||||
import com.mojang.datafixers.util.Pair;
|
||||
import net.minecraft.client.renderer.ShaderInstance;
|
||||
import net.minecraft.server.packs.resources.ResourceProvider;
|
||||
import net.minecraftforge.eventbus.api.Cancelable;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.fml.LogicalSide;
|
||||
import net.minecraftforge.fml.event.IModBusEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Fired to allow mods to register custom {@linkplain ShaderInstance shaders}.
|
||||
* This event is fired after the default Minecraft shaders have been registered.
|
||||
*
|
||||
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.</p>
|
||||
*
|
||||
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
|
||||
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
|
||||
*/
|
||||
public class RegisterShadersEvent extends Event implements IModBusEvent {
|
||||
private final ResourceProvider resourceProvider;
|
||||
private final List<Pair<ShaderInstance, Consumer<ShaderInstance>>> shaderList;
|
||||
|
||||
@ApiStatus.Internal
|
||||
public RegisterShadersEvent(ResourceProvider resourceProvider, List<Pair<ShaderInstance, Consumer<ShaderInstance>>> shaderList) {
|
||||
this.resourceProvider = resourceProvider;
|
||||
this.shaderList = shaderList;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the client-side resource provider}
|
||||
*/
|
||||
public ResourceProvider getResourceProvider() {
|
||||
return resourceProvider;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a shader, and a callback for when the shader is loaded.
|
||||
*
|
||||
* <p>When creating a {@link ShaderInstance}, pass in the {@linkplain #getResourceProvider()
|
||||
* client-side resource provider} as the resource provider.</p>
|
||||
*
|
||||
* <p>Mods should not store the shader instance passed into this method. Instead, mods should store the shader
|
||||
* passed into the registered load callback.</p>
|
||||
*
|
||||
* @param shaderInstance a shader
|
||||
* @param onLoaded a callback for when the shader is loaded
|
||||
*/
|
||||
public void registerShader(ShaderInstance shaderInstance, Consumer<ShaderInstance> onLoaded) {
|
||||
shaderList.add(Pair.of(shaderInstance, onLoaded));
|
||||
}
|
||||
}
|
||||
@@ -32,15 +32,13 @@ public class RenderArmEvent extends Event {
|
||||
private final PoseStack poseStack;
|
||||
private final MultiBufferSource multiBufferSource;
|
||||
private final int packedLight;
|
||||
private final AbstractClientPlayer player;
|
||||
private final HumanoidArm arm;
|
||||
|
||||
@ApiStatus.Internal
|
||||
public RenderArmEvent(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, AbstractClientPlayer player, HumanoidArm arm) {
|
||||
public RenderArmEvent(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, HumanoidArm arm) {
|
||||
this.poseStack = poseStack;
|
||||
this.multiBufferSource = multiBufferSource;
|
||||
this.packedLight = packedLight;
|
||||
this.player = player;
|
||||
this.arm = arm;
|
||||
}
|
||||
|
||||
@@ -73,12 +71,4 @@ public class RenderArmEvent extends Event {
|
||||
public int getPackedLight() {
|
||||
return packedLight;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the client player that is having their arm rendered} In general, this will be the same as
|
||||
* {@link net.minecraft.client.Minecraft#player}.
|
||||
*/
|
||||
public AbstractClientPlayer getPlayer() {
|
||||
return player;
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import net.minecraft.client.renderer.LightTexture;
|
||||
import net.minecraft.client.renderer.MultiBufferSource;
|
||||
import net.minecraft.client.renderer.entity.ItemFrameRenderer;
|
||||
import net.minecraft.world.entity.decoration.ItemFrame;
|
||||
import net.minecraft.client.renderer.entity.state.ItemFrameRenderState;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.eventbus.api.Cancelable;
|
||||
@@ -31,18 +31,16 @@ import org.jetbrains.annotations.ApiStatus;
|
||||
*/
|
||||
@Cancelable
|
||||
public class RenderItemInFrameEvent extends Event {
|
||||
private final ItemStack itemStack;
|
||||
private final ItemFrame itemFrameEntity;
|
||||
private final ItemFrameRenderState state;
|
||||
private final ItemFrameRenderer<?> renderer;
|
||||
private final PoseStack poseStack;
|
||||
private final MultiBufferSource multiBufferSource;
|
||||
private final int packedLight;
|
||||
|
||||
@ApiStatus.Internal
|
||||
public RenderItemInFrameEvent(ItemFrame itemFrame, ItemFrameRenderer<?> renderItemFrame, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
itemStack = itemFrame.getItem();
|
||||
itemFrameEntity = itemFrame;
|
||||
renderer = renderItemFrame;
|
||||
public RenderItemInFrameEvent(ItemFrameRenderState state, ItemFrameRenderer<?> renderItemFrame, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
this.state = state;
|
||||
this.renderer = renderItemFrame;
|
||||
this.poseStack = poseStack;
|
||||
this.multiBufferSource = multiBufferSource;
|
||||
this.packedLight = packedLight;
|
||||
@@ -52,14 +50,14 @@ public class RenderItemInFrameEvent extends Event {
|
||||
* {@return the item stack being rendered}
|
||||
*/
|
||||
public ItemStack getItemStack() {
|
||||
return itemStack;
|
||||
return getItemFrameState().itemStack;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the item frame entity}
|
||||
*/
|
||||
public ItemFrame getItemFrameEntity() {
|
||||
return itemFrameEntity;
|
||||
public ItemFrameRenderState getItemFrameState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,247 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.client.event;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
|
||||
import net.minecraft.client.Camera;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.GameRenderer;
|
||||
import net.minecraft.client.renderer.LevelRenderer;
|
||||
import net.minecraft.client.renderer.LightTexture;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.renderer.culling.Frustum;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraftforge.client.ForgeRenderTypes;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.eventbus.api.Cancelable;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.fml.LogicalSide;
|
||||
import net.minecraftforge.fml.event.IModBusEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.joml.Matrix4f;
|
||||
|
||||
/**
|
||||
* Fires at various times during LevelRenderer.renderLevel.
|
||||
* Check {@link #getStage} to render during the appropriate time for your use case.
|
||||
*
|
||||
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}. </p>
|
||||
*
|
||||
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
|
||||
* only on the {@linkplain LogicalSide#CLIENT logical client}. </p>
|
||||
*/
|
||||
public class RenderLevelStageEvent extends Event {
|
||||
private final Stage stage;
|
||||
private final LevelRenderer levelRenderer;
|
||||
private final Matrix4f poseStack;
|
||||
private final Matrix4f projectionMatrix;
|
||||
private final int renderTick;
|
||||
private final float partialTick;
|
||||
private final Camera camera;
|
||||
private final Frustum frustum;
|
||||
|
||||
public RenderLevelStageEvent(Stage stage, LevelRenderer levelRenderer, Matrix4f poseStack, Matrix4f projectionMatrix, int renderTick, float partialTick, Camera camera, Frustum frustum) {
|
||||
this.stage = stage;
|
||||
this.levelRenderer = levelRenderer;
|
||||
this.poseStack = poseStack;
|
||||
this.projectionMatrix = projectionMatrix;
|
||||
this.renderTick = renderTick;
|
||||
this.partialTick = partialTick;
|
||||
this.camera = camera;
|
||||
this.frustum = frustum;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the current {@linkplain Stage stage} that is being rendered. Check this before doing rendering to ensure
|
||||
* that rendering happens at the appropriate time.}
|
||||
*/
|
||||
public Stage getStage() {
|
||||
return stage;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the level renderer}
|
||||
*/
|
||||
public LevelRenderer getLevelRenderer() {
|
||||
return levelRenderer;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Mojang has stopped passing around PosStacks. getProjectionMatrix should be enough.
|
||||
*/
|
||||
@Deprecated(forRemoval = true, since = "1.21")
|
||||
public Matrix4f getPoseStack() {
|
||||
return poseStack;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the projection matrix}
|
||||
*/
|
||||
public Matrix4f getProjectionMatrix() {
|
||||
return projectionMatrix;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the current "ticks" value in the {@linkplain LevelRenderer level renderer}}
|
||||
*/
|
||||
public int getRenderTick() {
|
||||
return renderTick;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the current partialTick value used for rendering}
|
||||
*/
|
||||
public float getPartialTick() {
|
||||
return partialTick;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the camera}
|
||||
*/
|
||||
public Camera getCamera() {
|
||||
return camera;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the frustum}
|
||||
*/
|
||||
public Frustum getFrustum() {
|
||||
return frustum;
|
||||
}
|
||||
|
||||
/**
|
||||
* Use to create a custom {@linkplain RenderLevelStageEvent.Stage stages}.
|
||||
* Fired after the LevelRenderer has been created.
|
||||
*
|
||||
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}. </p>
|
||||
*
|
||||
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
|
||||
* only on the {@linkplain LogicalSide#CLIENT logical client}. </p>
|
||||
*/
|
||||
public static class RegisterStageEvent extends Event implements IModBusEvent {
|
||||
/**
|
||||
* @param name The name of your Stage.
|
||||
* @param renderType
|
||||
* If not null, called automatically by LevelRenderer.renderChunkLayer if the RenderType passed into it matches this one.
|
||||
* If null, needs to be called manually by whoever implements it.
|
||||
*
|
||||
* @throws IllegalArgumentException if the RenderType passed is already mapped to a Stage.
|
||||
*/
|
||||
public Stage register(ResourceLocation name, @Nullable RenderType renderType) throws IllegalArgumentException {
|
||||
return Stage.register(name, renderType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A time during level rendering for you to render custom things into the world.
|
||||
* @see RegisterStageEvent
|
||||
*/
|
||||
public static class Stage {
|
||||
private static final Map<RenderType, Stage> RENDER_TYPE_STAGES = new HashMap<>();
|
||||
|
||||
/**
|
||||
* Use this to render custom objects into the skybox.
|
||||
* Called regardless of if they sky actually renders or not.
|
||||
*/
|
||||
public static final Stage AFTER_SKY = register("after_sky", null);
|
||||
/**
|
||||
* Use this to render custom block-like geometry into the world.
|
||||
*/
|
||||
public static final Stage AFTER_SOLID_BLOCKS = register("after_solid_blocks", RenderType.solid());
|
||||
/**
|
||||
* Use this to render custom block-like geometry into the world.
|
||||
*/
|
||||
public static final Stage AFTER_CUTOUT_MIPPED_BLOCKS_BLOCKS = register("after_cutout_mipped_blocks", RenderType.cutoutMipped());
|
||||
/**
|
||||
* Use this to render custom block-like geometry into the world.
|
||||
*/
|
||||
public static final Stage AFTER_CUTOUT_BLOCKS = register("after_cutout_blocks", RenderType.cutout());
|
||||
/**
|
||||
* Use this to render custom block-like geometry into the world.
|
||||
*/
|
||||
public static final Stage AFTER_ENTITIES = register("after_entities", null);
|
||||
/**
|
||||
* Use this to render custom block-like geometry into the world.
|
||||
*/
|
||||
public static final Stage AFTER_BLOCK_ENTITIES = register("after_block_entities", null);
|
||||
/**
|
||||
* Use this to render custom block-like geometry into the world.
|
||||
* Due to how transparency sorting works, this stage may not work properly with translucency. If you intend to render translucency,
|
||||
* try using {@link #AFTER_TRIPWIRE_BLOCKS} or {@link #AFTER_PARTICLES}.
|
||||
* Although this is called within a fabulous graphics target, it does not function properly in many cases.
|
||||
*/
|
||||
public static final Stage AFTER_TRANSLUCENT_BLOCKS = register("after_translucent_blocks", RenderType.translucent());
|
||||
/**
|
||||
* Use this to render custom block-like geometry into the world.
|
||||
*/
|
||||
public static final Stage AFTER_TRIPWIRE_BLOCKS = register("after_tripwire_blocks", RenderType.tripwire());
|
||||
/**
|
||||
* Use this to render custom effects into the world, such as custom entity-like objects or special rendering effects.
|
||||
* Called within a fabulous graphics target.
|
||||
* Happens after entities render.
|
||||
*
|
||||
* @see ForgeRenderTypes#TRANSLUCENT_ON_PARTICLES_TARGET
|
||||
*/
|
||||
public static final Stage AFTER_PARTICLES = register("after_particles", null);
|
||||
/**
|
||||
* Use this to render custom weather effects into the world.
|
||||
* Called within a fabulous graphics target.
|
||||
*/
|
||||
public static final Stage AFTER_WEATHER = register("after_weather", null);
|
||||
/**
|
||||
* Use this to render after everything in the level has been rendered.
|
||||
* Called after {@link LevelRenderer#renderLevel(PoseStack, float, long, boolean, Camera, GameRenderer, LightTexture, Matrix4f)} finishes.
|
||||
*/
|
||||
public static final Stage AFTER_LEVEL = register("after_level", null);
|
||||
|
||||
private final String name;
|
||||
|
||||
private Stage(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
private static Stage register(ResourceLocation name, @Nullable RenderType renderType) throws IllegalArgumentException {
|
||||
Stage stage = new Stage(name.toString());
|
||||
if (renderType != null && RENDER_TYPE_STAGES.putIfAbsent(renderType, stage) != null)
|
||||
throw new IllegalArgumentException("Attempted to replace an existing RenderLevelStageEvent.Stage for a RenderType: Stage = " + stage + ", RenderType = " + renderType);
|
||||
return stage;
|
||||
}
|
||||
|
||||
private static Stage register(String name, @Nullable RenderType renderType) throws IllegalArgumentException {
|
||||
return register(ResourceLocation.parse(name), renderType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the {@linkplain Stage stage} bound to the {@linkplain RenderType render type}, or null if no value is present}
|
||||
*/
|
||||
@Nullable
|
||||
public static Stage fromRenderType(RenderType renderType) {
|
||||
return RENDER_TYPE_STAGES.get(renderType);
|
||||
}
|
||||
|
||||
/** Internal just to make our patch smaller, it just fires the event. If you have good reason for this to be external, ask. */
|
||||
@ApiStatus.Internal
|
||||
public void dispatch(LevelRenderer levelRenderer, Matrix4f poseStack, Matrix4f projectionMatrix, int renderTick, Camera camera, Frustum frustum) {
|
||||
var mc = Minecraft.getInstance();
|
||||
var profiler = mc.getProfiler();
|
||||
profiler.push(this.toString());
|
||||
MinecraftForge.EVENT_BUS.post(new RenderLevelStageEvent(this, levelRenderer, poseStack, projectionMatrix, renderTick, mc.getTimer().getRealtimeDeltaTicks(), camera, frustum));
|
||||
profiler.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import net.minecraft.client.model.EntityModel;
|
||||
import net.minecraft.client.renderer.LightTexture;
|
||||
import net.minecraft.client.renderer.MultiBufferSource;
|
||||
import net.minecraft.client.renderer.entity.LivingEntityRenderer;
|
||||
import net.minecraft.client.renderer.entity.state.LivingEntityRenderState;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.eventbus.api.Cancelable;
|
||||
@@ -31,19 +32,17 @@ import org.jetbrains.annotations.ApiStatus;
|
||||
* @see RenderPlayerEvent
|
||||
* @see LivingEntityRenderer
|
||||
*/
|
||||
public abstract class RenderLivingEvent<T extends LivingEntity, M extends EntityModel<T>> extends Event {
|
||||
private final LivingEntity entity;
|
||||
private final LivingEntityRenderer<T, M> renderer;
|
||||
private final float partialTick;
|
||||
public abstract class RenderLivingEvent<T extends LivingEntity, S extends LivingEntityRenderState, M extends EntityModel<? super S>> extends Event {
|
||||
private final S state;
|
||||
private final LivingEntityRenderer<T, S, M> renderer;
|
||||
private final PoseStack poseStack;
|
||||
private final MultiBufferSource multiBufferSource;
|
||||
private final int packedLight;
|
||||
|
||||
@ApiStatus.Internal
|
||||
protected RenderLivingEvent(LivingEntity entity, LivingEntityRenderer<T, M> renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
this.entity = entity;
|
||||
protected RenderLivingEvent(S state, LivingEntityRenderer<T, S, M> renderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
this.state = state;
|
||||
this.renderer = renderer;
|
||||
this.partialTick = partialTick;
|
||||
this.poseStack = poseStack;
|
||||
this.multiBufferSource = multiBufferSource;
|
||||
this.packedLight = packedLight;
|
||||
@@ -52,24 +51,17 @@ public abstract class RenderLivingEvent<T extends LivingEntity, M extends Entity
|
||||
/**
|
||||
* @return the living entity being rendered
|
||||
*/
|
||||
public LivingEntity getEntity() {
|
||||
return entity;
|
||||
public S getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the renderer for the living entity
|
||||
*/
|
||||
public LivingEntityRenderer<T, M> getRenderer() {
|
||||
public LivingEntityRenderer<T, S, M> getRenderer() {
|
||||
return renderer;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the partial tick}
|
||||
*/
|
||||
public float getPartialTick() {
|
||||
return partialTick;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the pose stack used for rendering}
|
||||
*/
|
||||
@@ -108,10 +100,10 @@ public abstract class RenderLivingEvent<T extends LivingEntity, M extends Entity
|
||||
* @param <M> the model for the living entity
|
||||
*/
|
||||
@Cancelable
|
||||
public static class Pre<T extends LivingEntity, M extends EntityModel<T>> extends RenderLivingEvent<T, M> {
|
||||
public static class Pre<T extends LivingEntity, S extends LivingEntityRenderState, M extends EntityModel<? super S>> extends RenderLivingEvent<T, S, M> {
|
||||
@ApiStatus.Internal
|
||||
public Pre(LivingEntity entity, LivingEntityRenderer<T, M> renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
super(entity, renderer, partialTick, poseStack, multiBufferSource, packedLight);
|
||||
public Pre(S state, LivingEntityRenderer<T, S, M> renderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
super(state, renderer, poseStack, multiBufferSource, packedLight);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,10 +118,10 @@ public abstract class RenderLivingEvent<T extends LivingEntity, M extends Entity
|
||||
* @param <T> the living entity that was rendered
|
||||
* @param <M> the model for the living entity
|
||||
*/
|
||||
public static class Post<T extends LivingEntity, M extends EntityModel<T>> extends RenderLivingEvent<T, M> {
|
||||
public static class Post<T extends LivingEntity, S extends LivingEntityRenderState, M extends EntityModel<? super S>> extends RenderLivingEvent<T, S, M> {
|
||||
@ApiStatus.Internal
|
||||
public Post(LivingEntity entity, LivingEntityRenderer<T, M> renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
super(entity, renderer, partialTick, poseStack, multiBufferSource, packedLight);
|
||||
public Post(S state, LivingEntityRenderer<T, S, M> renderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
super(state, renderer, poseStack, multiBufferSource, packedLight);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,10 +8,9 @@ package net.minecraftforge.client.event;
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import net.minecraft.client.renderer.MultiBufferSource;
|
||||
import net.minecraft.client.renderer.entity.EntityRenderer;
|
||||
import net.minecraft.client.renderer.entity.state.EntityRenderState;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.entity.EntityEvent;
|
||||
import net.minecraftforge.eventbus.api.Cancelable;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.fml.LogicalSide;
|
||||
@@ -33,25 +32,29 @@ import org.jetbrains.annotations.ApiStatus;
|
||||
* @see EntityRenderer
|
||||
*/
|
||||
@Event.HasResult
|
||||
public class RenderNameTagEvent extends EntityEvent {
|
||||
public class RenderNameTagEvent extends Event {
|
||||
private Component nameplateContent;
|
||||
private final EntityRenderState state;
|
||||
private final Component originalContent;
|
||||
private final EntityRenderer<?> entityRenderer;
|
||||
private final EntityRenderer<?, ?> entityRenderer;
|
||||
private final PoseStack poseStack;
|
||||
private final MultiBufferSource multiBufferSource;
|
||||
private final int packedLight;
|
||||
private final float partialTick;
|
||||
|
||||
@ApiStatus.Internal
|
||||
public RenderNameTagEvent(Entity entity, Component content, EntityRenderer<?> entityRenderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, float partialTick) {
|
||||
super(entity);
|
||||
public RenderNameTagEvent(EntityRenderState state, Component content, EntityRenderer<?, ?> entityRenderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
this.state = state;
|
||||
this.originalContent = content;
|
||||
this.setContent(this.originalContent);
|
||||
this.entityRenderer = entityRenderer;
|
||||
this.poseStack = poseStack;
|
||||
this.multiBufferSource = multiBufferSource;
|
||||
this.packedLight = packedLight;
|
||||
this.partialTick = partialTick;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T extends EntityRenderState> T getState() {
|
||||
return (T)state;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -80,7 +83,7 @@ public class RenderNameTagEvent extends EntityEvent {
|
||||
/**
|
||||
* {@return the entity renderer rendering the nameplate}
|
||||
*/
|
||||
public EntityRenderer<?> getEntityRenderer() {
|
||||
public EntityRenderer<?, ?> getEntityRenderer() {
|
||||
return this.entityRenderer;
|
||||
}
|
||||
|
||||
@@ -106,11 +109,4 @@ public class RenderNameTagEvent extends EntityEvent {
|
||||
public int getPackedLight() {
|
||||
return this.packedLight;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the partial tick}
|
||||
*/
|
||||
public float getPartialTick() {
|
||||
return this.partialTick;
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,10 @@ import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import net.minecraft.client.renderer.LightTexture;
|
||||
import net.minecraft.client.renderer.MultiBufferSource;
|
||||
import net.minecraft.client.renderer.entity.player.PlayerRenderer;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.client.renderer.entity.state.PlayerRenderState;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.entity.player.PlayerEvent;
|
||||
import net.minecraftforge.eventbus.api.Cancelable;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.fml.LogicalSide;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
@@ -24,23 +24,26 @@ import org.jetbrains.annotations.ApiStatus;
|
||||
* @see RenderPlayerEvent.Post
|
||||
* @see PlayerRenderer
|
||||
*/
|
||||
public abstract class RenderPlayerEvent extends PlayerEvent {
|
||||
public abstract class RenderPlayerEvent extends Event {
|
||||
private final PlayerRenderState state;
|
||||
private final PlayerRenderer renderer;
|
||||
private final float partialTick;
|
||||
private final PoseStack poseStack;
|
||||
private final MultiBufferSource multiBufferSource;
|
||||
private final int packedLight;
|
||||
|
||||
@ApiStatus.Internal
|
||||
protected RenderPlayerEvent(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
super(player);
|
||||
protected RenderPlayerEvent(PlayerRenderState state, PlayerRenderer renderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
this.state = state;
|
||||
this.renderer = renderer;
|
||||
this.partialTick = partialTick;
|
||||
this.poseStack = poseStack;
|
||||
this.multiBufferSource = multiBufferSource;
|
||||
this.packedLight = packedLight;
|
||||
}
|
||||
|
||||
public PlayerRenderState getState() {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the player entity renderer}
|
||||
*/
|
||||
@@ -48,13 +51,6 @@ public abstract class RenderPlayerEvent extends PlayerEvent {
|
||||
return renderer;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the partial tick}
|
||||
*/
|
||||
public float getPartialTick() {
|
||||
return partialTick;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the pose stack used for rendering}
|
||||
*/
|
||||
@@ -92,8 +88,8 @@ public abstract class RenderPlayerEvent extends PlayerEvent {
|
||||
@Cancelable
|
||||
public static class Pre extends RenderPlayerEvent {
|
||||
@ApiStatus.Internal
|
||||
public Pre(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
super(player, renderer, partialTick, poseStack, multiBufferSource, packedLight);
|
||||
public Pre(PlayerRenderState state, PlayerRenderer renderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
super(state, renderer, poseStack, multiBufferSource, packedLight);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,8 +103,8 @@ public abstract class RenderPlayerEvent extends PlayerEvent {
|
||||
*/
|
||||
public static class Post extends RenderPlayerEvent {
|
||||
@ApiStatus.Internal
|
||||
public Post(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
super(player, renderer, partialTick, poseStack, multiBufferSource, packedLight);
|
||||
public Post(PlayerRenderState state, PlayerRenderer renderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
|
||||
super(state, renderer, poseStack, multiBufferSource, packedLight);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent;
|
||||
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipPositioner;
|
||||
import net.minecraft.network.chat.FormattedText;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.inventory.tooltip.TooltipComponent;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
@@ -20,6 +21,7 @@ import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.fml.LogicalSide;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
@@ -30,7 +32,7 @@ import java.util.List;
|
||||
*
|
||||
* @see RenderTooltipEvent.GatherComponents
|
||||
* @see RenderTooltipEvent.Pre
|
||||
* @see RenderTooltipEvent.Color
|
||||
* @see RenderTooltipEvent.Background
|
||||
*/
|
||||
public abstract class RenderTooltipEvent extends Event
|
||||
{
|
||||
@@ -113,7 +115,7 @@ public abstract class RenderTooltipEvent extends Event
|
||||
*
|
||||
* <p>This event is {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.
|
||||
* If this event is cancelled, then the list of components will be empty, causing the tooltip to not be rendered and
|
||||
* the corresponding {@link RenderTooltipEvent.Pre} and {@link RenderTooltipEvent.Color} to not be fired.</p>
|
||||
* the corresponding {@link RenderTooltipEvent.Pre} and {@link RenderTooltipEvent.Background} to not be fired.</p>
|
||||
*
|
||||
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
|
||||
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
|
||||
@@ -202,7 +204,7 @@ public abstract class RenderTooltipEvent extends Event
|
||||
*
|
||||
* <p>This event is {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.
|
||||
* If this event is cancelled, then the tooltip will not be rendered and the corresponding
|
||||
* {@link RenderTooltipEvent.Color} will not be fired.</p>
|
||||
* {@link RenderTooltipEvent.Background} will not be fired.</p>
|
||||
*
|
||||
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
|
||||
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
|
||||
@@ -279,151 +281,44 @@ public abstract class RenderTooltipEvent extends Event
|
||||
}
|
||||
|
||||
/**
|
||||
* Fired when the colours for the tooltip background are determined.
|
||||
* This can be used to modify the background color and the border's gradient colors.
|
||||
* Fired when the tooltip background prefix is determined.
|
||||
* This can be used to modify the textures to be used for the tooltip background.
|
||||
*
|
||||
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.</p>
|
||||
*
|
||||
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
|
||||
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
|
||||
*/
|
||||
public static class Color extends RenderTooltipEvent
|
||||
{
|
||||
private final int originalBackground;
|
||||
private final int originalBorderStart;
|
||||
private final int originalBorderEnd;
|
||||
private int backgroundStart;
|
||||
private int backgroundEnd;
|
||||
private int borderStart;
|
||||
private int borderEnd;
|
||||
public static class Background extends RenderTooltipEvent {
|
||||
private final ResourceLocation originalBackground;
|
||||
private ResourceLocation background;
|
||||
|
||||
@ApiStatus.Internal
|
||||
public Color(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, @NotNull Font fr, int background, int borderStart, int borderEnd, @NotNull List<ClientTooltipComponent> components)
|
||||
{
|
||||
public Background(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, @NotNull Font fr, @NotNull List<ClientTooltipComponent> components, @Nullable ResourceLocation background) {
|
||||
super(stack, graphics, x, y, fr, components);
|
||||
this.originalBackground = background;
|
||||
this.originalBorderStart = borderStart;
|
||||
this.originalBorderEnd = borderEnd;
|
||||
this.backgroundStart = background;
|
||||
this.backgroundEnd = background;
|
||||
this.borderStart = borderStart;
|
||||
this.borderEnd = borderEnd;
|
||||
this.background = background;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the gradient start color for the tooltip background (top edge)}
|
||||
* Sets the new prefix for the background texture
|
||||
*/
|
||||
public int getBackgroundStart()
|
||||
{
|
||||
return backgroundStart;
|
||||
public void setBackground(ResourceLocation background) {
|
||||
this.background = background;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the gradient end color for the tooltip background (bottom edge)}
|
||||
* @return the potentially modified background's prefix, can be null for default
|
||||
*/
|
||||
public int getBackgroundEnd()
|
||||
{
|
||||
return backgroundEnd;
|
||||
public ResourceLocation getBackground() {
|
||||
return this.background;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the new color for the tooltip background. This sets both the gradient start and end color for the
|
||||
* background to this color.
|
||||
*
|
||||
* @param background the new color for the tooltip background
|
||||
* @return the original tooltip background's prefix, can be null for default
|
||||
*/
|
||||
public void setBackground(int background)
|
||||
{
|
||||
this.backgroundStart = background;
|
||||
this.backgroundEnd = background;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the new start color for the gradient of the tooltip background (top edge).
|
||||
*
|
||||
* @param backgroundStart the new start color for the tooltip background
|
||||
*/
|
||||
public void setBackgroundStart(int backgroundStart)
|
||||
{
|
||||
this.backgroundStart = backgroundStart;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the new end color for the gradient of the tooltip background (bottom edge).
|
||||
*
|
||||
* @param backgroundEnd the new end color for the tooltip background
|
||||
*/
|
||||
public void setBackgroundEnd(int backgroundEnd)
|
||||
{
|
||||
this.backgroundEnd = backgroundEnd;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the gradient start color for the tooltip border (top edge)}
|
||||
*/
|
||||
public int getBorderStart()
|
||||
{
|
||||
return borderStart;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the new start color for the gradient of the tooltip border (top edge).
|
||||
*
|
||||
* @param borderStart the new start color for the tooltip border
|
||||
*/
|
||||
public void setBorderStart(int borderStart)
|
||||
{
|
||||
this.borderStart = borderStart;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the gradient end color for the tooltip border (bottom edge)}
|
||||
*/
|
||||
public int getBorderEnd()
|
||||
{
|
||||
return borderEnd;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the new end color for the gradient of the tooltip border (bottom edge).
|
||||
*
|
||||
* @param borderEnd the new end color for the tooltip border
|
||||
*/
|
||||
public void setBorderEnd(int borderEnd)
|
||||
{
|
||||
this.borderEnd = borderEnd;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the original tooltip background's gradient start color (top edge)}
|
||||
*/
|
||||
public int getOriginalBackgroundStart()
|
||||
{
|
||||
public ResourceLocation getOriginalBackground() {
|
||||
return originalBackground;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the original tooltip background's gradient end color (bottom edge)}
|
||||
*/
|
||||
public int getOriginalBackgroundEnd()
|
||||
{
|
||||
return originalBackground;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the original tooltip border's gradient start color (top edge)}
|
||||
*/
|
||||
public int getOriginalBorderStart()
|
||||
{
|
||||
return originalBorderStart;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the original tooltip border's gradient end color (bottom edge)}
|
||||
*/
|
||||
public int getOriginalBorderEnd()
|
||||
{
|
||||
return originalBorderEnd;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import com.mojang.blaze3d.platform.InputConstants;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.components.events.GuiEventListener;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import net.minecraft.client.gui.screens.inventory.EffectRenderingInventoryScreen;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.api.distmarker.OnlyIn;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
@@ -248,7 +247,7 @@ public abstract class ScreenEvent extends Event {
|
||||
}
|
||||
|
||||
/**
|
||||
* Fired ahead of rendering any active mob effects in the {@link EffectRenderingInventoryScreen inventory screen}.
|
||||
* Fired ahead of rendering any active mob effects in the {@link EffectsInInventory inventory screen}.
|
||||
* Can be used to select the size of the effects display (full or compact) or even hide or replace vanilla's rendering entirely.
|
||||
* This event can also be used to modify the horizontal position of the stack of effects being rendered.
|
||||
*
|
||||
|
||||
@@ -22,17 +22,14 @@ import net.minecraftforge.fml.LogicalSide;
|
||||
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
|
||||
*/
|
||||
@Cancelable
|
||||
public class ToastAddEvent extends Event
|
||||
{
|
||||
public class ToastAddEvent extends Event {
|
||||
private final Toast toast;
|
||||
|
||||
public ToastAddEvent(Toast toast)
|
||||
{
|
||||
public ToastAddEvent(Toast toast) {
|
||||
this.toast = toast;
|
||||
}
|
||||
|
||||
public Toast getToast()
|
||||
{
|
||||
public Toast getToast() {
|
||||
return toast;
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,7 @@ public abstract class ViewportEvent extends Event {
|
||||
private float nearPlaneDistance;
|
||||
private FogShape fogShape;
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
@ApiStatus.Internal
|
||||
public RenderFog(FogMode mode, FogType type, Camera camera, float partialTicks, float nearPlaneDistance, float farPlaneDistance, FogShape fogShape) {
|
||||
super(Minecraft.getInstance().gameRenderer, camera, partialTicks);
|
||||
@@ -186,6 +187,7 @@ public abstract class ViewportEvent extends Event {
|
||||
private float green;
|
||||
private float blue;
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
@ApiStatus.Internal
|
||||
public ComputeFogColor(Camera camera, float partialTicks, float red, float green, float blue) {
|
||||
super(Minecraft.getInstance().gameRenderer, camera, partialTicks);
|
||||
@@ -327,10 +329,10 @@ public abstract class ViewportEvent extends Event {
|
||||
*/
|
||||
public static class ComputeFov extends ViewportEvent {
|
||||
private final boolean usedConfiguredFov;
|
||||
private double fov;
|
||||
private float fov;
|
||||
|
||||
@ApiStatus.Internal
|
||||
public ComputeFov(GameRenderer renderer, Camera camera, double renderPartialTicks, double fov, boolean usedConfiguredFov) {
|
||||
public ComputeFov(GameRenderer renderer, Camera camera, double renderPartialTicks, float fov, boolean usedConfiguredFov) {
|
||||
super(renderer, camera, renderPartialTicks);
|
||||
this.usedConfiguredFov = usedConfiguredFov;
|
||||
this.setFOV(fov);
|
||||
@@ -339,7 +341,7 @@ public abstract class ViewportEvent extends Event {
|
||||
/**
|
||||
* {@return the raw field of view value}
|
||||
*/
|
||||
public double getFOV() {
|
||||
public float getFOV() {
|
||||
return fov;
|
||||
}
|
||||
|
||||
@@ -348,7 +350,7 @@ public abstract class ViewportEvent extends Event {
|
||||
*
|
||||
* @param fov the new FOV value
|
||||
*/
|
||||
public void setFOV(double fov) {
|
||||
public void setFOV(float fov) {
|
||||
this.fov = fov;
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ import java.util.List;
|
||||
/**
|
||||
* Extension interface for {@link IForgeBakedModel}.
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public interface IForgeBakedModel {
|
||||
private BakedModel self() {
|
||||
return (BakedModel)this;
|
||||
@@ -89,7 +90,7 @@ public interface IForgeBakedModel {
|
||||
* @see #getRenderPasses(ItemStack, boolean)
|
||||
*/
|
||||
default List<RenderType> getRenderTypes(ItemStack itemStack, boolean fabulous) {
|
||||
return List.of(RenderTypeHelper.getFallbackItemRenderType(itemStack, self(), fabulous));
|
||||
return List.of(RenderTypeHelper.getFallbackItemRenderType(itemStack, self()));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -11,19 +11,16 @@ import net.minecraft.world.level.BlockAndTintGetter;
|
||||
/**
|
||||
* Extension interface for {@link BlockAndTintGetter}.
|
||||
*/
|
||||
public interface IForgeBlockAndTintGetter
|
||||
{
|
||||
private BlockAndTintGetter self()
|
||||
{
|
||||
return (BlockAndTintGetter) this;
|
||||
public interface IForgeBlockAndTintGetter {
|
||||
private BlockAndTintGetter self() {
|
||||
return (BlockAndTintGetter)this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the shade for a given normal.
|
||||
* Alternate version of the vanilla method taking in a {@link Direction}.
|
||||
*/
|
||||
default float getShade(float normalX, float normalY, float normalZ, boolean shade)
|
||||
{
|
||||
return self().getShade(Direction.getNearest(normalX, normalY, normalZ), shade);
|
||||
default float getShade(float normalX, float normalY, float normalZ, boolean shade) {
|
||||
return self().getShade(Direction.getApproximateNearest(normalX, normalY, normalZ), shade);
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.client.extensions;
|
||||
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import net.minecraft.client.Camera;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.client.renderer.DimensionSpecialEffects;
|
||||
import net.minecraft.client.renderer.LightTexture;
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
/**
|
||||
* Extension interface for {@link DimensionSpecialEffects}.
|
||||
*/
|
||||
public interface IForgeDimensionSpecialEffects {
|
||||
private DimensionSpecialEffects self() {
|
||||
return (DimensionSpecialEffects)this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the clouds of this dimension.
|
||||
*
|
||||
* @return true to prevent vanilla cloud rendering
|
||||
*/
|
||||
default boolean renderClouds(ClientLevel level, int ticks, float partialTick, PoseStack poseStack, double camX, double camY, double camZ, Matrix4f projectionMatrix) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the sky of this dimension.
|
||||
*
|
||||
* @return true to prevent vanilla sky rendering
|
||||
*/
|
||||
default boolean renderSky(ClientLevel level, int ticks, float partialTick, Camera camera, Matrix4f projectionMatrix, boolean isFoggy, Runnable setupFog) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the snow and rain effects of this dimension.
|
||||
*
|
||||
* @return true to prevent vanilla snow and rain rendering
|
||||
*/
|
||||
default boolean renderSnowAndRain(ClientLevel level, int ticks, float partialTick, LightTexture lightTexture, double camX, double camY, double camZ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ticks the rain of this dimension.
|
||||
*
|
||||
* @return true to prevent vanilla rain ticking
|
||||
*/
|
||||
default boolean tickRain(ClientLevel level, int ticks, Camera camera) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows for manipulating the coloring of the lightmap texture.
|
||||
* Will be called for each 16*16 combination of sky/block light values.
|
||||
*
|
||||
* @param level The current level (client-side).
|
||||
* @param partialTicks Progress between ticks.
|
||||
* @param skyDarken Current darkness of the sky (can be used to calculate sky light).
|
||||
* @param blockLightRedFlicker Block light flicker factor (red color) (can be used to calculate block light).
|
||||
* @param skyLight Sky light brightness (accounting for sky darkness).
|
||||
* @param pixelX X-coordinate of the lightmap texture (block).
|
||||
* @param pixelY Y-coordinate of the lightmap texture (sky).
|
||||
* @param colors The color values that will be used: [r, g, b].
|
||||
* @see LightTexture#updateLightTexture(float)
|
||||
*/
|
||||
default void adjustLightmapColors(ClientLevel level, float partialTicks, float skyDarken, float blockLightRedFlicker, float skyLight, int pixelX, int pixelY, Vector3f colors) {}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.client.extensions;
|
||||
|
||||
import net.minecraft.client.renderer.entity.layers.ElytraLayer;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
|
||||
public interface IForgeElytraLayer<T> {
|
||||
/**
|
||||
* Determines if the ElytraLayer should render.
|
||||
* ItemStack and Entity are provided for modder convenience,
|
||||
* For example, using the same ElytraLayer for multiple custom Elytra.
|
||||
*
|
||||
* @param stack The Elytra ItemStack
|
||||
* @param entity The entity being rendered.
|
||||
* @return If the ElytraLayer should render.
|
||||
*/
|
||||
default boolean shouldRender(ItemStack stack, T entity) {
|
||||
return stack.getItem() == Items.ELYTRA;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the texture to use with this ElytraLayer.
|
||||
* This assumes the vanilla Elytra model.
|
||||
*
|
||||
* @param stack The Elytra ItemStack.
|
||||
* @param entity The entity being rendered.
|
||||
* @return The texture.
|
||||
*/
|
||||
default ResourceLocation getElytraTexture(ItemStack stack, T entity) {
|
||||
return ElytraLayer.WINGS_LOCATION;
|
||||
}
|
||||
}
|
||||
@@ -11,11 +11,12 @@ import net.minecraft.network.chat.FormattedText;
|
||||
/**
|
||||
* Extension interface for {@link Font}.
|
||||
*/
|
||||
public interface IForgeFont
|
||||
{
|
||||
public interface IForgeFont {
|
||||
FormattedText ELLIPSIS = FormattedText.of("...");
|
||||
|
||||
Font self();
|
||||
default Font self() {
|
||||
return (Font)this;
|
||||
}
|
||||
|
||||
/**
|
||||
* If the width of the text exceeds {@code maxWidth}, an ellipse is added and the text is substringed.
|
||||
@@ -24,17 +25,16 @@ public interface IForgeFont
|
||||
* @param maxWidth the maximum width of the text
|
||||
* @return the ellipsized text
|
||||
*/
|
||||
default FormattedText ellipsize(FormattedText text, int maxWidth)
|
||||
{
|
||||
default FormattedText ellipsize(FormattedText text, int maxWidth) {
|
||||
final Font self = self();
|
||||
final int strWidth = self.width(text);
|
||||
final int ellipsisWidth = self.width(ELLIPSIS);
|
||||
if (strWidth > maxWidth)
|
||||
{
|
||||
if (ellipsisWidth >= maxWidth) return self.substrByWidth(text, maxWidth);
|
||||
if (strWidth > maxWidth) {
|
||||
if (ellipsisWidth >= maxWidth)
|
||||
return self.substrByWidth(text, maxWidth);
|
||||
return FormattedText.composite(
|
||||
self.substrByWidth(text, maxWidth - ellipsisWidth),
|
||||
ELLIPSIS
|
||||
self.substrByWidth(text, maxWidth - ellipsisWidth),
|
||||
ELLIPSIS
|
||||
);
|
||||
}
|
||||
return text;
|
||||
|
||||
@@ -6,16 +6,15 @@
|
||||
package net.minecraftforge.client.extensions;
|
||||
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
|
||||
/**
|
||||
* Extension interface for {@link GuiGraphics}.
|
||||
*/
|
||||
public interface IForgeGuiGraphics
|
||||
{
|
||||
private GuiGraphics self()
|
||||
{
|
||||
return (GuiGraphics) this;
|
||||
public interface IForgeGuiGraphics {
|
||||
private GuiGraphics self() {
|
||||
return (GuiGraphics)this;
|
||||
}
|
||||
|
||||
int DEFAULT_BACKGROUND_COLOR = 0xF0100010;
|
||||
@@ -28,8 +27,7 @@ public interface IForgeGuiGraphics
|
||||
int[] TEXT_COLOR_CODES = new int[] { 0, 170, 43520, 43690, 11141120, 11141290, 16755200, 11184810, 5592405, 5592575, 5635925, 5636095, 16733525, 16733695, 16777045, 16777215,
|
||||
0, 42, 10752, 10794, 2752512, 2752554, 2763264, 2763306, 1381653, 1381695, 1392405, 1392447, 4134165, 4134207, 4144917, 4144959 };
|
||||
|
||||
default int getColorFromFormattingCharacter(char c, boolean isLighter)
|
||||
{
|
||||
default int getColorFromFormattingCharacter(char c, boolean isLighter) {
|
||||
return TEXT_COLOR_CODES[isLighter ? "0123456789abcdef".indexOf(c) : "0123456789abcdef".indexOf(c) + 16];
|
||||
}
|
||||
|
||||
@@ -48,8 +46,7 @@ public interface IForgeGuiGraphics
|
||||
* @param textureHeight the height of the box texture in the resource location image
|
||||
* @param borderSize the size of the box's borders
|
||||
*/
|
||||
default void blitWithBorder(ResourceLocation texture, int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight, int borderSize)
|
||||
{
|
||||
default void blitWithBorder(ResourceLocation texture, int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight, int borderSize) {
|
||||
this.blitWithBorder(texture, x, y, u, v, width, height, textureWidth, textureHeight, borderSize, borderSize, borderSize, borderSize);
|
||||
}
|
||||
|
||||
@@ -71,8 +68,7 @@ public interface IForgeGuiGraphics
|
||||
* @param leftBorder the size of the box's left border
|
||||
* @param rightBorder the size of the box's right border
|
||||
*/
|
||||
default void blitWithBorder(ResourceLocation texture, int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight, int topBorder, int bottomBorder, int leftBorder, int rightBorder)
|
||||
{
|
||||
default void blitWithBorder(ResourceLocation texture, int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight, int topBorder, int bottomBorder, int leftBorder, int rightBorder) {
|
||||
int fillerWidth = textureWidth - leftBorder - rightBorder;
|
||||
int fillerHeight = textureHeight - topBorder - bottomBorder;
|
||||
int canvasWidth = width - leftBorder - rightBorder;
|
||||
@@ -84,56 +80,50 @@ public interface IForgeGuiGraphics
|
||||
|
||||
// Draw Border
|
||||
// Top Left
|
||||
self().blit(texture, x, y, u, v, leftBorder, topBorder);
|
||||
self().blit(RenderType::guiTextured, texture, x, y, 0, u, v, leftBorder, topBorder, 256, 256);
|
||||
// Top Right
|
||||
self().blit(texture, x + leftBorder + canvasWidth, y, u + leftBorder + fillerWidth, v, rightBorder, topBorder);
|
||||
self().blit(RenderType::guiTextured, texture, x + leftBorder + canvasWidth, y, 0, u + leftBorder + fillerWidth, v, rightBorder, topBorder, 256, 256);
|
||||
// Bottom Left
|
||||
self().blit(texture, x, y + topBorder + canvasHeight, u, v + topBorder + fillerHeight, leftBorder, bottomBorder);
|
||||
self().blit(RenderType::guiTextured, texture, x, y + topBorder + canvasHeight, 0, u, v + topBorder + fillerHeight, leftBorder, bottomBorder, 256, 256);
|
||||
// Bottom Right
|
||||
self().blit(texture, x + leftBorder + canvasWidth, y + topBorder + canvasHeight, u + leftBorder + fillerWidth, v + topBorder + fillerHeight, rightBorder, bottomBorder);
|
||||
self().blit(RenderType::guiTextured, texture, x + leftBorder + canvasWidth, y + topBorder + canvasHeight, 0, u + leftBorder + fillerWidth, v + topBorder + fillerHeight, rightBorder, bottomBorder, 256, 256);
|
||||
|
||||
for (int i = 0; i < xPasses + (remainderWidth > 0 ? 1 : 0); i++)
|
||||
{
|
||||
for (int i = 0; i < xPasses + (remainderWidth > 0 ? 1 : 0); i++) {
|
||||
// Top Border
|
||||
self().blit(texture, x + leftBorder + (i * fillerWidth), y, u + leftBorder, v, (i == xPasses ? remainderWidth : fillerWidth), topBorder);
|
||||
self().blit(RenderType::guiTextured, texture, x + leftBorder + (i * fillerWidth), y, 0, u + leftBorder, v, (i == xPasses ? remainderWidth : fillerWidth), topBorder, 256, 256);
|
||||
// Bottom Border
|
||||
self().blit(texture, x + leftBorder + (i * fillerWidth), y + topBorder + canvasHeight, u + leftBorder, v + topBorder + fillerHeight, (i == xPasses ? remainderWidth : fillerWidth), bottomBorder);
|
||||
self().blit(RenderType::guiTextured, texture, x + leftBorder + (i * fillerWidth), y + topBorder + canvasHeight, 0, u + leftBorder, v + topBorder + fillerHeight, (i == xPasses ? remainderWidth : fillerWidth), bottomBorder, 256, 256);
|
||||
|
||||
// Throw in some filler for good measure
|
||||
for (int j = 0; j < yPasses + (remainderHeight > 0 ? 1 : 0); j++)
|
||||
self().blit(texture, x + leftBorder + (i * fillerWidth), y + topBorder + (j * fillerHeight), u + leftBorder, v + topBorder, (i == xPasses ? remainderWidth : fillerWidth), (j == yPasses ? remainderHeight : fillerHeight));
|
||||
self().blit(RenderType::guiTextured, texture, x + leftBorder + (i * fillerWidth), y + topBorder + (j * fillerHeight), 0, u + leftBorder, v + topBorder, (i == xPasses ? remainderWidth : fillerWidth), (j == yPasses ? remainderHeight : fillerHeight), 256, 256);
|
||||
}
|
||||
|
||||
// Side Borders
|
||||
for (int j = 0; j < yPasses + (remainderHeight > 0 ? 1 : 0); j++)
|
||||
{
|
||||
for (int j = 0; j < yPasses + (remainderHeight > 0 ? 1 : 0); j++) {
|
||||
// Left Border
|
||||
self().blit(texture, x, y + topBorder + (j * fillerHeight), u, v + topBorder, leftBorder, (j == yPasses ? remainderHeight : fillerHeight));
|
||||
self().blit(RenderType::guiTextured, texture, x, y + topBorder + (j * fillerHeight), 0, u, v + topBorder, leftBorder, (j == yPasses ? remainderHeight : fillerHeight), 256, 256);
|
||||
// Right Border
|
||||
self().blit(texture, x + leftBorder + canvasWidth, y + topBorder + (j * fillerHeight), u + leftBorder + fillerWidth, v + topBorder, rightBorder, (j == yPasses ? remainderHeight : fillerHeight));
|
||||
self().blit(RenderType::guiTextured, texture, x + leftBorder + canvasWidth, y + topBorder + (j * fillerHeight), 0, u + leftBorder + fillerWidth, v + topBorder, rightBorder, (j == yPasses ? remainderHeight : fillerHeight), 256, 256);
|
||||
}
|
||||
}
|
||||
|
||||
default void blitInscribed(ResourceLocation texture, int x, int y, int boundsWidth, int boundsHeight, int rectWidth, int rectHeight)
|
||||
{
|
||||
default void blitInscribed(ResourceLocation texture, int x, int y, int boundsWidth, int boundsHeight, int rectWidth, int rectHeight) {
|
||||
this.blitInscribed(texture, x, y, boundsWidth, boundsHeight, rectWidth, rectHeight, true, true);
|
||||
}
|
||||
|
||||
default void blitInscribed(ResourceLocation texture, int x, int y, int boundsWidth, int boundsHeight, int rectWidth, int rectHeight, boolean centerX, boolean centerY)
|
||||
{
|
||||
if (rectWidth * boundsHeight > rectHeight * boundsWidth)
|
||||
{
|
||||
default void blitInscribed(ResourceLocation texture, int x, int y, int boundsWidth, int boundsHeight, int rectWidth, int rectHeight, boolean centerX, boolean centerY) {
|
||||
if (rectWidth * boundsHeight > rectHeight * boundsWidth) {
|
||||
int h = boundsHeight;
|
||||
boundsHeight = (int) (boundsWidth * ((double) rectHeight / rectWidth));
|
||||
if (centerY) y += (h - boundsHeight) / 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
int w = boundsWidth;
|
||||
boundsWidth = (int) (boundsHeight * ((double) rectWidth / rectHeight));
|
||||
if (centerX) x += (w - boundsWidth) / 2;
|
||||
}
|
||||
|
||||
self().blit(texture, x, y, boundsWidth, boundsHeight, 0.0f,0.0f, rectWidth, rectHeight, rectWidth, rectHeight);
|
||||
//self().blit(RenderType::guiTextured, texture, x, y, boundsWidth, boundsHeight, 0.0f,0.0f, rectWidth, rectHeight, rectWidth, rectHeight);
|
||||
self().blit(RenderType::guiTextured, texture, x, y, 0.0f, 0.0f, boundsWidth, boundsHeight, boundsWidth, boundsHeight);
|
||||
}
|
||||
}
|
||||
+22
-58
@@ -13,6 +13,7 @@ import java.util.stream.Stream;
|
||||
import net.minecraft.client.Camera;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.client.renderer.FogParameters;
|
||||
import net.minecraft.client.renderer.FogRenderer;
|
||||
import net.minecraft.client.renderer.ScreenEffectRenderer;
|
||||
import net.minecraft.core.BlockPos;
|
||||
@@ -33,22 +34,18 @@ import org.joml.Vector3f;
|
||||
*
|
||||
* @see FluidType#initializeClient(Consumer)
|
||||
*/
|
||||
public interface IClientFluidTypeExtensions
|
||||
{
|
||||
public interface IClientFluidTypeExtensions {
|
||||
IClientFluidTypeExtensions DEFAULT = new IClientFluidTypeExtensions() { };
|
||||
|
||||
static IClientFluidTypeExtensions of(FluidState state)
|
||||
{
|
||||
static IClientFluidTypeExtensions of(FluidState state) {
|
||||
return of(state.getFluidType());
|
||||
}
|
||||
|
||||
static IClientFluidTypeExtensions of(Fluid fluid)
|
||||
{
|
||||
static IClientFluidTypeExtensions of(Fluid fluid) {
|
||||
return of(fluid.getFluidType());
|
||||
}
|
||||
|
||||
static IClientFluidTypeExtensions of(FluidType type)
|
||||
{
|
||||
static IClientFluidTypeExtensions of(FluidType type) {
|
||||
return type.getRenderPropertiesInternal() instanceof IClientFluidTypeExtensions props ? props : DEFAULT;
|
||||
}
|
||||
|
||||
@@ -62,8 +59,7 @@ public interface IClientFluidTypeExtensions
|
||||
*
|
||||
* @return the tint applied to the fluid's textures in ARGB format
|
||||
*/
|
||||
default int getTintColor()
|
||||
{
|
||||
default int getTintColor() {
|
||||
return 0xFFFFFFFF;
|
||||
}
|
||||
|
||||
@@ -79,8 +75,7 @@ public interface IClientFluidTypeExtensions
|
||||
*
|
||||
* @return the reference of the texture to apply to a source fluid
|
||||
*/
|
||||
default ResourceLocation getStillTexture()
|
||||
{
|
||||
default ResourceLocation getStillTexture() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -96,8 +91,7 @@ public interface IClientFluidTypeExtensions
|
||||
*
|
||||
* @return the reference of the texture to apply to a flowing fluid
|
||||
*/
|
||||
default ResourceLocation getFlowingTexture()
|
||||
{
|
||||
default ResourceLocation getFlowingTexture() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -115,26 +109,10 @@ public interface IClientFluidTypeExtensions
|
||||
* a non-opaque block
|
||||
*/
|
||||
@Nullable
|
||||
default ResourceLocation getOverlayTexture()
|
||||
{
|
||||
default ResourceLocation getOverlayTexture() {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Add entries to assets/minecraft/atlases/blocks.json if your texture location is not already covered by the default atlas search locations.
|
||||
// /**
|
||||
// * Returns a stream of textures applied to a fluid.
|
||||
// *
|
||||
// * <p>This is used by the {@link net.minecraft.client.resources.model.ModelBakery} to load in all textures that
|
||||
// * can be applied on reload.
|
||||
// *
|
||||
// * @return a stream of textures applied to a fluid
|
||||
// */
|
||||
// default Stream<ResourceLocation> getTextures()
|
||||
// {
|
||||
// return Stream.of(this.getStillTexture(), this.getFlowingTexture(), this.getOverlayTexture())
|
||||
// .filter(Objects::nonNull);
|
||||
// }
|
||||
|
||||
/**
|
||||
* Returns the location of the texture to apply to the camera when it is
|
||||
* within the fluid. If no location is specified, no overlay will be applied.
|
||||
@@ -148,8 +126,7 @@ public interface IClientFluidTypeExtensions
|
||||
* within the fluid
|
||||
*/
|
||||
@Nullable
|
||||
default ResourceLocation getRenderOverlayTexture(Minecraft mc)
|
||||
{
|
||||
default ResourceLocation getRenderOverlayTexture(Minecraft mc) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -160,8 +137,7 @@ public interface IClientFluidTypeExtensions
|
||||
* @param mc the client instance
|
||||
* @param poseStack the transformations representing the current rendering position
|
||||
*/
|
||||
default void renderOverlay(Minecraft mc, PoseStack poseStack)
|
||||
{
|
||||
default void renderOverlay(Minecraft mc, PoseStack poseStack) {
|
||||
ResourceLocation texture = this.getRenderOverlayTexture(mc);
|
||||
if (texture != null)
|
||||
ScreenEffectRenderer.renderFluid(mc, poseStack, texture);
|
||||
@@ -182,8 +158,7 @@ public interface IClientFluidTypeExtensions
|
||||
* @return the color of the fog
|
||||
*/
|
||||
@NotNull
|
||||
default Vector3f modifyFogColor(Camera camera, float partialTick, ClientLevel level, int renderDistance, float darkenWorldAmount, Vector3f fluidFogColor)
|
||||
{
|
||||
default Vector3f modifyFogColor(Camera camera, float partialTick, ClientLevel level, int renderDistance, float darkenWorldAmount, Vector3f fluidFogColor) {
|
||||
return fluidFogColor;
|
||||
}
|
||||
|
||||
@@ -195,12 +170,9 @@ public interface IClientFluidTypeExtensions
|
||||
* @param mode the type of fog being rendered
|
||||
* @param renderDistance the render distance of the client
|
||||
* @param partialTick the delta time of where the current frame is within a tick
|
||||
* @param nearDistance the near plane of where the fog starts to render
|
||||
* @param farDistance the far plane of where the fog ends rendering
|
||||
* @param shape the shape of the fog being rendered
|
||||
*/
|
||||
default void modifyFogRender(Camera camera, FogRenderer.FogMode mode, float renderDistance, float partialTick, float nearDistance, float farDistance, FogShape shape)
|
||||
{
|
||||
default FogParameters modifyFogRender(Camera camera, FogRenderer.FogMode mode, float renderDistance, float partialTick, FogParameters original) {
|
||||
return original;
|
||||
}
|
||||
|
||||
/* Level-Based Accessors */
|
||||
@@ -220,8 +192,7 @@ public interface IClientFluidTypeExtensions
|
||||
* @param pos the position of the fluid
|
||||
* @return the reference of the texture to apply to a source fluid
|
||||
*/
|
||||
default ResourceLocation getStillTexture(FluidState state, BlockAndTintGetter getter, BlockPos pos)
|
||||
{
|
||||
default ResourceLocation getStillTexture(FluidState state, BlockAndTintGetter getter, BlockPos pos) {
|
||||
return this.getStillTexture();
|
||||
}
|
||||
|
||||
@@ -240,8 +211,7 @@ public interface IClientFluidTypeExtensions
|
||||
* @param pos the position of the fluid
|
||||
* @return the reference of the texture to apply to a flowing fluid
|
||||
*/
|
||||
default ResourceLocation getFlowingTexture(FluidState state, BlockAndTintGetter getter, BlockPos pos)
|
||||
{
|
||||
default ResourceLocation getFlowingTexture(FluidState state, BlockAndTintGetter getter, BlockPos pos) {
|
||||
return this.getFlowingTexture();
|
||||
}
|
||||
|
||||
@@ -261,8 +231,7 @@ public interface IClientFluidTypeExtensions
|
||||
* @return the reference of the texture to apply to a fluid directly touching
|
||||
* a non-opaque block
|
||||
*/
|
||||
default ResourceLocation getOverlayTexture(FluidState state, BlockAndTintGetter getter, BlockPos pos)
|
||||
{
|
||||
default ResourceLocation getOverlayTexture(FluidState state, BlockAndTintGetter getter, BlockPos pos) {
|
||||
return this.getOverlayTexture();
|
||||
}
|
||||
|
||||
@@ -277,8 +246,7 @@ public interface IClientFluidTypeExtensions
|
||||
* @param pos the position of the fluid
|
||||
* @return the tint applied to the fluid's textures in ARGB format
|
||||
*/
|
||||
default int getTintColor(FluidState state, BlockAndTintGetter getter, BlockPos pos)
|
||||
{
|
||||
default int getTintColor(FluidState state, BlockAndTintGetter getter, BlockPos pos) {
|
||||
return this.getTintColor();
|
||||
}
|
||||
|
||||
@@ -293,8 +261,7 @@ public interface IClientFluidTypeExtensions
|
||||
* @param stack the stack the fluid is in
|
||||
* @return the tint applied to the fluid's textures in ARGB format
|
||||
*/
|
||||
default int getTintColor(FluidStack stack)
|
||||
{
|
||||
default int getTintColor(FluidStack stack) {
|
||||
return this.getTintColor();
|
||||
}
|
||||
|
||||
@@ -311,8 +278,7 @@ public interface IClientFluidTypeExtensions
|
||||
* @param stack the stack the fluid is in
|
||||
* @return the reference of the texture to apply to a source fluid
|
||||
*/
|
||||
default ResourceLocation getStillTexture(FluidStack stack)
|
||||
{
|
||||
default ResourceLocation getStillTexture(FluidStack stack) {
|
||||
return this.getStillTexture();
|
||||
}
|
||||
|
||||
@@ -329,8 +295,7 @@ public interface IClientFluidTypeExtensions
|
||||
* @param stack the stack the fluid is in
|
||||
* @return the reference of the texture to apply to a flowing fluid
|
||||
*/
|
||||
default ResourceLocation getFlowingTexture(FluidStack stack)
|
||||
{
|
||||
default ResourceLocation getFlowingTexture(FluidStack stack) {
|
||||
return this.getFlowingTexture();
|
||||
}
|
||||
|
||||
@@ -348,8 +313,7 @@ public interface IClientFluidTypeExtensions
|
||||
* @return the reference of the texture to apply to a fluid directly touching
|
||||
* a non-opaque block
|
||||
*/
|
||||
default ResourceLocation getOverlayTexture(FluidStack stack)
|
||||
{
|
||||
default ResourceLocation getOverlayTexture(FluidStack stack) {
|
||||
return this.getOverlayTexture();
|
||||
}
|
||||
}
|
||||
+17
-27
@@ -12,6 +12,8 @@ import net.minecraft.client.model.HumanoidModel;
|
||||
import net.minecraft.client.model.Model;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.client.renderer.BlockEntityWithoutLevelRenderer;
|
||||
import net.minecraft.client.renderer.entity.state.HumanoidRenderState;
|
||||
import net.minecraft.client.renderer.entity.state.LivingEntityRenderState;
|
||||
import net.minecraft.client.resources.model.BakedModel;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
@@ -34,17 +36,14 @@ import java.util.function.Consumer;
|
||||
*
|
||||
* @see Item#initializeClient(Consumer)
|
||||
*/
|
||||
public interface IClientItemExtensions
|
||||
{
|
||||
public interface IClientItemExtensions {
|
||||
IClientItemExtensions DEFAULT = new IClientItemExtensions() { };
|
||||
|
||||
static IClientItemExtensions of(ItemStack stack)
|
||||
{
|
||||
static IClientItemExtensions of(ItemStack stack) {
|
||||
return of(stack.getItem());
|
||||
}
|
||||
|
||||
static IClientItemExtensions of(Item item)
|
||||
{
|
||||
static IClientItemExtensions of(Item item) {
|
||||
return item.getRenderPropertiesInternal() instanceof IClientItemExtensions e ? e : DEFAULT;
|
||||
}
|
||||
|
||||
@@ -57,8 +56,7 @@ public interface IClientItemExtensions
|
||||
* @return A {@link Font} or null to use the default
|
||||
*/
|
||||
@Nullable
|
||||
default Font getFont(ItemStack stack, FontContext context)
|
||||
{
|
||||
default Font getFont(ItemStack stack, FontContext context) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -72,8 +70,7 @@ public interface IClientItemExtensions
|
||||
* @return A custom ArmPose that can be used to define movement of the arm
|
||||
*/
|
||||
@Nullable
|
||||
default HumanoidModel.ArmPose getArmPose(LivingEntity entityLiving, InteractionHand hand, ItemStack itemStack)
|
||||
{
|
||||
default HumanoidModel.ArmPose getArmPose(LivingEntity entityLiving, InteractionHand hand, ItemStack itemStack) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -96,7 +93,7 @@ public interface IClientItemExtensions
|
||||
/**
|
||||
* Queries the humanoid armor model for this item when it's equipped.
|
||||
*
|
||||
* @param livingEntity The entity wearing the armor
|
||||
* @param state The entity wearing the armor
|
||||
* @param itemStack The item stack
|
||||
* @param equipmentSlot The slot the item is in
|
||||
* @param original The original armor model. Will have attributes set.
|
||||
@@ -104,14 +101,13 @@ public interface IClientItemExtensions
|
||||
* @see #getGenericArmorModel(LivingEntity, ItemStack, EquipmentSlot, HumanoidModel)
|
||||
*/
|
||||
@NotNull
|
||||
default HumanoidModel<?> getHumanoidArmorModel(LivingEntity livingEntity, ItemStack itemStack, EquipmentSlot equipmentSlot, HumanoidModel<?> original)
|
||||
{
|
||||
default HumanoidModel<?> getHumanoidArmorModel(LivingEntityRenderState state, ItemStack itemStack, EquipmentSlot equipmentSlot, HumanoidModel<?> original) {
|
||||
return original;
|
||||
}
|
||||
|
||||
/**
|
||||
* Queries the armor model for this item when it's equipped. Useful in place of
|
||||
* {@link #getHumanoidArmorModel(LivingEntity, ItemStack, EquipmentSlot, HumanoidModel)} for wrapping the original
|
||||
* {@link #getHumanoidArmorModel(LivingEntityRenderState, ItemStack, EquipmentSlot, HumanoidModel)} for wrapping the original
|
||||
* model or returning anything non-standard.
|
||||
* <p>
|
||||
* If you override this method you are responsible for copying any properties you care about from the original model.
|
||||
@@ -121,14 +117,12 @@ public interface IClientItemExtensions
|
||||
* @param equipmentSlot The slot the item is in
|
||||
* @param original The original armor model. Will have attributes set.
|
||||
* @return A Model to be rendered. Relevant properties must be copied over manually.
|
||||
* @see #getHumanoidArmorModel(LivingEntity, ItemStack, EquipmentSlot, HumanoidModel)
|
||||
* @see #getHumanoidArmorModel(LivingEntityRenderState, ItemStack, EquipmentSlot, HumanoidModel)
|
||||
*/
|
||||
@NotNull
|
||||
default Model getGenericArmorModel(LivingEntity livingEntity, ItemStack itemStack, EquipmentSlot equipmentSlot, HumanoidModel<?> original)
|
||||
{
|
||||
HumanoidModel<?> replacement = getHumanoidArmorModel(livingEntity, itemStack, equipmentSlot, original);
|
||||
if (replacement != original)
|
||||
{
|
||||
default Model getGenericArmorModel(HumanoidRenderState state, ItemStack itemStack, EquipmentSlot equipmentSlot, HumanoidModel<?> original) {
|
||||
HumanoidModel<?> replacement = getHumanoidArmorModel(state, itemStack, equipmentSlot, original);
|
||||
if (replacement != original) {
|
||||
ForgeHooksClient.copyModelProperties(original, replacement);
|
||||
return replacement;
|
||||
}
|
||||
@@ -146,9 +140,7 @@ public interface IClientItemExtensions
|
||||
* @param height Viewport height
|
||||
* @param partialTick Partial tick time, useful for interpolation
|
||||
*/
|
||||
default void renderHelmetOverlay(ItemStack stack, Player player, int width, int height, float partialTick)
|
||||
{
|
||||
}
|
||||
default void renderHelmetOverlay(ItemStack stack, Player player, int width, int height, float partialTick) { }
|
||||
|
||||
/**
|
||||
* Queries this item's renderer.
|
||||
@@ -158,13 +150,11 @@ public interface IClientItemExtensions
|
||||
* <p>
|
||||
* By default, returns vanilla's block entity renderer.
|
||||
*/
|
||||
default BlockEntityWithoutLevelRenderer getCustomRenderer()
|
||||
{
|
||||
default BlockEntityWithoutLevelRenderer getCustomRenderer() {
|
||||
return Minecraft.getInstance().getItemRenderer().getBlockEntityRenderer();
|
||||
}
|
||||
|
||||
enum FontContext
|
||||
{
|
||||
enum FontContext {
|
||||
/**
|
||||
* Used to display the amount of items in the {@link ItemStack}.
|
||||
*/
|
||||
|
||||
+5
-5
@@ -7,7 +7,7 @@ package net.minecraftforge.client.extensions.common;
|
||||
|
||||
import net.minecraft.client.gui.Gui;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.screens.inventory.EffectRenderingInventoryScreen;
|
||||
import net.minecraft.client.gui.screens.inventory.EffectsInInventory;
|
||||
import net.minecraft.world.effect.MobEffect;
|
||||
import net.minecraft.world.effect.MobEffectInstance;
|
||||
import net.minecraftforge.fml.LogicalSide;
|
||||
@@ -53,14 +53,14 @@ public interface IClientMobEffectExtensions {
|
||||
* This can be used to render icons from your own texture sheet.
|
||||
*
|
||||
* @param instance The effect instance
|
||||
* @param screen The effect-rendering screen
|
||||
* @param effects The effect-rendering screen
|
||||
* @param guiGraphics The gui graphics
|
||||
* @param x The x coordinate
|
||||
* @param y The y coordinate
|
||||
* @param blitOffset The blit offset
|
||||
* @return true to prevent default rendering, false otherwise
|
||||
*/
|
||||
default boolean renderInventoryIcon(MobEffectInstance instance, EffectRenderingInventoryScreen<?> screen, GuiGraphics guiGraphics, int x, int y, int blitOffset) {
|
||||
default boolean renderInventoryIcon(MobEffectInstance instance, EffectsInInventory effects, GuiGraphics guiGraphics, int x, int y, int blitOffset) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -68,14 +68,14 @@ public interface IClientMobEffectExtensions {
|
||||
* Renders the text of the specified effect in the player's inventory.
|
||||
*
|
||||
* @param instance The effect instance
|
||||
* @param screen The effect-rendering screen
|
||||
* @param effects The effect-rendering screen
|
||||
* @param guiGraphics The gui graphics
|
||||
* @param x The x coordinate
|
||||
* @param y The y coordinate
|
||||
* @param blitOffset The blit offset
|
||||
* @return true to prevent default rendering, false otherwise
|
||||
*/
|
||||
default boolean renderInventoryText(MobEffectInstance instance, EffectRenderingInventoryScreen<?> screen, GuiGraphics guiGraphics, int x, int y, int blitOffset) {
|
||||
default boolean renderInventoryText(MobEffectInstance instance, EffectsInInventory effects, GuiGraphics guiGraphics, int x, int y, int blitOffset) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -21,30 +21,28 @@ import java.util.function.Function;
|
||||
* <p>
|
||||
* Provides a lookup.
|
||||
*/
|
||||
public final class ClientTooltipComponentManager
|
||||
{
|
||||
public final class ClientTooltipComponentManager {
|
||||
private static ImmutableMap<Class<? extends TooltipComponent>, Function<TooltipComponent, ClientTooltipComponent>> FACTORIES;
|
||||
|
||||
/**
|
||||
* Creates a client component for the given argument, or null if unsupported.
|
||||
*/
|
||||
@Nullable
|
||||
public static ClientTooltipComponent createClientTooltipComponent(TooltipComponent component)
|
||||
{
|
||||
public static ClientTooltipComponent createClientTooltipComponent(TooltipComponent component) {
|
||||
var factory = FACTORIES.get(component.getClass());
|
||||
return factory != null ? factory.apply(component) : null;
|
||||
var ret = factory != null ? factory.apply(component) : null;
|
||||
if (ret == null)
|
||||
throw new IllegalArgumentException("Unknown TooltipComponent");
|
||||
return ret;
|
||||
}
|
||||
|
||||
@ApiStatus.Internal
|
||||
public static void init()
|
||||
{
|
||||
public static void init() {
|
||||
var factories = new HashMap<Class<? extends TooltipComponent>, Function<TooltipComponent, ClientTooltipComponent>>();
|
||||
var event = new RegisterClientTooltipComponentFactoriesEvent(factories);
|
||||
ModLoader.get().postEventWrapContainerInModOrder(event);
|
||||
FACTORIES = ImmutableMap.copyOf(factories);
|
||||
}
|
||||
|
||||
private ClientTooltipComponentManager()
|
||||
{
|
||||
}
|
||||
private ClientTooltipComponentManager() { }
|
||||
}
|
||||
@@ -21,9 +21,6 @@ import net.minecraftforge.fml.ModLoadingException;
|
||||
import net.minecraftforge.fml.ModLoadingWarning;
|
||||
import net.minecraftforge.client.gui.widget.ExtendedButton;
|
||||
import net.minecraftforge.fml.loading.FMLPaths;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
@@ -32,7 +29,6 @@ import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public class LoadingErrorScreen extends ErrorScreen {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private final Path modsDir;
|
||||
private final Path logFile;
|
||||
private final List<ModLoadingException> modLoadErrors;
|
||||
@@ -137,7 +133,8 @@ public class LoadingErrorScreen extends ErrorScreen {
|
||||
|
||||
@Override
|
||||
public void render(GuiGraphics guiGraphics, int entryIdx, int top, int left, final int entryWidth, final int entryHeight, final int mouseX, final int mouseY, final boolean p_194999_5_, final float partialTick) {
|
||||
Font font = Minecraft.getInstance().font;
|
||||
var mc = Minecraft.getInstance();
|
||||
Font font = mc.font;
|
||||
var strings = font.split(message, LoadingEntryList.this.width - 20);
|
||||
int y = top + 2;
|
||||
for (var string : strings) {
|
||||
|
||||
@@ -8,6 +8,7 @@ package net.minecraftforge.client.gui;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.components.Button;
|
||||
import net.minecraft.client.gui.screens.TitleScreen;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
@@ -51,7 +52,7 @@ public class TitleScreenModUpdateIndicator extends Screen {
|
||||
int w = modButton.getWidth();
|
||||
int h = modButton.getHeight();
|
||||
|
||||
guiGraphics.blit(VERSION_CHECK_ICONS, x + w - (h / 2 + 4), y + (h / 2 - 4), showNotification.getSheetOffset() * 8, (showNotification.isAnimated() && ((System.currentTimeMillis() / 800 & 1) == 1)) ? 8 : 0, 8, 8, 64, 16);
|
||||
guiGraphics.blit(RenderType::guiTextured, VERSION_CHECK_ICONS, x + w - (h / 2 + 4), y + (h / 2 - 4), showNotification.getSheetOffset() * 8, (showNotification.isAnimated() && ((System.currentTimeMillis() / 800 & 1) == 1)) ? 8 : 0, 8, 8, 64, 16);
|
||||
}
|
||||
|
||||
public static TitleScreenModUpdateIndicator init(TitleScreen guiMainMenu, Button modButton) {
|
||||
|
||||
@@ -8,6 +8,7 @@ package net.minecraftforge.client.gui.widget;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.components.Button;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.locale.Language;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.FormattedText;
|
||||
@@ -19,23 +20,17 @@ import net.minecraft.network.chat.FormattedText;
|
||||
* trimming the end of the string and adding an ellipsis.<br/><br/>
|
||||
*
|
||||
* The code that handles drawing the button is in GuiUtils.
|
||||
*
|
||||
* @author bspkrs
|
||||
*/
|
||||
public class ExtendedButton extends Button
|
||||
{
|
||||
public ExtendedButton(int xPos, int yPos, int width, int height, Component displayString, OnPress handler)
|
||||
{
|
||||
public class ExtendedButton extends Button {
|
||||
public ExtendedButton(int xPos, int yPos, int width, int height, Component displayString, OnPress handler) {
|
||||
this(xPos, yPos, width, height, displayString, handler, DEFAULT_NARRATION);
|
||||
}
|
||||
|
||||
public ExtendedButton(int xPos, int yPos, int width, int height, Component displayString, OnPress handler, CreateNarration createNarration)
|
||||
{
|
||||
public ExtendedButton(int xPos, int yPos, int width, int height, Component displayString, OnPress handler, CreateNarration createNarration) {
|
||||
super(xPos, yPos, width, height, displayString, handler, createNarration);
|
||||
}
|
||||
|
||||
public ExtendedButton(Button.Builder builder)
|
||||
{
|
||||
public ExtendedButton(Button.Builder builder) {
|
||||
super(builder);
|
||||
}
|
||||
|
||||
@@ -43,11 +38,9 @@ public class ExtendedButton extends Button
|
||||
* Draws this button to the screen.
|
||||
*/
|
||||
@Override
|
||||
public void renderWidget(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick)
|
||||
{
|
||||
public void renderWidget(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
int k = !this.active ? 0 : (this.isHoveredOrFocused() ? 2 : 1);
|
||||
guiGraphics.blitSprite(SPRITES.get(this.active, this.isHoveredOrFocused()), this.getX(), this.getY(), this.getWidth(), this.getHeight());
|
||||
guiGraphics.blitSprite(RenderType::guiTextured, SPRITES.get(this.active, this.isHoveredOrFocused()), this.getX(), this.getY(), this.getWidth(), this.getHeight());
|
||||
|
||||
final FormattedText buttonText = mc.font.ellipsize(this.getMessage(), this.width - 6); // Remove 6 pixels so that the text is always contained within the button's borders
|
||||
guiGraphics.drawCenteredString(mc.font, Language.getInstance().getVisualOrder(buttonText), this.getX() + this.width / 2, this.getY() + (this.height - 8) / 2, getFGColor());
|
||||
|
||||
@@ -8,6 +8,7 @@ package net.minecraftforge.client.gui.widget;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.components.AbstractSliderButton;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.util.Mth;
|
||||
import org.lwjgl.glfw.GLFW;
|
||||
@@ -193,8 +194,8 @@ public class ForgeSlider extends AbstractSliderButton {
|
||||
@Override
|
||||
public void renderWidget(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
|
||||
final Minecraft mc = Minecraft.getInstance();
|
||||
guiGraphics.blitSprite(this.getSprite(), this.getX(), this.getY(), this.getWidth(), this.getHeight());
|
||||
guiGraphics.blitSprite(this.getHandleSprite(), this.getX() + (int)(this.value * (double)(this.width - 8)), this.getY(), 8, this.getHeight());
|
||||
guiGraphics.blitSprite(RenderType::guiTextured, this.getSprite(), this.getX(), this.getY(), this.getWidth(), this.getHeight());
|
||||
guiGraphics.blitSprite(RenderType::guiTextured, this.getHandleSprite(), this.getX() + (int)(this.value * (double)(this.width - 8)), this.getY(), 8, this.getHeight());
|
||||
|
||||
renderScrollingString(guiGraphics, mc.font, 2, getFGColor() | Mth.ceil(this.alpha * 255.0F) << 24);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ package net.minecraftforge.client.gui.widget;
|
||||
import net.minecraft.client.gui.Font;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.components.ObjectSelectionList;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.FormattedText;
|
||||
@@ -20,16 +21,14 @@ import net.minecraftforge.forgespi.language.IModInfo;
|
||||
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
|
||||
public class ModListWidget extends ObjectSelectionList<ModListWidget.ModEntry>
|
||||
{
|
||||
public class ModListWidget extends ObjectSelectionList<ModListWidget.ModEntry> {
|
||||
private static String stripControlCodes(String value) { return net.minecraft.util.StringUtil.stripColor(value); }
|
||||
private static final ResourceLocation VERSION_CHECK_ICONS = ResourceLocation.fromNamespaceAndPath(ForgeVersion.MOD_ID, "textures/gui/version_check_icons.png");
|
||||
private final int listWidth;
|
||||
|
||||
private final ModListScreen parent;
|
||||
|
||||
public ModListWidget(ModListScreen parent, int listWidth, int top, int bottom)
|
||||
{
|
||||
public ModListWidget(ModListScreen parent, int listWidth, int top, int bottom) {
|
||||
super(parent.getMinecraftInstance(), listWidth, bottom, top, parent.getFontRenderer().lineHeight * 2 + 8);
|
||||
this.parent = parent;
|
||||
this.listWidth = listWidth;
|
||||
@@ -37,14 +36,12 @@ public class ModListWidget extends ObjectSelectionList<ModListWidget.ModEntry>
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getScrollbarPosition()
|
||||
{
|
||||
protected int getScrollbarPosition() {
|
||||
return this.listWidth;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getRowWidth()
|
||||
{
|
||||
public int getRowWidth() {
|
||||
return this.listWidth;
|
||||
}
|
||||
|
||||
@@ -84,26 +81,23 @@ public class ModListWidget extends ObjectSelectionList<ModListWidget.ModEntry>
|
||||
Font font = this.parent.getFontRenderer();
|
||||
guiGraphics.drawString(font, Language.getInstance().getVisualOrder(FormattedText.composite(font.substrByWidth(name, listWidth))), left + 3, top + 2, 0xFFFFFF, false);
|
||||
guiGraphics.drawString(font, Language.getInstance().getVisualOrder(FormattedText.composite(font.substrByWidth(version, listWidth))), left + 3, top + 2 + font.lineHeight, 0xCCCCCC, false);
|
||||
if (vercheck.status().shouldDraw())
|
||||
{
|
||||
if (vercheck.status().shouldDraw()) {
|
||||
//TODO: Consider adding more icons for visualization
|
||||
RenderSystem.setShaderColor(1, 1, 1, 1);
|
||||
guiGraphics.pose().pushPose();
|
||||
guiGraphics.blit(VERSION_CHECK_ICONS, getX() + width - 12, top + entryHeight / 4, vercheck.status().getSheetOffset() * 8, (vercheck.status().isAnimated() && ((System.currentTimeMillis() / 800 & 1)) == 1) ? 8 : 0, 8, 8, 64, 16);
|
||||
guiGraphics.blit(RenderType::guiTextured, VERSION_CHECK_ICONS, getX() + width - 12, top + entryHeight / 4, vercheck.status().getSheetOffset() * 8, (vercheck.status().isAnimated() && ((System.currentTimeMillis() / 800 & 1)) == 1) ? 8 : 0, 8, 8, 64, 16);
|
||||
guiGraphics.pose().popPose();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mouseClicked(double p_mouseClicked_1_, double p_mouseClicked_3_, int p_mouseClicked_5_)
|
||||
{
|
||||
public boolean mouseClicked(double p_mouseClicked_1_, double p_mouseClicked_3_, int p_mouseClicked_5_) {
|
||||
parent.setSelected(this);
|
||||
ModListWidget.this.setSelected(this);
|
||||
return false;
|
||||
}
|
||||
|
||||
public IModInfo getInfo()
|
||||
{
|
||||
public IModInfo getInfo() {
|
||||
return modInfo;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,9 +13,7 @@ import net.minecraft.client.gui.components.Renderable;
|
||||
import net.minecraft.client.gui.components.events.AbstractContainerEventHandler;
|
||||
import net.minecraft.client.gui.components.events.GuiEventListener;
|
||||
import net.minecraft.client.gui.narration.NarratableEntry;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import net.minecraft.client.renderer.GameRenderer;
|
||||
|
||||
import net.minecraft.client.renderer.CoreShaders;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@@ -290,7 +288,7 @@ public abstract class ScrollPanel extends AbstractContainerEventHandler implemen
|
||||
int barBgGreen = this.barBgColor >> 8 & 0xff;
|
||||
int barBgBlue = this.barBgColor & 0xff;
|
||||
|
||||
RenderSystem.setShader(GameRenderer::getPositionColorShader);
|
||||
RenderSystem.setShader(CoreShaders.POSITION_COLOR);
|
||||
BufferBuilder worldr = tess.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);
|
||||
worldr.addVertex(barLeft, this.bottom, 0.0F).setColor(barBgRed, barBgGreen, barBgBlue, barBgAlpha);
|
||||
worldr.addVertex(barLeft + barWidth, this.bottom, 0.0F).setColor(barBgRed, barBgGreen, barBgBlue, barBgAlpha);
|
||||
|
||||
@@ -23,7 +23,6 @@ import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.util.profiling.ProfilerFiller;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.api.distmarker.OnlyIn;
|
||||
@@ -59,7 +58,7 @@ public class ClientModLoader {
|
||||
}
|
||||
}
|
||||
|
||||
private static CompletableFuture<Void> onResourceReload(final PreparableReloadListener.PreparationBarrier stage, final ResourceManager resourceManager, final ProfilerFiller prepareProfiler, final ProfilerFiller executeProfiler, final Executor asyncExecutor, final Executor syncExecutor) {
|
||||
private static CompletableFuture<Void> onResourceReload(final PreparableReloadListener.PreparationBarrier stage, final ResourceManager resourceManager, final Executor asyncExecutor, final Executor syncExecutor) {
|
||||
return CompletableFuture.runAsync(createRunnableWithCatch(() -> startModLoading(ModWorkManager.wrappedExecutor(syncExecutor), asyncExecutor)), ModWorkManager.parallelExecutor())
|
||||
.thenCompose(stage::wait)
|
||||
.thenRunAsync(() -> finishModLoading(ModWorkManager.wrappedExecutor(syncExecutor), asyncExecutor), ModWorkManager.parallelExecutor());
|
||||
|
||||
@@ -6,24 +6,19 @@
|
||||
package net.minecraftforge.client.loading;
|
||||
|
||||
import com.mojang.blaze3d.platform.GlConst;
|
||||
import com.mojang.blaze3d.platform.GlStateManager;
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
import com.mojang.blaze3d.vertex.BufferBuilder;
|
||||
import com.mojang.blaze3d.vertex.BufferUploader;
|
||||
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
|
||||
import com.mojang.blaze3d.vertex.Tesselator;
|
||||
import com.mojang.blaze3d.vertex.VertexFormat;
|
||||
import com.mojang.blaze3d.vertex.VertexSorting;
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.screens.LoadingOverlay;
|
||||
import net.minecraft.client.renderer.GameRenderer;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.client.renderer.CoreShaders;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.server.packs.resources.ReloadInstance;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraftforge.fml.StartupMessageManager;
|
||||
import net.minecraftforge.fml.earlydisplay.ColourScheme;
|
||||
import net.minecraftforge.fml.earlydisplay.DisplayWindow;
|
||||
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
@@ -43,19 +38,15 @@ import java.util.function.Supplier;
|
||||
* It is somewhat a copy of the superclass render method.
|
||||
*/
|
||||
public class ForgeLoadingOverlay extends LoadingOverlay {
|
||||
private static final ResourceLocation MOJANG_STUDIOS_LOGO_LOCATION = ResourceLocation.withDefaultNamespace("textures/gui/title/mojangstudios.png");
|
||||
private final Minecraft minecraft;
|
||||
private final ReloadInstance reload;
|
||||
private final Consumer<Optional<Throwable>> onFinish;
|
||||
private final DisplayWindow displayWindow;
|
||||
private final ProgressMeter progress;
|
||||
private long fadeOutStart = -1L;
|
||||
|
||||
public ForgeLoadingOverlay(final Minecraft mc, final ReloadInstance reloader, final Consumer<Optional<Throwable>> errorConsumer, DisplayWindow displayWindow) {
|
||||
super(mc, reloader, errorConsumer, false);
|
||||
this.minecraft = mc;
|
||||
this.reload = reloader;
|
||||
this.onFinish = errorConsumer;
|
||||
this.displayWindow = displayWindow;
|
||||
displayWindow.addMojangTexture(mc.getTextureManager().getTexture(MOJANG_STUDIOS_LOGO_LOCATION).getId());
|
||||
this.progress = StartupMessageManager.prependProgressBar("Minecraft Progress", 100);
|
||||
@@ -66,98 +57,48 @@ public class ForgeLoadingOverlay extends LoadingOverlay {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(final @NotNull GuiGraphics graphics, final int mouseX, final int mouseY, final float partialTick) {
|
||||
long millis = Util.getMillis();
|
||||
float fadeouttimer = this.fadeOutStart > -1L ? (float)(millis - this.fadeOutStart) / 1000.0F : -1.0F;
|
||||
protected boolean renderContents(GuiGraphics gui, float fade) {
|
||||
progress.setAbsolute(Mth.clamp((int)(this.reload.getActualProgress() * 100f), 0, 100));
|
||||
var fade = 1.0F - Mth.clamp(fadeouttimer - 1.0F, 0.0F, 1.0F);
|
||||
var colour = this.displayWindow.context().colourScheme().background();
|
||||
RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, fade);
|
||||
if (fadeouttimer >= 1.0F) {
|
||||
if (this.minecraft.screen != null) {
|
||||
this.minecraft.screen.render(graphics, 0, 0, partialTick);
|
||||
}
|
||||
displayWindow.render(0xff);
|
||||
} else {
|
||||
GlStateManager._clearColor(colour.redf(), colour.greenf(), colour.bluef(), 1f);
|
||||
GlStateManager._clear(GlConst.GL_COLOR_BUFFER_BIT, Minecraft.ON_OSX);
|
||||
displayWindow.render(0xFF);
|
||||
}
|
||||
RenderSystem.enableBlend();
|
||||
RenderSystem.blendFunc(GlConst.GL_SRC_ALPHA, GlConst.GL_ONE_MINUS_SRC_ALPHA);
|
||||
|
||||
int alpha = (int)(fade * 255);
|
||||
this.displayWindow.render(alpha);
|
||||
|
||||
int width = gui.guiWidth();
|
||||
int height = gui.guiHeight();
|
||||
|
||||
var fbWidth = this.minecraft.getWindow().getWidth();
|
||||
var fbHeight = this.minecraft.getWindow().getHeight();
|
||||
GL30C.glViewport(0, 0, fbWidth, fbHeight);
|
||||
final var twidth = this.displayWindow.context().width();
|
||||
final var theight = this.displayWindow.context().height();
|
||||
var wscale = (float)fbWidth / twidth;
|
||||
var hscale = (float)fbHeight / theight;
|
||||
var scale = this.displayWindow.context().scale() * Math.min(wscale, hscale) / 2f;
|
||||
var wleft = Mth.clamp(fbWidth * 0.5f - scale * twidth, 0, fbWidth);
|
||||
var wtop = Mth.clamp(fbHeight * 0.5f - scale * theight, 0, fbHeight);
|
||||
var wright = Mth.clamp(fbWidth * 0.5f + scale * twidth, 0, fbWidth);
|
||||
var wbottom = Mth.clamp(fbHeight * 0.5f + scale * theight, 0, fbHeight);
|
||||
GlStateManager.glActiveTexture(GlConst.GL_TEXTURE0);
|
||||
RenderSystem.disableCull();
|
||||
BufferBuilder bufferbuilder = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);
|
||||
|
||||
RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, fade);
|
||||
RenderSystem.getModelViewMatrix().identity();
|
||||
RenderSystem.setProjectionMatrix(new Matrix4f().setOrtho(0.0F, fbWidth, 0.0F, fbHeight, 0.1f, -0.1f), VertexSorting.ORTHOGRAPHIC_Z);
|
||||
RenderSystem.setShader(GameRenderer::getPositionColorShader);
|
||||
// This is fill in around the edges - it's empty solid colour
|
||||
|
||||
// top box from hpos
|
||||
addQuad(bufferbuilder, 0, fbWidth, wtop, fbHeight, colour, fade);
|
||||
// bottom box to hpos
|
||||
addQuad(bufferbuilder, 0, fbWidth, 0, wtop, colour, fade);
|
||||
// left box to wpos
|
||||
addQuad(bufferbuilder, 0, wleft, wtop, wbottom, colour, fade);
|
||||
// right box from wpos
|
||||
addQuad(bufferbuilder, wright, fbWidth, wtop, wbottom, colour, fade);
|
||||
BufferUploader.drawWithShader(bufferbuilder.buildOrThrow());
|
||||
|
||||
// This is the actual screen data from the loading screen
|
||||
Matrix4f pos = gui.pose().last().pose();
|
||||
RenderSystem.enableBlend();
|
||||
RenderSystem.blendFunc(GlConst.GL_SRC_ALPHA, GlConst.GL_ONE_MINUS_SRC_ALPHA);
|
||||
RenderSystem.setShader(GameRenderer::getPositionTexColorShader);
|
||||
RenderSystem.setShader(CoreShaders.POSITION_TEX_COLOR);
|
||||
RenderSystem.setShaderTexture(0, displayWindow.getFramebufferTextureId());
|
||||
bufferbuilder = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR);
|
||||
bufferbuilder.addVertex(wleft, wbottom, 0f).setUv(0, 0).setColor(1f, 1f, 1f, fade);
|
||||
bufferbuilder.addVertex(wright, wbottom, 0f).setUv(1, 0).setColor(1f, 1f, 1f, fade);
|
||||
bufferbuilder.addVertex(wright, wtop, 0f).setUv(1, 1).setColor(1f, 1f, 1f, fade);
|
||||
bufferbuilder.addVertex(wleft, wtop, 0f).setUv(0, 1).setColor(1f, 1f, 1f, fade);
|
||||
GL30C.glTexParameterIi(GlConst.GL_TEXTURE_2D, GlConst.GL_TEXTURE_MIN_FILTER, GlConst.GL_NEAREST);
|
||||
GL30C.glTexParameterIi(GlConst.GL_TEXTURE_2D, GlConst.GL_TEXTURE_MAG_FILTER, GlConst.GL_NEAREST);
|
||||
BufferUploader.drawWithShader(bufferbuilder.buildOrThrow());
|
||||
|
||||
var buf = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR);
|
||||
buf.addVertex(pos, 0, 0, 0f).setUv(0, 0).setColor(1f, 1f, 1f, fade);
|
||||
buf.addVertex(pos, 0, height, 0f).setUv(0, 1).setColor(1f, 1f, 1f, fade);
|
||||
buf.addVertex(pos, width, height, 0f).setUv(1, 1).setColor(1f, 1f, 1f, fade);
|
||||
buf.addVertex(pos, width, 0, 0f).setUv(1, 0).setColor(1f, 1f, 1f, fade);
|
||||
BufferUploader.drawWithShader(buf.buildOrThrow());
|
||||
|
||||
// I dont know what exactly this does, but without it the screen flickers black.
|
||||
// So as a hack we just render the mojang logo as a 0x0 cube
|
||||
// TODO: Remove this when early screen is re-written to not be a texture based renderer
|
||||
var logo = gui.getBufferSource().getBuffer(RenderType.mojangLogo());
|
||||
logo.addVertex(pos, 0, 0, 0f).setUv(0, 0).setColor(1f, 1f, 1f, fade);
|
||||
logo.addVertex(pos, 0, 0, 0f).setUv(0, 1).setColor(1f, 1f, 1f, fade);
|
||||
logo.addVertex(pos, 0, 0, 0f).setUv(1, 1).setColor(1f, 1f, 1f, fade);
|
||||
logo.addVertex(pos, 0, 0, 0f).setUv(1, 0).setColor(1f, 1f, 1f, fade);
|
||||
|
||||
RenderSystem.defaultBlendFunc();
|
||||
RenderSystem.disableBlend();
|
||||
RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1f);
|
||||
|
||||
if (fadeouttimer >= 2.0F) {
|
||||
this.minecraft.setOverlay(null);
|
||||
this.displayWindow.close();
|
||||
}
|
||||
|
||||
if (this.fadeOutStart == -1L && this.reload.isDone()) {
|
||||
progress.complete();
|
||||
this.fadeOutStart = Util.getMillis();
|
||||
try {
|
||||
this.reload.checkExceptions();
|
||||
this.onFinish.accept(Optional.empty());
|
||||
} catch (Throwable throwable) {
|
||||
this.onFinish.accept(Optional.of(throwable));
|
||||
}
|
||||
|
||||
if (this.minecraft.screen != null) {
|
||||
this.minecraft.screen.init(this.minecraft, this.minecraft.getWindow().getGuiScaledWidth(), this.minecraft.getWindow().getGuiScaledHeight());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void addQuad(BufferBuilder bufferbuilder, float x0, float x1, float y0, float y1, ColourScheme.Colour colour, float fade) {
|
||||
bufferbuilder.addVertex(x0, y0, 0f).setColor(colour.redf(), colour.greenf(), colour.bluef(), fade);
|
||||
bufferbuilder.addVertex(x0, y1, 0f).setColor(colour.redf(), colour.greenf(), colour.bluef(), fade);
|
||||
bufferbuilder.addVertex(x1, y1, 0f).setColor(colour.redf(), colour.greenf(), colour.bluef(), fade);
|
||||
bufferbuilder.addVertex(x1, y0, 0f).setColor(colour.redf(), colour.greenf(), colour.bluef(), fade);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@ package net.minecraftforge.client.model;
|
||||
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.renderer.block.model.BakedOverrides;
|
||||
import net.minecraft.client.renderer.block.model.BakedQuad;
|
||||
import net.minecraft.client.renderer.block.model.ItemOverrides;
|
||||
import net.minecraft.client.renderer.block.model.ItemTransforms;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.resources.model.BakedModel;
|
||||
@@ -31,116 +31,97 @@ import java.util.List;
|
||||
* <p>
|
||||
* Useful for creating wrapper baked models which only override certain properties.
|
||||
*/
|
||||
public abstract class BakedModelWrapper<T extends BakedModel> implements BakedModel
|
||||
{
|
||||
public abstract class BakedModelWrapper<T extends BakedModel> implements BakedModel {
|
||||
protected final T originalModel;
|
||||
|
||||
public BakedModelWrapper(T originalModel)
|
||||
{
|
||||
public BakedModelWrapper(T originalModel) {
|
||||
this.originalModel = originalModel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand)
|
||||
{
|
||||
public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand) {
|
||||
return originalModel.getQuads(state, side, rand);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean useAmbientOcclusion()
|
||||
{
|
||||
public boolean useAmbientOcclusion() {
|
||||
return originalModel.useAmbientOcclusion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean useAmbientOcclusion(BlockState state)
|
||||
{
|
||||
public boolean useAmbientOcclusion(BlockState state) {
|
||||
return originalModel.useAmbientOcclusion(state);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean useAmbientOcclusion(BlockState state, RenderType renderType)
|
||||
{
|
||||
public boolean useAmbientOcclusion(BlockState state, RenderType renderType) {
|
||||
return originalModel.useAmbientOcclusion(state, renderType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isGui3d()
|
||||
{
|
||||
public boolean isGui3d() {
|
||||
return originalModel.isGui3d();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean usesBlockLight()
|
||||
{
|
||||
public boolean usesBlockLight() {
|
||||
return originalModel.usesBlockLight();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCustomRenderer()
|
||||
{
|
||||
public boolean isCustomRenderer() {
|
||||
return originalModel.isCustomRenderer();
|
||||
}
|
||||
|
||||
@Override
|
||||
public TextureAtlasSprite getParticleIcon()
|
||||
{
|
||||
public TextureAtlasSprite getParticleIcon() {
|
||||
return originalModel.getParticleIcon();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemTransforms getTransforms()
|
||||
{
|
||||
public ItemTransforms getTransforms() {
|
||||
return originalModel.getTransforms();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemOverrides getOverrides()
|
||||
{
|
||||
return originalModel.getOverrides();
|
||||
public BakedOverrides overrides() {
|
||||
return originalModel.overrides();
|
||||
}
|
||||
|
||||
@Override
|
||||
public BakedModel applyTransform(ItemDisplayContext cameraTransformType, PoseStack poseStack, boolean applyLeftHandTransform)
|
||||
{
|
||||
public BakedModel applyTransform(ItemDisplayContext cameraTransformType, PoseStack poseStack, boolean applyLeftHandTransform) {
|
||||
return originalModel.applyTransform(cameraTransformType, poseStack, applyLeftHandTransform);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TextureAtlasSprite getParticleIcon(@NotNull ModelData data)
|
||||
{
|
||||
public TextureAtlasSprite getParticleIcon(@NotNull ModelData data) {
|
||||
return originalModel.getParticleIcon(data);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData extraData, @Nullable RenderType renderType)
|
||||
{
|
||||
public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData extraData, @Nullable RenderType renderType) {
|
||||
return originalModel.getQuads(state, side, rand, extraData, renderType);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public ModelData getModelData(@NotNull BlockAndTintGetter level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull ModelData modelData)
|
||||
{
|
||||
public ModelData getModelData(@NotNull BlockAndTintGetter level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull ModelData modelData) {
|
||||
return originalModel.getModelData(level, pos, state, modelData);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data)
|
||||
{
|
||||
public ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data) {
|
||||
return originalModel.getRenderTypes(state, rand, data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<RenderType> getRenderTypes(ItemStack itemStack, boolean fabulous)
|
||||
{
|
||||
public List<RenderType> getRenderTypes(ItemStack itemStack, boolean fabulous) {
|
||||
return originalModel.getRenderTypes(itemStack, fabulous);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BakedModel> getRenderPasses(ItemStack itemStack, boolean fabulous)
|
||||
{
|
||||
public List<BakedModel> getRenderPasses(ItemStack itemStack, boolean fabulous) {
|
||||
return originalModel.getRenderPasses(itemStack, fabulous);
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,6 @@ import java.util.function.Function;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.renderer.block.model.BakedQuad;
|
||||
import net.minecraft.client.renderer.block.model.BlockModel;
|
||||
import net.minecraft.client.renderer.block.model.ItemOverrides;
|
||||
import net.minecraft.client.renderer.block.model.ItemTransforms;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.resources.model.BakedModel;
|
||||
@@ -33,7 +32,6 @@ import net.minecraft.client.resources.model.ModelState;
|
||||
import net.minecraft.client.resources.model.UnbakedModel;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.BlockAndTintGetter;
|
||||
@@ -56,20 +54,17 @@ import org.jetbrains.annotations.Nullable;
|
||||
* These respect component visibility as specified in {@link IGeometryBakingContext} and can additionally be provided
|
||||
* with an item-specific render ordering, for multi-pass arrangements.
|
||||
*/
|
||||
public class CompositeModel implements IUnbakedGeometry<CompositeModel>
|
||||
{
|
||||
public class CompositeModel implements IUnbakedGeometry<CompositeModel> {
|
||||
private final ImmutableMap<String, BlockModel> children;
|
||||
private final ImmutableList<String> itemPasses;
|
||||
|
||||
public CompositeModel(ImmutableMap<String, BlockModel> children, ImmutableList<String> itemPasses)
|
||||
{
|
||||
public CompositeModel(ImmutableMap<String, BlockModel> children, ImmutableList<String> itemPasses) {
|
||||
this.children = children;
|
||||
this.itemPasses = itemPasses;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, ItemOverrides overrides)
|
||||
{
|
||||
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState) {
|
||||
Material particleLocation = context.getMaterial("particle");
|
||||
TextureAtlasSprite particle = spriteGetter.apply(particleLocation);
|
||||
|
||||
@@ -78,13 +73,12 @@ public class CompositeModel implements IUnbakedGeometry<CompositeModel>
|
||||
modelState = UnbakedGeometryHelper.composeRootTransformIntoModelState(modelState, rootTransform);
|
||||
|
||||
var bakedPartsBuilder = ImmutableMap.<String, BakedModel>builder();
|
||||
for (var entry : children.entrySet())
|
||||
{
|
||||
for (var entry : children.entrySet()) {
|
||||
var name = entry.getKey();
|
||||
if (!context.isComponentVisible(name, true))
|
||||
continue;
|
||||
var model = entry.getValue();
|
||||
bakedPartsBuilder.put(name, model.bake(baker, model, spriteGetter, modelState, true));
|
||||
bakedPartsBuilder.put(name, model.bake(baker, spriteGetter, modelState));
|
||||
}
|
||||
var bakedParts = bakedPartsBuilder.build();
|
||||
|
||||
@@ -97,53 +91,44 @@ public class CompositeModel implements IUnbakedGeometry<CompositeModel>
|
||||
itemPassesBuilder.add(model);
|
||||
}
|
||||
|
||||
return new Baked(context.isGui3d(), context.useBlockLight(), context.useAmbientOcclusion(), particle, context.getTransforms(), overrides, bakedParts, itemPassesBuilder.build());
|
||||
return new Baked(context.isGui3d(), context.useBlockLight(), context.useAmbientOcclusion(), particle, context.getTransforms(), bakedParts, itemPassesBuilder.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resolveParents(Function<ResourceLocation, UnbakedModel> modelGetter, IGeometryBakingContext context)
|
||||
{
|
||||
children.values().forEach(child -> child.resolveParents(modelGetter));
|
||||
public void resolveDependencies(UnbakedModel.Resolver resolver, IGeometryBakingContext context) {
|
||||
children.values().forEach(child -> child.resolveDependencies(resolver));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> getConfigurableComponentNames()
|
||||
{
|
||||
public Set<String> getConfigurableComponentNames() {
|
||||
return children.keySet();
|
||||
}
|
||||
|
||||
public static class Baked implements IDynamicBakedModel
|
||||
{
|
||||
public static class Baked implements IDynamicBakedModel {
|
||||
private final boolean isAmbientOcclusion;
|
||||
private final boolean isGui3d;
|
||||
private final boolean isSideLit;
|
||||
private final TextureAtlasSprite particle;
|
||||
private final ItemOverrides overrides;
|
||||
private final ItemTransforms transforms;
|
||||
private final ImmutableMap<String, BakedModel> children;
|
||||
private final ImmutableList<BakedModel> itemPasses;
|
||||
|
||||
public Baked(boolean isGui3d, boolean isSideLit, boolean isAmbientOcclusion, TextureAtlasSprite particle, ItemTransforms transforms, ItemOverrides overrides, ImmutableMap<String, BakedModel> children, ImmutableList<BakedModel> itemPasses)
|
||||
{
|
||||
public Baked(boolean isGui3d, boolean isSideLit, boolean isAmbientOcclusion, TextureAtlasSprite particle, ItemTransforms transforms, ImmutableMap<String, BakedModel> children, ImmutableList<BakedModel> itemPasses) {
|
||||
this.children = children;
|
||||
this.isAmbientOcclusion = isAmbientOcclusion;
|
||||
this.isGui3d = isGui3d;
|
||||
this.isSideLit = isSideLit;
|
||||
this.particle = particle;
|
||||
this.overrides = overrides;
|
||||
this.transforms = transforms;
|
||||
this.itemPasses = itemPasses;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData data, @Nullable RenderType renderType)
|
||||
{
|
||||
public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData data, @Nullable RenderType renderType) {
|
||||
List<List<BakedQuad>> quadLists = new ArrayList<>();
|
||||
for (Map.Entry<String, BakedModel> entry : children.entrySet())
|
||||
{
|
||||
if (renderType == null || (state != null && entry.getValue().getRenderTypes(state, rand, data).contains(renderType)))
|
||||
{
|
||||
for (Map.Entry<String, BakedModel> entry : children.entrySet()) {
|
||||
if (renderType == null || (state != null && entry.getValue().getRenderTypes(state, rand, data).contains(renderType))) {
|
||||
quadLists.add(entry.getValue().getQuads(state, side, rand, CompositeModel.Data.resolve(data, entry.getKey()), renderType));
|
||||
}
|
||||
}
|
||||
@@ -151,8 +136,7 @@ public class CompositeModel implements IUnbakedGeometry<CompositeModel>
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull ModelData getModelData(@NotNull BlockAndTintGetter level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull ModelData modelData)
|
||||
{
|
||||
public @NotNull ModelData getModelData(@NotNull BlockAndTintGetter level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull ModelData modelData) {
|
||||
var builder = Data.builder();
|
||||
for (var entry : children.entrySet())
|
||||
builder.with(entry.getKey(), entry.getValue().getModelData(level, pos, state, Data.resolve(modelData, entry.getKey())));
|
||||
@@ -160,50 +144,37 @@ public class CompositeModel implements IUnbakedGeometry<CompositeModel>
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean useAmbientOcclusion()
|
||||
{
|
||||
public boolean useAmbientOcclusion() {
|
||||
return isAmbientOcclusion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isGui3d()
|
||||
{
|
||||
public boolean isGui3d() {
|
||||
return isGui3d;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean usesBlockLight()
|
||||
{
|
||||
public boolean usesBlockLight() {
|
||||
return isSideLit;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCustomRenderer()
|
||||
{
|
||||
public boolean isCustomRenderer() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TextureAtlasSprite getParticleIcon()
|
||||
{
|
||||
public TextureAtlasSprite getParticleIcon() {
|
||||
return particle;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemOverrides getOverrides()
|
||||
{
|
||||
return overrides;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemTransforms getTransforms()
|
||||
{
|
||||
public ItemTransforms getTransforms() {
|
||||
return transforms;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data)
|
||||
{
|
||||
public ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data) {
|
||||
var sets = new ArrayList<ChunkRenderTypeSet>();
|
||||
for (Map.Entry<String, BakedModel> entry : children.entrySet())
|
||||
sets.add(entry.getValue().getRenderTypes(state, rand, CompositeModel.Data.resolve(data, entry.getKey())));
|
||||
@@ -211,68 +182,55 @@ public class CompositeModel implements IUnbakedGeometry<CompositeModel>
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BakedModel> getRenderPasses(ItemStack itemStack, boolean fabulous)
|
||||
{
|
||||
public List<BakedModel> getRenderPasses(ItemStack itemStack, boolean fabulous) {
|
||||
return itemPasses;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public BakedModel getPart(String name)
|
||||
{
|
||||
public BakedModel getPart(String name) {
|
||||
return children.get(name);
|
||||
}
|
||||
|
||||
public static Builder builder(IGeometryBakingContext owner, TextureAtlasSprite particle, ItemOverrides overrides, ItemTransforms cameraTransforms)
|
||||
{
|
||||
return builder(owner.useAmbientOcclusion(), owner.isGui3d(), owner.useBlockLight(), particle, overrides, cameraTransforms);
|
||||
public static Builder builder(IGeometryBakingContext owner, TextureAtlasSprite particle, ItemTransforms cameraTransforms) {
|
||||
return builder(owner.useAmbientOcclusion(), owner.isGui3d(), owner.useBlockLight(), particle, cameraTransforms);
|
||||
}
|
||||
|
||||
public static Builder builder(boolean isAmbientOcclusion, boolean isGui3d, boolean isSideLit, TextureAtlasSprite particle, ItemOverrides overrides, ItemTransforms cameraTransforms)
|
||||
{
|
||||
return new Builder(isAmbientOcclusion, isGui3d, isSideLit, particle, overrides, cameraTransforms);
|
||||
public static Builder builder(boolean isAmbientOcclusion, boolean isGui3d, boolean isSideLit, TextureAtlasSprite particle, ItemTransforms cameraTransforms) {
|
||||
return new Builder(isAmbientOcclusion, isGui3d, isSideLit, particle, cameraTransforms);
|
||||
}
|
||||
|
||||
public static class Builder
|
||||
{
|
||||
public static class Builder {
|
||||
private final boolean isAmbientOcclusion;
|
||||
private final boolean isGui3d;
|
||||
private final boolean isSideLit;
|
||||
private final List<BakedModel> children = new ArrayList<>();
|
||||
private final List<BakedQuad> quads = new ArrayList<>();
|
||||
private final ItemOverrides overrides;
|
||||
private final ItemTransforms transforms;
|
||||
private TextureAtlasSprite particle;
|
||||
private RenderTypeGroup lastRenderTypes = RenderTypeGroup.EMPTY;
|
||||
|
||||
private Builder(boolean isAmbientOcclusion, boolean isGui3d, boolean isSideLit, TextureAtlasSprite particle, ItemOverrides overrides, ItemTransforms transforms)
|
||||
{
|
||||
private Builder(boolean isAmbientOcclusion, boolean isGui3d, boolean isSideLit, TextureAtlasSprite particle, ItemTransforms transforms) {
|
||||
this.isAmbientOcclusion = isAmbientOcclusion;
|
||||
this.isGui3d = isGui3d;
|
||||
this.isSideLit = isSideLit;
|
||||
this.particle = particle;
|
||||
this.overrides = overrides;
|
||||
this.transforms = transforms;
|
||||
}
|
||||
|
||||
public void addLayer(BakedModel model)
|
||||
{
|
||||
public void addLayer(BakedModel model) {
|
||||
flushQuads(null);
|
||||
children.add(model);
|
||||
}
|
||||
|
||||
private void addLayer(RenderTypeGroup renderTypes, List<BakedQuad> quads)
|
||||
{
|
||||
var modelBuilder = IModelBuilder.of(isAmbientOcclusion, isSideLit, isGui3d, transforms, overrides, particle, renderTypes);
|
||||
private void addLayer(RenderTypeGroup renderTypes, List<BakedQuad> quads) {
|
||||
var modelBuilder = IModelBuilder.of(isAmbientOcclusion, isSideLit, isGui3d, transforms, particle, renderTypes);
|
||||
quads.forEach(modelBuilder::addUnculledFace);
|
||||
children.add(modelBuilder.build());
|
||||
}
|
||||
|
||||
private void flushQuads(RenderTypeGroup renderTypes)
|
||||
{
|
||||
if (!Objects.equals(renderTypes, lastRenderTypes))
|
||||
{
|
||||
if (!quads.isEmpty())
|
||||
{
|
||||
private void flushQuads(RenderTypeGroup renderTypes) {
|
||||
if (!Objects.equals(renderTypes, lastRenderTypes)) {
|
||||
if (!quads.isEmpty()) {
|
||||
addLayer(lastRenderTypes, quads);
|
||||
quads.clear();
|
||||
}
|
||||
@@ -280,41 +238,35 @@ public class CompositeModel implements IUnbakedGeometry<CompositeModel>
|
||||
}
|
||||
}
|
||||
|
||||
public Builder setParticle(TextureAtlasSprite particleSprite)
|
||||
{
|
||||
public Builder setParticle(TextureAtlasSprite particleSprite) {
|
||||
this.particle = particleSprite;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder addQuads(RenderTypeGroup renderTypes, BakedQuad... quadsToAdd)
|
||||
{
|
||||
public Builder addQuads(RenderTypeGroup renderTypes, BakedQuad... quadsToAdd) {
|
||||
flushQuads(renderTypes);
|
||||
Collections.addAll(quads, quadsToAdd);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder addQuads(RenderTypeGroup renderTypes, Collection<BakedQuad> quadsToAdd)
|
||||
{
|
||||
public Builder addQuads(RenderTypeGroup renderTypes, Collection<BakedQuad> quadsToAdd) {
|
||||
flushQuads(renderTypes);
|
||||
quads.addAll(quadsToAdd);
|
||||
return this;
|
||||
}
|
||||
|
||||
public BakedModel build()
|
||||
{
|
||||
if (!quads.isEmpty())
|
||||
{
|
||||
public BakedModel build() {
|
||||
if (!quads.isEmpty()) {
|
||||
addLayer(lastRenderTypes, quads);
|
||||
}
|
||||
var childrenBuilder = ImmutableMap.<String, BakedModel>builder();
|
||||
var itemPassesBuilder = ImmutableList.<BakedModel>builder();
|
||||
int i = 0;
|
||||
for (var model : this.children)
|
||||
{
|
||||
for (var model : this.children) {
|
||||
childrenBuilder.put("model_" + (i++), model);
|
||||
itemPassesBuilder.add(model);
|
||||
}
|
||||
return new Baked(isGui3d, isSideLit, isAmbientOcclusion, particle, transforms, overrides, childrenBuilder.build(), itemPassesBuilder.build());
|
||||
return new Baked(isGui3d, isSideLit, isAmbientOcclusion, particle, transforms, childrenBuilder.build(), itemPassesBuilder.build());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,20 +275,17 @@ public class CompositeModel implements IUnbakedGeometry<CompositeModel>
|
||||
/**
|
||||
* A model data container which stores data for child components.
|
||||
*/
|
||||
public static class Data
|
||||
{
|
||||
public static class Data {
|
||||
public static final ModelProperty<Data> PROPERTY = new ModelProperty<>();
|
||||
|
||||
private final Map<String, ModelData> partData;
|
||||
|
||||
private Data(Map<String, ModelData> partData)
|
||||
{
|
||||
private Data(Map<String, ModelData> partData) {
|
||||
this.partData = partData;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public ModelData get(String name)
|
||||
{
|
||||
public ModelData get(String name) {
|
||||
return partData.get(name);
|
||||
}
|
||||
|
||||
@@ -347,8 +296,7 @@ public class CompositeModel implements IUnbakedGeometry<CompositeModel>
|
||||
* @param name The name of the part to get data for
|
||||
* @return The data for the part, or the one passed in if not found
|
||||
*/
|
||||
public static ModelData resolve(ModelData modelData, String name)
|
||||
{
|
||||
public static ModelData resolve(ModelData modelData, String name) {
|
||||
var compositeData = modelData.get(PROPERTY);
|
||||
if (compositeData == null)
|
||||
return modelData;
|
||||
@@ -356,39 +304,31 @@ public class CompositeModel implements IUnbakedGeometry<CompositeModel>
|
||||
return partData != null ? partData : modelData;
|
||||
}
|
||||
|
||||
public static Builder builder()
|
||||
{
|
||||
public static Builder builder() {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
public static final class Builder
|
||||
{
|
||||
public static final class Builder {
|
||||
private final Map<String, ModelData> partData = new IdentityHashMap<>();
|
||||
|
||||
public Builder with(String name, ModelData data)
|
||||
{
|
||||
public Builder with(String name, ModelData data) {
|
||||
partData.put(name, data);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Data build()
|
||||
{
|
||||
public Data build() {
|
||||
return new Data(partData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Loader implements IGeometryLoader<CompositeModel>
|
||||
{
|
||||
public static final class Loader implements IGeometryLoader<CompositeModel> {
|
||||
public static final Loader INSTANCE = new Loader();
|
||||
|
||||
private Loader()
|
||||
{
|
||||
}
|
||||
private Loader() { }
|
||||
|
||||
@Override
|
||||
public CompositeModel read(JsonObject jsonObject, JsonDeserializationContext deserializationContext)
|
||||
{
|
||||
public CompositeModel read(JsonObject jsonObject, JsonDeserializationContext deserializationContext) {
|
||||
List<String> itemPasses = new ArrayList<>();
|
||||
ImmutableMap.Builder<String, BlockModel> childrenBuilder = ImmutableMap.builder();
|
||||
readChildren(jsonObject, "children", deserializationContext, childrenBuilder, itemPasses);
|
||||
@@ -397,8 +337,7 @@ public class CompositeModel implements IUnbakedGeometry<CompositeModel>
|
||||
if (children.isEmpty())
|
||||
throw new JsonParseException("Composite model requires a \"children\" element with at least one element.");
|
||||
|
||||
if (jsonObject.has("item_render_order"))
|
||||
{
|
||||
if (jsonObject.has("item_render_order")) {
|
||||
itemPasses.clear();
|
||||
for (var element : jsonObject.getAsJsonArray("item_render_order"))
|
||||
{
|
||||
@@ -412,13 +351,11 @@ public class CompositeModel implements IUnbakedGeometry<CompositeModel>
|
||||
return new CompositeModel(children, ImmutableList.copyOf(itemPasses));
|
||||
}
|
||||
|
||||
private void readChildren(JsonObject jsonObject, String name, JsonDeserializationContext deserializationContext, ImmutableMap.Builder<String, BlockModel> children, List<String> itemPasses)
|
||||
{
|
||||
private void readChildren(JsonObject jsonObject, String name, JsonDeserializationContext deserializationContext, ImmutableMap.Builder<String, BlockModel> children, List<String> itemPasses) {
|
||||
if (!jsonObject.has(name))
|
||||
return;
|
||||
var childrenJsonObject = jsonObject.getAsJsonObject(name);
|
||||
for (Map.Entry<String, JsonElement> entry : childrenJsonObject.entrySet())
|
||||
{
|
||||
for (Map.Entry<String, JsonElement> entry : childrenJsonObject.entrySet()) {
|
||||
children.put(entry.getKey(), deserializationContext.deserialize(entry.getValue(), BlockModel.class));
|
||||
itemPasses.add(entry.getKey()); // We can do this because GSON preserves ordering during deserialization
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import com.mojang.math.Transformation;
|
||||
import net.minecraft.client.color.item.ItemColor;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.renderer.block.model.ItemOverrides;
|
||||
import net.minecraft.client.renderer.block.model.BakedOverrides;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.resources.model.BakedModel;
|
||||
import net.minecraft.client.resources.model.BlockModelRotation;
|
||||
@@ -56,8 +56,7 @@ import static net.minecraftforge.client.model.geometry.StandaloneGeometryBakingC
|
||||
*
|
||||
* @see Colors
|
||||
*/
|
||||
public class DynamicFluidContainerModel implements IUnbakedGeometry<DynamicFluidContainerModel>
|
||||
{
|
||||
public class DynamicFluidContainerModel implements IUnbakedGeometry<DynamicFluidContainerModel> {
|
||||
// Depth offsets to prevent Z-fighting
|
||||
private static final Transformation FLUID_TRANSFORM = new Transformation(new Vector3f(), new Quaternionf(), new Vector3f(1, 1, 1.002f), new Quaternionf());
|
||||
private static final Transformation COVER_TRANSFORM = new Transformation(new Vector3f(), new Quaternionf(), new Vector3f(1, 1, 1.004f), new Quaternionf());
|
||||
@@ -67,16 +66,14 @@ public class DynamicFluidContainerModel implements IUnbakedGeometry<DynamicFluid
|
||||
private final boolean coverIsMask;
|
||||
private final boolean applyFluidLuminosity;
|
||||
|
||||
private DynamicFluidContainerModel(Fluid fluid, boolean flipGas, boolean coverIsMask, boolean applyFluidLuminosity)
|
||||
{
|
||||
private DynamicFluidContainerModel(Fluid fluid, boolean flipGas, boolean coverIsMask, boolean applyFluidLuminosity) {
|
||||
this.fluid = fluid;
|
||||
this.flipGas = flipGas;
|
||||
this.coverIsMask = coverIsMask;
|
||||
this.applyFluidLuminosity = applyFluidLuminosity;
|
||||
}
|
||||
|
||||
public static RenderTypeGroup getLayerRenderTypes(boolean unlit)
|
||||
{
|
||||
public static RenderTypeGroup getLayerRenderTypes(boolean unlit) {
|
||||
return new RenderTypeGroup(RenderType.translucent(), unlit ? ForgeRenderTypes.ITEM_UNSORTED_UNLIT_TRANSLUCENT.get() : ForgeRenderTypes.ITEM_UNSORTED_TRANSLUCENT.get());
|
||||
}
|
||||
|
||||
@@ -84,14 +81,12 @@ public class DynamicFluidContainerModel implements IUnbakedGeometry<DynamicFluid
|
||||
* Returns a new ModelDynBucket representing the given fluid, but with the same
|
||||
* other properties (flipGas, tint, coverIsMask).
|
||||
*/
|
||||
public DynamicFluidContainerModel withFluid(Fluid newFluid)
|
||||
{
|
||||
public DynamicFluidContainerModel withFluid(Fluid newFluid) {
|
||||
return new DynamicFluidContainerModel(newFluid, flipGas, coverIsMask, applyFluidLuminosity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, ItemOverrides overrides)
|
||||
{
|
||||
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState) {
|
||||
Material particleLocation = context.hasMaterial("particle") ? context.getMaterial("particle") : null;
|
||||
Material baseLocation = context.hasMaterial("base") ? context.getMaterial("base") : null;
|
||||
Material fluidMaskLocation = context.hasMaterial("fluid") ? context.getMaterial("fluid") : null;
|
||||
@@ -108,8 +103,7 @@ public class DynamicFluidContainerModel implements IUnbakedGeometry<DynamicFluid
|
||||
if (particleSprite == null && !coverIsMask) particleSprite = coverSprite;
|
||||
|
||||
// If the fluid is lighter than air, rotate 180deg to turn it upside down
|
||||
if (flipGas && fluid != Fluids.EMPTY && fluid.getFluidType().isLighterThanAir())
|
||||
{
|
||||
if (flipGas && fluid != Fluids.EMPTY && fluid.getFluidType().isLighterThanAir()) {
|
||||
modelState = new SimpleModelState(
|
||||
modelState.getRotation().compose(
|
||||
new Transformation(null, new Quaternionf(0, 0, 1, 0), null, null)));
|
||||
@@ -117,23 +111,20 @@ public class DynamicFluidContainerModel implements IUnbakedGeometry<DynamicFluid
|
||||
|
||||
// We need to disable GUI 3D and block lighting for this to render properly
|
||||
var itemContext = StandaloneGeometryBakingContext.builder(context).withGui3d(false).withUseBlockLight(false).build(LOCATION);
|
||||
var modelBuilder = CompositeModel.Baked.builder(itemContext, particleSprite, new ContainedFluidOverrideHandler(overrides, baker, itemContext, this), context.getTransforms());
|
||||
var modelBuilder = CompositeModel.Baked.builder(itemContext, particleSprite, /*new ContainedFluidOverrideHandler(baker, itemContext, this),*/ context.getTransforms());
|
||||
|
||||
var normalRenderTypes = getLayerRenderTypes(false);
|
||||
|
||||
if (baseLocation != null && baseSprite != null)
|
||||
{
|
||||
if (baseLocation != null && baseSprite != null) {
|
||||
// Base texture
|
||||
var unbaked = UnbakedGeometryHelper.createUnbakedItemElements(0, baseSprite.contents());
|
||||
var quads = UnbakedGeometryHelper.bakeElements(unbaked, $ -> baseSprite, modelState);
|
||||
modelBuilder.addQuads(normalRenderTypes, quads);
|
||||
}
|
||||
|
||||
if (fluidMaskLocation != null && fluidSprite != null)
|
||||
{
|
||||
if (fluidMaskLocation != null && fluidSprite != null) {
|
||||
TextureAtlasSprite templateSprite = spriteGetter.apply(fluidMaskLocation);
|
||||
if (templateSprite != null)
|
||||
{
|
||||
if (templateSprite != null) {
|
||||
// Fluid layer
|
||||
var transformedState = new SimpleModelState(modelState.getRotation().compose(FLUID_TRANSFORM), modelState.isUvLocked());
|
||||
var unbaked = UnbakedGeometryHelper.createUnbakedItemMaskElements(1, templateSprite.contents()); // Use template as mask
|
||||
@@ -147,11 +138,9 @@ public class DynamicFluidContainerModel implements IUnbakedGeometry<DynamicFluid
|
||||
}
|
||||
}
|
||||
|
||||
if (coverSprite != null)
|
||||
{
|
||||
if (coverSprite != null) {
|
||||
var sprite = coverIsMask ? baseSprite : coverSprite;
|
||||
if (sprite != null)
|
||||
{
|
||||
if (sprite != null) {
|
||||
// Cover/overlay
|
||||
var transformedState = new SimpleModelState(modelState.getRotation().compose(COVER_TRANSFORM), modelState.isUvLocked());
|
||||
var unbaked = UnbakedGeometryHelper.createUnbakedItemMaskElements(2, coverSprite.contents()); // Use cover as mask
|
||||
@@ -192,16 +181,14 @@ public class DynamicFluidContainerModel implements IUnbakedGeometry<DynamicFluid
|
||||
}
|
||||
}
|
||||
|
||||
private static final class ContainedFluidOverrideHandler extends ItemOverrides
|
||||
{
|
||||
private static final class ContainedFluidOverrideHandler extends BakedOverrides {
|
||||
private final Map<String, BakedModel> cache = Maps.newHashMap(); // contains all the baked models since they'll never change
|
||||
private final ItemOverrides nested;
|
||||
private final BakedOverrides nested;
|
||||
private final ModelBaker baker;
|
||||
private final IGeometryBakingContext owner;
|
||||
private final DynamicFluidContainerModel parent;
|
||||
|
||||
private ContainedFluidOverrideHandler(ItemOverrides nested, ModelBaker baker, IGeometryBakingContext owner, DynamicFluidContainerModel parent)
|
||||
{
|
||||
private ContainedFluidOverrideHandler(BakedOverrides nested, ModelBaker baker, IGeometryBakingContext owner, DynamicFluidContainerModel parent) {
|
||||
this.nested = nested;
|
||||
this.baker = baker;
|
||||
this.owner = owner;
|
||||
@@ -209,35 +196,32 @@ public class DynamicFluidContainerModel implements IUnbakedGeometry<DynamicFluid
|
||||
}
|
||||
|
||||
@Override
|
||||
public BakedModel resolve(BakedModel originalModel, ItemStack stack, @Nullable ClientLevel level, @Nullable LivingEntity entity, int seed)
|
||||
{
|
||||
BakedModel overridden = nested.resolve(originalModel, stack, level, entity, seed);
|
||||
if (overridden != originalModel) return overridden;
|
||||
return FluidUtil.getFluidContained(stack)
|
||||
.map(fluidStack -> {
|
||||
Fluid fluid = fluidStack.getFluid();
|
||||
String name = ForgeRegistries.FLUIDS.getKey(fluid).toString();
|
||||
public BakedModel findOverride(ItemStack stack, @Nullable ClientLevel level, @Nullable LivingEntity entity, int seed) {
|
||||
BakedModel overridden = nested.findOverride(stack, level, entity, seed);
|
||||
if (overridden != null)
|
||||
return overridden;
|
||||
|
||||
if (!cache.containsKey(name))
|
||||
{
|
||||
DynamicFluidContainerModel unbaked = this.parent.withFluid(fluid);
|
||||
BakedModel bakedModel = unbaked.bake(owner, baker, Material::sprite, BlockModelRotation.X0_Y0, originalModel.getOverrides());
|
||||
cache.put(name, bakedModel);
|
||||
return bakedModel;
|
||||
}
|
||||
var fluidStack = FluidUtil.getFluidContained(stack).orElse(null);
|
||||
if (fluidStack == null)
|
||||
return null;
|
||||
|
||||
return cache.get(name);
|
||||
})
|
||||
// not a fluid item apparently
|
||||
.orElse(originalModel); // empty bucket
|
||||
Fluid fluid = fluidStack.getFluid();
|
||||
String name = ForgeRegistries.FLUIDS.getKey(fluid).toString();
|
||||
|
||||
if (!cache.containsKey(name)) {
|
||||
DynamicFluidContainerModel unbaked = this.parent.withFluid(fluid);
|
||||
BakedModel bakedModel = unbaked.bake(owner, baker, Material::sprite, BlockModelRotation.X0_Y0);//, nested);
|
||||
cache.put(name, bakedModel);
|
||||
return bakedModel;
|
||||
}
|
||||
|
||||
return cache.get(name);
|
||||
}
|
||||
}
|
||||
|
||||
public static class Colors implements ItemColor
|
||||
{
|
||||
public static class Colors implements ItemColor {
|
||||
@Override
|
||||
public int getColor(@NotNull ItemStack stack, int tintIndex)
|
||||
{
|
||||
public int getColor(@NotNull ItemStack stack, int tintIndex) {
|
||||
if (tintIndex != 1) return 0xFFFFFFFF;
|
||||
return FluidUtil.getFluidContained(stack)
|
||||
.map(fluidStack -> IClientFluidTypeExtensions.of(fluidStack.getFluid()).getTintColor(fluidStack))
|
||||
|
||||
@@ -5,24 +5,18 @@
|
||||
|
||||
package net.minecraftforge.client.model;
|
||||
|
||||
import com.mojang.datafixers.util.Pair;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import net.minecraft.client.renderer.block.model.ItemOverrides;
|
||||
import net.minecraft.client.renderer.block.model.ItemTransforms;
|
||||
import net.minecraft.client.renderer.texture.MissingTextureAtlasSprite;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlas;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.resources.model.BakedModel;
|
||||
import net.minecraft.client.resources.model.Material;
|
||||
import net.minecraft.client.resources.model.ModelBaker;
|
||||
import net.minecraft.client.resources.model.ModelState;
|
||||
import net.minecraft.client.resources.model.SimpleBakedModel;
|
||||
import net.minecraft.client.resources.model.UnbakedModel;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.inventory.InventoryMenu;
|
||||
import net.minecraftforge.client.RenderTypeGroup;
|
||||
import net.minecraftforge.client.model.geometry.IGeometryBakingContext;
|
||||
import net.minecraftforge.client.model.geometry.IGeometryLoader;
|
||||
@@ -35,40 +29,32 @@ import net.minecraftforge.client.textures.UnitTextureAtlasSprite;
|
||||
* <p>
|
||||
* You can access it as a {@link BakedModel}, an {@link IUnbakedGeometry} or an {@link IGeometryLoader}.
|
||||
*/
|
||||
public class EmptyModel extends SimpleUnbakedGeometry<EmptyModel>
|
||||
{
|
||||
public class EmptyModel extends SimpleUnbakedGeometry<EmptyModel> {
|
||||
public static final BakedModel BAKED = new Baked();
|
||||
public static final EmptyModel INSTANCE = new EmptyModel();
|
||||
public static final IGeometryLoader<EmptyModel> LOADER = (json, ctx) -> INSTANCE;
|
||||
|
||||
private EmptyModel()
|
||||
{
|
||||
}
|
||||
private EmptyModel() { }
|
||||
|
||||
@Override
|
||||
protected void addQuads(IGeometryBakingContext owner, IModelBuilder<?> modelBuilder, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelTransform)
|
||||
{
|
||||
protected void addQuads(IGeometryBakingContext owner, IModelBuilder<?> modelBuilder, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelTransform) {
|
||||
// NO-OP
|
||||
}
|
||||
|
||||
@Override
|
||||
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, ItemOverrides overrides)
|
||||
{
|
||||
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState) {
|
||||
return BAKED;
|
||||
}
|
||||
|
||||
private static class Baked extends SimpleBakedModel
|
||||
{
|
||||
private static final Material MISSING_TEXTURE = new Material(TextureAtlas.LOCATION_BLOCKS, MissingTextureAtlasSprite.getLocation());
|
||||
private static class Baked extends SimpleBakedModel {
|
||||
private static final Material MISSING_TEXTURE = new Material(InventoryMenu.BLOCK_ATLAS, MissingTextureAtlasSprite.getLocation());
|
||||
|
||||
public Baked()
|
||||
{
|
||||
super(List.of(), Map.of(), false, false, false, UnitTextureAtlasSprite.INSTANCE, ItemTransforms.NO_TRANSFORMS, ItemOverrides.EMPTY, RenderTypeGroup.EMPTY);
|
||||
public Baked() {
|
||||
super(List.of(), Map.of(), false, false, false, UnitTextureAtlasSprite.INSTANCE, ItemTransforms.NO_TRANSFORMS, RenderTypeGroup.EMPTY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TextureAtlasSprite getParticleIcon()
|
||||
{
|
||||
public TextureAtlasSprite getParticleIcon() {
|
||||
return MISSING_TEXTURE.sprite();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.client.model;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import net.minecraft.client.renderer.ItemModelShaper;
|
||||
import net.minecraft.client.resources.model.BakedModel;
|
||||
import net.minecraft.client.resources.model.ModelBakery;
|
||||
import net.minecraft.client.resources.model.ModelManager;
|
||||
import net.minecraft.client.resources.model.ModelResourceLocation;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Wrapper around {@link ItemModelShaper} that cleans up the internal maps to respect ID remapping.
|
||||
*/
|
||||
public class ForgeItemModelShaper extends ItemModelShaper {
|
||||
private final Map<Holder.Reference<Item>, ModelResourceLocation> locations = Maps.newHashMap();
|
||||
private final Map<Holder.Reference<Item>, BakedModel> models = Maps.newHashMap();
|
||||
|
||||
public ForgeItemModelShaper(ModelManager manager) {
|
||||
super(manager);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public BakedModel getItemModel(Item item) {
|
||||
return models.get(ForgeRegistries.ITEMS.getDelegateOrThrow(item));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void register(Item item, ModelResourceLocation location) {
|
||||
Holder.Reference<Item> key = ForgeRegistries.ITEMS.getDelegateOrThrow(item);
|
||||
locations.put(key, location);
|
||||
models.put(key, getModelManager().getModel(location));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void rebuildCache() {
|
||||
final ModelManager manager = this.getModelManager();
|
||||
for (Map.Entry<Holder.Reference<Item>, ModelResourceLocation> e : locations.entrySet()) {
|
||||
models.put(e.getKey(), manager.getModel(e.getValue()));
|
||||
}
|
||||
}
|
||||
|
||||
public ModelResourceLocation getLocation(@NotNull ItemStack stack) {
|
||||
ModelResourceLocation location = locations.get(ForgeRegistries.ITEMS.getDelegateOrThrow(stack.getItem()));
|
||||
return location == null ? ModelBakery.MISSING_MODEL_VARIANT : location;
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@
|
||||
package net.minecraftforge.client.model;
|
||||
|
||||
import net.minecraft.client.renderer.block.model.BakedQuad;
|
||||
import net.minecraft.client.renderer.block.model.ItemOverrides;
|
||||
import net.minecraft.client.renderer.block.model.ItemTransforms;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.resources.model.BakedModel;
|
||||
@@ -22,24 +21,22 @@ import java.util.List;
|
||||
* Provides a generic base implementation via {@link #of(boolean, boolean, boolean, ItemTransforms, ItemOverrides, TextureAtlasSprite, RenderTypeGroup)}
|
||||
* and a quad-collecting alternative via {@link #collecting(List)}.
|
||||
*/
|
||||
public interface IModelBuilder<T extends IModelBuilder<T>>
|
||||
{
|
||||
public interface IModelBuilder<T extends IModelBuilder<T>> {
|
||||
/**
|
||||
* Creates a new model builder that uses the provided attributes in the final baked model.
|
||||
*/
|
||||
static IModelBuilder<?> of(boolean hasAmbientOcclusion, boolean usesBlockLight, boolean isGui3d,
|
||||
ItemTransforms transforms, ItemOverrides overrides, TextureAtlasSprite particle,
|
||||
RenderTypeGroup renderTypes)
|
||||
{
|
||||
return new Simple(hasAmbientOcclusion, usesBlockLight, isGui3d, transforms, overrides, particle, renderTypes);
|
||||
ItemTransforms transforms, TextureAtlasSprite particle,
|
||||
RenderTypeGroup renderTypes
|
||||
){
|
||||
return new Simple(hasAmbientOcclusion, usesBlockLight, isGui3d, transforms, particle, renderTypes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new model builder that collects quads to the provided list, returning
|
||||
* {@linkplain EmptyModel#BAKED an empty model} if you call {@link #build()}.
|
||||
*/
|
||||
static IModelBuilder<?> collecting(List<BakedQuad> quads)
|
||||
{
|
||||
static IModelBuilder<?> collecting(List<BakedQuad> quads) {
|
||||
return new Collecting(quads);
|
||||
}
|
||||
|
||||
@@ -49,69 +46,58 @@ public interface IModelBuilder<T extends IModelBuilder<T>>
|
||||
|
||||
BakedModel build();
|
||||
|
||||
class Simple implements IModelBuilder<Simple>
|
||||
{
|
||||
class Simple implements IModelBuilder<Simple> {
|
||||
private final SimpleBakedModel.Builder builder;
|
||||
private final RenderTypeGroup renderTypes;
|
||||
|
||||
private Simple(boolean hasAmbientOcclusion, boolean usesBlockLight, boolean isGui3d,
|
||||
ItemTransforms transforms, ItemOverrides overrides, TextureAtlasSprite particle,
|
||||
RenderTypeGroup renderTypes)
|
||||
{
|
||||
this.builder = new SimpleBakedModel.Builder(hasAmbientOcclusion, usesBlockLight, isGui3d, transforms, overrides).particle(particle);
|
||||
ItemTransforms transforms, TextureAtlasSprite particle, RenderTypeGroup renderTypes
|
||||
) {
|
||||
this.builder = new SimpleBakedModel.Builder(hasAmbientOcclusion, usesBlockLight, isGui3d, transforms).particle(particle);
|
||||
this.renderTypes = renderTypes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Simple addCulledFace(Direction facing, BakedQuad quad)
|
||||
{
|
||||
public Simple addCulledFace(Direction facing, BakedQuad quad) {
|
||||
builder.addCulledFace(facing, quad);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Simple addUnculledFace(BakedQuad quad)
|
||||
{
|
||||
public Simple addUnculledFace(BakedQuad quad) {
|
||||
builder.addUnculledFace(quad);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@Override
|
||||
public BakedModel build()
|
||||
{
|
||||
public BakedModel build() {
|
||||
return builder.renderTypes(renderTypes).build();
|
||||
}
|
||||
}
|
||||
|
||||
class Collecting implements IModelBuilder<Collecting>
|
||||
{
|
||||
class Collecting implements IModelBuilder<Collecting> {
|
||||
private final List<BakedQuad> quads;
|
||||
|
||||
private Collecting(List<BakedQuad> quads)
|
||||
{
|
||||
private Collecting(List<BakedQuad> quads) {
|
||||
this.quads = quads;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collecting addCulledFace(Direction facing, BakedQuad quad)
|
||||
{
|
||||
public Collecting addCulledFace(Direction facing, BakedQuad quad) {
|
||||
quads.add(quad);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collecting addUnculledFace(BakedQuad quad)
|
||||
{
|
||||
public Collecting addUnculledFace(BakedQuad quad) {
|
||||
quads.add(quad);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BakedModel build()
|
||||
{
|
||||
public BakedModel build() {
|
||||
return EmptyModel.BAKED;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ public interface IQuadTransformer {
|
||||
|
||||
private static BakedQuad copy(BakedQuad quad) {
|
||||
var vertices = quad.getVertices();
|
||||
return new BakedQuad(Arrays.copyOf(vertices, vertices.length), quad.getTintIndex(), quad.getDirection(), quad.getSprite(), quad.isShade(), quad.hasAmbientOcclusion());
|
||||
return new BakedQuad(Arrays.copyOf(vertices, vertices.length), quad.getTintIndex(), quad.getDirection(), quad.getSprite(), quad.isShade(), quad.getLightEmission(), quad.hasAmbientOcclusion());
|
||||
}
|
||||
|
||||
private static int findOffset(VertexFormatElement element) {
|
||||
|
||||
@@ -7,14 +7,12 @@ package net.minecraftforge.client.model;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.gson.JsonDeserializationContext;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParseException;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.renderer.block.model.ItemModelGenerator;
|
||||
import net.minecraft.client.renderer.block.model.ItemOverrides;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.resources.model.BakedModel;
|
||||
import net.minecraft.client.resources.model.Material;
|
||||
@@ -29,7 +27,6 @@ import net.minecraftforge.client.model.geometry.IUnbakedGeometry;
|
||||
import net.minecraftforge.client.model.geometry.UnbakedGeometryHelper;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
@@ -38,43 +35,36 @@ import java.util.function.Function;
|
||||
* - Not limited to an arbitrary number of layers (5)
|
||||
* - Support for per-layer render types
|
||||
*/
|
||||
public class ItemLayerModel implements IUnbakedGeometry<ItemLayerModel>
|
||||
{
|
||||
public class ItemLayerModel implements IUnbakedGeometry<ItemLayerModel> {
|
||||
@Nullable
|
||||
private ImmutableList<Material> textures;
|
||||
private final Int2ObjectMap<ResourceLocation> renderTypeNames;
|
||||
|
||||
private ItemLayerModel(@Nullable ImmutableList<Material> textures, Int2ObjectMap<ResourceLocation> renderTypeNames)
|
||||
{
|
||||
private ItemLayerModel(@Nullable ImmutableList<Material> textures, Int2ObjectMap<ResourceLocation> renderTypeNames) {
|
||||
this.textures = textures;
|
||||
this.renderTypeNames = renderTypeNames;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, ItemOverrides overrides)
|
||||
{
|
||||
if (textures == null)
|
||||
{
|
||||
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState) {
|
||||
if (textures == null) {
|
||||
ImmutableList.Builder<Material> builder = ImmutableList.builder();
|
||||
for (int i = 0; context.hasMaterial("layer" + i); i++)
|
||||
{
|
||||
builder.add(context.getMaterial("layer" + i));
|
||||
}
|
||||
textures = builder.build();
|
||||
}
|
||||
|
||||
TextureAtlasSprite particle = spriteGetter.apply(
|
||||
context.hasMaterial("particle") ? context.getMaterial("particle") : textures.get(0)
|
||||
context.hasMaterial("particle") ? context.getMaterial("particle") : textures.get(0)
|
||||
);
|
||||
var rootTransform = context.getRootTransform();
|
||||
if (!rootTransform.isIdentity())
|
||||
modelState = UnbakedGeometryHelper.composeRootTransformIntoModelState(modelState, rootTransform);
|
||||
|
||||
var normalRenderTypes = new RenderTypeGroup(RenderType.translucent(), ForgeRenderTypes.ITEM_UNSORTED_TRANSLUCENT.get());
|
||||
CompositeModel.Baked.Builder builder = CompositeModel.Baked.builder(context, particle, overrides, context.getTransforms());
|
||||
for (int i = 0; i < textures.size(); i++)
|
||||
{
|
||||
TextureAtlasSprite sprite = spriteGetter.apply(textures.get(i));
|
||||
var builder = CompositeModel.Baked.builder(context, particle, context.getTransforms());
|
||||
for (int i = 0; i < textures.size(); i++) {
|
||||
var sprite = spriteGetter.apply(textures.get(i));
|
||||
var unbaked = UnbakedGeometryHelper.createUnbakedItemElements(i, sprite.contents());
|
||||
var quads = UnbakedGeometryHelper.bakeElements(unbaked, $ -> sprite, modelState);
|
||||
var renderTypeName = renderTypeNames.get(i);
|
||||
@@ -85,19 +75,15 @@ public class ItemLayerModel implements IUnbakedGeometry<ItemLayerModel>
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
public static final class Loader implements IGeometryLoader<ItemLayerModel>
|
||||
{
|
||||
public static final class Loader implements IGeometryLoader<ItemLayerModel> {
|
||||
public static final Loader INSTANCE = new Loader();
|
||||
|
||||
@Override
|
||||
public ItemLayerModel read(JsonObject jsonObject, JsonDeserializationContext deserializationContext)
|
||||
{
|
||||
public ItemLayerModel read(JsonObject jsonObject, JsonDeserializationContext deserializationContext) {
|
||||
var renderTypeNames = new Int2ObjectOpenHashMap<ResourceLocation>();
|
||||
if (jsonObject.has("render_types"))
|
||||
{
|
||||
if (jsonObject.has("render_types")) {
|
||||
var renderTypes = jsonObject.getAsJsonObject("render_types");
|
||||
for (Map.Entry<String, JsonElement> entry : renderTypes.entrySet())
|
||||
{
|
||||
for (var entry : renderTypes.entrySet()) {
|
||||
var renderType = ResourceLocation.parse(entry.getKey());
|
||||
for (var layer : entry.getValue().getAsJsonArray())
|
||||
if (renderTypeNames.put(layer.getAsInt(), renderType) != null)
|
||||
@@ -108,15 +94,12 @@ public class ItemLayerModel implements IUnbakedGeometry<ItemLayerModel>
|
||||
return new ItemLayerModel(null, renderTypeNames);
|
||||
}
|
||||
|
||||
protected void readLayerData(JsonObject jsonObject, String name, Int2ObjectOpenHashMap<ResourceLocation> renderTypeNames, Int2ObjectMap<ForgeFaceData> layerData, boolean logWarning)
|
||||
{
|
||||
protected void readLayerData(JsonObject jsonObject, String name, Int2ObjectOpenHashMap<ResourceLocation> renderTypeNames, Int2ObjectMap<ForgeFaceData> layerData, boolean logWarning) {
|
||||
if (!jsonObject.has(name))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var fullbrightLayers = jsonObject.getAsJsonObject(name);
|
||||
for (var entry : fullbrightLayers.entrySet())
|
||||
{
|
||||
for (var entry : fullbrightLayers.entrySet()) {
|
||||
int layer = Integer.parseInt(entry.getKey());
|
||||
var data = ForgeFaceData.read(entry.getValue(), ForgeFaceData.DEFAULT);
|
||||
layerData.put(layer, data);
|
||||
|
||||
@@ -17,7 +17,6 @@ import java.util.function.Function;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.renderer.block.model.BakedQuad;
|
||||
import net.minecraft.client.renderer.block.model.BlockModel;
|
||||
import net.minecraft.client.renderer.block.model.ItemOverrides;
|
||||
import net.minecraft.client.renderer.block.model.ItemTransforms;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.resources.model.BakedModel;
|
||||
@@ -26,7 +25,6 @@ import net.minecraft.client.resources.model.ModelBaker;
|
||||
import net.minecraft.client.resources.model.ModelState;
|
||||
import net.minecraft.client.resources.model.UnbakedModel;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.util.GsonHelper;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.item.ItemDisplayContext;
|
||||
@@ -42,112 +40,91 @@ import org.jetbrains.annotations.Nullable;
|
||||
/**
|
||||
* A model composed of multiple sub-models which are picked based on the {@link ItemDisplayContext} being used.
|
||||
*/
|
||||
public class SeparateTransformsModel implements IUnbakedGeometry<SeparateTransformsModel>
|
||||
{
|
||||
public class SeparateTransformsModel implements IUnbakedGeometry<SeparateTransformsModel> {
|
||||
private final BlockModel baseModel;
|
||||
private final ImmutableMap<ItemDisplayContext, BlockModel> perspectives;
|
||||
|
||||
public SeparateTransformsModel(BlockModel baseModel, ImmutableMap<ItemDisplayContext, BlockModel> perspectives)
|
||||
{
|
||||
public SeparateTransformsModel(BlockModel baseModel, ImmutableMap<ItemDisplayContext, BlockModel> perspectives) {
|
||||
this.baseModel = baseModel;
|
||||
this.perspectives = perspectives;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, ItemOverrides overrides)
|
||||
{
|
||||
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState) {
|
||||
return new Baked(
|
||||
context.useAmbientOcclusion(), context.isGui3d(), context.useBlockLight(),
|
||||
spriteGetter.apply(context.getMaterial("particle")), overrides,
|
||||
baseModel.bake(baker, baseModel, spriteGetter, modelState, context.useBlockLight()),
|
||||
ImmutableMap.copyOf(Maps.transformValues(perspectives, value -> {
|
||||
return value.bake(baker, value, spriteGetter, modelState, context.useBlockLight());
|
||||
}))
|
||||
context.useAmbientOcclusion(),
|
||||
context.isGui3d(),
|
||||
context.useBlockLight(),
|
||||
spriteGetter.apply(context.getMaterial("particle")),
|
||||
baseModel.bake(spriteGetter, modelState, context.useBlockLight()),
|
||||
ImmutableMap.copyOf(Maps.transformValues(perspectives, value -> {
|
||||
return value.bake(spriteGetter, modelState, context.useBlockLight());
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resolveParents(Function<ResourceLocation, UnbakedModel> modelGetter, IGeometryBakingContext context)
|
||||
{
|
||||
baseModel.resolveParents(modelGetter);
|
||||
perspectives.values().forEach(model -> model.resolveParents(modelGetter));
|
||||
public void resolveDependencies(UnbakedModel.Resolver resolver, IGeometryBakingContext context) {
|
||||
baseModel.resolveDependencies(resolver);
|
||||
perspectives.values().forEach(model -> model.resolveDependencies(resolver));
|
||||
}
|
||||
|
||||
public static class Baked implements IDynamicBakedModel
|
||||
{
|
||||
public static class Baked implements IDynamicBakedModel {
|
||||
private final boolean isAmbientOcclusion;
|
||||
private final boolean isGui3d;
|
||||
private final boolean isSideLit;
|
||||
private final TextureAtlasSprite particle;
|
||||
private final ItemOverrides overrides;
|
||||
private final BakedModel baseModel;
|
||||
private final ImmutableMap<ItemDisplayContext, BakedModel> perspectives;
|
||||
|
||||
public Baked(boolean isAmbientOcclusion, boolean isGui3d, boolean isSideLit, TextureAtlasSprite particle, ItemOverrides overrides, BakedModel baseModel, ImmutableMap<ItemDisplayContext, BakedModel> perspectives)
|
||||
{
|
||||
public Baked(boolean isAmbientOcclusion, boolean isGui3d, boolean isSideLit, TextureAtlasSprite particle, BakedModel baseModel, ImmutableMap<ItemDisplayContext, BakedModel> perspectives) {
|
||||
this.isAmbientOcclusion = isAmbientOcclusion;
|
||||
this.isGui3d = isGui3d;
|
||||
this.isSideLit = isSideLit;
|
||||
this.particle = particle;
|
||||
this.overrides = overrides;
|
||||
this.baseModel = baseModel;
|
||||
this.perspectives = perspectives;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData data, @Nullable RenderType renderType)
|
||||
{
|
||||
public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData data, @Nullable RenderType renderType) {
|
||||
return baseModel.getQuads(state, side, rand, data, renderType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean useAmbientOcclusion()
|
||||
{
|
||||
public boolean useAmbientOcclusion() {
|
||||
return isAmbientOcclusion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isGui3d()
|
||||
{
|
||||
public boolean isGui3d() {
|
||||
return isGui3d;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean usesBlockLight()
|
||||
{
|
||||
public boolean usesBlockLight() {
|
||||
return isSideLit;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCustomRenderer()
|
||||
{
|
||||
public boolean isCustomRenderer() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TextureAtlasSprite getParticleIcon()
|
||||
{
|
||||
public TextureAtlasSprite getParticleIcon() {
|
||||
return particle;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemOverrides getOverrides()
|
||||
{
|
||||
return overrides;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemTransforms getTransforms()
|
||||
{
|
||||
public ItemTransforms getTransforms() {
|
||||
return ItemTransforms.NO_TRANSFORMS;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BakedModel applyTransform(ItemDisplayContext cameraTransformType, PoseStack poseStack, boolean applyLeftHandTransform)
|
||||
{
|
||||
if (perspectives.containsKey(cameraTransformType))
|
||||
{
|
||||
public BakedModel applyTransform(ItemDisplayContext cameraTransformType, PoseStack poseStack, boolean applyLeftHandTransform) {
|
||||
if (perspectives.containsKey(cameraTransformType)) {
|
||||
BakedModel p = perspectives.get(cameraTransformType);
|
||||
return p.applyTransform(cameraTransformType, poseStack, applyLeftHandTransform);
|
||||
}
|
||||
@@ -155,32 +132,25 @@ public class SeparateTransformsModel implements IUnbakedGeometry<SeparateTransfo
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data)
|
||||
{
|
||||
public ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data) {
|
||||
return baseModel.getRenderTypes(state, rand, data);
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Loader implements IGeometryLoader<SeparateTransformsModel>
|
||||
{
|
||||
public static final class Loader implements IGeometryLoader<SeparateTransformsModel> {
|
||||
public static final Loader INSTANCE = new Loader();
|
||||
|
||||
private Loader()
|
||||
{
|
||||
}
|
||||
private Loader() { }
|
||||
|
||||
@Override
|
||||
public SeparateTransformsModel read(JsonObject jsonObject, JsonDeserializationContext deserializationContext)
|
||||
{
|
||||
public SeparateTransformsModel read(JsonObject jsonObject, JsonDeserializationContext deserializationContext) {
|
||||
BlockModel baseModel = deserializationContext.deserialize(GsonHelper.getAsJsonObject(jsonObject, "base"), BlockModel.class);
|
||||
|
||||
JsonObject perspectiveData = GsonHelper.getAsJsonObject(jsonObject, "perspectives");
|
||||
|
||||
Map<ItemDisplayContext, BlockModel> perspectives = new HashMap<>();
|
||||
for (ItemDisplayContext transform : ItemDisplayContext.values())
|
||||
{
|
||||
if (perspectiveData.has(transform.getSerializedName()))
|
||||
{
|
||||
for (ItemDisplayContext transform : ItemDisplayContext.values()) {
|
||||
if (perspectiveData.has(transform.getSerializedName())) {
|
||||
BlockModel perspectiveModel = deserializationContext.deserialize(GsonHelper.getAsJsonObject(perspectiveData, transform.getSerializedName()), BlockModel.class);
|
||||
perspectives.put(transform, perspectiveModel);
|
||||
}
|
||||
|
||||
@@ -33,19 +33,16 @@ import java.util.Set;
|
||||
* @see BakedModel#getQuads(BlockState, Direction, RandomSource, ModelData, RenderType)
|
||||
* @see BakedModel#getModelData(BlockAndTintGetter, BlockPos, BlockState, ModelData)
|
||||
*/
|
||||
public final class ModelData
|
||||
{
|
||||
public final class ModelData {
|
||||
public static final ModelData EMPTY = ModelData.builder().build();
|
||||
|
||||
private final Map<ModelProperty<?>, Object> properties;
|
||||
|
||||
private ModelData(Map<ModelProperty<?>, Object> properties)
|
||||
{
|
||||
private ModelData(Map<ModelProperty<?>, Object> properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public Set<ModelProperty<?>> getProperties()
|
||||
{
|
||||
public Set<ModelProperty<?>> getProperties() {
|
||||
return properties.keySet();
|
||||
}
|
||||
|
||||
@@ -54,45 +51,37 @@ public final class ModelData
|
||||
return properties.containsKey(property);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Nullable
|
||||
public <T> T get(ModelProperty<T> property)
|
||||
{
|
||||
return (T) properties.get(property);
|
||||
public <T> T get(ModelProperty<T> property) {
|
||||
return (T)properties.get(property);
|
||||
}
|
||||
|
||||
public Builder derive()
|
||||
{
|
||||
public Builder derive() {
|
||||
return new Builder(this);
|
||||
}
|
||||
|
||||
public static Builder builder()
|
||||
{
|
||||
public static Builder builder() {
|
||||
return new Builder(null);
|
||||
}
|
||||
|
||||
public static final class Builder
|
||||
{
|
||||
public static final class Builder {
|
||||
private final Map<ModelProperty<?>, Object> properties = new IdentityHashMap<>();
|
||||
|
||||
private Builder(@Nullable ModelData parent)
|
||||
{
|
||||
private Builder(@Nullable ModelData parent) {
|
||||
if (parent != null)
|
||||
{
|
||||
properties.putAll(parent.properties);
|
||||
}
|
||||
}
|
||||
|
||||
@Contract("_, _ -> this")
|
||||
public <T> Builder with(ModelProperty<T> property, T value)
|
||||
{
|
||||
public <T> Builder with(ModelProperty<T> property, T value) {
|
||||
Preconditions.checkState(property.test(value), "The provided value is invalid for this property.");
|
||||
properties.put(property, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Contract("-> new")
|
||||
public ModelData build()
|
||||
{
|
||||
public ModelData build() {
|
||||
return new ModelData(Collections.unmodifiableMap(properties));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,6 +67,11 @@ public class ModelDataManager {
|
||||
return getAt(new ChunkPos(pos)).get(pos);
|
||||
}
|
||||
|
||||
public ModelData getAtOrEmpty(BlockPos pos) {
|
||||
var ret = getAt(pos);
|
||||
return ret == null ? ModelData.EMPTY : ret;
|
||||
}
|
||||
|
||||
public Map<BlockPos, ModelData> getAt(SectionPos pos) {
|
||||
return getAt(pos.chunk());
|
||||
}
|
||||
|
||||
@@ -380,6 +380,7 @@ public class ModelBuilder<T extends ModelBuilder<T>> extends ModelFile {
|
||||
private RotationBuilder rotation;
|
||||
private boolean shade = true;
|
||||
private ForgeFaceData data = ForgeFaceData.DEFAULT;
|
||||
private int emission = 0;
|
||||
|
||||
private void validateCoordinate(float coord, char name) {
|
||||
Preconditions.checkArgument(!(coord < -16.0F) && !(coord > 32.0F), "Position " + name + " out of range, must be within [-16, 32]. Found: %d", coord);
|
||||
@@ -559,14 +560,23 @@ public class ModelBuilder<T extends ModelBuilder<T>> extends ModelFile {
|
||||
return this;
|
||||
}
|
||||
|
||||
public ElementBuilder emission(int value) {
|
||||
this.emission = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
private BiConsumer<Direction, FaceBuilder> addTexture(String texture) {
|
||||
return ($, f) -> f.texture(texture);
|
||||
}
|
||||
|
||||
BlockElement build() {
|
||||
Map<Direction, BlockElementFace> faces = this.faces.entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().build(), (k1, k2) -> { throw new IllegalArgumentException(); }, LinkedHashMap::new));
|
||||
return new BlockElement(from, to, faces, rotation == null ? null : rotation.build(), shade);
|
||||
var faces = new LinkedHashMap<Direction, BlockElementFace>();
|
||||
for (var entry : this.faces.entrySet()) {
|
||||
if (faces.containsKey(entry.getKey()))
|
||||
throw new IllegalArgumentException("Multiple faces defined for Direction: " + entry.getKey().getName());
|
||||
faces.put(entry.getKey(), entry.getValue().build());
|
||||
}
|
||||
return new BlockElement(from, to, faces, rotation == null ? null : rotation.build(), shade, emission);
|
||||
}
|
||||
|
||||
public T end() { return self(); }
|
||||
|
||||
+28
-46
@@ -21,9 +21,7 @@ import com.google.gson.JsonObject;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.properties.Property;
|
||||
|
||||
public final class MultiPartBlockStateBuilder implements IGeneratedBlockState
|
||||
{
|
||||
|
||||
public final class MultiPartBlockStateBuilder implements IGeneratedBlockState {
|
||||
private final List<PartBuilder> parts = new ArrayList<>();
|
||||
private final Block owner;
|
||||
|
||||
@@ -35,7 +33,7 @@ public final class MultiPartBlockStateBuilder implements IGeneratedBlockState
|
||||
* Creates a builder for models to assign to a {@link PartBuilder}, which when
|
||||
* completed via {@link ConfiguredModel.Builder#addModel()} will assign the
|
||||
* resultant set of models to the part and return it for further processing.
|
||||
*
|
||||
*
|
||||
* @return the model builder
|
||||
* @see ConfiguredModel.Builder
|
||||
*/
|
||||
@@ -80,7 +78,7 @@ public final class MultiPartBlockStateBuilder implements IGeneratedBlockState
|
||||
/**
|
||||
* Set a condition for this part, which consists of a property and a set of
|
||||
* valid values. Can be called multiple times for multiple different properties.
|
||||
*
|
||||
*
|
||||
* @param <T> the type of the property value
|
||||
* @param prop the property
|
||||
* @param values a set of valid values
|
||||
@@ -109,8 +107,7 @@ public final class MultiPartBlockStateBuilder implements IGeneratedBlockState
|
||||
* Allows having nested groups of conditions if there are not any normal conditions.
|
||||
* @throws IllegalStateException if {@code !conditions.isEmpty()}
|
||||
*/
|
||||
public final ConditionGroup nestedGroup()
|
||||
{
|
||||
public final ConditionGroup nestedGroup() {
|
||||
Preconditions.checkState(conditions.isEmpty(), "Can't have nested condition groups if there are already normal conditions");
|
||||
ConditionGroup group = new ConditionGroup();
|
||||
this.nestedConditionGroups.add(group);
|
||||
@@ -123,9 +120,7 @@ public final class MultiPartBlockStateBuilder implements IGeneratedBlockState
|
||||
JsonObject out = new JsonObject();
|
||||
if (!conditions.isEmpty()) {
|
||||
out.add("when", MultiPartBlockStateBuilder.toJson(this.conditions, this.useOr));
|
||||
}
|
||||
else if (!nestedConditionGroups.isEmpty())
|
||||
{
|
||||
} else if (!nestedConditionGroups.isEmpty()) {
|
||||
out.add("when", MultiPartBlockStateBuilder.toJson(this.nestedConditionGroups, this.useOr));
|
||||
}
|
||||
out.add("apply", models.toJSON());
|
||||
@@ -136,8 +131,7 @@ public final class MultiPartBlockStateBuilder implements IGeneratedBlockState
|
||||
return b.getStateDefinition().getProperties().containsAll(conditions.keySet());
|
||||
}
|
||||
|
||||
public class ConditionGroup
|
||||
{
|
||||
public class ConditionGroup {
|
||||
public final Multimap<Property<?>, Comparable<?>> conditions = MultimapBuilder.linkedHashKeys().arrayListValues().build();
|
||||
public final List<ConditionGroup> nestedConditionGroups = new ArrayList<>();
|
||||
private ConditionGroup parent = null;
|
||||
@@ -160,8 +154,7 @@ public final class MultiPartBlockStateBuilder implements IGeneratedBlockState
|
||||
* @throws IllegalStateException if {@code !nestedConditionGroups.isEmpty()}
|
||||
*/
|
||||
@SafeVarargs
|
||||
public final <T extends Comparable<T>> ConditionGroup condition(Property<T> prop, T... values)
|
||||
{
|
||||
public final <T extends Comparable<T>> ConditionGroup condition(Property<T> prop, T... values) {
|
||||
Preconditions.checkNotNull(prop, "Property must not be null");
|
||||
Preconditions.checkNotNull(values, "Value list must not be null");
|
||||
Preconditions.checkArgument(values.length > 0, "Value list must not be empty");
|
||||
@@ -176,8 +169,7 @@ public final class MultiPartBlockStateBuilder implements IGeneratedBlockState
|
||||
* Allows having nested groups of conditions if there are not any normal conditions.
|
||||
* @throws IllegalStateException if {@code !conditions.isEmpty()}
|
||||
*/
|
||||
public ConditionGroup nestedGroup()
|
||||
{
|
||||
public ConditionGroup nestedGroup() {
|
||||
Preconditions.checkState(conditions.isEmpty(), "Can't have nested condition groups if there are already normal conditions");
|
||||
ConditionGroup group = new ConditionGroup();
|
||||
group.parent = this;
|
||||
@@ -187,23 +179,21 @@ public final class MultiPartBlockStateBuilder implements IGeneratedBlockState
|
||||
|
||||
/**
|
||||
* Ends this nested condition group and returns the parent condition group
|
||||
*
|
||||
*
|
||||
* @throws IllegalStateException If this is not a nested condition group
|
||||
*/
|
||||
public ConditionGroup endNestedGroup()
|
||||
{
|
||||
public ConditionGroup endNestedGroup() {
|
||||
if (parent == null)
|
||||
throw new IllegalStateException("This condition group is not nested, use end() instead");
|
||||
throw new IllegalStateException("This condition group is not nested, use end() instead");
|
||||
return parent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends this condition group and returns the part builder
|
||||
*
|
||||
*
|
||||
* @throws IllegalStateException If this is a nested condition group
|
||||
*/
|
||||
public MultiPartBlockStateBuilder.PartBuilder end()
|
||||
{
|
||||
public MultiPartBlockStateBuilder.PartBuilder end() {
|
||||
if (this.parent != null)
|
||||
throw new IllegalStateException("This is a nested condition group, use endNestedGroup() instead");
|
||||
return MultiPartBlockStateBuilder.PartBuilder.this;
|
||||
@@ -212,58 +202,45 @@ public final class MultiPartBlockStateBuilder implements IGeneratedBlockState
|
||||
/**
|
||||
* Makes this part get applied if any of the conditions/condition groups are true, instead of all of them needing to be true.
|
||||
*/
|
||||
public ConditionGroup useOr()
|
||||
{
|
||||
public ConditionGroup useOr() {
|
||||
this.useOr = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
JsonObject toJson()
|
||||
{
|
||||
JsonObject toJson() {
|
||||
if (!this.conditions.isEmpty())
|
||||
{
|
||||
return MultiPartBlockStateBuilder.toJson(this.conditions, this.useOr);
|
||||
}
|
||||
else if (!this.nestedConditionGroups.isEmpty())
|
||||
{
|
||||
return MultiPartBlockStateBuilder.toJson(this.nestedConditionGroups, this.useOr);
|
||||
}
|
||||
return new JsonObject();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonObject toJson(List<PartBuilder.ConditionGroup> conditions, boolean useOr)
|
||||
{
|
||||
private static JsonObject toJson(List<PartBuilder.ConditionGroup> conditions, boolean useOr) {
|
||||
JsonObject groupJson = new JsonObject();
|
||||
JsonArray innerGroupJson = new JsonArray();
|
||||
groupJson.add(useOr ? "OR" : "AND", innerGroupJson);
|
||||
for (PartBuilder.ConditionGroup group : conditions)
|
||||
{
|
||||
innerGroupJson.add(group.toJson());
|
||||
}
|
||||
return groupJson;
|
||||
}
|
||||
|
||||
private static JsonObject toJson(Multimap<Property<?>, Comparable<?>> conditions, boolean useOr)
|
||||
{
|
||||
private static JsonObject toJson(Multimap<Property<?>, Comparable<?>> conditions, boolean useOr) {
|
||||
JsonObject groupJson = new JsonObject();
|
||||
for (Entry<Property<?>, Collection<Comparable<?>>> e : conditions.asMap().entrySet())
|
||||
{
|
||||
for (Entry<Property<?>, Collection<Comparable<?>>> e : conditions.asMap().entrySet()) {
|
||||
StringBuilder activeString = new StringBuilder();
|
||||
for (Comparable<?> val : e.getValue())
|
||||
{
|
||||
for (Comparable<?> val : e.getValue()) {
|
||||
if (!activeString.isEmpty())
|
||||
activeString.append("|");
|
||||
activeString.append(((Property) e.getKey()).getName(val));
|
||||
activeString.append(getName(e.getKey(), val));
|
||||
}
|
||||
groupJson.addProperty(e.getKey().getName(), activeString.toString());
|
||||
}
|
||||
if (useOr)
|
||||
{
|
||||
|
||||
if (useOr) {
|
||||
JsonArray innerWhen = new JsonArray();
|
||||
for (Entry<String, JsonElement> entry : groupJson.entrySet())
|
||||
{
|
||||
for (Entry<String, JsonElement> entry : groupJson.entrySet()) {
|
||||
JsonObject obj = new JsonObject();
|
||||
obj.add(entry.getKey(), entry.getValue());
|
||||
innerWhen.add(obj);
|
||||
@@ -273,4 +250,9 @@ public final class MultiPartBlockStateBuilder implements IGeneratedBlockState
|
||||
}
|
||||
return groupJson;
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
private static <T> String getName(Property<?> key, Comparable<?> value) {
|
||||
return ((Property)key).getName((Comparable)value);
|
||||
}
|
||||
}
|
||||
+26
-57
@@ -5,23 +5,17 @@
|
||||
|
||||
package net.minecraftforge.client.model.geometry;
|
||||
|
||||
import com.mojang.datafixers.util.Pair;
|
||||
import com.mojang.math.Transformation;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import net.minecraft.client.renderer.block.model.BlockModel;
|
||||
import net.minecraft.client.renderer.block.model.ItemOverrides;
|
||||
import net.minecraft.client.renderer.block.model.ItemTransforms;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.resources.model.BakedModel;
|
||||
import net.minecraft.client.resources.model.Material;
|
||||
import net.minecraft.client.resources.model.ModelBaker;
|
||||
import net.minecraft.client.resources.model.ModelState;
|
||||
import net.minecraft.client.resources.model.UnbakedModel;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
@@ -31,8 +25,7 @@ import org.jetbrains.annotations.Nullable;
|
||||
* <p>
|
||||
* Users should not be instantiating this themselves.
|
||||
*/
|
||||
public class BlockGeometryBakingContext implements IGeometryBakingContext
|
||||
{
|
||||
public class BlockGeometryBakingContext implements IGeometryBakingContext {
|
||||
public final BlockModel owner;
|
||||
public final VisibilityData visibilityData = new VisibilityData();
|
||||
@Nullable
|
||||
@@ -44,111 +37,93 @@ public class BlockGeometryBakingContext implements IGeometryBakingContext
|
||||
private boolean gui3d = true;
|
||||
|
||||
@ApiStatus.Internal
|
||||
public BlockGeometryBakingContext(BlockModel owner)
|
||||
{
|
||||
public BlockGeometryBakingContext(BlockModel owner) {
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getModelName()
|
||||
{
|
||||
public String getModelName() {
|
||||
return owner.name;
|
||||
}
|
||||
|
||||
public boolean hasCustomGeometry()
|
||||
{
|
||||
public boolean hasCustomGeometry() {
|
||||
return getCustomGeometry() != null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public IUnbakedGeometry<?> getCustomGeometry()
|
||||
{
|
||||
public IUnbakedGeometry<?> getCustomGeometry() {
|
||||
return owner.parent != null && customGeometry == null ? owner.parent.customData.getCustomGeometry() : customGeometry;
|
||||
}
|
||||
|
||||
public void setCustomGeometry(IUnbakedGeometry<?> geometry)
|
||||
{
|
||||
public void setCustomGeometry(IUnbakedGeometry<?> geometry) {
|
||||
this.customGeometry = geometry;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isComponentVisible(String part, boolean fallback)
|
||||
{
|
||||
public boolean isComponentVisible(String part, boolean fallback) {
|
||||
return owner.parent != null && !visibilityData.hasCustomVisibility(part) ?
|
||||
owner.parent.customData.isComponentVisible(part, fallback) :
|
||||
visibilityData.isVisible(part, fallback);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasMaterial(String name)
|
||||
{
|
||||
public boolean hasMaterial(String name) {
|
||||
return owner.hasTexture(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Material getMaterial(String name)
|
||||
{
|
||||
public Material getMaterial(String name) {
|
||||
return owner.getMaterial(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isGui3d()
|
||||
{
|
||||
public boolean isGui3d() {
|
||||
return gui3d;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean useBlockLight()
|
||||
{
|
||||
public boolean useBlockLight() {
|
||||
return owner.getGuiLight().lightLikeBlock();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean useAmbientOcclusion()
|
||||
{
|
||||
public boolean useAmbientOcclusion() {
|
||||
return owner.hasAmbientOcclusion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemTransforms getTransforms()
|
||||
{
|
||||
public ItemTransforms getTransforms() {
|
||||
return owner.getTransforms();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Transformation getRootTransform()
|
||||
{
|
||||
public Transformation getRootTransform() {
|
||||
if (rootTransform != null)
|
||||
return rootTransform;
|
||||
return owner.parent != null ? owner.parent.customData.getRootTransform() : Transformation.identity();
|
||||
}
|
||||
|
||||
public void setRootTransform(Transformation rootTransform)
|
||||
{
|
||||
public void setRootTransform(Transformation rootTransform) {
|
||||
this.rootTransform = rootTransform;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public ResourceLocation getRenderTypeHint()
|
||||
{
|
||||
public ResourceLocation getRenderTypeHint() {
|
||||
if (renderTypeHint != null)
|
||||
return renderTypeHint;
|
||||
return owner.parent != null ? owner.parent.customData.getRenderTypeHint() : null;
|
||||
}
|
||||
|
||||
public void setRenderTypeHint(ResourceLocation renderTypeHint)
|
||||
{
|
||||
public void setRenderTypeHint(ResourceLocation renderTypeHint) {
|
||||
this.renderTypeHint = renderTypeHint;
|
||||
}
|
||||
|
||||
public void setGui3d(boolean gui3d)
|
||||
{
|
||||
public void setGui3d(boolean gui3d) {
|
||||
this.gui3d = gui3d;
|
||||
}
|
||||
|
||||
public void copyFrom(BlockGeometryBakingContext other)
|
||||
{
|
||||
public void copyFrom(BlockGeometryBakingContext other) {
|
||||
this.customGeometry = other.customGeometry;
|
||||
this.rootTransform = other.rootTransform;
|
||||
this.visibilityData.copyFrom(other.visibilityData);
|
||||
@@ -156,35 +131,29 @@ public class BlockGeometryBakingContext implements IGeometryBakingContext
|
||||
this.gui3d = other.gui3d;
|
||||
}
|
||||
|
||||
public BakedModel bake(ModelBaker baker, Function<Material, TextureAtlasSprite> bakedTextureGetter, ModelState modelTransform, ItemOverrides overrides)
|
||||
{
|
||||
public BakedModel bake(ModelBaker baker, Function<Material, TextureAtlasSprite> bakedTextureGetter, ModelState modelTransform) {
|
||||
IUnbakedGeometry<?> geometry = getCustomGeometry();
|
||||
if (geometry == null)
|
||||
throw new IllegalStateException("Can not use custom baking without custom geometry");
|
||||
return geometry.bake(this, baker, bakedTextureGetter, modelTransform, overrides);
|
||||
return geometry.bake(this, baker, bakedTextureGetter, modelTransform);
|
||||
}
|
||||
|
||||
public static class VisibilityData
|
||||
{
|
||||
public static class VisibilityData {
|
||||
private final Map<String, Boolean> data = new HashMap<>();
|
||||
|
||||
public boolean hasCustomVisibility(String part)
|
||||
{
|
||||
public boolean hasCustomVisibility(String part) {
|
||||
return data.containsKey(part);
|
||||
}
|
||||
|
||||
public boolean isVisible(String part, boolean fallback)
|
||||
{
|
||||
public boolean isVisible(String part, boolean fallback) {
|
||||
return data.getOrDefault(part, fallback);
|
||||
}
|
||||
|
||||
public void setVisibilityState(String partName, boolean type)
|
||||
{
|
||||
public void setVisibilityState(String partName, boolean type) {
|
||||
data.put(partName, type);
|
||||
}
|
||||
|
||||
public void copyFrom(VisibilityData visibilityData)
|
||||
{
|
||||
public void copyFrom(VisibilityData visibilityData) {
|
||||
data.clear();
|
||||
data.putAll(visibilityData.data);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ package net.minecraftforge.client.model.geometry;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraftforge.client.event.ModelEvent;
|
||||
import net.minecraftforge.client.model.ElementsModel;
|
||||
import net.minecraftforge.fml.ModLoader;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
@@ -21,8 +20,7 @@ import java.util.stream.Collectors;
|
||||
* <p>
|
||||
* Provides a lookup.
|
||||
*/
|
||||
public final class GeometryLoaderManager
|
||||
{
|
||||
public final class GeometryLoaderManager {
|
||||
private static ImmutableMap<ResourceLocation, IGeometryLoader<?>> LOADERS;
|
||||
private static String LOADER_LIST;
|
||||
|
||||
@@ -30,22 +28,19 @@ public final class GeometryLoaderManager
|
||||
* Finds the {@link IGeometryLoader} for a given name, or null if not found.
|
||||
*/
|
||||
@Nullable
|
||||
public static IGeometryLoader<?> get(ResourceLocation name)
|
||||
{
|
||||
public static IGeometryLoader<?> get(ResourceLocation name) {
|
||||
return LOADERS.get(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a comma-separated list of all active loaders, for use in error messages.
|
||||
*/
|
||||
public static String getLoaderList()
|
||||
{
|
||||
public static String getLoaderList() {
|
||||
return LOADER_LIST;
|
||||
}
|
||||
|
||||
@ApiStatus.Internal
|
||||
public static void init()
|
||||
{
|
||||
public static void init() {
|
||||
var loaders = new HashMap<ResourceLocation, IGeometryLoader<?>>();
|
||||
var event = new ModelEvent.RegisterGeometryLoaders(loaders);
|
||||
ModLoader.get().postEventWrapContainerInModOrder(event);
|
||||
@@ -53,7 +48,5 @@ public final class GeometryLoaderManager
|
||||
LOADER_LIST = loaders.keySet().stream().map(ResourceLocation::toString).collect(Collectors.joining(", "));
|
||||
}
|
||||
|
||||
private GeometryLoaderManager()
|
||||
{
|
||||
}
|
||||
private GeometryLoaderManager() { }
|
||||
}
|
||||
@@ -21,8 +21,7 @@ import org.jetbrains.annotations.Nullable;
|
||||
* @see StandaloneGeometryBakingContext
|
||||
* @see BlockGeometryBakingContext
|
||||
*/
|
||||
public interface IGeometryBakingContext
|
||||
{
|
||||
public interface IGeometryBakingContext {
|
||||
/**
|
||||
* {@return the name of the model being baked for logging and caching purposes.}
|
||||
*/
|
||||
@@ -87,8 +86,7 @@ public interface IGeometryBakingContext
|
||||
/**
|
||||
* {@return a {@link RenderTypeGroup} with the given name, or the empty group if not found.}
|
||||
*/
|
||||
default RenderTypeGroup getRenderType(ResourceLocation name)
|
||||
{
|
||||
default RenderTypeGroup getRenderType(ResourceLocation name) {
|
||||
return NamedRenderTypeManager.get(name);
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,6 @@ import net.minecraftforge.client.event.RegisterClientReloadListenersEvent;
|
||||
* @see RegisterGeometryLoaders
|
||||
* @see RegisterClientReloadListenersEvent
|
||||
*/
|
||||
public interface IGeometryLoader<T extends IUnbakedGeometry<T>>
|
||||
{
|
||||
public interface IGeometryLoader<T extends IUnbakedGeometry<T>> {
|
||||
T read(JsonObject jsonObject, JsonDeserializationContext deserializationContext) throws JsonParseException;
|
||||
}
|
||||
@@ -9,14 +9,12 @@ import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
|
||||
import net.minecraft.client.renderer.block.model.BlockModel;
|
||||
import net.minecraft.client.renderer.block.model.ItemOverrides;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.resources.model.BakedModel;
|
||||
import net.minecraft.client.resources.model.Material;
|
||||
import net.minecraft.client.resources.model.ModelBaker;
|
||||
import net.minecraft.client.resources.model.ModelState;
|
||||
import net.minecraft.client.resources.model.UnbakedModel;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
|
||||
/**
|
||||
* General interface for any model that can be baked, superset of vanilla {@link UnbakedModel}.
|
||||
@@ -27,14 +25,14 @@ import net.minecraft.resources.ResourceLocation;
|
||||
* @see IGeometryBakingContext
|
||||
*/
|
||||
public interface IUnbakedGeometry<T extends IUnbakedGeometry<T>> {
|
||||
BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, ItemOverrides overrides);
|
||||
BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState);
|
||||
|
||||
/**
|
||||
* Resolve parents of nested {@link BlockModel}s which are later used in
|
||||
* {@link IUnbakedGeometry#bake(IGeometryBakingContext, ModelBaker, Function, ModelState, ItemOverrides)}
|
||||
* {@link IUnbakedGeometry#bake(IGeometryBakingContext, ModelBaker, Function, ModelState)}
|
||||
* via {@link BlockModel#resolveParents(Function)}
|
||||
*/
|
||||
default void resolveParents(Function<ResourceLocation, UnbakedModel> modelGetter, IGeometryBakingContext context) { }
|
||||
default void resolveDependencies(UnbakedModel.Resolver resolver, IGeometryBakingContext context) { }
|
||||
|
||||
/**
|
||||
* {@return a set of all the components whose visibility may be configured via {@link IGeometryBakingContext}}
|
||||
|
||||
@@ -7,7 +7,6 @@ package net.minecraftforge.client.model.geometry;
|
||||
|
||||
import java.util.function.Function;
|
||||
import net.minecraft.client.renderer.block.model.BakedQuad;
|
||||
import net.minecraft.client.renderer.block.model.ItemOverrides;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.resources.model.BakedModel;
|
||||
import net.minecraft.client.resources.model.Material;
|
||||
@@ -21,17 +20,15 @@ import net.minecraftforge.client.model.IModelBuilder;
|
||||
* Base class for implementations of {@link IUnbakedGeometry} which do not wish to handle model creation themselves,
|
||||
* instead supplying {@linkplain BakedQuad baked quads} through a builder.
|
||||
*/
|
||||
public abstract class SimpleUnbakedGeometry<T extends SimpleUnbakedGeometry<T>> implements IUnbakedGeometry<T>
|
||||
{
|
||||
public abstract class SimpleUnbakedGeometry<T extends SimpleUnbakedGeometry<T>> implements IUnbakedGeometry<T> {
|
||||
@Override
|
||||
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, ItemOverrides overrides)
|
||||
{
|
||||
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState) {
|
||||
TextureAtlasSprite particle = spriteGetter.apply(context.getMaterial("particle"));
|
||||
|
||||
var renderTypeHint = context.getRenderTypeHint();
|
||||
var renderTypes = renderTypeHint != null ? context.getRenderType(renderTypeHint) : RenderTypeGroup.EMPTY;
|
||||
IModelBuilder<?> builder = IModelBuilder.of(context.useAmbientOcclusion(), context.useBlockLight(), context.isGui3d(),
|
||||
context.getTransforms(), overrides, particle, renderTypes);
|
||||
context.getTransforms(), particle, renderTypes);
|
||||
|
||||
addQuads(context, builder, baker, spriteGetter, modelState);
|
||||
|
||||
|
||||
+43
-71
@@ -10,9 +10,10 @@ import com.mojang.math.Transformation;
|
||||
import it.unimi.dsi.fastutil.objects.Object2BooleanMap;
|
||||
import net.minecraft.client.renderer.block.model.ItemTransforms;
|
||||
import net.minecraft.client.renderer.texture.MissingTextureAtlasSprite;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlas;
|
||||
import net.minecraft.client.resources.model.Material;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.inventory.InventoryMenu;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Map;
|
||||
@@ -23,24 +24,20 @@ import java.util.function.Predicate;
|
||||
/**
|
||||
* A {@linkplain IGeometryBakingContext geometry baking context} that is not bound to block/item model loading.
|
||||
*/
|
||||
public class StandaloneGeometryBakingContext implements IGeometryBakingContext
|
||||
{
|
||||
public class StandaloneGeometryBakingContext implements IGeometryBakingContext {
|
||||
public static final ResourceLocation LOCATION = ResourceLocation.fromNamespaceAndPath("forge", "standalone");
|
||||
|
||||
public static final StandaloneGeometryBakingContext INSTANCE = create(LOCATION);
|
||||
|
||||
public static StandaloneGeometryBakingContext create(ResourceLocation modelName)
|
||||
{
|
||||
public static StandaloneGeometryBakingContext create(ResourceLocation modelName) {
|
||||
return builder().build(modelName);
|
||||
}
|
||||
|
||||
public static StandaloneGeometryBakingContext create(Map<String, ResourceLocation> textures)
|
||||
{
|
||||
public static StandaloneGeometryBakingContext create(Map<String, ResourceLocation> textures) {
|
||||
return create(LOCATION, textures);
|
||||
}
|
||||
|
||||
public static StandaloneGeometryBakingContext create(ResourceLocation modelName, Map<String, ResourceLocation> textures)
|
||||
{
|
||||
public static StandaloneGeometryBakingContext create(ResourceLocation modelName, Map<String, ResourceLocation> textures) {
|
||||
return builder().withTextures(textures, MissingTextureAtlasSprite.getLocation()).build(modelName);
|
||||
}
|
||||
|
||||
@@ -56,13 +53,14 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext
|
||||
private final ResourceLocation renderTypeHint;
|
||||
private final BiPredicate<String, Boolean> visibilityTest;
|
||||
|
||||
private StandaloneGeometryBakingContext(ResourceLocation modelName, Predicate<String> materialCheck,
|
||||
Function<String, Material> materialLookup, boolean isGui3d,
|
||||
boolean useBlockLight, boolean useAmbientOcclusion,
|
||||
ItemTransforms transforms, Transformation rootTransform,
|
||||
@Nullable ResourceLocation renderTypeHint,
|
||||
BiPredicate<String, Boolean> visibilityTest)
|
||||
{
|
||||
private StandaloneGeometryBakingContext(
|
||||
ResourceLocation modelName, Predicate<String> materialCheck,
|
||||
Function<String, Material> materialLookup, boolean isGui3d,
|
||||
boolean useBlockLight, boolean useAmbientOcclusion,
|
||||
ItemTransforms transforms, Transformation rootTransform,
|
||||
@Nullable ResourceLocation renderTypeHint,
|
||||
BiPredicate<String, Boolean> visibilityTest
|
||||
) {
|
||||
this.modelName = modelName;
|
||||
this.materialCheck = materialCheck;
|
||||
this.materialLookup = materialLookup;
|
||||
@@ -76,79 +74,66 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getModelName()
|
||||
{
|
||||
public String getModelName() {
|
||||
return modelName.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasMaterial(String name)
|
||||
{
|
||||
public boolean hasMaterial(String name) {
|
||||
return materialCheck.test(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Material getMaterial(String name)
|
||||
{
|
||||
public Material getMaterial(String name) {
|
||||
return materialLookup.apply(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isGui3d()
|
||||
{
|
||||
public boolean isGui3d() {
|
||||
return isGui3d;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean useBlockLight()
|
||||
{
|
||||
public boolean useBlockLight() {
|
||||
return useBlockLight;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean useAmbientOcclusion()
|
||||
{
|
||||
public boolean useAmbientOcclusion() {
|
||||
return useAmbientOcclusion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemTransforms getTransforms()
|
||||
{
|
||||
public ItemTransforms getTransforms() {
|
||||
return transforms;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Transformation getRootTransform()
|
||||
{
|
||||
public Transformation getRootTransform() {
|
||||
return rootTransform;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public ResourceLocation getRenderTypeHint()
|
||||
{
|
||||
public ResourceLocation getRenderTypeHint() {
|
||||
return renderTypeHint;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isComponentVisible(String component, boolean fallback)
|
||||
{
|
||||
public boolean isComponentVisible(String component, boolean fallback) {
|
||||
return visibilityTest.test(component, fallback);
|
||||
}
|
||||
|
||||
public static Builder builder()
|
||||
{
|
||||
public static Builder builder() {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
public static Builder builder(IGeometryBakingContext parent)
|
||||
{
|
||||
public static Builder builder(IGeometryBakingContext parent) {
|
||||
return new Builder(parent);
|
||||
}
|
||||
|
||||
public static final class Builder
|
||||
{
|
||||
private static final Material NO_MATERIAL = new Material(TextureAtlas.LOCATION_BLOCKS, MissingTextureAtlasSprite.getLocation());
|
||||
public static final class Builder {
|
||||
private static final Material NO_MATERIAL = new Material(InventoryMenu.BLOCK_ATLAS, MissingTextureAtlasSprite.getLocation());
|
||||
private Predicate<String> materialCheck = Predicates.alwaysFalse();
|
||||
private Function<String, Material> materialLookup = $ -> NO_MATERIAL;
|
||||
private boolean isGui3d = true;
|
||||
@@ -160,12 +145,9 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext
|
||||
private ResourceLocation renderTypeHint;
|
||||
private BiPredicate<String, Boolean> visibilityTest = (c, def) -> def;
|
||||
|
||||
private Builder()
|
||||
{
|
||||
}
|
||||
private Builder() { }
|
||||
|
||||
private Builder(IGeometryBakingContext parent)
|
||||
{
|
||||
private Builder(IGeometryBakingContext parent) {
|
||||
this.materialCheck = parent::hasMaterial;
|
||||
this.materialLookup = parent::getMaterial;
|
||||
this.isGui3d = parent.isGui3d();
|
||||
@@ -177,69 +159,59 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext
|
||||
this.visibilityTest = parent::isComponentVisible;
|
||||
}
|
||||
|
||||
public Builder withTextures(Map<String, ResourceLocation> textures, ResourceLocation defaultTexture)
|
||||
{
|
||||
return withTextures(TextureAtlas.LOCATION_BLOCKS, textures, defaultTexture);
|
||||
public Builder withTextures(Map<String, ResourceLocation> textures, ResourceLocation defaultTexture) {
|
||||
return withTextures(InventoryMenu.BLOCK_ATLAS, textures, defaultTexture);
|
||||
}
|
||||
|
||||
public Builder withTextures(ResourceLocation atlasLocation, Map<String, ResourceLocation> textures, ResourceLocation defaultTexture)
|
||||
{
|
||||
public Builder withTextures(ResourceLocation atlasLocation, Map<String, ResourceLocation> textures, ResourceLocation defaultTexture) {
|
||||
this.materialCheck = textures::containsKey;
|
||||
this.materialLookup = name -> new Material(atlasLocation, textures.getOrDefault(name, defaultTexture));
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withMaterials(Map<String, Material> materials, Material defaultMaterial)
|
||||
{
|
||||
public Builder withMaterials(Map<String, Material> materials, Material defaultMaterial) {
|
||||
this.materialCheck = materials::containsKey;
|
||||
this.materialLookup = name -> materials.getOrDefault(name, defaultMaterial);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withGui3d(boolean isGui3d)
|
||||
{
|
||||
public Builder withGui3d(boolean isGui3d) {
|
||||
this.isGui3d = isGui3d;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withUseBlockLight(boolean useBlockLight)
|
||||
{
|
||||
public Builder withUseBlockLight(boolean useBlockLight) {
|
||||
this.useBlockLight = useBlockLight;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withUseAmbientOcclusion(boolean useAmbientOcclusion)
|
||||
{
|
||||
public Builder withUseAmbientOcclusion(boolean useAmbientOcclusion) {
|
||||
this.useAmbientOcclusion = useAmbientOcclusion;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withTransforms(ItemTransforms transforms)
|
||||
{
|
||||
public Builder withTransforms(ItemTransforms transforms) {
|
||||
this.transforms = transforms;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withRootTransform(Transformation rootTransform)
|
||||
{
|
||||
public Builder withRootTransform(Transformation rootTransform) {
|
||||
this.rootTransform = rootTransform;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withRenderTypeHint(ResourceLocation renderTypeHint)
|
||||
{
|
||||
public Builder withRenderTypeHint(ResourceLocation renderTypeHint) {
|
||||
this.renderTypeHint = renderTypeHint;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withVisibleComponents(Object2BooleanMap<String> parts)
|
||||
{
|
||||
@SuppressWarnings("deprecation")
|
||||
public Builder withVisibleComponents(Object2BooleanMap<String> parts) {
|
||||
this.visibilityTest = parts::getOrDefault;
|
||||
return this;
|
||||
}
|
||||
|
||||
public StandaloneGeometryBakingContext build(ResourceLocation modelName)
|
||||
{
|
||||
public StandaloneGeometryBakingContext build(ResourceLocation modelName) {
|
||||
return new StandaloneGeometryBakingContext(modelName, materialCheck, materialLookup, isGui3d, useBlockLight, useAmbientOcclusion, transforms, rootTransform, renderTypeHint, visibilityTest);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,10 +13,8 @@ import net.minecraft.client.renderer.block.model.BlockElementFace;
|
||||
import net.minecraft.client.renderer.block.model.BlockFaceUV;
|
||||
import net.minecraft.client.renderer.block.model.BlockModel;
|
||||
import net.minecraft.client.renderer.block.model.FaceBakery;
|
||||
import net.minecraft.client.renderer.block.model.ItemModelGenerator;
|
||||
import net.minecraft.client.renderer.texture.MissingTextureAtlasSprite;
|
||||
import net.minecraft.client.renderer.texture.SpriteContents;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlas;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.resources.model.BakedModel;
|
||||
import net.minecraft.client.resources.model.BuiltInModel;
|
||||
@@ -24,10 +22,11 @@ import net.minecraft.client.resources.model.Material;
|
||||
import net.minecraft.client.resources.model.ModelBaker;
|
||||
import net.minecraft.client.resources.model.ModelBakery;
|
||||
import net.minecraft.client.resources.model.ModelState;
|
||||
import net.minecraft.client.resources.model.SpecialModels;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.inventory.InventoryMenu;
|
||||
import net.minecraftforge.client.model.ElementsModel;
|
||||
import net.minecraftforge.client.model.ForgeFaceData;
|
||||
import net.minecraftforge.client.model.IModelBuilder;
|
||||
import net.minecraftforge.client.model.IQuadTransformer;
|
||||
import net.minecraftforge.client.model.QuadTransformers;
|
||||
@@ -47,9 +46,7 @@ import java.util.regex.Pattern;
|
||||
/**
|
||||
* Helper for dealing with unbaked models and geometries.
|
||||
*/
|
||||
public class UnbakedGeometryHelper
|
||||
{
|
||||
private static final ItemModelGenerator ITEM_MODEL_GENERATOR = new ItemModelGenerator();
|
||||
public class UnbakedGeometryHelper {
|
||||
private static final FaceBakery FACE_BAKERY = new FaceBakery();
|
||||
|
||||
/**
|
||||
@@ -72,51 +69,51 @@ public class UnbakedGeometryHelper
|
||||
/**
|
||||
* Resolves a material that may have been defined with a filesystem path instead of a proper {@link ResourceLocation}.
|
||||
* <p>
|
||||
* The target atlas will always be {@link TextureAtlas#LOCATION_BLOCKS}.
|
||||
* The target atlas will always be {@link InventoryMenu#BLOCK_ATLAS}.
|
||||
*/
|
||||
public static Material resolveDirtyMaterial(@Nullable String tex, IGeometryBakingContext owner)
|
||||
{
|
||||
public static Material resolveDirtyMaterial(@Nullable String tex, IGeometryBakingContext owner) {
|
||||
if (tex == null)
|
||||
return new Material(TextureAtlas.LOCATION_BLOCKS, MissingTextureAtlasSprite.getLocation());
|
||||
return new Material(InventoryMenu.BLOCK_ATLAS, MissingTextureAtlasSprite.getLocation());
|
||||
if (tex.startsWith("#"))
|
||||
return owner.getMaterial(tex);
|
||||
|
||||
// Attempt to convert a common (windows/linux/mac) filesystem path to a ResourceLocation.
|
||||
// This makes no promises, if it doesn't work, too bad, fix your mtl file.
|
||||
Matcher match = FILESYSTEM_PATH_TO_RESLOC.matcher(tex);
|
||||
if (match.matches())
|
||||
{
|
||||
if (match.matches()) {
|
||||
String namespace = match.group("namespace");
|
||||
String path = match.group("path").replace("\\", "/");
|
||||
tex = namespace != null ? namespace + ":" + path : path;
|
||||
}
|
||||
|
||||
return new Material(TextureAtlas.LOCATION_BLOCKS, ResourceLocation.parse(tex));
|
||||
return new Material(InventoryMenu.BLOCK_ATLAS, ResourceLocation.parse(tex));
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper for baking {@link BlockModel} instances. Handles baking custom geometries and deferring item model baking.
|
||||
*/
|
||||
/*
|
||||
@ApiStatus.Internal
|
||||
public static BakedModel bake(BlockModel blockModel, ModelBaker modelBaker, BlockModel owner, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, boolean guiLight3d)
|
||||
{
|
||||
public static BakedModel bake(BlockModel blockModel, ModelBaker modelBaker, BlockModel owner, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, boolean guiLight3d) {
|
||||
IUnbakedGeometry<?> customModel = blockModel.customData.getCustomGeometry();
|
||||
if (customModel != null)
|
||||
return customModel.bake(blockModel.customData, modelBaker, spriteGetter, modelState, blockModel.getOverrides(modelBaker, owner, spriteGetter));
|
||||
return customModel.bake(blockModel.customData, modelBaker, spriteGetter, modelState);
|
||||
|
||||
// Handle vanilla item models here, since vanilla has a shortcut for them
|
||||
if (blockModel.getRootModel() == ModelBakery.GENERATION_MARKER)
|
||||
return ITEM_MODEL_GENERATOR.generateBlockModel(spriteGetter, blockModel).bake(modelBaker, blockModel, spriteGetter, modelState, guiLight3d);
|
||||
if (blockModel.getRootModel() == SpecialModels.GENERATED_MARKER)
|
||||
return ModelBakery.ITEM_MODEL_GENERATOR.generateBlockModel(spriteGetter, blockModel).bake(modelBaker, blockModel, spriteGetter, modelState, guiLight3d);
|
||||
|
||||
if (blockModel.getRootModel() == ModelBakery.BLOCK_ENTITY_MARKER)
|
||||
{
|
||||
if (blockModel.getRootModel() == SpecialModels.BLOCK_ENTITY_MARKER) {
|
||||
var particleSprite = spriteGetter.apply(blockModel.getMaterial("particle"));
|
||||
return new BuiltInModel(blockModel.getTransforms(), blockModel.getOverrides(modelBaker, owner, spriteGetter), particleSprite, blockModel.getGuiLight().lightLikeBlock());
|
||||
return new BuiltInModel(blockModel.getTransforms(), particleSprite, blockModel.getGuiLight().lightLikeBlock());
|
||||
}
|
||||
|
||||
var elementsModel = new ElementsModel(blockModel.getElements());
|
||||
return elementsModel.bake(blockModel.customData, modelBaker, spriteGetter, modelState, blockModel.getOverrides(modelBaker, owner, spriteGetter));
|
||||
@SuppressWarnings("deprecation")
|
||||
var elements = blockModel.getElements();
|
||||
var elementsModel = new ElementsModel(elements);
|
||||
return elementsModel.bake(blockModel.customData, modelBaker, spriteGetter, modelState);
|
||||
}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a list of {@linkplain BlockElement block elements} in the shape of the specified sprite contents.
|
||||
@@ -124,9 +121,8 @@ public class UnbakedGeometryHelper
|
||||
* <p>
|
||||
* The {@link Direction#NORTH} and {@link Direction#SOUTH} faces take up the whole surface.
|
||||
*/
|
||||
public static List<BlockElement> createUnbakedItemElements(int layerIndex, SpriteContents spriteContents)
|
||||
{
|
||||
return ITEM_MODEL_GENERATOR.processFrames(layerIndex, "layer" + layerIndex, spriteContents);
|
||||
public static List<BlockElement> createUnbakedItemElements(int layerIndex, SpriteContents spriteContents) {
|
||||
return ModelBakery.ITEM_MODEL_GENERATOR.processFrames(layerIndex, "layer" + layerIndex, spriteContents);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -135,8 +131,7 @@ public class UnbakedGeometryHelper
|
||||
* <p>
|
||||
* The {@link Direction#NORTH} and {@link Direction#SOUTH} faces take up only the pixels the texture uses.
|
||||
*/
|
||||
public static List<BlockElement> createUnbakedItemMaskElements(int layerIndex, SpriteContents spriteContents)
|
||||
{
|
||||
public static List<BlockElement> createUnbakedItemMaskElements(int layerIndex, SpriteContents spriteContents) {
|
||||
var elements = createUnbakedItemElements(layerIndex, spriteContents);
|
||||
elements.remove(0); // Remove north and south faces
|
||||
|
||||
@@ -152,16 +147,12 @@ public class UnbakedGeometryHelper
|
||||
});
|
||||
|
||||
// Scan in search of opaque pixels
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
for (int y = 0; y < height; y++) {
|
||||
int xStart = -1;
|
||||
for (int x = 0; x < width; x++)
|
||||
{
|
||||
for (int x = 0; x < width; x++) {
|
||||
var opaque = bits.get(x + y * width);
|
||||
if (opaque == (xStart == -1)) // (opaque && -1) || (!opaque && !-1)
|
||||
{
|
||||
if (xStart == -1)
|
||||
{
|
||||
if (opaque == (xStart == -1)) { // (opaque && -1) || (!opaque && !-1)
|
||||
if (xStart == -1) {
|
||||
// We have found the start of a new segment, continue
|
||||
xStart = x;
|
||||
continue;
|
||||
@@ -187,9 +178,7 @@ public class UnbakedGeometryHelper
|
||||
Util.make(new HashMap<>(), map -> {
|
||||
for (Direction direction : Direction.values())
|
||||
map.put(direction, new BlockElementFace(null, layerIndex, "layer" + layerIndex, new BlockFaceUV(null, 0)));
|
||||
}),
|
||||
null,
|
||||
true
|
||||
})
|
||||
));
|
||||
|
||||
// Reset xStart
|
||||
@@ -203,13 +192,11 @@ public class UnbakedGeometryHelper
|
||||
/**
|
||||
* Bakes a list of {@linkplain BlockElement block elements} and feeds the baked quads to a {@linkplain IModelBuilder model builder}.
|
||||
*/
|
||||
public static void bakeElements(IModelBuilder<?> builder, List<BlockElement> elements, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState)
|
||||
{
|
||||
for (BlockElement element : elements)
|
||||
{
|
||||
public static void bakeElements(IModelBuilder<?> builder, List<BlockElement> elements, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState) {
|
||||
for (BlockElement element : elements) {
|
||||
element.faces.forEach((side, face) -> {
|
||||
var sprite = spriteGetter.apply(new Material(TextureAtlas.LOCATION_BLOCKS, ResourceLocation.parse(face.texture())));
|
||||
var quad = bakeElementFace(element, face, sprite, side, modelState);
|
||||
var sprite = spriteGetter.apply(new Material(InventoryMenu.BLOCK_ATLAS, ResourceLocation.parse(face.texture())));
|
||||
var quad = bakeElementFace(element, face, sprite, side, modelState, element.lightEmission);
|
||||
if (face.cullForDirection() == null)
|
||||
builder.addUnculledFace(quad);
|
||||
else
|
||||
@@ -221,8 +208,7 @@ public class UnbakedGeometryHelper
|
||||
/**
|
||||
* Bakes a list of {@linkplain BlockElement block elements} and returns the list of baked quads.
|
||||
*/
|
||||
public static List<BakedQuad> bakeElements(List<BlockElement> elements, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState)
|
||||
{
|
||||
public static List<BakedQuad> bakeElements(List<BlockElement> elements, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState) {
|
||||
if (elements.isEmpty())
|
||||
return List.of();
|
||||
var list = new ArrayList<BakedQuad>();
|
||||
@@ -233,9 +219,8 @@ public class UnbakedGeometryHelper
|
||||
/**
|
||||
* Turns a single {@link BlockElementFace} into a {@link BakedQuad}.
|
||||
*/
|
||||
public static BakedQuad bakeElementFace(BlockElement element, BlockElementFace face, TextureAtlasSprite sprite, Direction direction, ModelState state)
|
||||
{
|
||||
return FACE_BAKERY.bakeQuad(element.from, element.to, face, sprite, direction, state, element.rotation, element.shade);
|
||||
public static BakedQuad bakeElementFace(BlockElement element, BlockElementFace face, TextureAtlasSprite sprite, Direction direction, ModelState state, int lightEmission) {
|
||||
return FACE_BAKERY.bakeQuad(element.from, element.to, face, sprite, direction, state, element.rotation, element.shade, lightEmission);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -246,8 +231,7 @@ public class UnbakedGeometryHelper
|
||||
* @return an {@code IQuadTransformer} that applies the root transform to a baked quad that already has the
|
||||
* transformation of the given {@code ModelState} applied to it
|
||||
*/
|
||||
public static IQuadTransformer applyRootTransform(ModelState modelState, Transformation rootTransform)
|
||||
{
|
||||
public static IQuadTransformer applyRootTransform(ModelState modelState, Transformation rootTransform) {
|
||||
// Move the origin of the ModelState transform and its inverse from the negative corner to the block center
|
||||
// to replicate the way the ModelState transform is applied in the FaceBakery by moving the vertices such that
|
||||
// the negative corner acts as the block center
|
||||
@@ -258,8 +242,7 @@ public class UnbakedGeometryHelper
|
||||
/**
|
||||
* {@return a {@link ModelState} that combines the existing model state and the {@linkplain Transformation root transform}}
|
||||
*/
|
||||
public static ModelState composeRootTransformIntoModelState(ModelState modelState, Transformation rootTransform)
|
||||
{
|
||||
public static ModelState composeRootTransformIntoModelState(ModelState modelState, Transformation rootTransform) {
|
||||
// Move the origin of the root transform as if the negative corner were the block center to match the way the
|
||||
// ModelState transform is applied in the FaceBakery by moving the vertices to be centered on that corner
|
||||
rootTransform = rootTransform.applyOrigin(new Vector3f(-.5F, -.5F, -.5F));
|
||||
|
||||
+23
-47
@@ -27,47 +27,34 @@ import java.util.List;
|
||||
/**
|
||||
* Wrapper around {@link ModelBlockRenderer} to allow rendering blocks via Forge's lighting pipeline.
|
||||
*/
|
||||
public class ForgeModelBlockRenderer extends ModelBlockRenderer
|
||||
{
|
||||
public class ForgeModelBlockRenderer extends ModelBlockRenderer {
|
||||
private static final Direction[] SIDES = Direction.values();
|
||||
|
||||
private final ThreadLocal<QuadLighter> flatLighter, smoothLighter;
|
||||
|
||||
public ForgeModelBlockRenderer(BlockColors colors)
|
||||
{
|
||||
public ForgeModelBlockRenderer(BlockColors colors) {
|
||||
super(colors);
|
||||
this.flatLighter = ThreadLocal.withInitial(() -> new FlatQuadLighter(colors));
|
||||
this.smoothLighter = ThreadLocal.withInitial(() -> new SmoothQuadLighter(colors));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tesselateWithoutAO(BlockAndTintGetter level, BakedModel model, BlockState state, BlockPos pos, PoseStack poseStack, VertexConsumer vertexConsumer, boolean checkSides, RandomSource rand, long seed, int packedOverlay, ModelData modelData, RenderType renderType)
|
||||
{
|
||||
public void tesselateWithoutAO(BlockAndTintGetter level, BakedModel model, BlockState state, BlockPos pos, PoseStack poseStack, VertexConsumer vertexConsumer, boolean checkSides, RandomSource rand, long seed, int packedOverlay, ModelData modelData, RenderType renderType) {
|
||||
if (ForgeConfig.CLIENT.experimentalForgeLightPipelineEnabled.get())
|
||||
{
|
||||
render(vertexConsumer, flatLighter.get(), level, model, state, pos, poseStack, checkSides, rand, seed, packedOverlay, modelData, renderType);
|
||||
}
|
||||
else
|
||||
{
|
||||
super.tesselateWithoutAO(level, model, state, pos, poseStack, vertexConsumer, checkSides, rand, seed, packedOverlay, modelData, renderType);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tesselateWithAO(BlockAndTintGetter level, BakedModel model, BlockState state, BlockPos pos, PoseStack poseStack, VertexConsumer vertexConsumer, boolean checkSides, RandomSource rand, long seed, int packedOverlay, ModelData modelData, RenderType renderType)
|
||||
{
|
||||
public void tesselateWithAO(BlockAndTintGetter level, BakedModel model, BlockState state, BlockPos pos, PoseStack poseStack, VertexConsumer vertexConsumer, boolean checkSides, RandomSource rand, long seed, int packedOverlay, ModelData modelData, RenderType renderType) {
|
||||
if (ForgeConfig.CLIENT.experimentalForgeLightPipelineEnabled.get())
|
||||
{
|
||||
render(vertexConsumer, smoothLighter.get(), level, model, state, pos, poseStack, checkSides, rand, seed, packedOverlay, modelData, renderType);
|
||||
}
|
||||
else
|
||||
{
|
||||
super.tesselateWithAO(level, model, state, pos, poseStack, vertexConsumer, checkSides, rand, seed, packedOverlay, modelData, renderType);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean render(VertexConsumer vertexConsumer, QuadLighter lighter, BlockAndTintGetter level, BakedModel model, BlockState state, BlockPos pos, PoseStack poseStack, boolean checkSides, RandomSource rand, long seed, int packedOverlay, ModelData modelData, RenderType renderType)
|
||||
{
|
||||
public static boolean render(VertexConsumer vertexConsumer, QuadLighter lighter, BlockAndTintGetter level, BakedModel model, BlockState state, BlockPos pos, PoseStack poseStack, boolean checkSides, RandomSource rand, long seed, int packedOverlay, ModelData modelData, RenderType renderType) {
|
||||
ForgeModelBlockRenderer renderer = (ForgeModelBlockRenderer)Minecraft.getInstance().getBlockRenderer().getModelRenderer();
|
||||
var pose = poseStack.last();
|
||||
var empty = true;
|
||||
@@ -76,64 +63,53 @@ public class ForgeModelBlockRenderer extends ModelBlockRenderer
|
||||
|
||||
rand.setSeed(seed);
|
||||
List<BakedQuad> quads = model.getQuads(state, null, rand, modelData, renderType);
|
||||
if (!quads.isEmpty())
|
||||
{
|
||||
if (!quads.isEmpty()) {
|
||||
empty = false;
|
||||
lighter.setup(level, pos, state);
|
||||
for (BakedQuad quad : quads)
|
||||
{
|
||||
if (smoothLighter && !quad.hasAmbientOcclusion())
|
||||
{
|
||||
if (flatLighter == null)
|
||||
{
|
||||
for (BakedQuad quad : quads) {
|
||||
if (smoothLighter && !quad.hasAmbientOcclusion()) {
|
||||
if (flatLighter == null) {
|
||||
flatLighter = renderer.flatLighter.get();
|
||||
flatLighter.setup(level, pos, state);
|
||||
}
|
||||
flatLighter.process(vertexConsumer, pose, quad, packedOverlay);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
lighter.process(vertexConsumer, pose, quad, packedOverlay);
|
||||
}
|
||||
}
|
||||
}
|
||||
var mutable = pos.mutable();
|
||||
|
||||
for (Direction side : SIDES)
|
||||
{
|
||||
if (checkSides && !Block.shouldRenderFace(state, level, pos, side, pos.relative(side)))
|
||||
{
|
||||
for (Direction side : SIDES) {
|
||||
mutable.setWithOffset(pos, side);
|
||||
if (checkSides && !Block.shouldRenderFace(level, pos, state, level.getBlockState(mutable), side))
|
||||
continue;
|
||||
}
|
||||
rand.setSeed(seed);
|
||||
quads = model.getQuads(state, side, rand, modelData, renderType);
|
||||
if (!quads.isEmpty())
|
||||
{
|
||||
if (empty)
|
||||
{
|
||||
if (!quads.isEmpty()) {
|
||||
if (empty) {
|
||||
empty = false;
|
||||
lighter.setup(level, pos, state);
|
||||
}
|
||||
for (BakedQuad quad : quads)
|
||||
{
|
||||
if (smoothLighter && !quad.hasAmbientOcclusion())
|
||||
{
|
||||
if (flatLighter == null)
|
||||
{
|
||||
|
||||
for (BakedQuad quad : quads) {
|
||||
if (smoothLighter && !quad.hasAmbientOcclusion()) {
|
||||
if (flatLighter == null) {
|
||||
flatLighter = renderer.flatLighter.get();
|
||||
flatLighter.setup(level, pos, state);
|
||||
}
|
||||
flatLighter.process(vertexConsumer, pose, quad, packedOverlay);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
lighter.process(vertexConsumer, pose, quad, packedOverlay);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lighter.reset();
|
||||
if (flatLighter != null)
|
||||
flatLighter.reset();
|
||||
|
||||
return !empty;
|
||||
}
|
||||
}
|
||||
@@ -21,8 +21,7 @@ import net.minecraft.world.phys.shapes.Shapes;
|
||||
* Implementation of {@link QuadLighter} that lights {@link BakedQuad baked quads} using ambient occlusion and
|
||||
* light interpolation.
|
||||
*/
|
||||
public class SmoothQuadLighter extends QuadLighter
|
||||
{
|
||||
public class SmoothQuadLighter extends QuadLighter {
|
||||
private static final Direction[] SIDES = Direction.values();
|
||||
|
||||
private final BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
|
||||
@@ -33,23 +32,18 @@ public class SmoothQuadLighter extends QuadLighter
|
||||
private final float[][][][] blockLight = new float[3][2][2][2];
|
||||
private final float[][][] ao = new float[3][3][3];
|
||||
|
||||
public SmoothQuadLighter(BlockColors colors)
|
||||
{
|
||||
public SmoothQuadLighter(BlockColors colors) {
|
||||
super(colors);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void computeLightingAt(BlockAndTintGetter level, BlockPos origin, BlockState state)
|
||||
{
|
||||
for (int x = 0; x <= 2; x++)
|
||||
{
|
||||
for (int y = 0; y <= 2; y++)
|
||||
{
|
||||
for (int z = 0; z <= 2; z++)
|
||||
{
|
||||
protected void computeLightingAt(BlockAndTintGetter level, BlockPos origin, BlockState state) {
|
||||
for (int x = 0; x <= 2; x++) {
|
||||
for (int y = 0; y <= 2; y++) {
|
||||
for (int z = 0; z <= 2; z++) {
|
||||
pos.setWithOffset(origin, x - 1, y - 1, z - 1);
|
||||
BlockState neighborState = level.getBlockState(pos);
|
||||
t[x][y][z] = neighborState.getLightBlock(level, pos) < 15;
|
||||
t[x][y][z] = neighborState.getLightBlock() < 15;
|
||||
int brightness = LevelRenderer.getLightColor(level, neighborState, pos);
|
||||
s[x][y][z] = LightTexture.sky(brightness);
|
||||
b[x][y][z] = LightTexture.block(brightness);
|
||||
@@ -57,16 +51,20 @@ public class SmoothQuadLighter extends QuadLighter
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Direction side : SIDES)
|
||||
{
|
||||
|
||||
for (Direction side : SIDES) {
|
||||
pos.setWithOffset(origin, side);
|
||||
BlockState neighborState = level.getBlockState(pos);
|
||||
|
||||
BlockState thisStateShape = state.canOcclude() && state.useShapeForLightOcclusion() ? state : Blocks.AIR.defaultBlockState();
|
||||
BlockState otherStateShape = neighborState.canOcclude() && neighborState.useShapeForLightOcclusion() ? neighborState : Blocks.AIR.defaultBlockState();
|
||||
|
||||
if (neighborState.getLightBlock(level, pos) == 15 || Shapes.faceShapeOccludes(thisStateShape.getFaceOcclusionShape(level, origin, side), otherStateShape.getFaceOcclusionShape(level, pos, side.getOpposite())))
|
||||
{
|
||||
if (neighborState.getLightBlock() == 15 ||
|
||||
Shapes.faceShapeOccludes(
|
||||
thisStateShape.getFaceOcclusionShape(side),
|
||||
otherStateShape.getFaceOcclusionShape(side.getOpposite())
|
||||
)
|
||||
) {
|
||||
int x = side.getStepX() + 1;
|
||||
int y = side.getStepY() + 1;
|
||||
int z = side.getStepZ() + 1;
|
||||
@@ -74,12 +72,10 @@ public class SmoothQuadLighter extends QuadLighter
|
||||
b[x][y][z] = Math.max(b[1][1][1] - 1, b[x][y][z]);
|
||||
}
|
||||
}
|
||||
for (int x = 0; x < 2; x++)
|
||||
{
|
||||
for (int y = 0; y < 2; y++)
|
||||
{
|
||||
for (int z = 0; z < 2; z++)
|
||||
{
|
||||
|
||||
for (int x = 0; x < 2; x++) {
|
||||
for (int y = 0; y < 2; y++) {
|
||||
for (int z = 0; z < 2; z++) {
|
||||
int x1 = x * 2;
|
||||
int y1 = y * 2;
|
||||
int z1 = z * 2;
|
||||
@@ -116,8 +112,7 @@ public class SmoothQuadLighter extends QuadLighter
|
||||
}
|
||||
|
||||
@Override
|
||||
protected float calculateBrightness(float[] position)
|
||||
{
|
||||
protected float calculateBrightness(float[] position) {
|
||||
float x = position[0], y = position[1], z = position[2];
|
||||
int sx = x < 0 ? 1 : 2;
|
||||
int sy = y < 0 ? 1 : 2;
|
||||
@@ -142,15 +137,13 @@ public class SmoothQuadLighter extends QuadLighter
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int calculateLightmap(float[] position, byte[] normal)
|
||||
{
|
||||
protected int calculateLightmap(float[] position, byte[] normal) {
|
||||
var block = (int) (calcLightmap(blockLight, position[0], position[1], position[2]) * 0xF0);
|
||||
var sky = (int) (calcLightmap(skyLight, position[0], position[1], position[2]) * 0xF0);
|
||||
return block | (sky << 16);
|
||||
}
|
||||
|
||||
private float combine(int c, int s1, int s2, int s3, boolean t0, boolean t1, boolean t2, boolean t3)
|
||||
{
|
||||
private float combine(int c, int s1, int s2, int s3, boolean t0, boolean t1, boolean t2, boolean t3) {
|
||||
if (c == 0 && !t0) c = Math.max(0, Math.max(s1, s2) - 1);
|
||||
if (s1 == 0 && !t1) s1 = Math.max(0, c - 1);
|
||||
if (s2 == 0 && !t2) s2 = Math.max(0, c - 1);
|
||||
@@ -158,14 +151,12 @@ public class SmoothQuadLighter extends QuadLighter
|
||||
return (c + s1 + s2 + s3) / (0xF * 4f);
|
||||
}
|
||||
|
||||
protected float calcLightmap(float[][][][] light, float x, float y, float z)
|
||||
{
|
||||
protected float calcLightmap(float[][][][] light, float x, float y, float z) {
|
||||
x *= 2;
|
||||
y *= 2;
|
||||
z *= 2;
|
||||
float l2 = x * x + y * y + z * z;
|
||||
if (l2 > 6 - 2e-2f)
|
||||
{
|
||||
if (l2 > 6 - 2e-2f) {
|
||||
float s = (float) Math.sqrt((6 - 2e-2f) / l2);
|
||||
x *= s;
|
||||
y *= s;
|
||||
@@ -176,40 +167,27 @@ public class SmoothQuadLighter extends QuadLighter
|
||||
float az = z > 0 ? z : -z;
|
||||
float e1 = 1 + 1e-4f;
|
||||
if (ax > 2 - 1e-4f && ay <= e1 && az <= e1)
|
||||
{
|
||||
x = x < 0 ? -2 + 1e-4f : 2 - 1e-4f;
|
||||
}
|
||||
else if (ay > 2 - 1e-4f && az <= e1 && ax <= e1)
|
||||
{
|
||||
y = y < 0 ? -2 + 1e-4f : 2 - 1e-4f;
|
||||
}
|
||||
else if (az > 2 - 1e-4f && ax <= e1 && ay <= e1)
|
||||
{
|
||||
z = z < 0 ? -2 + 1e-4f : 2 - 1e-4f;
|
||||
}
|
||||
ax = x > 0 ? x : -x;
|
||||
ay = y > 0 ? y : -y;
|
||||
az = z > 0 ? z : -z;
|
||||
if (ax <= e1 && ay + az > 3f - 1e-4f)
|
||||
{
|
||||
if (ax <= e1 && ay + az > 3f - 1e-4f) {
|
||||
float s = (3f - 1e-4f) / (ay + az);
|
||||
y *= s;
|
||||
z *= s;
|
||||
}
|
||||
else if (ay <= e1 && az + ax > 3f - 1e-4f)
|
||||
{
|
||||
} else if (ay <= e1 && az + ax > 3f - 1e-4f) {
|
||||
float s = (3f - 1e-4f) / (az + ax);
|
||||
z *= s;
|
||||
x *= s;
|
||||
}
|
||||
else if (az <= e1 && ax + ay > 3f - 1e-4f)
|
||||
{
|
||||
} else if (az <= e1 && ax + ay > 3f - 1e-4f) {
|
||||
float s = (3f - 1e-4f) / (ax + ay);
|
||||
x *= s;
|
||||
y *= s;
|
||||
}
|
||||
else if (ax + ay + az > 4 - 1e-4f)
|
||||
{
|
||||
} else if (ax + ay + az > 4 - 1e-4f) {
|
||||
float s = (4 - 1e-4f) / (ax + ay + az);
|
||||
x *= s;
|
||||
y *= s;
|
||||
@@ -219,12 +197,9 @@ public class SmoothQuadLighter extends QuadLighter
|
||||
float l = 0;
|
||||
float s = 0;
|
||||
|
||||
for (int ix = 0; ix <= 1; ix++)
|
||||
{
|
||||
for (int iy = 0; iy <= 1; iy++)
|
||||
{
|
||||
for (int iz = 0; iz <= 1; iz++)
|
||||
{
|
||||
for (int ix = 0; ix <= 1; ix++) {
|
||||
for (int iy = 0; iy <= 1; iy++) {
|
||||
for (int iz = 0; iz <= 1; iz++) {
|
||||
float vx = x * (1 - ix * 2);
|
||||
float vy = y * (1 - iy * 2);
|
||||
float vz = z * (1 - iz * 2);
|
||||
|
||||
@@ -431,7 +431,7 @@ public class ObjModel extends SimpleUnbakedGeometry<ObjModel>
|
||||
quadBaker.setNormal(normal.x(), normal.y(), normal.z());
|
||||
if (i == 0)
|
||||
{
|
||||
quadBaker.setDirection(Direction.getNearest(normal.x(), normal.y(), normal.z()));
|
||||
quadBaker.setDirection(Direction.getApproximateNearest(normal.x(), normal.y(), normal.z()));
|
||||
}
|
||||
pos[i] = position;
|
||||
norm[i] = normal;
|
||||
|
||||
+27
-43
@@ -26,8 +26,7 @@ import java.util.function.Consumer;
|
||||
* This consumer accepts data in {@link com.mojang.blaze3d.vertex.DefaultVertexFormat#BLOCK} and is not picky about
|
||||
* ordering or missing elements, but will not automatically populate missing data (color will be black, for example).
|
||||
*/
|
||||
public class QuadBakingVertexConsumer implements VertexConsumer
|
||||
{
|
||||
public class QuadBakingVertexConsumer implements VertexConsumer {
|
||||
private final Map<VertexFormatElement, Integer> ELEMENT_OFFSETS = Util.make(new IdentityHashMap<>(), map -> {
|
||||
int i = 0;
|
||||
for (var element : DefaultVertexFormat.BLOCK.getElements())
|
||||
@@ -46,15 +45,14 @@ public class QuadBakingVertexConsumer implements VertexConsumer
|
||||
private TextureAtlasSprite sprite = UnitTextureAtlasSprite.INSTANCE;
|
||||
private boolean shade;
|
||||
private boolean hasAmbientOcclusion;
|
||||
private int lightEmission;
|
||||
|
||||
public QuadBakingVertexConsumer(Consumer<BakedQuad> quadConsumer)
|
||||
{
|
||||
public QuadBakingVertexConsumer(Consumer<BakedQuad> quadConsumer) {
|
||||
this.quadConsumer = quadConsumer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer addVertex(float x, float y, float z)
|
||||
{
|
||||
public VertexConsumer addVertex(float x, float y, float z) {
|
||||
if (vertexIndex++ == MAX_VERTICES)
|
||||
build();
|
||||
|
||||
@@ -66,8 +64,7 @@ public class QuadBakingVertexConsumer implements VertexConsumer
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setNormal(float x, float y, float z)
|
||||
{
|
||||
public VertexConsumer setNormal(float x, float y, float z) {
|
||||
int offset = vertexIndex * IQuadTransformer.STRIDE + IQuadTransformer.NORMAL;
|
||||
quadData[offset] = ((int) (x * 127.0f) & 0xFF) |
|
||||
(((int) (y * 127.0f) & 0xFF) << 8) |
|
||||
@@ -76,8 +73,7 @@ public class QuadBakingVertexConsumer implements VertexConsumer
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setColor(int r, int g, int b, int a)
|
||||
{
|
||||
public VertexConsumer setColor(int r, int g, int b, int a) {
|
||||
int offset = vertexIndex * IQuadTransformer.STRIDE + IQuadTransformer.COLOR;
|
||||
quadData[offset] = ((a & 0xFF) << 24) |
|
||||
((b & 0xFF) << 16) |
|
||||
@@ -87,8 +83,7 @@ public class QuadBakingVertexConsumer implements VertexConsumer
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv(float u, float v)
|
||||
{
|
||||
public VertexConsumer setUv(float u, float v) {
|
||||
int offset = vertexIndex * IQuadTransformer.STRIDE + IQuadTransformer.UV0;
|
||||
quadData[offset] = Float.floatToRawIntBits(u);
|
||||
quadData[offset + 1] = Float.floatToRawIntBits(v);
|
||||
@@ -96,10 +91,8 @@ public class QuadBakingVertexConsumer implements VertexConsumer
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv1(int u, int v)
|
||||
{
|
||||
if (IQuadTransformer.UV1 >= 0) // Vanilla doesn't support this, but it may be added by a 3rd party
|
||||
{
|
||||
public VertexConsumer setUv1(int u, int v) {
|
||||
if (IQuadTransformer.UV1 >= 0) { // Vanilla doesn't support this, but it may be added by a 3rd party
|
||||
int offset = vertexIndex * IQuadTransformer.STRIDE + IQuadTransformer.UV1;
|
||||
quadData[offset] = (u & 0xFFFF) | ((v & 0xFFFF) << 16);
|
||||
}
|
||||
@@ -107,28 +100,24 @@ public class QuadBakingVertexConsumer implements VertexConsumer
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv2(int u, int v)
|
||||
{
|
||||
public VertexConsumer setUv2(int u, int v) {
|
||||
int offset = vertexIndex * IQuadTransformer.STRIDE + IQuadTransformer.UV2;
|
||||
quadData[offset] = (u & 0xFFFF) | ((v & 0xFFFF) << 16);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer misc(VertexFormatElement element, int... rawData)
|
||||
{
|
||||
public VertexConsumer misc(VertexFormatElement element, int... rawData) {
|
||||
Integer baseOffset = ELEMENT_OFFSETS.get(element);
|
||||
if (baseOffset != null)
|
||||
{
|
||||
if (baseOffset != null) {
|
||||
int offset = vertexIndex * IQuadTransformer.STRIDE + baseOffset;
|
||||
System.arraycopy(rawData, 0, quadData, offset, rawData.length);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public BakedQuad build()
|
||||
{
|
||||
BakedQuad quad = new BakedQuad(quadData, tintIndex, direction, sprite, shade, hasAmbientOcclusion);
|
||||
public BakedQuad build() {
|
||||
BakedQuad quad = new BakedQuad(quadData, tintIndex, direction, sprite, shade, lightEmission, hasAmbientOcclusion);
|
||||
// We have a full quad, pass it to the consumer and reset
|
||||
quadConsumer.accept(quad);
|
||||
vertexIndex = 0;
|
||||
@@ -136,48 +125,43 @@ public class QuadBakingVertexConsumer implements VertexConsumer
|
||||
return quad;
|
||||
}
|
||||
|
||||
public void setTintIndex(int tintIndex)
|
||||
{
|
||||
public void setTintIndex(int tintIndex) {
|
||||
this.tintIndex = tintIndex;
|
||||
}
|
||||
|
||||
public void setDirection(Direction direction)
|
||||
{
|
||||
public void setDirection(Direction direction) {
|
||||
this.direction = direction;
|
||||
}
|
||||
|
||||
public void setSprite(TextureAtlasSprite sprite)
|
||||
{
|
||||
public void setSprite(TextureAtlasSprite sprite) {
|
||||
this.sprite = sprite;
|
||||
}
|
||||
|
||||
public void setShade(boolean shade)
|
||||
{
|
||||
public void setShade(boolean shade) {
|
||||
this.shade = shade;
|
||||
}
|
||||
|
||||
public void setHasAmbientOcclusion(boolean hasAmbientOcclusion)
|
||||
{
|
||||
public void setHasAmbientOcclusion(boolean hasAmbientOcclusion) {
|
||||
this.hasAmbientOcclusion = hasAmbientOcclusion;
|
||||
}
|
||||
|
||||
public static class Buffered extends QuadBakingVertexConsumer
|
||||
{
|
||||
public void setLightEmission(int value) {
|
||||
this.lightEmission = value;
|
||||
}
|
||||
|
||||
public static class Buffered extends QuadBakingVertexConsumer {
|
||||
private final BakedQuad[] output;
|
||||
|
||||
public Buffered()
|
||||
{
|
||||
public Buffered() {
|
||||
this(new BakedQuad[1]);
|
||||
}
|
||||
|
||||
private Buffered(BakedQuad[] output)
|
||||
{
|
||||
private Buffered(BakedQuad[] output) {
|
||||
super(q -> output[0] = q);
|
||||
this.output = output;
|
||||
}
|
||||
|
||||
public BakedQuad getQuad()
|
||||
{
|
||||
public BakedQuad getQuad() {
|
||||
var quad = Preconditions.checkNotNull(output[0], "No quad has been emitted. Vertices in buffer: " + vertexIndex);
|
||||
output[0] = null;
|
||||
return quad;
|
||||
|
||||
@@ -8,22 +8,19 @@ package net.minecraftforge.client.settings;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
|
||||
public enum KeyConflictContext implements IKeyConflictContext
|
||||
{
|
||||
public enum KeyConflictContext implements IKeyConflictContext {
|
||||
/**
|
||||
* Universal key bindings are used in every context and will conflict with any other context.
|
||||
* Key Bindings are universal by default.
|
||||
*/
|
||||
UNIVERSAL {
|
||||
@Override
|
||||
public boolean isActive()
|
||||
{
|
||||
public boolean isActive() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean conflicts(IKeyConflictContext other)
|
||||
{
|
||||
public boolean conflicts(IKeyConflictContext other) {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
@@ -32,15 +29,14 @@ public enum KeyConflictContext implements IKeyConflictContext
|
||||
* Gui key bindings are only used when a {@link Screen} is open.
|
||||
*/
|
||||
GUI {
|
||||
@SuppressWarnings("resource")
|
||||
@Override
|
||||
public boolean isActive()
|
||||
{
|
||||
public boolean isActive() {
|
||||
return Minecraft.getInstance().screen != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean conflicts(IKeyConflictContext other)
|
||||
{
|
||||
public boolean conflicts(IKeyConflictContext other) {
|
||||
return this == other;
|
||||
}
|
||||
},
|
||||
@@ -50,14 +46,12 @@ public enum KeyConflictContext implements IKeyConflictContext
|
||||
*/
|
||||
IN_GAME {
|
||||
@Override
|
||||
public boolean isActive()
|
||||
{
|
||||
public boolean isActive() {
|
||||
return !GUI.isActive();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean conflicts(IKeyConflictContext other)
|
||||
{
|
||||
public boolean conflicts(IKeyConflictContext other) {
|
||||
return this == other;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ public final class CreativeModeTabRegistry {
|
||||
*/
|
||||
@Nullable
|
||||
public static CreativeModeTab getTab(ResourceLocation name) {
|
||||
return BuiltInRegistries.CREATIVE_MODE_TAB.get(name);
|
||||
return BuiltInRegistries.CREATIVE_MODE_TAB.getValue(name);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -178,14 +178,15 @@ public final class CreativeModeTabRegistry {
|
||||
public static void sortTabs() {
|
||||
edges.clear();
|
||||
|
||||
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.get(CreativeModeTabs.HOTBAR));
|
||||
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.get(CreativeModeTabs.SEARCH));
|
||||
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.get(CreativeModeTabs.OP_BLOCKS));
|
||||
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.get(CreativeModeTabs.INVENTORY));
|
||||
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.getValue(CreativeModeTabs.HOTBAR));
|
||||
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.getValue(CreativeModeTabs.SEARCH));
|
||||
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.getValue(CreativeModeTabs.OP_BLOCKS));
|
||||
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.getValue(CreativeModeTabs.INVENTORY));
|
||||
|
||||
final List<Holder<CreativeModeTab>> indexed = BuiltInRegistries.CREATIVE_MODE_TAB.holders()
|
||||
.filter(c -> !DEFAULT_TABS.contains(c.get()))
|
||||
.collect(Collectors.toList());
|
||||
final List<? extends Holder<CreativeModeTab>> indexed = BuiltInRegistries.CREATIVE_MODE_TAB
|
||||
.listElements()
|
||||
.filter(c -> !DEFAULT_TABS.contains(c.get()))
|
||||
.toList();
|
||||
int vanillaTabs = 10;
|
||||
|
||||
for (int i = 0; i < vanillaTabs; i++) { // Vanilla ordering
|
||||
|
||||
@@ -104,9 +104,6 @@ public class ForgeConfig {
|
||||
|
||||
public final BooleanValue calculateAllNormals;
|
||||
|
||||
public final BooleanValue stabilizeDirectionGetNearest;
|
||||
|
||||
|
||||
Client(ForgeConfigSpec.Builder builder) {
|
||||
builder.comment("Client only settings, mostly things related to rendering")
|
||||
.push("client");
|
||||
@@ -142,11 +139,6 @@ public class ForgeConfig {
|
||||
.translation("forge.configgui.calculateAllNormals")
|
||||
.define("calculateAllNormals", false);
|
||||
|
||||
stabilizeDirectionGetNearest = builder
|
||||
.comment("When enabled, a slightly biased Direction#getNearest calculation will be used to prevent normal fighting on 45 degree angle faces.")
|
||||
.translation("forge.configgui.stabilizeDirectionGetNearest")
|
||||
.define("stabilizeDirectionGetNearest", true);
|
||||
|
||||
builder.pop();
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
@@ -40,15 +41,12 @@ import com.mojang.serialization.Lifecycle;
|
||||
import io.netty.handler.codec.DecoderException;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.NonNullList;
|
||||
import net.minecraft.core.component.DataComponentMap;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.core.particles.ParticleTypes;
|
||||
@@ -56,12 +54,12 @@ import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.VarInt;
|
||||
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.PlainTextContents.LiteralContents;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.tags.TagKey;
|
||||
@@ -80,11 +78,10 @@ import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.ai.Brain;
|
||||
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
|
||||
import net.minecraft.world.entity.ai.attributes.DefaultAttributes;
|
||||
import net.minecraft.world.entity.monster.EnderMan;
|
||||
import net.minecraft.world.entity.monster.Monster;
|
||||
import net.minecraft.world.inventory.ContainerLevelAccess;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import net.minecraft.world.item.crafting.RecipeType;
|
||||
import net.minecraft.world.item.enchantment.Enchantments;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.material.Fluids;
|
||||
@@ -92,6 +89,7 @@ import net.minecraft.world.level.storage.LevelStorageSource;
|
||||
import net.minecraft.world.level.storage.WorldData;
|
||||
import net.minecraft.world.level.storage.loot.LootContext;
|
||||
import net.minecraft.world.level.storage.loot.LootPool;
|
||||
import net.minecraft.world.level.storage.loot.LootTable;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.item.enchantment.EnchantmentHelper;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
@@ -113,7 +111,6 @@ import net.minecraft.network.protocol.login.ClientboundCustomQueryPacket;
|
||||
import net.minecraft.network.protocol.login.ServerboundCustomQueryAnswerPacket;
|
||||
import net.minecraft.stats.Stats;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.minecraft.world.level.block.entity.FurnaceBlockEntity;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
@@ -139,7 +136,7 @@ import net.minecraftforge.event.RegisterStructureConversionsEvent;
|
||||
import net.minecraftforge.event.entity.EntityAttributeCreationEvent;
|
||||
import net.minecraftforge.event.entity.EntityAttributeModificationEvent;
|
||||
import net.minecraftforge.event.entity.item.ItemTossEvent;
|
||||
import net.minecraftforge.event.entity.living.EnderManAngerEvent;
|
||||
import net.minecraftforge.event.entity.living.MonsterDisguiseEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingAttackEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingBreatheEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingDamageEvent;
|
||||
@@ -183,7 +180,6 @@ import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.damagesource.DamageSource;
|
||||
@@ -551,8 +547,9 @@ public final class ForgeHooks {
|
||||
|
||||
@NotNull
|
||||
public static ItemStack getCraftingRemainingItem(@NotNull ItemStack stack) {
|
||||
if (stack.getItem().hasCraftingRemainingItem(stack)) {
|
||||
stack = stack.getItem().getCraftingRemainingItem(stack);
|
||||
var remainder = stack.getCraftingRemainder();
|
||||
if (!remainder.isEmpty()) {
|
||||
stack = remainder;
|
||||
if (!stack.isEmpty() && stack.isDamageableItem() && stack.getDamageValue() > stack.getMaxDamage()) {
|
||||
ForgeEventFactory.onPlayerDestroyItem(CRAFTING_PLAYER.get(), stack, (EquipmentSlot)null);
|
||||
return ItemStack.EMPTY;
|
||||
@@ -674,7 +671,7 @@ public final class ForgeHooks {
|
||||
ResourceLocation registryName = ForgeRegistries.ITEMS.getKey(item);
|
||||
String modId = registryName == null ? null : registryName.getNamespace();
|
||||
if ("minecraft".equals(modId)) {
|
||||
if (item instanceof EnchantedBookItem) {
|
||||
if (itemStack.is(Items.ENCHANTED_BOOK)) {
|
||||
var enchants = EnchantmentHelper.getEnchantmentsForCrafting(itemStack);
|
||||
if (enchants.size() == 1) {
|
||||
var enchant = enchants.keySet().iterator().next();
|
||||
@@ -695,12 +692,9 @@ public final class ForgeHooks {
|
||||
return modId;
|
||||
}
|
||||
|
||||
public static boolean onFarmlandTrample(Level level, BlockPos pos, BlockState state, float fallDistance, Entity entity) {
|
||||
if (entity.canTrample(state, pos, fallDistance)) {
|
||||
BlockEvent.FarmlandTrampleEvent event = new BlockEvent.FarmlandTrampleEvent(level, pos, state, fallDistance, entity);
|
||||
MinecraftForge.EVENT_BUS.post(event);
|
||||
return !event.isCanceled();
|
||||
}
|
||||
public static boolean onFarmlandTrample(ServerLevel level, BlockPos pos, BlockState state, float fallDistance, Entity entity) {
|
||||
if (entity.canTrample(level, state, pos, fallDistance))
|
||||
return !ForgeEventFactory.fireFarmlandTrampleEvent(level, pos, state, fallDistance, entity);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -711,17 +705,6 @@ public final class ForgeHooks {
|
||||
return event.getVanillaNoteId();
|
||||
}
|
||||
|
||||
public static boolean hasNoElements(Ingredient ingredient) {
|
||||
ItemStack[] items = ingredient.getItems();
|
||||
if (items.length == 0) return true;
|
||||
if (items.length == 1) {
|
||||
//If we potentially added a barrier due to the ingredient being an empty tag, try and check if it is the stack we added
|
||||
ItemStack item = items[0];
|
||||
return item.getItem() == Items.BARRIER && item.getHoverName() instanceof MutableComponent hoverName && hoverName.getString().startsWith("Empty Tag: ");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static EntityDataSerializer<?> getSerializer(int id, CrudeIncrementalIntIdentityHashBiMap<EntityDataSerializer<?>> vanilla) {
|
||||
EntityDataSerializer<?> serializer = vanilla.byId(id);
|
||||
@@ -745,34 +728,13 @@ public final class ForgeHooks {
|
||||
return id;
|
||||
}
|
||||
|
||||
public static boolean canEntityDestroy(Level level, BlockPos pos, LivingEntity entity) {
|
||||
public static boolean canEntityDestroy(ServerLevel level, BlockPos pos, LivingEntity entity) {
|
||||
if (!level.isLoaded(pos))
|
||||
return false;
|
||||
BlockState state = level.getBlockState(pos);
|
||||
return ForgeEventFactory.getMobGriefingEvent(level, entity) && state.canEntityDestroy(level, pos, entity) && ForgeEventFactory.onEntityDestroyBlock(entity, pos, state);
|
||||
}
|
||||
|
||||
private static final Map<Holder.Reference<Item>, Integer> VANILLA_BURNS = new HashMap<>();
|
||||
|
||||
/**
|
||||
* Gets the burn time of this itemstack.
|
||||
*/
|
||||
public static int getBurnTime(ItemStack stack, @Nullable RecipeType<?> recipeType) {
|
||||
if (stack.isEmpty())
|
||||
return 0;
|
||||
else {
|
||||
Item item = stack.getItem();
|
||||
int ret = stack.getBurnTime(recipeType);
|
||||
return ForgeEventFactory.getItemBurnTime(stack, ret == -1 ? VANILLA_BURNS.getOrDefault(ForgeRegistries.ITEMS.getDelegateOrThrow(item), 0) : ret, recipeType);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static synchronized void updateBurns() {
|
||||
VANILLA_BURNS.clear();
|
||||
FurnaceBlockEntity.getFuel().forEach((k, v) -> VANILLA_BURNS.put(ForgeRegistries.ITEMS.getDelegateOrThrow(k), v));
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the modification of loot table drops via the registered Global Loot Modifiers,
|
||||
* so that custom effects can be processed.
|
||||
@@ -787,10 +749,10 @@ public final class ForgeHooks {
|
||||
* @apiNote The given context will be modified by this method to also store the ID of the
|
||||
* loot table being queried.
|
||||
*/
|
||||
public static ObjectArrayList<ItemStack> modifyLoot(ResourceLocation lootTableId, ObjectArrayList<ItemStack> generatedLoot, LootContext context) {
|
||||
context.setQueriedLootTableId(lootTableId); // In case the ID was set via copy constructor, this will be ignored: intended
|
||||
public static ObjectArrayList<ItemStack> modifyLoot(LootTable table, ObjectArrayList<ItemStack> generatedLoot, LootContext context) {
|
||||
context.setQueriedLootTableId(table.getLootTableId()); // In case the ID was set via copy constructor, this will be ignored: intended
|
||||
for (var mod : ForgeInternalHandler.getLootModifierManager().getAllLootMods())
|
||||
generatedLoot = mod.apply(generatedLoot, context);
|
||||
generatedLoot = mod.apply(table, generatedLoot, context);
|
||||
return generatedLoot;
|
||||
}
|
||||
|
||||
@@ -976,8 +938,14 @@ public final class ForgeHooks {
|
||||
throw new IllegalArgumentException("Unknown lifecycle.");
|
||||
}
|
||||
|
||||
public static boolean shouldSuppressEnderManAnger(EnderMan enderMan, Player player, ItemStack mask) {
|
||||
return mask.isEnderMask(player, enderMan) || MinecraftForge.EVENT_BUS.post(new EnderManAngerEvent(enderMan, player));
|
||||
public static Predicate<LivingEntity> isNotDisguised(Monster monster) {
|
||||
return (entity) -> {
|
||||
if (!(entity instanceof Player player))
|
||||
return true;
|
||||
|
||||
var mask = player.getItemBySlot(EquipmentSlot.HEAD);
|
||||
return !mask.isMonsterDisguise(player, monster) || MinecraftForge.EVENT_BUS.post(new MonsterDisguiseEvent(monster, player));
|
||||
};
|
||||
}
|
||||
|
||||
private static final Lazy<Map<String, StructuresBecomeConfiguredFix.Conversion>> FORGE_CONVERSION_MAP = Lazy.concurrentOf(() -> {
|
||||
@@ -1031,6 +999,7 @@ public final class ForgeHooks {
|
||||
* @param refillAirAmount The amount of air to refill when the entity is able to breathe
|
||||
* @implNote This method needs to closely replicate the logic found right after the call site in {@link LivingEntity#baseTick()} as it overrides it.
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public static void onLivingBreathe(LivingEntity entity, int consumeAirAmount, int refillAirAmount) {
|
||||
// Check things that vanilla considers to be air - these will cause the air supply to be increased.
|
||||
boolean isAir = entity.getEyeInFluidType().isAir() || entity.level().getBlockState(BlockPos.containing(entity.getX(), entity.getEyeY(), entity.getZ())).is(Blocks.BUBBLE_COLUMN);
|
||||
@@ -1160,14 +1129,14 @@ public final class ForgeHooks {
|
||||
|
||||
@ApiStatus.Internal
|
||||
public static Packet<ClientGamePacketListener> getEntitySpawnPacket(Entity entity) {
|
||||
if (!(entity instanceof IEntityAdditionalSpawnData add))
|
||||
if (!(entity instanceof IEntityAdditionalSpawnData))
|
||||
throw new IllegalArgumentException(entity.getClass() + " is not an instance of " + IEntityAdditionalSpawnData.class);
|
||||
|
||||
return NetworkDirection.PLAY_TO_CLIENT.buildPacket(NetworkInitialization.PLAY, new SpawnEntity(entity));
|
||||
}
|
||||
|
||||
@ApiStatus.Internal
|
||||
public static boolean readAndTestCondition(RegistryOps<JsonElement> ops, JsonObject json) {
|
||||
public static boolean readAndTestCondition(DynamicOps<JsonElement> ops, JsonObject json) {
|
||||
if (!json.has(ICondition.DEFAULT_FIELD))
|
||||
return true;
|
||||
|
||||
@@ -1187,15 +1156,18 @@ public final class ForgeHooks {
|
||||
|
||||
@Nullable
|
||||
@ApiStatus.Internal
|
||||
public static JsonObject readConditionalAdvancement(RegistryOps<JsonElement> context, JsonObject json) {
|
||||
var entries = GsonHelper.getAsJsonArray(json, "advancements", null);
|
||||
public static JsonElement readConditional(DynamicOps<JsonElement> context, JsonElement json) {
|
||||
if (!json.isJsonObject())
|
||||
return json;
|
||||
|
||||
var entries = GsonHelper.getAsJsonArray(json.getAsJsonObject(), "forge:conditional", null);
|
||||
if (entries == null)
|
||||
return readAndTestCondition(context, json) ? json : null;
|
||||
return readAndTestCondition(context, json.getAsJsonObject()) ? json : null;
|
||||
|
||||
int idx = 0;
|
||||
for (var ele : entries) {
|
||||
if (!ele.isJsonObject())
|
||||
throw new JsonSyntaxException("Invalid advancement entry at index " + idx + " Must be JsonObject");
|
||||
throw new JsonSyntaxException("Invalid forge:conditonal entry at index " + idx + " Must be JsonObject");
|
||||
|
||||
if (readAndTestCondition(context, ele.getAsJsonObject()))
|
||||
return ele.getAsJsonObject();
|
||||
@@ -1207,7 +1179,7 @@ public final class ForgeHooks {
|
||||
}
|
||||
|
||||
@ApiStatus.Internal
|
||||
public static Codec<Ingredient> enhanceIngredientCodec(Codec<Ingredient> vanilla) {
|
||||
public static Codec<Ingredient> ingredientBaseCodec(Codec<Ingredient> vanilla) {
|
||||
return Codec.lazyInitialized(() ->
|
||||
Codec.<Ingredient, Ingredient>either(
|
||||
ForgeRegistries.INGREDIENT_SERIALIZERS.get().getCodec().dispatch(Ingredient::serializer, IIngredientSerializer::codec),
|
||||
@@ -1223,39 +1195,31 @@ public final class ForgeHooks {
|
||||
public static StreamCodec<RegistryFriendlyByteBuf, Ingredient> ingredientStreamCodec() {
|
||||
return StreamCodec.<RegistryFriendlyByteBuf, Ingredient>of(
|
||||
(buf, value) -> {
|
||||
if (value.isVanilla()) {
|
||||
var items = value.getItems();
|
||||
ByteBufCodecs.writeCount(buf, items.length, Integer.MAX_VALUE);
|
||||
for (var item : items) {
|
||||
ItemStack.STREAM_CODEC.encode(buf, item);
|
||||
}
|
||||
} else {
|
||||
@SuppressWarnings("unchecked")
|
||||
var serializer = (IIngredientSerializer<Ingredient>)value.serializer();
|
||||
@SuppressWarnings("unchecked")
|
||||
var serializer = (IIngredientSerializer<Ingredient>)value.serializer();
|
||||
if (!value.isVanilla()) {
|
||||
var key = ForgeRegistries.INGREDIENT_SERIALIZERS.get().getKey(serializer);
|
||||
if (key == null)
|
||||
throw new IllegalArgumentException("Tried to write unregistered Ingredient to network: " + value);
|
||||
|
||||
buf.writeVarInt(-1); // Our Marker
|
||||
buf.writeResourceLocation(key);
|
||||
serializer.write(buf, value);
|
||||
}
|
||||
serializer.write(buf, value);
|
||||
},
|
||||
(buf) -> {
|
||||
var size = ByteBufCodecs.readCount(buf, Integer.MAX_VALUE);
|
||||
buf.markReaderIndex();
|
||||
var size = VarInt.read(buf);
|
||||
IIngredientSerializer<?> serializer = Ingredient.VANILLA_SERIALIZER;
|
||||
if (size != -1) {
|
||||
var ret = NonNullList.<ItemStack>createWithCapacity(size);
|
||||
for (int x = 0; x < size; x++) {
|
||||
ret.add(ItemStack.STREAM_CODEC.decode(buf));
|
||||
}
|
||||
return Ingredient.fromValues(ret.stream().map(Ingredient.ItemValue::new));
|
||||
buf.resetReaderIndex();
|
||||
} else {
|
||||
var key = buf.readResourceLocation();
|
||||
var serializer = ForgeRegistries.INGREDIENT_SERIALIZERS.get().getValue(key);
|
||||
serializer = ForgeRegistries.INGREDIENT_SERIALIZERS.get().getValue(key);
|
||||
if (serializer == null)
|
||||
throw new DecoderException("Could not read ingredient of type: " + key);
|
||||
return serializer.read(buf);
|
||||
}
|
||||
return serializer.read(buf);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ import java.util.Objects;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
//TODO, this should be re-evaluated now that ITextComponents are passed everywhere instaed of strings.
|
||||
//TODO, this should be re-evaluated now that ITextComponents are passed everywhere instead of strings.
|
||||
public class ForgeI18n {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
// From FontRenderer.renderCharAtPos
|
||||
|
||||
@@ -18,16 +18,15 @@ import net.minecraftforge.event.entity.EntityJoinLevelEvent;
|
||||
import net.minecraftforge.event.entity.player.PlayerEvent;
|
||||
import net.minecraftforge.event.level.ChunkEvent;
|
||||
import net.minecraftforge.event.network.ConnectionStartEvent;
|
||||
import net.minecraftforge.event.server.ServerStoppingEvent;
|
||||
import net.minecraftforge.eventbus.api.EventPriority;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.event.TagsUpdatedEvent;
|
||||
import net.minecraftforge.event.TickEvent;
|
||||
import net.minecraftforge.event.TickEvent.ClientTickEvent;
|
||||
import net.minecraftforge.event.TickEvent.ServerTickEvent;
|
||||
import net.minecraftforge.fml.LogicalSide;
|
||||
import net.minecraftforge.network.filters.NetworkFilters;
|
||||
import net.minecraftforge.common.util.LogicalSidedProvider;
|
||||
import net.minecraftforge.server.command.ForgeCommand;
|
||||
import net.minecraftforge.server.permission.events.PermissionGatherEvent;
|
||||
import net.minecraftforge.server.command.ConfigCommand;
|
||||
|
||||
public class ForgeInternalHandler {
|
||||
@@ -44,7 +43,7 @@ public class ForgeInternalHandler {
|
||||
event.setCanceled(true);
|
||||
@SuppressWarnings("resource")
|
||||
var executor = LogicalSidedProvider.WORKQUEUE.get(event.getLevel().isClientSide ? LogicalSide.CLIENT : LogicalSide.SERVER);
|
||||
executor.tell(new TickTask(0, () -> event.getLevel().addFreshEntity(newEntity)));
|
||||
executor.schedule(new TickTask(0, () -> event.getLevel().addFreshEntity(newEntity)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,12 +84,6 @@ public class ForgeInternalHandler {
|
||||
UsernameCache.setUsername(event.getEntity().getUUID(), event.getEntity().getGameProfile().getName());
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void tagsUpdated(TagsUpdatedEvent event) {
|
||||
if (event.shouldUpdateStaticData())
|
||||
ForgeHooks.updateBurns();
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onCommandsRegister(RegisterCommandsEvent event) {
|
||||
new ForgeCommand(event.getDispatcher());
|
||||
@@ -126,5 +119,16 @@ public class ForgeInternalHandler {
|
||||
public void onConnectionStart(ConnectionStartEvent event) {
|
||||
NetworkFilters.injectIfNecessary(event.getConnection());
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void serverStopping(ServerStoppingEvent evt) {
|
||||
WorldWorkerManager.clear();
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void registerPermissionNodes(PermissionGatherEvent.Nodes event) {
|
||||
event.addNodes(ForgeMod.USE_SELECTORS_PERMISSION);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -28,7 +28,6 @@ import net.minecraft.world.entity.ai.attributes.Attribute;
|
||||
import net.minecraft.world.entity.ai.attributes.RangedAttribute;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
import net.minecraft.world.item.ItemDisplayContext;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import net.minecraft.world.item.crafting.RecipeSerializer;
|
||||
import net.minecraft.world.level.BlockAndTintGetter;
|
||||
import net.minecraft.world.level.BlockGetter;
|
||||
@@ -62,8 +61,8 @@ 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.TagsUpdatedEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fluids.FluidType;
|
||||
import net.minecraftforge.fluids.ForgeFlowingFluid;
|
||||
import net.minecraftforge.fml.*;
|
||||
@@ -78,11 +77,10 @@ import net.minecraftforge.registries.holdersets.NotHolderSet;
|
||||
import net.minecraftforge.registries.holdersets.OrHolderSet;
|
||||
import net.minecraftforge.network.NetworkInitialization;
|
||||
import net.minecraftforge.network.tasks.ForgeNetworkConfigurationHandler;
|
||||
import net.minecraftforge.event.server.ServerStoppingEvent;
|
||||
import net.minecraftforge.event.entity.EntityAttributeModificationEvent;
|
||||
import net.minecraftforge.data.event.GatherDataEvent;
|
||||
import net.minecraftforge.server.command.EnumArgument;
|
||||
import net.minecraftforge.server.command.ModIdArgument;
|
||||
import net.minecraftforge.server.permission.events.PermissionGatherEvent;
|
||||
import net.minecraftforge.server.permission.nodes.PermissionNode;
|
||||
import net.minecraftforge.server.permission.nodes.PermissionTypes;
|
||||
import net.minecraftforge.unsafe.UnsafeHacks;
|
||||
@@ -393,25 +391,22 @@ public class ForgeMod {
|
||||
modEventBus.addListener(this::gatherData);
|
||||
modEventBus.addListener(this::registerFluids);
|
||||
modEventBus.addListener(this::registerVanillaDisplayContexts);
|
||||
for (DeferredRegister<?> r : registries) {
|
||||
r.register(modEventBus);
|
||||
}
|
||||
modEventBus.addListener(this::onRegisterAttributes);
|
||||
ForgeDeferredRegistriesSetup.setup(modEventBus);
|
||||
for (var reg : registries)
|
||||
reg.register(modEventBus);
|
||||
|
||||
MinecraftForge.EVENT_BUS.addListener(this::serverStopping);
|
||||
context.registerConfig(ModConfig.Type.CLIENT, ForgeConfig.clientSpec);
|
||||
context.registerConfig(ModConfig.Type.SERVER, ForgeConfig.serverSpec);
|
||||
context.registerConfig(ModConfig.Type.COMMON, ForgeConfig.commonSpec);
|
||||
modEventBus.register(ForgeConfig.class);
|
||||
ForgeDeferredRegistriesSetup.setup(modEventBus);
|
||||
|
||||
// Forge does not display problems when the remote is not matching.
|
||||
context.registerDisplayTest(IExtensionPoint.DisplayTest.IGNORE_ALL_VERSION);
|
||||
StartupMessageManager.addModMessage("Forge version "+ForgeVersion.getVersion());
|
||||
|
||||
MinecraftForge.EVENT_BUS.addListener(VillagerTradingManager::loadTrades);
|
||||
MinecraftForge.EVENT_BUS.register(MinecraftForge.INTERNAL_HANDLER);
|
||||
MinecraftForge.EVENT_BUS.addListener(this::mappingChanged);
|
||||
MinecraftForge.EVENT_BUS.addListener(this::tagsUpdated);
|
||||
MinecraftForge.EVENT_BUS.addListener(this::registerPermissionNodes);
|
||||
MinecraftForge.EVENT_BUS.register(new ForgeNetworkConfigurationHandler());
|
||||
|
||||
ForgeRegistries.ITEMS.tags().addOptionalTagDefaults(Tags.Items.ENCHANTING_FUELS, Set.of(ForgeRegistries.ITEMS.getDelegateOrThrow(Items.LAPIS_LAZULI)));
|
||||
@@ -426,16 +421,13 @@ public class ForgeMod {
|
||||
//VanillaPacketSplitter.register();
|
||||
}
|
||||
|
||||
public void serverStopping(ServerStoppingEvent evt) {
|
||||
WorldWorkerManager.clear();
|
||||
}
|
||||
|
||||
public void mappingChanged(IdMappingEvent evt) {
|
||||
Ingredient.invalidateAll();
|
||||
}
|
||||
|
||||
public void tagsUpdated(TagsUpdatedEvent evt) {
|
||||
Ingredient.invalidateAll();
|
||||
@SubscribeEvent
|
||||
public void onRegisterAttributes(EntityAttributeModificationEvent event) {
|
||||
for (var type : event.getTypes()) {
|
||||
event.add(type, ForgeMod.SWIM_SPEED.getHolder().get());
|
||||
event.add(type, ForgeMod.NAMETAG_DISTANCE.getHolder().get());
|
||||
}
|
||||
}
|
||||
|
||||
public void gatherData(GatherDataEvent event) {
|
||||
@@ -457,7 +449,7 @@ public class ForgeMod {
|
||||
gen.addProvider(event.includeServer(), new ForgeEntityTypeTagsProvider(packOutput, lookupProvider, existingFileHelper));
|
||||
gen.addProvider(event.includeServer(), new ForgeFluidTagsProvider(packOutput, lookupProvider, existingFileHelper));
|
||||
gen.addProvider(event.includeServer(), new ForgeEnchantmentTagsProvider(packOutput, lookupProvider, existingFileHelper));
|
||||
gen.addProvider(event.includeServer(), new ForgeRecipeProvider(packOutput, lookupProvider));
|
||||
gen.addProvider(event.includeServer(), new ForgeRecipeProvider.Runner(packOutput, lookupProvider));
|
||||
gen.addProvider(event.includeServer(), new ForgeLootTableProvider(packOutput, lookupProvider));
|
||||
gen.addProvider(event.includeServer(), new ForgeBiomeTagsProvider(packOutput, lookupProvider, existingFileHelper));
|
||||
gen.addProvider(event.includeServer(), new ForgeStructureTagsProvider(packOutput, lookupProvider, existingFileHelper));
|
||||
@@ -526,10 +518,6 @@ public class ForgeMod {
|
||||
public static final PermissionNode<Boolean> USE_SELECTORS_PERMISSION = new PermissionNode<>("forge", "use_entity_selectors",
|
||||
PermissionTypes.BOOLEAN, (player, uuid, contexts) -> player != null && player.hasPermissions(Commands.LEVEL_GAMEMASTERS));
|
||||
|
||||
public void registerPermissionNodes(PermissionGatherEvent.Nodes event) {
|
||||
event.addNodes(USE_SELECTORS_PERMISSION);
|
||||
}
|
||||
|
||||
/**
|
||||
* TODO: Remove when {@link ForgeRegistry#addAlias(ResourceLocation, ResourceLocation)} is elevated to {@link IForgeRegistry}.
|
||||
*/
|
||||
|
||||
@@ -7,10 +7,10 @@ package net.minecraftforge.common;
|
||||
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.dispenser.DispenseItemBehavior;
|
||||
import net.minecraft.util.FastColor;
|
||||
import net.minecraft.util.ARGB;
|
||||
import net.minecraft.world.entity.EntitySpawnReason;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.Mob;
|
||||
import net.minecraft.world.entity.MobSpawnType;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.SpawnEggItem;
|
||||
import net.minecraft.world.level.block.DispenserBlock;
|
||||
@@ -47,6 +47,7 @@ public class ForgeSpawnEggItem extends SpawnEggItem {
|
||||
return DEFAULT_DISPENSE_BEHAVIOR;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@Nullable
|
||||
public static SpawnEggItem fromEntityType(@Nullable EntityType<?> type) {
|
||||
SpawnEggItem ret = TYPE_MAP.get(type);
|
||||
@@ -63,7 +64,7 @@ public class ForgeSpawnEggItem extends SpawnEggItem {
|
||||
EntityType<?> type = ((SpawnEggItem)stack.getItem()).getType(stack);
|
||||
|
||||
try {
|
||||
type.spawn(source.level(), stack, null, source.pos().relative(face), MobSpawnType.DISPENSER, face != Direction.UP, false);
|
||||
type.spawn(source.level(), stack, null, source.pos().relative(face), EntitySpawnReason.DISPENSER, face != Direction.UP, false);
|
||||
} catch (Exception exception) {
|
||||
DispenseItemBehavior.LOGGER.error("Error while dispensing spawn egg from dispenser at {}", source.pos(), exception);
|
||||
return ItemStack.EMPTY;
|
||||
@@ -95,8 +96,8 @@ public class ForgeSpawnEggItem extends SpawnEggItem {
|
||||
for (ForgeSpawnEggItem egg : MOD_EGGS) {
|
||||
event.register((stack, layer) -> {
|
||||
int color = egg.getColor(layer);
|
||||
if (FastColor.ARGB32.alpha(color) == 0)
|
||||
color = FastColor.ARGB32.opaque(color);
|
||||
if (ARGB.alpha(color) == 0)
|
||||
color = ARGB.opaque(color);
|
||||
return color;
|
||||
}, egg);
|
||||
}
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.item.Tier;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Helper class to define a custom tier
|
||||
*/
|
||||
@SuppressWarnings("ClassCanBeRecord") // can't make it a record because the method names will be obfuscated
|
||||
public final class ForgeTier implements Tier {
|
||||
private final int uses;
|
||||
private final float speed;
|
||||
private final float attackDamageBonus;
|
||||
private final int enchantmentValue;
|
||||
@NotNull
|
||||
private final TagKey<Block> tag;
|
||||
@NotNull
|
||||
private final Supplier<Ingredient> repairIngredient;
|
||||
@NotNull
|
||||
public final TagKey<Block> incorrectBlocks;
|
||||
|
||||
public ForgeTier(int uses, float speed, float attackDamageBonus, int enchantmentValue,
|
||||
@NotNull TagKey<Block> tag, @NotNull Supplier<Ingredient> repairIngredient,
|
||||
@NotNull TagKey<Block> incorrectBlocks) {
|
||||
this.uses = uses;
|
||||
this.speed = speed;
|
||||
this.attackDamageBonus = attackDamageBonus;
|
||||
this.enchantmentValue = enchantmentValue;
|
||||
this.tag = tag;
|
||||
this.repairIngredient = repairIngredient;
|
||||
this.incorrectBlocks = incorrectBlocks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getUses() {
|
||||
return this.uses;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getSpeed() {
|
||||
return this.speed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getAttackDamageBonus() {
|
||||
return this.attackDamageBonus;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getEnchantmentValue() {
|
||||
return this.enchantmentValue;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public TagKey<Block> getTag() {
|
||||
return this.tag;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TagKey<Block> getIncorrectBlocksForDrops() {
|
||||
return this.incorrectBlocks;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public Ingredient getRepairIngredient() {
|
||||
return this.repairIngredient.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ForgeTier[" +
|
||||
"uses=" + uses + ", " +
|
||||
"speed=" + speed + ", " +
|
||||
"attackDamageBonus=" + attackDamageBonus + ", " +
|
||||
"enchantmentValue=" + enchantmentValue + ", " +
|
||||
"tag=" + tag + ", " +
|
||||
"incorrect=" + incorrectBlocks+ ", " +
|
||||
"repairIngredient=" + repairIngredient + ']';
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.vehicle.AbstractMinecart;
|
||||
|
||||
/**
|
||||
* This class defines a replacement for the default minecart collision code.
|
||||
* Only one handler can be registered at a time. It it registered with AbstractMinecartEntity.registerCollisionHandler().
|
||||
* If you use this, make it a configuration option.
|
||||
* @author CovertJaguar
|
||||
*/
|
||||
public interface IMinecartCollisionHandler
|
||||
{
|
||||
|
||||
/**
|
||||
* This basically replaces the function of the same name in EntityMinecart.
|
||||
* Code in IMinecartHooks.applyEntityCollisionHook is still run.
|
||||
* @param cart The cart that called the collision.
|
||||
* @param other The object it collided with.
|
||||
*/
|
||||
void onEntityCollision(AbstractMinecart cart, Entity other);
|
||||
|
||||
/**
|
||||
* This function replaced the function of the same name in EntityMinecart.
|
||||
* It is used to define whether minecarts collide with specific entities,
|
||||
* for example items.
|
||||
* @param cart The cart for which the collision box was requested.
|
||||
* @param other The entity requesting the collision box.
|
||||
* @return The collision box or null.
|
||||
*/
|
||||
AABB getCollisionBox(AbstractMinecart cart, Entity other);
|
||||
|
||||
/**
|
||||
* This function is used to define the box used for detecting minecart collisions.
|
||||
* It is generally bigger that the normal collision box.
|
||||
* @param cart The cart for which the collision box was requested.
|
||||
* @return The collision box, cannot be null.
|
||||
*/
|
||||
AABB getMinecartCollisionBox(AbstractMinecart cart);
|
||||
|
||||
/**
|
||||
* This function replaces the function of the same name in EntityMinecart.
|
||||
* It defines whether minecarts are solid to the player.
|
||||
* @param cart The cart for which the bounding box was requested.
|
||||
* @return The bounding box or null.
|
||||
*/
|
||||
AABB getBoundingBox(AbstractMinecart cart);
|
||||
}
|
||||
|
||||
@@ -23,14 +23,11 @@ import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class MinecraftForge
|
||||
{
|
||||
|
||||
public class MinecraftForge {
|
||||
/**
|
||||
* The EventBus for all the Forge Events.
|
||||
*
|
||||
@@ -46,8 +43,7 @@ public class MinecraftForge
|
||||
/**
|
||||
* Method invoked by FML before any other mods are loaded.
|
||||
*/
|
||||
public static void initialize()
|
||||
{
|
||||
public static void initialize() {
|
||||
LOGGER.info(FORGE,"MinecraftForge v{} Initialized", ForgeVersion.getVersion());
|
||||
|
||||
UsernameCache.load();
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.TagKey;
|
||||
@@ -47,7 +48,10 @@ public final class TagConventionMigrationHelper {
|
||||
registryAccess.registries().forEach(registryEntry -> {
|
||||
if (registryEntry.key().location().getNamespace().equals(ResourceLocation.DEFAULT_NAMESPACE)) {
|
||||
FOUND_LEGACY_TAGS.addAll(
|
||||
registryEntry.value().getTagNames().filter(TagConventionMappings.MAPPINGS::containsKey).toList()
|
||||
registryEntry.value().getTags()
|
||||
.map(HolderSet.Named::key)
|
||||
.filter(TagConventionMappings.MAPPINGS::containsKey)
|
||||
.toList()
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -60,7 +64,7 @@ public final class TagConventionMigrationHelper {
|
||||
Warning for mod devs: Found known legacy tags that have direct common convention equivalents - consider migrating these to improve compatibility with other mods.
|
||||
Note: This feature isn't fully comprehensive - see Forge's net.minecraftforge.common.Tags class for a full list of tags.
|
||||
You can disable this message by setting "migrationHelperMode" to "OFF" in Forge's common config.
|
||||
|
||||
|
||||
Here are some suggestions for replacements:""".stripIndent());
|
||||
|
||||
for (var legacyTag : FOUND_LEGACY_TAGS) {
|
||||
|
||||
@@ -84,7 +84,7 @@ public class ConditionalAdvancement {
|
||||
public JsonObject build(HolderLookup.Provider lookup) {
|
||||
var json = new JsonObject();
|
||||
var array = new JsonArray();
|
||||
json.add("advancements", array);
|
||||
json.add("forge:conditional", array);
|
||||
|
||||
var ops = lookup.createSerializationContext(JsonOps.INSTANCE);
|
||||
|
||||
|
||||
@@ -28,17 +28,21 @@ import net.minecraft.advancements.Advancement;
|
||||
import net.minecraft.advancements.AdvancementHolder;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.HolderLookup.Provider;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.data.recipes.RecipeBuilder;
|
||||
import net.minecraft.data.recipes.RecipeOutput;
|
||||
import net.minecraft.world.Container;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.CraftingInput;
|
||||
import net.minecraft.world.item.crafting.PlacementInfo;
|
||||
import net.minecraft.world.item.crafting.Recipe;
|
||||
import net.minecraft.world.item.crafting.RecipeBookCategories;
|
||||
import net.minecraft.world.item.crafting.RecipeBookCategory;
|
||||
import net.minecraft.world.item.crafting.RecipeSerializer;
|
||||
import net.minecraft.world.item.crafting.RecipeType;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraftforge.common.crafting.conditions.ConditionCodec;
|
||||
import net.minecraftforge.common.crafting.conditions.ICondition;
|
||||
@@ -50,7 +54,7 @@ import org.jetbrains.annotations.Nullable;
|
||||
* disabling the entire recipe, it has sub-recipes that themselves have conditions.
|
||||
*
|
||||
* And when being deserialized it returns the first entry that passes the conditional check.
|
||||
* This basically means that you can have muultiple variants all use the same recipe name, and
|
||||
* This basically means that you can have multiple variants all use the same recipe name, and
|
||||
* only one will ever be loaded.
|
||||
*
|
||||
* This also means that you can wrap ALL recipes in a Conditional even those that don't explicitly
|
||||
@@ -67,7 +71,7 @@ public class ConditionalRecipe {
|
||||
|
||||
private final RecipeOutput bouncer = new RecipeOutput() {
|
||||
@Override
|
||||
public void accept(ResourceLocation id, Recipe<?> value, @Nullable AdvancementHolder advancement) {
|
||||
public void accept(ResourceKey<Recipe<?>> id, Recipe<?> value, @Nullable AdvancementHolder advancement) {
|
||||
recipe(id, value, advancement);
|
||||
}
|
||||
|
||||
@@ -78,7 +82,7 @@ public class ConditionalRecipe {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(ResourceLocation id, Recipe<?> recipe, ResourceLocation advancementId, JsonElement advancement) {
|
||||
public void accept(ResourceKey<Recipe<?>> id, Recipe<?> recipe, ResourceLocation advancementId, JsonElement advancement) {
|
||||
AdvancementHolder holder = null;
|
||||
if (advancement != null) {
|
||||
Advancement adv = Advancement.CODEC.parse(JsonOps.INSTANCE, advancement).getOrThrow(JsonParseException::new);
|
||||
@@ -91,6 +95,9 @@ public class ConditionalRecipe {
|
||||
public Provider registry() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void includeRootAdvancement() { }
|
||||
};
|
||||
|
||||
@Nullable
|
||||
@@ -120,7 +127,7 @@ public class ConditionalRecipe {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder recipe(ResourceLocation id, Recipe<?> recipe, @Nullable AdvancementHolder advancement) {
|
||||
public Builder recipe(ResourceKey<Recipe<?>> id, Recipe<?> recipe, @Nullable AdvancementHolder advancement) {
|
||||
if (condition == null)
|
||||
throw new IllegalStateException("Can not add a recipe with no conditions.");
|
||||
recipes.add(new InnerRecipe(this.condition, recipe));
|
||||
@@ -163,7 +170,8 @@ public class ConditionalRecipe {
|
||||
advancementId = null;
|
||||
}
|
||||
|
||||
out.accept(id, new Wrapper(mainCondition, recipes), advancementId, advancement);
|
||||
var key = ResourceKey.create(Registries.RECIPE, id);
|
||||
out.accept(key, new Wrapper(mainCondition, recipes), advancementId, advancement);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,10 +181,14 @@ public class ConditionalRecipe {
|
||||
private static class Wrapper implements Recipe<CraftingInput> {
|
||||
@Override public boolean matches(CraftingInput inv, Level level) { return false; }
|
||||
@Override public ItemStack assemble(CraftingInput inv, HolderLookup.Provider reg) { return null; }
|
||||
@Override public boolean canCraftInDimensions(int width, int height) { return false; }
|
||||
@Override public ItemStack getResultItem(HolderLookup.Provider reg) { return null; }
|
||||
@Override public RecipeSerializer<?> getSerializer() { return ConditionalRecipe.SERIALZIER; }
|
||||
@Override public RecipeType<?> getType() { throw new UnsupportedOperationException(); }
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
@Override
|
||||
public RecipeSerializer<? extends Recipe<CraftingInput>> getSerializer() {
|
||||
return (RecipeSerializer)ConditionalRecipe.SERIALZIER;
|
||||
}
|
||||
|
||||
@Override public RecipeType<? extends Recipe<CraftingInput>> getType() { throw new UnsupportedOperationException(); }
|
||||
|
||||
@Nullable private final ICondition main;
|
||||
private final List<InnerRecipe> recipes;
|
||||
@@ -185,6 +197,16 @@ public class ConditionalRecipe {
|
||||
this.recipes = recipes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlacementInfo placementInfo() {
|
||||
return PlacementInfo.NOT_PLACEABLE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RecipeBookCategory recipeBookCategory() {
|
||||
return RecipeBookCategories.STONECUTTER;
|
||||
}
|
||||
|
||||
}
|
||||
private static final MapCodec<Recipe<?>> CODEC = Codec.of(new MapEncoder.Implementation<>() {
|
||||
@Override
|
||||
|
||||
@@ -7,36 +7,27 @@ package net.minecraftforge.common.crafting.conditions;
|
||||
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.TagManager;
|
||||
import net.minecraft.tags.TagKey;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
|
||||
public class ConditionContext implements ICondition.IContext {
|
||||
private final TagManager tagManager;
|
||||
private Map<ResourceKey<?>, Map<ResourceLocation, Collection<Holder<?>>>> loadedTags = null;
|
||||
private final List<Registry.PendingTags<?>> pendingTags;
|
||||
|
||||
public ConditionContext(TagManager tagManager) {
|
||||
this.tagManager = tagManager;
|
||||
public ConditionContext(List<Registry.PendingTags<?>> pendingTags) {
|
||||
this.pendingTags = pendingTags;
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
@Override
|
||||
public <T> Map<ResourceLocation, Collection<Holder<T>>> getAllTags(ResourceKey<? extends Registry<T>> registry) {
|
||||
if (loadedTags == null) {
|
||||
var tags = tagManager.getResult();
|
||||
if (tags.isEmpty()) throw new IllegalStateException("Tags have not been loaded yet.");
|
||||
|
||||
loadedTags = new IdentityHashMap<>();
|
||||
for (var loadResult : tags) {
|
||||
var map = Collections.unmodifiableMap(loadResult.tags());
|
||||
loadedTags.put(loadResult.key(), (Map)map);
|
||||
}
|
||||
public <T> Collection<Holder<T>> getTag(TagKey<T> key) {
|
||||
for (var entry : this.pendingTags) {
|
||||
if (entry.key() != key.registry())
|
||||
continue;
|
||||
@SuppressWarnings("unchecked")
|
||||
var typed = ((Registry.PendingTags<T>)entry);
|
||||
return typed.getPending(key);
|
||||
}
|
||||
return (Map)loadedTags.getOrDefault(registry, Collections.emptyMap());
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
@@ -42,14 +42,14 @@ public interface ICondition {
|
||||
|
||||
IContext EMPTY = new IContext() {
|
||||
@Override
|
||||
public <T> Map<ResourceLocation, Collection<Holder<T>>> getAllTags(ResourceKey<? extends Registry<T>> registry) {
|
||||
return Collections.emptyMap();
|
||||
public <T> Collection<Holder<T>> getTag(TagKey<T> key) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
};
|
||||
|
||||
IContext TAGS_INVALID = new IContext() {
|
||||
@Override
|
||||
public <T> Map<ResourceLocation, Collection<Holder<T>>> getAllTags(ResourceKey<? extends Registry<T>> registry) {
|
||||
public <T> Collection<Holder<T>> getTag(TagKey<T> key) {
|
||||
throw new UnsupportedOperationException("Usage of tag-based conditions is not permitted in this context!");
|
||||
}
|
||||
};
|
||||
@@ -57,14 +57,6 @@ public interface ICondition {
|
||||
/**
|
||||
* Return the requested tag if available, or an empty tag otherwise.
|
||||
*/
|
||||
default <T> Collection<Holder<T>> getTag(TagKey<T> key) {
|
||||
return getAllTags(key.registry()).getOrDefault(key.location(), Set.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all the loaded tags for the passed registry, or an empty map if none is available.
|
||||
* Note that the map and the tags are unmodifiable.
|
||||
*/
|
||||
<T> Map<ResourceLocation, Collection<Holder<T>>> getAllTags(ResourceKey<? extends Registry<T>> registry);
|
||||
<T> Collection<Holder<T>> getTag(TagKey<T> key);
|
||||
}
|
||||
}
|
||||
+4
-17
@@ -5,12 +5,12 @@
|
||||
|
||||
package net.minecraftforge.common.crafting.ingredients;
|
||||
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import net.minecraft.world.level.ItemLike;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Extension of {@link Ingredient} which makes most methods custom ingredients need to implement abstract, and removes the static constructors
|
||||
@@ -19,12 +19,11 @@ import java.util.stream.Stream;
|
||||
public abstract class AbstractIngredient extends Ingredient {
|
||||
/** Empty constructor, for the sake of dynamic ingredients */
|
||||
protected AbstractIngredient() {
|
||||
super(Stream.of());
|
||||
super(HolderSet.empty(), false);
|
||||
}
|
||||
|
||||
/** Value constructor, for ingredients that have some vanilla representation */
|
||||
protected AbstractIngredient(Stream<? extends Value> values) {
|
||||
super(values);
|
||||
protected AbstractIngredient(HolderSet<Item> items) {
|
||||
super(items);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -36,12 +35,6 @@ public abstract class AbstractIngredient extends Ingredient {
|
||||
|
||||
/* Hide vanilla ingredient static constructors to reduce errors with constructing custom ingredients */
|
||||
|
||||
/** @deprecated use {@link Ingredient#fromValues(Stream)} */
|
||||
@Deprecated
|
||||
public static Ingredient fromValues(Stream<? extends Ingredient.Value> values) {
|
||||
throw new UnsupportedOperationException("Use Ingredient.fromValues()");
|
||||
}
|
||||
|
||||
/** @deprecated use {@link Ingredient#of()} */
|
||||
@Deprecated
|
||||
public static Ingredient of() {
|
||||
@@ -60,12 +53,6 @@ public abstract class AbstractIngredient extends Ingredient {
|
||||
throw new UnsupportedOperationException("Use Ingredient.of()");
|
||||
}
|
||||
|
||||
/** @deprecated use {@link Ingredient#of(Stream)} (Stream)} */
|
||||
@Deprecated
|
||||
public static Ingredient of(Stream<ItemStack> stacks) {
|
||||
throw new UnsupportedOperationException("Use Ingredient.of()");
|
||||
}
|
||||
|
||||
/** @deprecated use {@link Ingredient#of(TagKey)} (Stream)} */
|
||||
@Deprecated
|
||||
public static Ingredient of(TagKey<Item> tag) {
|
||||
|
||||
+17
-38
@@ -9,15 +9,13 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntComparators;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
@@ -36,8 +34,7 @@ public class CompoundIngredient extends AbstractIngredient {
|
||||
}
|
||||
|
||||
private final List<Ingredient> children;
|
||||
private ItemStack[] stacks;
|
||||
private IntList itemIds;
|
||||
private List<Holder<Item>> items;
|
||||
private final boolean isSimple;
|
||||
|
||||
private CompoundIngredient(List<Ingredient> children) {
|
||||
@@ -47,32 +44,14 @@ public class CompoundIngredient extends AbstractIngredient {
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public ItemStack[] getItems() {
|
||||
if (stacks == null) {
|
||||
List<ItemStack> tmp = Lists.newArrayList();
|
||||
for (Ingredient child : children)
|
||||
Collections.addAll(tmp, child.getItems());
|
||||
stacks = tmp.toArray(new ItemStack[tmp.size()]);
|
||||
|
||||
public List<Holder<Item>> items() {
|
||||
if (this.items == null) {
|
||||
var tmp = new ArrayList<Holder<Item>>();
|
||||
for (var child : children)
|
||||
tmp.addAll(child.items());
|
||||
this.items = Collections.unmodifiableList(tmp);
|
||||
}
|
||||
return stacks;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public IntList getStackingIds() {
|
||||
boolean childrenNeedInvalidation = false;
|
||||
for (Ingredient child : children)
|
||||
childrenNeedInvalidation |= child.checkInvalidation();
|
||||
if (childrenNeedInvalidation || this.itemIds == null || checkInvalidation()) {
|
||||
this.markValid();
|
||||
this.itemIds = new IntArrayList();
|
||||
for (Ingredient child : children)
|
||||
this.itemIds.addAll(child.getStackingIds());
|
||||
this.itemIds.sort(IntComparators.NATURAL_COMPARATOR);
|
||||
}
|
||||
|
||||
return this.itemIds;
|
||||
return this.items;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -80,7 +59,12 @@ public class CompoundIngredient extends AbstractIngredient {
|
||||
if (target == null)
|
||||
return false;
|
||||
|
||||
return children.stream().anyMatch(c -> c.test(target));
|
||||
for (var child : children) {
|
||||
if (child.test(target))
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -88,11 +72,6 @@ public class CompoundIngredient extends AbstractIngredient {
|
||||
return isSimple;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return children.stream().allMatch(Ingredient::isEmpty);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IIngredientSerializer<? extends Ingredient> serializer() {
|
||||
return SERIALIZER;
|
||||
@@ -100,7 +79,7 @@ public class CompoundIngredient extends AbstractIngredient {
|
||||
|
||||
public static final MapCodec<CompoundIngredient> CODEC = RecordCodecBuilder.mapCodec(builder ->
|
||||
builder.group(
|
||||
Ingredient.CODEC_NONEMPTY.listOf().fieldOf("children").forGetter(i -> i.children)
|
||||
Ingredient.CODEC.listOf().fieldOf("children").forGetter(i -> i.children)
|
||||
).apply(builder, CompoundIngredient::new)
|
||||
);
|
||||
|
||||
|
||||
+24
-38
@@ -8,16 +8,16 @@ package net.minecraftforge.common.crafting.ingredients;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntComparators;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.world.entity.player.StackedContents;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/** Ingredient that matches everything from the first ingredient that is not included in the second ingredient */
|
||||
public class DifferenceIngredient extends AbstractIngredient {
|
||||
@@ -33,8 +33,7 @@ public class DifferenceIngredient extends AbstractIngredient {
|
||||
|
||||
private final Ingredient base;
|
||||
private final Ingredient subtracted;
|
||||
private ItemStack[] filteredMatchingStacks;
|
||||
private IntList packedMatchingStacks;
|
||||
private List<Holder<Item>> items = null;
|
||||
|
||||
private DifferenceIngredient(Ingredient base, Ingredient subtracted) {
|
||||
this.base = base;
|
||||
@@ -48,18 +47,26 @@ public class DifferenceIngredient extends AbstractIngredient {
|
||||
return base.test(stack) && !subtracted.test(stack);
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@Override
|
||||
public ItemStack[] getItems() {
|
||||
if (this.filteredMatchingStacks == null)
|
||||
this.filteredMatchingStacks = Arrays.stream(base.getItems())
|
||||
.filter(stack -> !subtracted.test(stack))
|
||||
.toArray(ItemStack[]::new);
|
||||
return filteredMatchingStacks;
|
||||
}
|
||||
public List<Holder<Item>> items() {
|
||||
if (this.items == null) {
|
||||
var tmp = new ArrayList<Holder<Item>>();
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return base.isEmpty();
|
||||
for (var base : this.base.items()) {
|
||||
boolean match = false;
|
||||
for (var item : this.subtracted.items()) {
|
||||
if (base.is(item)) {
|
||||
match = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!match)
|
||||
tmp.add(base);
|
||||
}
|
||||
this.items = Collections.unmodifiableList(tmp);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -67,27 +74,6 @@ public class DifferenceIngredient extends AbstractIngredient {
|
||||
return base.isSimple() && subtracted.isSimple();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void invalidate() {
|
||||
super.invalidate();
|
||||
this.filteredMatchingStacks = null;
|
||||
this.packedMatchingStacks = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IntList getStackingIds() {
|
||||
if (this.packedMatchingStacks == null || checkInvalidation()) {
|
||||
markValid();
|
||||
var matchingStacks = getItems();
|
||||
this.packedMatchingStacks = new IntArrayList(matchingStacks.length);
|
||||
for (var stack : matchingStacks)
|
||||
this.packedMatchingStacks.add(StackedContents.getStackingIndex(stack));
|
||||
|
||||
this.packedMatchingStacks.sort(IntComparators.NATURAL_COMPARATOR);
|
||||
}
|
||||
return packedMatchingStacks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IIngredientSerializer<DifferenceIngredient> serializer() {
|
||||
return SERIALIZER;
|
||||
|
||||
+11
-4
@@ -7,6 +7,8 @@ package net.minecraftforge.common.crafting.ingredients;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import net.minecraft.core.HolderGetter;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
@@ -25,19 +27,24 @@ public interface IIngredientBuilder {
|
||||
return CompoundIngredient.of(values);
|
||||
}
|
||||
|
||||
default Ingredient intersection(@SuppressWarnings("rawtypes") TagKey... values) {
|
||||
return intersection(Arrays.stream(values).map(Ingredient::of).toArray(Ingredient[]::new));
|
||||
@SuppressWarnings("unchecked")
|
||||
default Ingredient intersection(HolderGetter<Item> lookup, @SuppressWarnings("rawtypes") TagKey... values) {
|
||||
return intersection(Arrays.stream(values).map(k -> holder(lookup, (TagKey<Item>)k)).map(Ingredient::of).toArray(Ingredient[]::new));
|
||||
}
|
||||
|
||||
default Ingredient intersection(Ingredient... values) {
|
||||
return IntersectionIngredient.of(values);
|
||||
}
|
||||
|
||||
default Ingredient difference(TagKey<Item> base, TagKey<Item> subtracted) {
|
||||
return difference(Ingredient.of(base), Ingredient.of(subtracted));
|
||||
default Ingredient difference(HolderGetter<Item> lookup, TagKey<Item> base, TagKey<Item> subtracted) {
|
||||
return difference(Ingredient.of(holder(lookup, base)), Ingredient.of(holder(lookup, subtracted)));
|
||||
}
|
||||
|
||||
default Ingredient difference(Ingredient base, Ingredient subtracted) {
|
||||
return DifferenceIngredient.of(base, subtracted);
|
||||
}
|
||||
|
||||
private static HolderSet<Item> holder(HolderGetter<Item> lookup, TagKey<Item> key) {
|
||||
return lookup.getOrThrow(key);
|
||||
}
|
||||
}
|
||||
-21
@@ -5,12 +5,9 @@
|
||||
|
||||
package net.minecraftforge.common.crafting.ingredients;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import com.mojang.serialization.MapCodec;
|
||||
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
|
||||
public interface IIngredientSerializer<T extends Ingredient> {
|
||||
@@ -18,22 +15,4 @@ public interface IIngredientSerializer<T extends Ingredient> {
|
||||
|
||||
void write(RegistryFriendlyByteBuf buffer, T value);
|
||||
T read(RegistryFriendlyByteBuf buffer);
|
||||
|
||||
|
||||
IIngredientSerializer<Ingredient> VANILLA = new IIngredientSerializer<>() {
|
||||
@Override
|
||||
public MapCodec<? extends Ingredient> codec() {
|
||||
return Ingredient.VANILLA_MAP_CODEC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(RegistryFriendlyByteBuf buffer, Ingredient value) {
|
||||
ItemStack.LIST_STREAM_CODEC.encode(buffer, Arrays.asList(value.getItems()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Ingredient read(RegistryFriendlyByteBuf buffer) {
|
||||
return Ingredient.of(ItemStack.LIST_STREAM_CODEC.decode(buffer).stream());
|
||||
}
|
||||
};
|
||||
}
|
||||
+28
-44
@@ -8,11 +8,9 @@ package net.minecraftforge.common.crafting.ingredients;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntComparators;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.world.entity.player.StackedContents;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
@@ -40,8 +38,7 @@ public class IntersectionIngredient extends AbstractIngredient {
|
||||
|
||||
private final List<Ingredient> children;
|
||||
private final boolean isSimple;
|
||||
private ItemStack[] intersectedMatchingStacks = null;
|
||||
private IntList packedMatchingStacks = null;
|
||||
private List<Holder<Item>> items = null;
|
||||
|
||||
private IntersectionIngredient(List<Ingredient> children) {
|
||||
if (children.size() < 2)
|
||||
@@ -62,26 +59,33 @@ public class IntersectionIngredient extends AbstractIngredient {
|
||||
return true;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@Override
|
||||
public ItemStack[] getItems() {
|
||||
if (this.intersectedMatchingStacks == null) {
|
||||
this.intersectedMatchingStacks = Arrays
|
||||
.stream(children.get(0).getItems())
|
||||
.filter(stack -> {
|
||||
// the first ingredient is treated as a base, filtered by the second onwards
|
||||
for (int i = 1; i < children.size(); i++)
|
||||
if (!children.get(i).test(stack))
|
||||
return false;
|
||||
return true;
|
||||
})
|
||||
.toArray(ItemStack[]::new);
|
||||
}
|
||||
return intersectedMatchingStacks;
|
||||
}
|
||||
public List<Holder<Item>> items() {
|
||||
if (this.items == null) {
|
||||
var tmp = new ArrayList<Holder<Item>>();
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return children.stream().anyMatch(Ingredient::isEmpty);
|
||||
for (var base : children.get(0).items()) {
|
||||
boolean allMatch = true;
|
||||
for (int i = 1; i < children.size(); i++) {
|
||||
boolean match = false;
|
||||
for (var item : children.get(i).items()) {
|
||||
if (base.is(item)) {
|
||||
match = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!match) {
|
||||
allMatch = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (allMatch)
|
||||
tmp.add(base);
|
||||
}
|
||||
this.items = Collections.unmodifiableList(tmp);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -89,26 +93,6 @@ public class IntersectionIngredient extends AbstractIngredient {
|
||||
return isSimple;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void invalidate() {
|
||||
super.invalidate();
|
||||
this.intersectedMatchingStacks = null;
|
||||
this.packedMatchingStacks = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IntList getStackingIds() {
|
||||
if (this.packedMatchingStacks == null || checkInvalidation()) {
|
||||
markValid();
|
||||
var matchingStacks = getItems();
|
||||
this.packedMatchingStacks = new IntArrayList(matchingStacks.length);
|
||||
for (var stack : matchingStacks)
|
||||
this.packedMatchingStacks.add(StackedContents.getStackingIndex(stack));
|
||||
this.packedMatchingStacks.sort(IntComparators.NATURAL_COMPARATOR);
|
||||
}
|
||||
return packedMatchingStacks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IIngredientSerializer<IntersectionIngredient> serializer() {
|
||||
return SERIALIZER;
|
||||
|
||||
+29
-19
@@ -9,21 +9,22 @@ import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
import net.minecraft.advancements.critereon.NbtPredicate;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.TagParser;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.component.CustomData;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import net.minecraft.world.level.ItemLike;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@@ -33,34 +34,41 @@ public class PartialNBTIngredient extends AbstractIngredient {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
private final List<Item> items;
|
||||
private final CompoundTag nbt;
|
||||
private final NbtPredicate predicate;
|
||||
|
||||
private PartialNBTIngredient(List<Item> items, CompoundTag nbt) {
|
||||
super(items.stream().map(item -> {
|
||||
var stack = new ItemStack(item);
|
||||
// copy NBT to prevent the stack from modifying the original, as capabilities or vanilla item durability will modify the tag
|
||||
stack.set(DataComponents.CUSTOM_DATA, CustomData.of(nbt.copy()));
|
||||
return new Ingredient.ItemValue(stack);
|
||||
}));
|
||||
private PartialNBTIngredient(HolderSet<Item> items, CompoundTag nbt) {
|
||||
super(items);
|
||||
|
||||
if (items.isEmpty())
|
||||
if (items.size() == 0)
|
||||
throw new IllegalArgumentException("Cannot create a PartialNBTIngredient with no items");
|
||||
|
||||
this.items = Collections.unmodifiableList(items);
|
||||
this.nbt = nbt;
|
||||
this.predicate = new NbtPredicate(nbt);
|
||||
}
|
||||
|
||||
/** Creates a new ingredient matching any item from the list, containing the given NBT */
|
||||
@SuppressWarnings("deprecation")
|
||||
public static PartialNBTIngredient of(CompoundTag nbt, ItemLike... items) {
|
||||
return new PartialNBTIngredient(Arrays.stream(items).map(ItemLike::asItem).toList(), nbt);
|
||||
return of(
|
||||
HolderSet.direct(
|
||||
Arrays.stream(items)
|
||||
.map(ItemLike::asItem)
|
||||
.map(Item::builtInRegistryHolder)
|
||||
.toList()
|
||||
),
|
||||
nbt);
|
||||
}
|
||||
|
||||
/** Creates a new ingredient matching the given item, containing the given NBT */
|
||||
@SuppressWarnings("deprecation")
|
||||
public static PartialNBTIngredient of(ItemLike item, CompoundTag nbt) {
|
||||
return new PartialNBTIngredient(List.of(item.asItem()), nbt);
|
||||
return of(HolderSet.direct(item.asItem().builtInRegistryHolder()), nbt);
|
||||
}
|
||||
|
||||
/** Creates a new ingredient matching the given item, containing the given NBT */
|
||||
public static PartialNBTIngredient of(HolderSet<Item> items, CompoundTag nbt) {
|
||||
return new PartialNBTIngredient(items, nbt);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -68,7 +76,7 @@ public class PartialNBTIngredient extends AbstractIngredient {
|
||||
if (input == null)
|
||||
return false;
|
||||
var nbt = input.get(DataComponents.CUSTOM_DATA);
|
||||
return nbt != null && items.contains(input.getItem()) && predicate.matches(nbt.copyTag());
|
||||
return nbt != null && input.is(this.values) && predicate.matches(nbt.copyTag());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -83,12 +91,14 @@ public class PartialNBTIngredient extends AbstractIngredient {
|
||||
|
||||
public static final MapCodec<PartialNBTIngredient> CODEC = RecordCodecBuilder.mapCodec(builder ->
|
||||
builder.group(
|
||||
ForgeRegistries.ITEMS.getCodec().listOf().fieldOf("items").forGetter(i -> i.items),
|
||||
Ingredient.NON_AIR_HOLDER_SET_CODEC.fieldOf("items").forGetter(i -> i.values),
|
||||
TagParser.AS_CODEC.fieldOf("nbt").forGetter(i -> i.nbt)
|
||||
).apply(builder, PartialNBTIngredient::new)
|
||||
);
|
||||
|
||||
public static final IIngredientSerializer<PartialNBTIngredient> SERIALIZER = new IIngredientSerializer<>() {
|
||||
private final StreamCodec<RegistryFriendlyByteBuf, HolderSet<Item>> HOLDER_SET = ByteBufCodecs.holderSet(Registries.ITEM);
|
||||
|
||||
@Override
|
||||
public MapCodec<? extends PartialNBTIngredient> codec() {
|
||||
return CODEC;
|
||||
@@ -96,14 +106,14 @@ public class PartialNBTIngredient extends AbstractIngredient {
|
||||
|
||||
@Override
|
||||
public PartialNBTIngredient read(RegistryFriendlyByteBuf buffer) {
|
||||
var items = buffer.readList(b -> Item.STREAM_CODEC.decode(buffer).get());
|
||||
var items = HOLDER_SET.decode(buffer);
|
||||
var nbt = buffer.readNbt();
|
||||
return new PartialNBTIngredient(items, Objects.requireNonNull(nbt));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(RegistryFriendlyByteBuf buffer, PartialNBTIngredient value) {
|
||||
buffer.writeCollection(value.items, (b, item) -> Item.STREAM_CODEC.encode(buffer, item.builtInRegistryHolder()));
|
||||
HOLDER_SET.encode(buffer, value.values);
|
||||
buffer.writeNbt(value.nbt);
|
||||
}
|
||||
};
|
||||
|
||||
+3
-3
@@ -5,8 +5,7 @@
|
||||
|
||||
package net.minecraftforge.common.crafting.ingredients;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
@@ -24,7 +23,7 @@ public class StrictNBTIngredient extends AbstractIngredient {
|
||||
|
||||
private final ItemStack stack;
|
||||
private StrictNBTIngredient(ItemStack stack) {
|
||||
super(Stream.of(new Ingredient.ItemValue(stack)));
|
||||
super(HolderSet.direct(stack.getItemHolder()));
|
||||
this.stack = stack;
|
||||
}
|
||||
|
||||
@@ -32,6 +31,7 @@ public class StrictNBTIngredient extends AbstractIngredient {
|
||||
public boolean test(@Nullable ItemStack input) {
|
||||
if (input == null)
|
||||
return false;
|
||||
|
||||
//Can't use areItemStacksEqualUsingNBTShareTag because it compares stack size as well
|
||||
var inbt = input.get(DataComponents.CUSTOM_DATA);
|
||||
var tnbt = this.stack.get(DataComponents.CUSTOM_DATA);
|
||||
|
||||
@@ -27,10 +27,37 @@ public final class ForgeEntityTypeTagsProvider extends EntityTypeTagsProvider {
|
||||
@Override
|
||||
public void addTags(HolderLookup.Provider lookupProvider) {
|
||||
tag(BOSSES)
|
||||
.add(EntityType.ENDER_DRAGON, EntityType.WITHER)
|
||||
.addOptionalTag(forgeTagKey("bosses"));
|
||||
tag(MINECARTS).add(EntityType.MINECART, EntityType.CHEST_MINECART, EntityType.FURNACE_MINECART, EntityType.HOPPER_MINECART, EntityType.SPAWNER_MINECART, EntityType.TNT_MINECART, EntityType.COMMAND_BLOCK_MINECART);
|
||||
tag(BOATS).add(EntityType.BOAT, EntityType.CHEST_BOAT);
|
||||
.add(EntityType.ENDER_DRAGON, EntityType.WITHER)
|
||||
.addOptionalTag(forgeTagKey("bosses"));
|
||||
tag(MINECARTS).add(
|
||||
EntityType.MINECART,
|
||||
EntityType.CHEST_MINECART,
|
||||
EntityType.FURNACE_MINECART,
|
||||
EntityType.HOPPER_MINECART,
|
||||
EntityType.SPAWNER_MINECART,
|
||||
EntityType.TNT_MINECART,
|
||||
EntityType.COMMAND_BLOCK_MINECART
|
||||
);
|
||||
tag(BOATS).add(
|
||||
EntityType.ACACIA_BOAT,
|
||||
EntityType.ACACIA_CHEST_BOAT,
|
||||
EntityType.BIRCH_BOAT,
|
||||
EntityType.BIRCH_CHEST_BOAT,
|
||||
EntityType.CHERRY_BOAT,
|
||||
EntityType.CHERRY_CHEST_BOAT,
|
||||
EntityType.DARK_OAK_BOAT,
|
||||
EntityType.DARK_OAK_CHEST_BOAT,
|
||||
EntityType.JUNGLE_BOAT,
|
||||
EntityType.JUNGLE_CHEST_BOAT,
|
||||
EntityType.MANGROVE_BOAT,
|
||||
EntityType.MANGROVE_CHEST_BOAT,
|
||||
EntityType.OAK_BOAT,
|
||||
EntityType.OAK_CHEST_BOAT,
|
||||
EntityType.PALE_OAK_BOAT,
|
||||
EntityType.PALE_OAK_CHEST_BOAT,
|
||||
EntityType.SPRUCE_BOAT,
|
||||
EntityType.SPRUCE_CHEST_BOAT
|
||||
);
|
||||
tag(CAPTURING_NOT_SUPPORTED);
|
||||
tag(TELEPORTING_NOT_SUPPORTED);
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ package net.minecraftforge.common.data;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.data.PackOutput;
|
||||
import net.minecraft.data.tags.IntrinsicHolderTagsProvider;
|
||||
import net.minecraft.data.tags.ItemTagsProvider;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.BlockTags;
|
||||
@@ -32,7 +31,7 @@ public final class ForgeItemTagsProvider extends ItemTagsProvider {
|
||||
super(output, lookupProvider, blockTagProvider, "forge", existingFileHelper);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@SuppressWarnings({ "unchecked", "removal" })
|
||||
@Override
|
||||
public void addTags(HolderLookup.Provider lookupProvider) {
|
||||
copy(Tags.Blocks.BARRELS, Tags.Items.BARRELS);
|
||||
@@ -518,7 +517,7 @@ public final class ForgeItemTagsProvider extends ItemTagsProvider {
|
||||
for (DyeColor color : DyeColor.values()) {
|
||||
ResourceLocation key = ResourceLocation.fromNamespaceAndPath("minecraft", pattern.replace("{color}", color.getName()));
|
||||
TagKey<Item> tag = getForgeItemTag(prefix + color.getName());
|
||||
Item item = BuiltInRegistries.ITEM.get(key);
|
||||
Item item = BuiltInRegistries.ITEM.getValue(key);
|
||||
if (item == null || item == Items.AIR)
|
||||
throw new IllegalStateException("Unknown vanilla item: " + key);
|
||||
tag(tag).add(item);
|
||||
@@ -582,11 +581,11 @@ public final class ForgeItemTagsProvider extends ItemTagsProvider {
|
||||
}
|
||||
|
||||
private static TagKey<Block> forgeBlockTagKey(String path) {
|
||||
return BlockTags.create(ResourceLocation.fromNamespaceAndPath("forge", path));
|
||||
return BlockTags.create(forgeRl(path));
|
||||
}
|
||||
|
||||
private static TagKey<Item> forgeItemTagKey(String path) {
|
||||
return ItemTags.create(ResourceLocation.fromNamespaceAndPath("forge", path));
|
||||
return ItemTags.create(forgeRl(path));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -8,21 +8,23 @@ package net.minecraftforge.common.data;
|
||||
import com.google.gson.JsonElement;
|
||||
import net.minecraft.advancements.AdvancementHolder;
|
||||
import net.minecraft.advancements.Advancement.Builder;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.HolderLookup.Provider;
|
||||
import net.minecraft.data.CachedOutput;
|
||||
import net.minecraft.core.HolderLookup.RegistryLookup;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.data.PackOutput;
|
||||
import net.minecraft.data.recipes.RecipeOutput;
|
||||
import net.minecraft.data.recipes.RecipeProvider;
|
||||
import net.minecraft.data.recipes.packs.VanillaRecipeProvider;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import net.minecraft.world.item.crafting.Ingredient.ItemValue;
|
||||
import net.minecraft.world.item.crafting.Ingredient.TagValue;
|
||||
import net.minecraft.world.item.crafting.Ingredient.Value;
|
||||
import net.minecraft.world.item.crafting.Recipe;
|
||||
import net.minecraft.world.item.crafting.ShapedRecipe;
|
||||
import net.minecraft.world.item.crafting.ShapedRecipePattern;
|
||||
@@ -30,10 +32,13 @@ import net.minecraft.world.item.crafting.ShapelessRecipe;
|
||||
import net.minecraft.world.level.ItemLike;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraftforge.common.Tags;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.unsafe.UnsafeFieldAccess;
|
||||
import net.minecraftforge.unsafe.UnsafeHacks;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
@@ -43,19 +48,26 @@ import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public final class ForgeRecipeProvider extends VanillaRecipeProvider {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private final RegistryLookup<Item> items;
|
||||
private final Map<Item, TagKey<Item>> replacements = HashMap.newHashMap(12);
|
||||
private final Set<ResourceLocation> excludes = HashSet.newHashSet(16);
|
||||
private final Set<ResourceKey<Recipe<?>>> excludes = HashSet.newHashSet(16);
|
||||
private final UnsafeFieldAccess<ShapelessRecipe, List<Ingredient>> INGREDIENTS = UnsafeHacks.findField(ShapelessRecipe.class, "ingredients");
|
||||
private final UnsafeFieldAccess<ShapedRecipe, ShapedRecipePattern> PATTERN = UnsafeHacks.findField(ShapedRecipe.class, "pattern");
|
||||
private final UnsafeFieldAccess<Ingredient, HolderSet<Item>> VALUES = UnsafeHacks.findField(Ingredient.class, "values");
|
||||
|
||||
public ForgeRecipeProvider(PackOutput packOutput, CompletableFuture<HolderLookup.Provider> lookup) {
|
||||
super(packOutput, lookup);
|
||||
private ForgeRecipeProvider(HolderLookup.Provider lookup, RecipeOutput output) {
|
||||
super(lookup, new Wrapped(output));
|
||||
((Wrapped)this.output).setSelf(this);
|
||||
this.items = lookup.lookupOrThrow(Registries.ITEM);
|
||||
}
|
||||
|
||||
private void exclude(ItemLike item) {
|
||||
excludes.add(ForgeRegistries.ITEMS.getKey(item.asItem()));
|
||||
exclude(BuiltInRegistries.ITEM.getKey(item.asItem()).toString());
|
||||
}
|
||||
|
||||
private void exclude(String name) {
|
||||
excludes.add(ResourceLocation.parse(name));
|
||||
excludes.add(ResourceKey.create(Registries.RECIPE, ResourceLocation.parse(name)));
|
||||
}
|
||||
|
||||
private void replace(ItemLike item, TagKey<Item> tag) {
|
||||
@@ -63,7 +75,7 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void buildRecipes(RecipeOutput consumer) {
|
||||
protected void buildRecipes() {
|
||||
replace(Items.STICK, Tags.Items.RODS_WOODEN);
|
||||
replace(Items.GOLD_INGOT, Tags.Items.INGOTS_GOLD);
|
||||
replace(Items.IRON_INGOT, Tags.Items.INGOTS_IRON);
|
||||
@@ -96,32 +108,11 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
|
||||
exclude(Blocks.COBBLED_DEEPSLATE_SLAB);
|
||||
exclude(Blocks.COBBLED_DEEPSLATE_WALL);
|
||||
|
||||
super.buildRecipes(new RecipeOutput() {
|
||||
@Override
|
||||
public void accept(ResourceLocation id, Recipe<?> recipe, AdvancementHolder advancement) {
|
||||
var modified = enhance(id, recipe);
|
||||
if (modified != null)
|
||||
consumer.accept(id, modified, advancement);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Builder advancement() {
|
||||
return consumer.advancement();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(ResourceLocation id, Recipe<?> recipe, ResourceLocation advancementId, JsonElement advancement) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Provider registry() {
|
||||
return consumer.registry();
|
||||
}
|
||||
});
|
||||
super.buildRecipes();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private Recipe<?> enhance(ResourceLocation id, Recipe<?> vanilla) {
|
||||
private Recipe<?> enhance(ResourceKey<Recipe<?>> id, Recipe<?> vanilla) {
|
||||
if (vanilla instanceof ShapelessRecipe shapeless)
|
||||
return enhance(id, shapeless);
|
||||
if (vanilla instanceof ShapedRecipe shaped)
|
||||
@@ -130,8 +121,8 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private Recipe<?> enhance(ResourceLocation id, ShapelessRecipe vanilla) {
|
||||
List<Ingredient> ingredients = getField(ShapelessRecipe.class, vanilla, 3);
|
||||
private Recipe<?> enhance(ResourceKey<Recipe<?>> id, ShapelessRecipe vanilla) {
|
||||
List<Ingredient> ingredients = INGREDIENTS.get(vanilla);
|
||||
boolean modified = false;
|
||||
for (int x = 0; x < ingredients.size(); x++) {
|
||||
Ingredient ing = enhance(id, ingredients.get(x));
|
||||
@@ -144,21 +135,8 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
protected CompletableFuture<?> saveAdvancement(CachedOutput output, ResourceLocation advancementId, JsonElement advancement) {
|
||||
// NOOP - We don't replace any of the advancement things yet...
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CompletableFuture<?> buildAdvancement(CachedOutput p_253674_, HolderLookup.Provider p_335995_, AdvancementHolder p_297687_) {
|
||||
// NOOP - We don't replace any of the advancement things yet...
|
||||
return CompletableFuture.allOf();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private Recipe<?> enhance(ResourceLocation id, ShapedRecipe vanilla) {
|
||||
ShapedRecipePattern pattern = getField(ShapedRecipe.class, vanilla, 2);
|
||||
private Recipe<?> enhance(ResourceKey<Recipe<?>> id, ShapedRecipe vanilla) {
|
||||
ShapedRecipePattern pattern = PATTERN.get(vanilla);
|
||||
var data = pattern.data().orElseThrow(() -> new IllegalStateException("Weird shaped recipe, data is missing? " + id + " " + vanilla));
|
||||
Map<Character, Ingredient> ingredients = data.key();
|
||||
boolean modified = false;
|
||||
@@ -173,36 +151,92 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private Ingredient enhance(ResourceLocation name, Ingredient vanilla) {
|
||||
private Ingredient enhance(ResourceKey<Recipe<?>> name, Ingredient vanilla) {
|
||||
if (excludes.contains(name))
|
||||
return null;
|
||||
|
||||
boolean modified = false;
|
||||
List<Value> items = new ArrayList<>();
|
||||
Value[] vanillaItems = getField(Ingredient.class, vanilla, 3); //This will probably crash between versions, if null fix index
|
||||
for (Value entry : vanillaItems) {
|
||||
if (entry instanceof ItemValue) {
|
||||
ItemStack stack = entry.getItems().stream().findFirst().orElse(ItemStack.EMPTY);
|
||||
TagKey<Item> replacement = replacements.get(stack.getItem());
|
||||
if (replacement != null) {
|
||||
items.add(new TagValue(replacement));
|
||||
modified = true;
|
||||
} else
|
||||
items.add(entry);
|
||||
HolderSet<Item> vanillaItems = VALUES.get(vanilla);
|
||||
var unwraped = vanillaItems.unwrap();
|
||||
|
||||
if (unwraped.left().isPresent()) // Already a tag
|
||||
return null;
|
||||
|
||||
Ingredient ret = null;
|
||||
var items = new ArrayList<Holder<Item>>();
|
||||
for (var entry : unwraped.right().get()) {
|
||||
var item = entry.get();
|
||||
var replacement = replacements.get(item);
|
||||
if (replacement != null) {
|
||||
if (ret != null) {
|
||||
LOGGER.warn("Failed to enahnce {} ingredient has multiple input items", name);
|
||||
return null;
|
||||
}
|
||||
ret = Ingredient.of(this.items.getOrThrow(replacement));
|
||||
} else
|
||||
items.add(entry);
|
||||
}
|
||||
return modified ? Ingredient.fromValues(items.stream()) : null;
|
||||
|
||||
if (ret != null && !items.isEmpty()) {
|
||||
LOGGER.warn("Failed to enahnce {} ingredient has multiple input items", name);
|
||||
return null;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T, R> R getField(Class<T> clz, T inst, int index) {
|
||||
Field fld = clz.getDeclaredFields()[index];
|
||||
fld.setAccessible(true);
|
||||
try {
|
||||
return (R) fld.get(inst);
|
||||
} catch (IllegalArgumentException | IllegalAccessException e) {
|
||||
throw new RuntimeException(e);
|
||||
public static class Runner extends RecipeProvider.Runner {
|
||||
public Runner(PackOutput output, CompletableFuture<Provider> registries) {
|
||||
super(output, registries);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return ForgeRecipeProvider.class.getSimpleName();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected RecipeProvider createRecipeProvider(Provider registries, RecipeOutput output) {
|
||||
return new ForgeRecipeProvider(registries, output);
|
||||
}
|
||||
}
|
||||
|
||||
private static class Wrapped implements RecipeOutput {
|
||||
private final RecipeOutput wrapped;
|
||||
private ForgeRecipeProvider self;
|
||||
|
||||
private Wrapped(RecipeOutput wrapped) {
|
||||
this.wrapped = wrapped;
|
||||
}
|
||||
|
||||
private void setSelf(ForgeRecipeProvider self) {
|
||||
this.self = self;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(ResourceKey<Recipe<?>> id, Recipe<?> recipe, AdvancementHolder advancement) {
|
||||
var modified = self.enhance(id, recipe);
|
||||
if (modified != null)
|
||||
wrapped.accept(id, modified, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Builder advancement() {
|
||||
return wrapped.advancement();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(ResourceKey<Recipe<?>> id, Recipe<?> recipe, ResourceLocation advancementId, JsonElement advancement) {
|
||||
var modified = self.enhance(id, recipe);
|
||||
if (modified != null)
|
||||
wrapped.accept(id, modified, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Provider registry() {
|
||||
return wrapped.registry();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void includeRootAdvancement() {}
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,7 @@ public abstract class LanguageProvider implements DataProvider {
|
||||
}
|
||||
|
||||
public void add(ItemStack key, String name) {
|
||||
add(key.getDescriptionId(), name);
|
||||
add(key.getItem().getDescriptionId(), name);
|
||||
}
|
||||
|
||||
public void addEnchantment(Supplier<? extends Enchantment> key, String name) {
|
||||
|
||||
@@ -26,8 +26,7 @@ import org.apache.logging.log4j.Logger;
|
||||
* Data provider for the {@code sounds.json} file, which identifies sound definitions
|
||||
* for the various sound events in Minecraft.
|
||||
*/
|
||||
public abstract class SoundDefinitionsProvider implements DataProvider
|
||||
{
|
||||
public abstract class SoundDefinitionsProvider implements DataProvider {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private final PackOutput output;
|
||||
private final String modId;
|
||||
@@ -42,8 +41,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
|
||||
* @param modId The mod ID of the current mod.
|
||||
* @param helper The existing file helper provided by the event you are initializing this provider in.
|
||||
*/
|
||||
protected SoundDefinitionsProvider(final PackOutput output, final String modId, final ExistingFileHelper helper)
|
||||
{
|
||||
protected SoundDefinitionsProvider(final PackOutput output, final String modId, final ExistingFileHelper helper) {
|
||||
this.output = output;
|
||||
this.modId = modId;
|
||||
this.helper = helper;
|
||||
@@ -55,13 +53,11 @@ public abstract class SoundDefinitionsProvider implements DataProvider
|
||||
public abstract void registerSounds();
|
||||
|
||||
@Override
|
||||
public CompletableFuture<?> run(CachedOutput cache)
|
||||
{
|
||||
public CompletableFuture<?> run(CachedOutput cache) {
|
||||
this.sounds.clear();
|
||||
this.registerSounds();
|
||||
this.validate();
|
||||
if (!this.sounds.isEmpty())
|
||||
{
|
||||
if (!this.sounds.isEmpty()) {
|
||||
return this.save(cache, this.output.getOutputFolder(PackOutput.Target.RESOURCE_PACK).resolve(this.modId).resolve("sounds.json"));
|
||||
}
|
||||
|
||||
@@ -69,8 +65,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName()
|
||||
{
|
||||
public String getName() {
|
||||
return "Sound Definitions";
|
||||
}
|
||||
|
||||
@@ -79,8 +74,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
|
||||
* Creates a new {@link SoundDefinition}, which will host a set of
|
||||
* {@link SoundDefinition.Sound}s and the necessary parameters.
|
||||
*/
|
||||
protected static SoundDefinition definition()
|
||||
{
|
||||
protected static SoundDefinition definition() {
|
||||
return SoundDefinition.definition();
|
||||
}
|
||||
|
||||
@@ -90,8 +84,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
|
||||
* @param name The name of the sound to create.
|
||||
* @param type The type of sound to create.
|
||||
*/
|
||||
protected static SoundDefinition.Sound sound(final ResourceLocation name, final SoundDefinition.SoundType type)
|
||||
{
|
||||
protected static SoundDefinition.Sound sound(final ResourceLocation name, final SoundDefinition.SoundType type) {
|
||||
return SoundDefinition.Sound.sound(name, type);
|
||||
}
|
||||
|
||||
@@ -101,8 +94,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
|
||||
*
|
||||
* @param name The name of the sound to create.
|
||||
*/
|
||||
protected static SoundDefinition.Sound sound(final ResourceLocation name)
|
||||
{
|
||||
protected static SoundDefinition.Sound sound(final ResourceLocation name) {
|
||||
return sound(name, SoundDefinition.SoundType.SOUND);
|
||||
}
|
||||
|
||||
@@ -112,8 +104,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
|
||||
* @param name The name of the sound to create.
|
||||
* @param type The type of sound to create.
|
||||
*/
|
||||
protected static SoundDefinition.Sound sound(final String name, final SoundDefinition.SoundType type)
|
||||
{
|
||||
protected static SoundDefinition.Sound sound(final String name, final SoundDefinition.SoundType type) {
|
||||
return sound(ResourceLocation.parse(name), type);
|
||||
}
|
||||
|
||||
@@ -123,8 +114,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
|
||||
*
|
||||
* @param name The name of the sound to create.
|
||||
*/
|
||||
protected static SoundDefinition.Sound sound(final String name)
|
||||
{
|
||||
protected static SoundDefinition.Sound sound(final String name) {
|
||||
return sound(ResourceLocation.parse(name));
|
||||
}
|
||||
|
||||
@@ -139,8 +129,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
|
||||
* @param soundEvent A {@code Supplier} for the given {@link SoundEvent}.
|
||||
* @param definition A {@link SoundDefinition} that defines the given sound.
|
||||
*/
|
||||
protected void add(final Supplier<SoundEvent> soundEvent, final SoundDefinition definition)
|
||||
{
|
||||
protected void add(final Supplier<SoundEvent> soundEvent, final SoundDefinition definition) {
|
||||
this.add(soundEvent.get(), definition);
|
||||
}
|
||||
|
||||
@@ -155,9 +144,8 @@ public abstract class SoundDefinitionsProvider implements DataProvider
|
||||
* @param soundEvent A {@link SoundEvent}.
|
||||
* @param definition The {@link SoundDefinition} that defines the given event.
|
||||
*/
|
||||
protected void add(final SoundEvent soundEvent, final SoundDefinition definition)
|
||||
{
|
||||
this.add(soundEvent.getLocation(), definition);
|
||||
protected void add(final SoundEvent soundEvent, final SoundDefinition definition) {
|
||||
this.add(soundEvent.location(), definition);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -167,8 +155,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
|
||||
* @param soundEvent The {@link ResourceLocation} that identifies the event.
|
||||
* @param definition The {@link SoundDefinition} that defines the given event.
|
||||
*/
|
||||
protected void add(final ResourceLocation soundEvent, final SoundDefinition definition)
|
||||
{
|
||||
protected void add(final ResourceLocation soundEvent, final SoundDefinition definition) {
|
||||
this.addSounds(soundEvent.getPath(), definition);
|
||||
}
|
||||
|
||||
@@ -184,42 +171,32 @@ public abstract class SoundDefinitionsProvider implements DataProvider
|
||||
* @param soundEvent The name of the {@link SoundEvent}.
|
||||
* @param definition The {@link SoundDefinition} that defines the given event.
|
||||
*/
|
||||
protected void add(final String soundEvent, final SoundDefinition definition)
|
||||
{
|
||||
protected void add(final String soundEvent, final SoundDefinition definition) {
|
||||
this.add(ResourceLocation.parse(soundEvent), definition);
|
||||
}
|
||||
|
||||
private void addSounds(final String soundEvent, final SoundDefinition definition)
|
||||
{
|
||||
private void addSounds(final String soundEvent, final SoundDefinition definition) {
|
||||
if (this.sounds.put(soundEvent, definition) != null)
|
||||
{
|
||||
throw new IllegalStateException("Sound event '" + this.modId + ":" + soundEvent + "' already exists");
|
||||
}
|
||||
}
|
||||
|
||||
// Internal handling stuff
|
||||
private void validate()
|
||||
{
|
||||
private void validate() {
|
||||
final List<String> notValid = this.sounds.entrySet().stream()
|
||||
.filter(it -> !this.validate(it.getKey(), it.getValue()))
|
||||
.map(Map.Entry::getKey)
|
||||
.map(it -> this.modId + ":" + it)
|
||||
.toList();
|
||||
if (!notValid.isEmpty())
|
||||
{
|
||||
throw new IllegalStateException("Found invalid sound events: " + notValid);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean validate(final String name, final SoundDefinition def)
|
||||
{
|
||||
private boolean validate(final String name, final SoundDefinition def) {
|
||||
return def.soundList().stream().allMatch(it -> this.validate(name,it));
|
||||
}
|
||||
|
||||
private boolean validate(final String name, final SoundDefinition.Sound sound)
|
||||
{
|
||||
switch (sound.type())
|
||||
{
|
||||
private boolean validate(final String name, final SoundDefinition.Sound sound) {
|
||||
switch (sound.type()) {
|
||||
case SOUND: return this.validateSound(name, sound.name());
|
||||
case EVENT: return this.validateEvent(name, sound.name());
|
||||
}
|
||||
@@ -230,34 +207,27 @@ public abstract class SoundDefinitionsProvider implements DataProvider
|
||||
throw new IllegalArgumentException("The given sound '" + sound.name() + "' does not have a valid type: expected either SOUND or EVENT, but found " + sound.type());
|
||||
}
|
||||
|
||||
private boolean validateSound(final String soundName, final ResourceLocation name)
|
||||
{
|
||||
private boolean validateSound(final String soundName, final ResourceLocation name) {
|
||||
final boolean valid = this.helper.exists(name, PackType.CLIENT_RESOURCES, ".ogg", "sounds");
|
||||
if (!valid)
|
||||
{
|
||||
if (!valid) {
|
||||
final String path = name.getNamespace() + ":sounds/" + name.getPath() + ".ogg";
|
||||
LOGGER.warn("Unable to find corresponding OGG file '{}' for sound event '{}'", path, soundName);
|
||||
}
|
||||
return valid;
|
||||
}
|
||||
|
||||
private boolean validateEvent(final String soundName, final ResourceLocation name)
|
||||
{
|
||||
private boolean validateEvent(final String soundName, final ResourceLocation name) {
|
||||
final boolean valid = this.sounds.containsKey(soundName) || ForgeRegistries.SOUND_EVENTS.containsKey(name);
|
||||
if (!valid)
|
||||
{
|
||||
LOGGER.warn("Unable to find event '{}' referenced from '{}'", name, soundName);
|
||||
}
|
||||
return valid;
|
||||
}
|
||||
|
||||
private CompletableFuture<?> save(final CachedOutput cache, final Path targetFile)
|
||||
{
|
||||
private CompletableFuture<?> save(final CachedOutput cache, final Path targetFile) {
|
||||
return DataProvider.saveStable(cache, mapToJson(this.sounds), targetFile);
|
||||
}
|
||||
|
||||
private static JsonObject mapToJson(final Map<String, SoundDefinition> map)
|
||||
{
|
||||
private static JsonObject mapToJson(final Map<String, SoundDefinition> map) {
|
||||
final JsonObject obj = new JsonObject();
|
||||
// namespaces are ignored when serializing
|
||||
map.forEach((k, v) -> obj.add(k, v.serialize()));
|
||||
|
||||
+7
-11
@@ -6,15 +6,14 @@
|
||||
package net.minecraftforge.common.extensions;
|
||||
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.vehicle.AbstractBoat;
|
||||
import net.minecraft.world.entity.vehicle.Boat;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import net.minecraftforge.fluids.FluidType;
|
||||
|
||||
public interface IForgeBoat
|
||||
{
|
||||
private Boat self()
|
||||
{
|
||||
return (Boat) this;
|
||||
public interface IForgeAbstractBoat {
|
||||
private AbstractBoat self() {
|
||||
return (AbstractBoat)this;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -23,8 +22,7 @@ public interface IForgeBoat
|
||||
* @param state the state of the fluid
|
||||
* @return {@code true} if the boat can be used, {@code false} otherwise
|
||||
*/
|
||||
default boolean canBoatInFluid(FluidState state)
|
||||
{
|
||||
default boolean canBoatInFluid(FluidState state) {
|
||||
return state.supportsBoating(self());
|
||||
}
|
||||
|
||||
@@ -34,8 +32,7 @@ public interface IForgeBoat
|
||||
* @param type the type of the fluid
|
||||
* @return {@code true} if the boat can be used, {@code false} otherwise
|
||||
*/
|
||||
default boolean canBoatInFluid(FluidType type)
|
||||
{
|
||||
default boolean canBoatInFluid(FluidType type) {
|
||||
return type.supportsBoating(self());
|
||||
}
|
||||
|
||||
@@ -47,8 +44,7 @@ public interface IForgeBoat
|
||||
* @param rider the rider of the boat
|
||||
* @return {@code true} if the fluid height should be updated, {@code false} otherwise
|
||||
*/
|
||||
default boolean shouldUpdateFluidWhileRiding(FluidState state, Entity rider)
|
||||
{
|
||||
default boolean shouldUpdateFluidWhileRiding(FluidState state, Entity rider) {
|
||||
return state.shouldUpdateWhileBoating(self(), rider);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 806 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user