Minecraft 1.21.5

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

No files matched your search

@@ -195,7 +195,7 @@ public class ClientCommandHandler {
MutableComponent details = Component.literal("")
.withStyle(ChatFormatting.GRAY)
.withStyle((style) -> style
.withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, reader.getString())));
.withClickEvent(new ClickEvent.SuggestCommand(reader.getString())));
if (position > 10)
details.append("...");
@@ -211,7 +211,7 @@ public class ClientCommandHandler {
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.ShowText(message)))
);
LOGGER.error("Error executing client command \"{}\"", command, generic);
}
@@ -6,16 +6,13 @@
package net.minecraftforge.client;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.resources.model.UnbakedGeometry;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.ModelEvent;
import net.minecraftforge.client.event.RegisterClientReloadListenersEvent;
import net.minecraftforge.client.event.RegisterNamedRenderTypesEvent;
import net.minecraftforge.client.model.CompositeModel;
import net.minecraftforge.client.model.DynamicFluidContainerModel;
import net.minecraftforge.client.model.ElementsModel;
import net.minecraftforge.client.model.EmptyModel;
import net.minecraftforge.client.model.ItemLayerModel;
import net.minecraftforge.client.model.SeparateTransformsModel;
import net.minecraftforge.client.model.ItemLayerGeometry;
import net.minecraftforge.client.model.obj.ObjLoader;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
@@ -24,13 +21,10 @@ import net.minecraftforge.fml.common.Mod;
public class ClientForgeMod {
@SubscribeEvent
public static void onRegisterGeometryLoaders(ModelEvent.RegisterGeometryLoaders event) {
event.register("empty", EmptyModel.LOADER);
event.register("elements", ElementsModel.Loader.INSTANCE);
event.register("empty", (json, ctx) -> UnbakedGeometry.EMPTY);
event.register("obj", ObjLoader.INSTANCE);
event.register("fluid_container", DynamicFluidContainerModel.Loader.INSTANCE);
event.register("composite", CompositeModel.Loader.INSTANCE);
event.register("item_layers", ItemLayerModel.Loader.INSTANCE);
event.register("separate_transforms", SeparateTransformsModel.Loader.INSTANCE);
event.register("item_layers", ItemLayerGeometry.Loader.INSTANCE);
}
@SubscribeEvent
@@ -5,21 +5,17 @@
package net.minecraftforge.client;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.platform.Window;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.datafixers.util.Either;
import com.mojang.math.Transformation;
import net.minecraft.ChatFormatting;
import net.minecraft.FileUtil;
import net.minecraft.client.Camera;
import net.minecraft.client.Minecraft;
@@ -50,24 +46,18 @@ import net.minecraft.client.renderer.FogRenderer;
import net.minecraft.client.renderer.LevelRenderer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
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.block.model.BlockElement;
import net.minecraft.client.renderer.block.model.BlockModel;
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;
import net.minecraft.client.resources.language.I18n;
import net.minecraft.client.resources.metadata.animation.FrameSize;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.resources.model.ModelBaker;
import net.minecraft.client.resources.model.ModelBakery;
import net.minecraft.client.resources.model.ModelDebugName;
import net.minecraft.client.resources.model.ModelManager;
import net.minecraft.client.resources.model.ModelState;
import net.minecraft.client.resources.model.ResolvedModel;
import net.minecraft.client.resources.model.SpriteGetter;
import net.minecraft.client.resources.model.UnbakedGeometry;
import net.minecraft.client.resources.sounds.SoundInstance;
import net.minecraft.client.sounds.SoundEngine;
import net.minecraft.core.BlockPos;
@@ -131,9 +121,9 @@ import net.minecraftforge.client.extensions.common.IClientItemExtensions;
import net.minecraftforge.client.extensions.common.IClientMobEffectExtensions;
import net.minecraftforge.client.gui.ClientTooltipComponentManager;
import net.minecraftforge.client.gui.ModMismatchDisconnectedScreen;
import net.minecraftforge.client.model.ForgeBlockModelData;
import net.minecraftforge.client.model.data.ModelData;
import net.minecraftforge.client.model.geometry.GeometryLoaderManager;
import net.minecraftforge.client.model.geometry.IUnbakedGeometry;
import net.minecraftforge.client.textures.ForgeTextureMetadata;
import net.minecraftforge.client.textures.TextureAtlasSpriteLoaderManager;
import net.minecraftforge.common.ForgeI18n;
@@ -143,7 +133,6 @@ import net.minecraftforge.fml.IExtensionPoint;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.ModLoader;
import net.minecraftforge.fml.VersionChecker;
import net.minecraftforge.gametest.ForgeGameTestHooks;
import net.minecraftforge.network.NetworkContext;
import net.minecraftforge.network.NetworkInitialization;
import net.minecraftforge.network.NetworkRegistry;
@@ -425,17 +414,6 @@ public class ForgeHooksClient {
};
}
public static boolean calculateFaceWithoutAO(BlockAndTintGetter getter, BlockState state, BlockPos pos, BakedQuad quad, boolean isFaceCubic, float[] brightness, int[] lightmap) {
if (quad.hasAmbientOcclusion())
return false;
BlockPos lightmapPos = isFaceCubic ? pos.relative(quad.getDirection()) : pos;
brightness[0] = brightness[1] = brightness[2] = brightness[3] = getter.getShade(quad.getDirection(), quad.isShade());
lightmap[0] = lightmap[1] = lightmap[2] = lightmap[3] = LevelRenderer.getLightColor(getter, state, lightmapPos);
return true;
}
private static int slotMainHand = 0;
public static boolean shouldCauseReequipAnimation(@NotNull ItemStack from, @NotNull ItemStack to, int slot) {
@@ -699,10 +677,6 @@ public class ForgeHooksClient {
return MinecraftForge.EVENT_BUS.post(event) ? "" : event.getMessage();
}
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);
return stackFont == null ? fallbackFont : stackFont;
@@ -850,7 +824,6 @@ public class ForgeHooksClient {
throw new IllegalStateException("Client hooks initialized more than once");
initializedClientHooks = true;
ForgeGameTestHooks.registerGametests();
ModLoader.get().postEvent(new RegisterClientReloadListenersEvent(resourceManager));
ModLoader.get().postEvent(new EntityRenderersEvent.RegisterLayerDefinitions());
ModLoader.get().postEvent(new EntityRenderersEvent.RegisterRenderers());
@@ -880,44 +853,44 @@ public class ForgeHooksClient {
|| ForgeEventFactoryClient.onScreenMouseDragPost(screen, mouseX, mouseY, mouseButton, dragX, dragY);
}
public static BlockModel deserializeBlockModel(BlockModel model, List<BlockElement> elements, JsonObject json, JsonDeserializationContext context) {
IUnbakedGeometry<?> geometry = null;
if (json.has("loader")) {
var name = ResourceLocation.parse(GsonHelper.getAsString(json, "loader"));
var loader = GeometryLoaderManager.get(name);
if (loader == null)
throw new JsonParseException(String.format(Locale.ENGLISH, "Model loader '%s' not found. Registered loaders: %s", name, GeometryLoaderManager.getLoaderList()));
public static @Nullable UnbakedGeometry deserializeBlockModelGeometry(JsonObject json, JsonDeserializationContext context) {
var name = GsonHelper.getAsString(json, "loader", null);
if (name == null)
return null;
geometry = loader.read(json, context);
var loader = GeometryLoaderManager.get(ResourceLocation.parse(name));
if (loader == null)
throw new JsonParseException(String.format(Locale.ENGLISH, "Model loader '%s' not found. Registered loaders: %s", name, GeometryLoaderManager.getLoaderList()));
return loader.read(json, context);
}
@Nullable
public static ForgeBlockModelData deserializeBlockModel(JsonObject json, JsonDeserializationContext context) {
Optional<ResourceLocation> renderType = Optional.empty();
Optional<ResourceLocation> renderTypeFast = Optional.empty();
Optional<Map<String, Boolean>> visibility = Optional.empty();
var transform = Optional.ofNullable(GsonHelper.getAsObject(json, "transform", null, context, Transformation.class));
var renderTypeName = GsonHelper.getAsString(json, "render_type", null);
if (renderTypeName != null)
renderType = Optional.of(ResourceLocation.parse(renderTypeName));
var renderTypeFastName = GsonHelper.getAsString(json, "render_type_fast", null);
if (renderTypeFastName != null)
renderTypeFast = Optional.of(ResourceLocation.parse(renderTypeFastName));
var visibilityJson = GsonHelper.getAsJsonObject(json, "visibility", null);
if (visibilityJson != null) {
var map = ImmutableMap.<String, Boolean>builder();
for (var part : visibilityJson.entrySet())
map.put(part.getKey(), part.getValue().getAsBoolean());
visibility = Optional.of(map.build());
}
if (geometry != null) {
elements.clear();
model.customData.setCustomGeometry(geometry);
}
if (json.has("transform")) {
JsonElement transform = json.get("transform");
model.customData.setRootTransform(context.deserialize(transform, Transformation.class));
}
if (json.has("render_type")) {
var renderTypeHintName = GsonHelper.getAsString(json, "render_type");
model.customData.setRenderTypeHint(ResourceLocation.parse(renderTypeHintName));
}
if (json.has("render_type_fast")) {
var renderTypeHintName = GsonHelper.getAsString(json, "render_type_fast");
model.customData.setRenderTypeFastHint(ResourceLocation.parse(renderTypeHintName));
}
if (json.has("visibility")) {
var visibility = GsonHelper.getAsJsonObject(json, "visibility");
for (var part : visibility.entrySet())
model.customData.visibilityData.setVisibilityState(part.getKey(), part.getValue().getAsBoolean());
}
return model;
return new ForgeBlockModelData(transform, renderType, renderTypeFast, visibility);
}
/** This is a dirty fucking hack, but it needs to send in the top most render type. */
@@ -944,9 +917,8 @@ public class ForgeHooksClient {
return group;
}
@Override
public BakedModel bake(ResourceLocation name, ModelState state) {
return parent.bake(name, state);
@Override public ResolvedModel getModel(ResourceLocation p_397309_) {
return parent.getModel(p_397309_);
}
@Override
@@ -955,8 +927,8 @@ public class ForgeHooksClient {
}
@Override
public ModelDebugName rootName() {
return parent.rootName();
public <T> T compute(SharedOperationKey<T> p_395456_) {
return parent.compute(p_395456_);
}
}
}
@@ -5,25 +5,37 @@
package net.minecraftforge.client;
import com.mojang.blaze3d.opengl.GlConst;
import com.mojang.blaze3d.opengl.GlTexture;
import com.mojang.blaze3d.pipeline.BlendFunction;
import com.mojang.blaze3d.pipeline.RenderPipeline;
import com.mojang.blaze3d.platform.DepthTestFunction;
import com.mojang.blaze3d.platform.DestFactor;
import com.mojang.blaze3d.platform.SourceFactor;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.textures.TextureFormat;
import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderPipelines;
import net.minecraft.client.renderer.RenderStateShard;
import net.minecraft.client.renderer.RenderStateShard.TextureStateShard;
import net.minecraft.client.renderer.RenderType;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.VertexFormat;
import net.minecraft.client.renderer.texture.TextureAtlas;
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 net.minecraftforge.fml.earlydisplay.DisplayWindow;
import java.util.function.Function;
import java.util.function.Supplier;
import org.jetbrains.annotations.ApiStatus;
import org.lwjgl.opengl.GL30C;
public enum ForgeRenderTypes {
ITEM_LAYERED_SOLID(()-> getItemLayeredSolid(blockAtlas())),
ITEM_LAYERED_CUTOUT(()-> getItemLayeredCutout(blockAtlas())),
@@ -34,10 +46,20 @@ public enum ForgeRenderTypes {
ITEM_UNSORTED_UNLIT_TRANSLUCENT(()-> getUnlitTranslucent(blockAtlas(), false)),
TRANSLUCENT_ON_PARTICLES_TARGET(() -> getTranslucentParticlesTarget(blockAtlas()));
/**
* Controls the texture filtering state for certain {@link RenderType Render Types}.
*
* @see ForgeRenderTypes#getText
* @see ForgeRenderTypes#getTextIntensity
* @see ForgeRenderTypes#getTextPolygonOffset
* @see ForgeRenderTypes#getTextIntensityPolygonOffset
* @see ForgeRenderTypes#getTextSeeThrough
* @see ForgeRenderTypes#getTextIntensitySeeThrough
*/
public static TriState enableTextTextureLinearFiltering = TriState.FALSE;
@SuppressWarnings("deprecation")
private static final ResourceLocation blockAtlas() {
private static ResourceLocation blockAtlas() {
return TextureAtlas.LOCATION_BLOCKS;
}
@@ -101,6 +123,8 @@ public enum ForgeRenderTypes {
}
/**
* @see #enableTextTextureLinearFiltering
*
* @return Replacement of {@link RenderType#text(ResourceLocation)}, but with optional linear texture filtering.
*/
public static RenderType getText(ResourceLocation locationIn) {
@@ -108,6 +132,8 @@ public enum ForgeRenderTypes {
}
/**
* @see #enableTextTextureLinearFiltering
*
* @return Replacement of {@link RenderType#textIntensity(ResourceLocation)}, but with optional linear texture filtering.
*/
public static RenderType getTextIntensity(ResourceLocation locationIn) {
@@ -115,6 +141,8 @@ public enum ForgeRenderTypes {
}
/**
* @see #enableTextTextureLinearFiltering
*
* @return Replacement of {@link RenderType#textPolygonOffset(ResourceLocation)}, but with optional linear texture filtering.
*/
public static RenderType getTextPolygonOffset(ResourceLocation locationIn) {
@@ -122,6 +150,8 @@ public enum ForgeRenderTypes {
}
/**
* @see #enableTextTextureLinearFiltering
*
* @return Replacement of {@link RenderType#textIntensityPolygonOffset(ResourceLocation)}, but with optional linear texture filtering.
*/
public static RenderType getTextIntensityPolygonOffset(ResourceLocation locationIn) {
@@ -129,6 +159,8 @@ public enum ForgeRenderTypes {
}
/**
* @see #enableTextTextureLinearFiltering
*
* @return Replacement of {@link RenderType#textSeeThrough(ResourceLocation)}, but with optional linear texture filtering.
*/
public static RenderType getTextSeeThrough(ResourceLocation locationIn) {
@@ -136,19 +168,34 @@ public enum ForgeRenderTypes {
}
/**
* @see #enableTextTextureLinearFiltering
*
* @return Replacement of {@link RenderType#textIntensitySeeThrough(ResourceLocation)}, but with optional linear texture filtering.
*/
public static RenderType getTextIntensitySeeThrough(ResourceLocation locationIn) {
return Internal.TEXT_INTENSITY_SEETHROUGH.apply(locationIn);
return Internal.TEXT_INTENSITY_SEE_THROUGH.apply(locationIn);
}
/**
* @return A variation of {@link RenderType#translucent()} that uses {@link OutputStateShard#PARTICLES_TARGET}
* @see #enableTextTextureLinearFiltering
*
* @return A variation of {@link RenderType#translucent()} that uses {@link RenderStateShard.OutputStateShard#PARTICLES_TARGET}
*/
public static RenderType getTranslucentParticlesTarget(ResourceLocation locationIn) {
return Internal.TRANSLUCENT_PARTICLES_TARGET.apply(locationIn);
}
/**
* Render type for rendering the early loading screen, not for modder consumption.
*
* @param window The early loading screen, so we can grab the buffer ID
*/
@ApiStatus.Internal
public static RenderType getLoadingOverlay(DisplayWindow window) {
return Internal.getLoadingOverlay(window);
}
// ----------------------------------------
// Implementation details below this line
// ----------------------------------------
@@ -164,190 +211,269 @@ public enum ForgeRenderTypes {
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 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);
// TODO: [VEN] Note that the names of these render types have been modified to match the names of their container constants,
// This was done for the sake of consistency, but it may be wrong. Need validation.
// Additionally, I am unsure if I have set all the flags correctly. Most of these don't have full docs on
// what they are meant to be used for, so I had to guess how to remap them to the new system.
private static abstract class Internal extends RenderType {
// TODO: [VEN] This is really just here because argument names are stripped I guess? Just as a weird doc thing?
private Internal(String name, int bufferSize, boolean affectsCrumbling, boolean sortOnUpload, Runnable setupState, Runnable clearState) {
super(name, bufferSize, affectsCrumbling, sortOnUpload, setupState, clearState);
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) {
final boolean sortingEnabled = false;
CompositeState renderState = CompositeState.builder()
.setShaderState(RenderType.RENDERTYPE_ENTITY_TRANSLUCENT_SHADER)
.setTextureState(new TextureStateShard(textureLocation, TriState.FALSE, false))
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
.setCullState(NO_CULL)
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true);
return create("forge_entity_unsorted_translucent", DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.QUADS, 256, true, sortingEnabled, renderState);
return create("forge_unsorted_translucent",
TRANSIENT_BUFFER_SIZE,
true,
false,
RenderPipelines.ENTITY_TRANSLUCENT,
CompositeState.builder()
.setTextureState(new TextureStateShard(textureLocation, TriState.FALSE, false))
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true));
}
/*
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 TextureStateShard(textureLocation, TriState.FALSE, false))
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
.setCullState(NO_CULL)
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.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(Internal::unlitTranslucentSorted);
private static RenderType unlitTranslucentSorted(ResourceLocation textureLocation) {
return create("forge_unlit_translucent_sorted",
TRANSIENT_BUFFER_SIZE,
true,
true,
RenderPipelines.ENTITY_TRANSLUCENT,
CompositeState.builder()
.setTextureState(new TextureStateShard(textureLocation, TriState.FALSE, false))
.setLightmapState(NO_LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true));
}
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) {
CompositeState renderState = CompositeState.builder()
.setShaderState(RENDERTYPE_ENTITY_TRANSLUCENT_UNLIT_SHADER)
.setTextureState(new TextureStateShard(textureLocation, TriState.FALSE, false))
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
.setCullState(NO_CULL)
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true);
return create("forge_entity_unlit_translucent", DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.QUADS, 256, true, sortingEnabled, renderState);
public static Function<ResourceLocation, RenderType> UNLIT_TRANSLUCENT_UNSORTED = Util.memoize(Internal::unlitTranslucentUnsorted);
private static RenderType unlitTranslucentUnsorted(ResourceLocation textureLocation) {
return create("forge_unlit_translucent_sorted",
TRANSIENT_BUFFER_SIZE,
true,
false,
RenderPipelines.ENTITY_TRANSLUCENT,
CompositeState.builder()
.setTextureState(new TextureStateShard(textureLocation, TriState.FALSE, false))
.setLightmapState(NO_LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true));
}
public static Function<ResourceLocation, RenderType> LAYERED_ITEM_SOLID = Util.memoize(Internal::layeredItemSolid);
private static RenderType layeredItemSolid(ResourceLocation locationIn) {
RenderType.CompositeState rendertype$state = RenderType.CompositeState.builder()
.setShaderState(RenderType.RENDERTYPE_ENTITY_SOLID_SHADER)
.setTextureState(new TextureStateShard(locationIn, TriState.FALSE, false))
.setTransparencyState(NO_TRANSPARENCY)
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true);
return create("forge_item_entity_solid", DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.QUADS, 256, true, false, rendertype$state);
return create(
"forge_layered_item_soild",
TRANSIENT_BUFFER_SIZE,
true,
false,
RenderPipelines.ENTITY_SOLID,
CompositeState.builder()
.setTextureState(new TextureStateShard(locationIn, TriState.FALSE, false))
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true)
);
}
public static Function<ResourceLocation, RenderType> LAYERED_ITEM_CUTOUT = Util.memoize(Internal::layeredItemCutout);
private static RenderType layeredItemCutout(ResourceLocation locationIn) {
RenderType.CompositeState rendertype$state = RenderType.CompositeState.builder()
.setShaderState(RenderType.RENDERTYPE_ENTITY_CUTOUT_SHADER)
.setTextureState(new TextureStateShard(locationIn, TriState.FALSE, false))
.setTransparencyState(NO_TRANSPARENCY)
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true);
return create("forge_item_entity_cutout", DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.QUADS, 256, true, false, rendertype$state);
return create(
"forge_layered_item_cutout",
TRANSIENT_BUFFER_SIZE,
true,
false,
RenderPipelines.ENTITY_CUTOUT,
CompositeState.builder()
.setTextureState(new TextureStateShard(locationIn, TriState.FALSE, false))
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true)
);
}
public static Function<ResourceLocation, RenderType> LAYERED_ITEM_CUTOUT_MIPPED = Util.memoize(Internal::layeredItemCutoutMipped);
private static RenderType layeredItemCutoutMipped(ResourceLocation locationIn) {
RenderType.CompositeState rendertype$state = RenderType.CompositeState.builder()
.setShaderState(RenderType.RENDERTYPE_ENTITY_SMOOTH_CUTOUT_SHADER)
.setTextureState(new TextureStateShard(locationIn, TriState.FALSE, true))
.setTransparencyState(NO_TRANSPARENCY)
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true);
return create("forge_item_entity_cutout_mipped", DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.QUADS, 256, true, false, rendertype$state);
return create(
"forge_layered_item_cutout_mipped",
TRANSIENT_BUFFER_SIZE,
true,
false,
RenderPipelines.ENTITY_SMOOTH_CUTOUT,
CompositeState.builder()
.setTextureState(new TextureStateShard(locationIn, TriState.FALSE, true))
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true)
);
}
public static Function<ResourceLocation, RenderType> LAYERED_ITEM_TRANSLUCENT = Util.memoize(Internal::layeredItemTranslucent);
private static RenderType layeredItemTranslucent(ResourceLocation locationIn) {
RenderType.CompositeState rendertype$state = RenderType.CompositeState.builder()
.setShaderState(RenderType.RENDERTYPE_ENTITY_TRANSLUCENT_SHADER)
.setTextureState(new TextureStateShard(locationIn, TriState.FALSE, false))
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true);
return create("forge_item_entity_translucent_cull", DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.QUADS, 256, true, true, rendertype$state);
return create(
"forge_layered_item_translucent",
TRANSIENT_BUFFER_SIZE,
true,
true,
RenderPipelines.ITEM_ENTITY_TRANSLUCENT_CULL,
CompositeState.builder()
.setTextureState(new TextureStateShard(locationIn, TriState.FALSE, false))
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true)
);
}
public static Function<ResourceLocation, RenderType> TEXT = Util.memoize(Internal::getText);
private static RenderType getText(ResourceLocation locationIn) {
RenderType.CompositeState rendertype$state = RenderType.CompositeState.builder()
.setShaderState(RENDERTYPE_TEXT_SHADER)
.setTextureState(new CustomizableTextureState(locationIn, () -> ForgeRenderTypes.enableTextTextureLinearFiltering, () -> false))
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
.setLightmapState(LIGHTMAP)
.createCompositeState(false);
return create("forge_text", DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP, VertexFormat.Mode.QUADS, 256, false, true, rendertype$state);
return create(
"forge_text",
SMALL_BUFFER_SIZE,
false,
true,
RenderPipelines.TEXT,
CompositeState.builder()
.setTextureState(new CustomizableTextureState(locationIn, false))
.setLightmapState(LIGHTMAP)
.createCompositeState(false)
);
}
public static Function<ResourceLocation, RenderType> TEXT_INTENSITY = Util.memoize(Internal::getTextIntensity);
private static RenderType getTextIntensity(ResourceLocation locationIn) {
RenderType.CompositeState rendertype$state = RenderType.CompositeState.builder()
.setShaderState(RENDERTYPE_TEXT_INTENSITY_SHADER)
.setTextureState(new CustomizableTextureState(locationIn, () -> ForgeRenderTypes.enableTextTextureLinearFiltering, () -> false))
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
.setLightmapState(LIGHTMAP)
.createCompositeState(false);
return create("text_intensity", DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP, VertexFormat.Mode.QUADS, 256, false, true, rendertype$state);
return create(
"forge_text_intensity",
SMALL_BUFFER_SIZE,
false,
false,
RenderPipelines.TEXT_INTENSITY,
CompositeState.builder()
.setTextureState(new CustomizableTextureState(locationIn, false))
.setLightmapState(LIGHTMAP)
.createCompositeState(false)
);
}
public static Function<ResourceLocation, RenderType> TEXT_POLYGON_OFFSET = Util.memoize(Internal::getTextPolygonOffset);
private static RenderType getTextPolygonOffset(ResourceLocation locationIn) {
RenderType.CompositeState rendertype$state = RenderType.CompositeState.builder()
.setShaderState(RENDERTYPE_TEXT_SHADER)
.setTextureState(new CustomizableTextureState(locationIn, () -> ForgeRenderTypes.enableTextTextureLinearFiltering, () -> false))
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
.setLightmapState(LIGHTMAP)
.setLayeringState(POLYGON_OFFSET_LAYERING)
.createCompositeState(false);
return create("text_intensity", DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP, VertexFormat.Mode.QUADS, 256, false, true, rendertype$state);
return create(
"forge_text_polygon_offset",
TRANSIENT_BUFFER_SIZE,
false,
true,
RenderPipelines.TEXT_POLYGON_OFFSET,
CompositeState.builder()
.setTextureState(new CustomizableTextureState(locationIn, () -> enableTextTextureLinearFiltering, () -> false))
.setLightmapState(LIGHTMAP)
.createCompositeState(false)
);
}
public static Function<ResourceLocation, RenderType> TEXT_INTENSITY_POLYGON_OFFSET = Util.memoize(Internal::getTextIntensityPolygonOffset);
private static RenderType getTextIntensityPolygonOffset(ResourceLocation locationIn) {
RenderType.CompositeState rendertype$state = RenderType.CompositeState.builder()
.setShaderState(RENDERTYPE_TEXT_INTENSITY_SHADER)
.setTextureState(new CustomizableTextureState(locationIn, () -> ForgeRenderTypes.enableTextTextureLinearFiltering, () -> false))
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
.setLightmapState(LIGHTMAP)
.setLayeringState(POLYGON_OFFSET_LAYERING)
.createCompositeState(false);
return create("text_intensity", DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP, VertexFormat.Mode.QUADS, 256, false, true, rendertype$state);
return create(
"forge_text_intensity_polygon_offset",
TRANSIENT_BUFFER_SIZE,
false,
true,
RenderPipelines.TEXT_INTENSITY,
CompositeState.builder()
.setTextureState(new CustomizableTextureState(locationIn, false))
.setLightmapState(LIGHTMAP)
.createCompositeState(false)
);
}
public static Function<ResourceLocation, RenderType> TEXT_SEETHROUGH = Util.memoize(Internal::getTextSeeThrough);
public static Function<ResourceLocation, RenderType> TEXT_SEE_THROUGH = Util.memoize(Internal::getTextSeeThrough);
/**
* Use {@link #TEXT_SEE_THROUGH} instead.
*/
@Deprecated
public static Function<ResourceLocation, RenderType> TEXT_SEETHROUGH = TEXT_SEE_THROUGH;
private static RenderType getTextSeeThrough(ResourceLocation locationIn) {
RenderType.CompositeState rendertype$state = RenderType.CompositeState.builder()
.setShaderState(RENDERTYPE_TEXT_SEE_THROUGH_SHADER)
.setTextureState(new CustomizableTextureState(locationIn, () -> ForgeRenderTypes.enableTextTextureLinearFiltering, () -> false))
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
.setLightmapState(LIGHTMAP)
.setDepthTestState(NO_DEPTH_TEST)
.setWriteMaskState(COLOR_WRITE)
.createCompositeState(false);
return create("forge_text_see_through", DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP, VertexFormat.Mode.QUADS, 256, false, true, rendertype$state);
return create(
"forge_text_see_through",
TRANSIENT_BUFFER_SIZE,
false,
false,
RenderPipelines.TEXT_SEE_THROUGH,
CompositeState.builder()
.setTextureState(new CustomizableTextureState(locationIn, false))
.setLightmapState(LIGHTMAP)
.createCompositeState(false)
);
}
public static Function<ResourceLocation, RenderType> TEXT_INTENSITY_SEETHROUGH = Util.memoize(Internal::getTextIntensitySeeThrough);
public static Function<ResourceLocation, RenderType> TEXT_INTENSITY_SEE_THROUGH = Util.memoize(Internal::getTextIntensitySeeThrough);
/**
* Use {@link #TEXT_INTENSITY_SEE_THROUGH} instead.
*/
@Deprecated
public static Function<ResourceLocation, RenderType> TEXT_INTENSITY_SEETHROUGH = TEXT_INTENSITY_SEE_THROUGH;
private static RenderType getTextIntensitySeeThrough(ResourceLocation locationIn) {
RenderType.CompositeState rendertype$state = RenderType.CompositeState.builder()
.setShaderState(RENDERTYPE_TEXT_INTENSITY_SEE_THROUGH_SHADER)
.setTextureState(new CustomizableTextureState(locationIn, () -> ForgeRenderTypes.enableTextTextureLinearFiltering, () -> false))
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
.setLightmapState(LIGHTMAP)
.setDepthTestState(NO_DEPTH_TEST)
.setWriteMaskState(COLOR_WRITE)
.createCompositeState(false);
return create("forge_text_see_through", DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP, VertexFormat.Mode.QUADS, 256, false, true, rendertype$state);
return create(
"forge_text_intensity_see_through",
TRANSIENT_BUFFER_SIZE,
false,
true,
RenderPipelines.TEXT_INTENSITY_SEE_THROUGH,
CompositeState.builder()
.setTextureState(new CustomizableTextureState(locationIn, false))
.setLightmapState(LIGHTMAP)
.createCompositeState(false)
);
}
public static Function<ResourceLocation, RenderType> TRANSLUCENT_PARTICLES_TARGET = Util.memoize(Internal::getTranslucentParticlesTarget);
private static RenderType getTranslucentParticlesTarget(ResourceLocation locationIn) {
RenderType.CompositeState rendertype$state = RenderType.CompositeState.builder()
.setShaderState(RENDERTYPE_TRANSLUCENT_SHADER)
.setTextureState(new TextureStateShard(locationIn, TriState.FALSE, true))
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
.setLightmapState(LIGHTMAP)
.setOutputState(PARTICLES_TARGET)
.createCompositeState(true);
return create("forge_translucent_particles_target", DefaultVertexFormat.BLOCK, VertexFormat.Mode.QUADS, 2097152, true, true, rendertype$state);
return create(
"forge_translucent_particles_target",
TRANSIENT_BUFFER_SIZE,
true,
true,
RenderPipelines.TRANSLUCENT_PARTICLE,
CompositeState.builder()
.setTextureState(new TextureStateShard(locationIn, TriState.FALSE, false))
.setOutputState(PARTICLES_TARGET)
.setLightmapState(LIGHTMAP)
.createCompositeState(true)
);
}
private static final RenderPipeline LOADING_PIPELINE = RenderPipeline.builder(RenderPipelines.GUI_TEXTURED_SNIPPET)
.withLocation("pipeline/forge/loading_overlay")
.withBlend(new BlendFunction(SourceFactor.SRC_ALPHA, DestFactor.ONE))
.withDepthTestFunction(DepthTestFunction.NO_DEPTH_TEST)
.withDepthWrite(false)
.build();
public static RenderType getLoadingOverlay(DisplayWindow window) {
return create(
"forge_loading_overlay",
TRANSIENT_BUFFER_SIZE,
false,
false,
LOADING_PIPELINE,
CompositeState.builder()
.setTextureState(new LoadingOverlayTextureState(window))
.createCompositeState(false)
);
}
}
private static class CustomizableTextureState extends TextureStateShard {
// [VEN] Here to make init shorter
private static final Supplier<TriState> BLUR_STATE = () -> enableTextTextureLinearFiltering;
private static final Supplier<Boolean> MIP_ON_STATE = () -> true;
private static final Supplier<Boolean> MIP_OFF_STATE = () -> false;
private CustomizableTextureState(ResourceLocation resLoc, boolean mipmap) {
this(resLoc, BLUR_STATE, mipmap ? MIP_ON_STATE : MIP_OFF_STATE);
}
private CustomizableTextureState(ResourceLocation resLoc, Supplier<TriState> blur, Supplier<Boolean> mipmap) {
super(resLoc, blur.get(), mipmap.get());
this.setupState = () -> {
@@ -356,7 +482,25 @@ public enum ForgeRenderTypes {
TextureManager manager = Minecraft.getInstance().getTextureManager();
var texture = manager.getTexture(resLoc);
texture.setFilter(this.blur, this.mipmap);
RenderSystem.setShaderTexture(0, resLoc);
RenderSystem.setShaderTexture(0, texture.getTexture());
};
}
}
private static class LoadingOverlayTextureState extends TextureStateShard {
private static final ResourceLocation LOADING_TEXTURE = ResourceLocation.fromNamespaceAndPath("forge", "loading_overlay");
private final GlTexture texture;
private LoadingOverlayTextureState(DisplayWindow window) {
super(LOADING_TEXTURE, TriState.DEFAULT, false);
this.texture = new GlTexture(LOADING_TEXTURE.toString(), TextureFormat.RGBA8,
window.context().width(), window.context().height(), 0,
window.getFramebufferTextureId()) {};
this.setupState = () -> {
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);
RenderSystem.setShaderTexture(0, texture);
};
}
}
@@ -14,8 +14,6 @@ import org.jetbrains.annotations.ApiStatus;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.gui.Font;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
@@ -23,24 +21,21 @@ import net.minecraftforge.client.event.RegisterItemDecorationsEvent;
import net.minecraftforge.fml.ModLoader;
@ApiStatus.Internal
public final class ItemDecoratorHandler
{
public final class ItemDecoratorHandler {
private final List<IItemDecorator> itemDecorators;
private static Map<Item, ItemDecoratorHandler> DECORATOR_LOOKUP = ImmutableMap.of();
private static final ItemDecoratorHandler EMPTY = new ItemDecoratorHandler();
private ItemDecoratorHandler()
{
private ItemDecoratorHandler() {
this.itemDecorators = ImmutableList.of();
}
private ItemDecoratorHandler(List<IItemDecorator> itemDecorators)
{
private ItemDecoratorHandler(List<IItemDecorator> itemDecorators) {
this.itemDecorators = ImmutableList.copyOf(itemDecorators);
}
public static void init()
{
public static void init() {
var decorators = new HashMap<Item, List<IItemDecorator>>();
var event = new RegisterItemDecorationsEvent(decorators);
ModLoader.get().postEventWrapContainerInModOrder(event);
@@ -52,25 +47,23 @@ public final class ItemDecoratorHandler
DECORATOR_LOOKUP = builder.build();
}
public static ItemDecoratorHandler of(ItemStack stack)
{
public static ItemDecoratorHandler of(ItemStack stack) {
return DECORATOR_LOOKUP.getOrDefault(stack.getItem(), EMPTY);
}
public void render(GuiGraphics guiGraphics, Font font, ItemStack stack, int xOffset, int yOffset)
{
public void render(GuiGraphics guiGraphics, Font font, ItemStack stack, int xOffset, int yOffset) {
resetRenderState();
for (IItemDecorator itemDecorator : itemDecorators)
{
for (IItemDecorator itemDecorator : itemDecorators) {
if (itemDecorator.render(guiGraphics, font, stack, xOffset, yOffset))
resetRenderState();
}
}
private void resetRenderState()
{
private void resetRenderState() {
/*
RenderSystem.enableDepthTest();
RenderSystem.enableBlend();
RenderSystem.defaultBlendFunc();
*/
}
}
@@ -7,8 +7,6 @@ package net.minecraftforge.client;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
@@ -9,7 +9,7 @@ import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import net.minecraft.client.renderer.ItemBlockRenderTypes;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.Sheets;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.renderer.block.model.BlockStateModel;
import net.minecraft.util.RandomSource;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
@@ -52,7 +52,7 @@ 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) {
public static RenderType getFallbackItemRenderType(ItemStack stack, BlockStateModel model) {
if (stack.getItem() instanceof BlockItem blockItem) {
var renderTypes = model.getRenderTypes(blockItem.getBlock().defaultBlockState(), RandomSource.create(42), ModelData.EMPTY);
if (renderTypes.contains(RenderType.translucent()))
@@ -149,17 +149,17 @@ public abstract class ModelEvent extends Event {
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public static class RegisterGeometryLoaders extends ModelEvent implements IModBusEvent {
private final Map<ResourceLocation, IGeometryLoader<?>> loaders;
private final Map<ResourceLocation, IGeometryLoader> loaders;
@ApiStatus.Internal
public RegisterGeometryLoaders(Map<ResourceLocation, IGeometryLoader<?>> loaders) {
public RegisterGeometryLoaders(Map<ResourceLocation, IGeometryLoader> loaders) {
this.loaders = loaders;
}
/**
* Registers a new geometry loader.
*/
public void register(String name, IGeometryLoader<?> loader) {
public void register(String name, IGeometryLoader loader) {
@SuppressWarnings("removal")
var namespace = ModLoadingContext.get().getActiveNamespace();
var key = ResourceLocation.fromNamespaceAndPath(namespace, name);
@@ -6,7 +6,6 @@
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;
import net.minecraftforge.eventbus.api.Event;
@@ -6,7 +6,6 @@
package net.minecraftforge.client.event;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.world.entity.HumanoidArm;
@@ -13,6 +13,7 @@ import net.minecraftforge.eventbus.api.Cancelable;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.LogicalSide;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
@@ -30,42 +31,31 @@ import java.io.IOException;
* @see Screenshot
*/
@Cancelable
public class ScreenshotEvent extends Event
{
public class ScreenshotEvent extends Event {
public static final Component DEFAULT_CANCEL_REASON = Component.literal("Screenshot canceled");
private final NativeImage image;
private File screenshotFile;
private Component resultMessage = null;
private @Nullable Component resultMessage = null;
@ApiStatus.Internal
public ScreenshotEvent(NativeImage image, File screenshotFile)
{
public ScreenshotEvent(NativeImage image, File screenshotFile) {
this.image = image;
this.screenshotFile = screenshotFile;
try
{
try {
this.screenshotFile = screenshotFile.getCanonicalFile(); // FORGE: Fix errors on Windows with paths that include \.\
} catch (IOException ignored)
{
}
} catch (IOException ignored) { }
}
/**
* {@return the in-memory image of the screenshot}
*/
public NativeImage getImage()
{
return image;
/** @return the in-memory image of the screenshot */
public NativeImage getImage() {
return this.image;
}
/**
* @return the file where the screenshot will be saved to
*/
public File getScreenshotFile()
{
return screenshotFile;
/** @return the file where the screenshot will be saved to */
public File getScreenshotFile() {
return this.screenshotFile;
}
/**
@@ -73,40 +63,36 @@ public class ScreenshotEvent extends Event
*
* @param screenshotFile the new filepath
*/
public void setScreenshotFile(File screenshotFile)
{
public void setScreenshotFile(File screenshotFile) {
this.screenshotFile = screenshotFile;
}
/**
* {@return the custom cancellation message, or {@code null} if no custom message is set}
*/
public Component getResultMessage()
{
return resultMessage;
/** @return the custom cancellation message, or {@code null} if no custom message is set */
public @Nullable Component getResultMessage() {
return this.resultMessage;
}
/**
* Sets the new custom cancellation message used to inform the player.
* <p>
* It may be {@code null}, in which case the {@linkplain #DEFAULT_CANCEL_REASON default cancel reason} will be used.
*
* @param resultMessage the new result message
*/
public void setResultMessage(Component resultMessage)
{
public void setResultMessage(Component resultMessage) {
this.resultMessage = resultMessage;
}
/**
* Returns the cancellation message to be used in informing the player.
*
* <p>If there is no custom message given ({@link #getResultMessage()} returns {@code null}), then
* <p>If there is no custom message given ({@link #getResultMessage()} == {@code null}), then
* the message will be the {@linkplain #DEFAULT_CANCEL_REASON default cancel reason message}.</p>
*
* @return the cancel message for the player
*/
public Component getCancelMessage()
{
return getResultMessage() != null ? getResultMessage() : DEFAULT_CANCEL_REASON;
public Component getCancelMessage() {
var message = this.getResultMessage();
return message != null ? message : DEFAULT_CANCEL_REASON;
}
}
@@ -1,111 +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.renderer.ItemBlockRenderTypes;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.block.model.BakedQuad;
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.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.util.RandomSource;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.client.ChunkRenderTypeSet;
import net.minecraftforge.client.RenderTypeHelper;
import net.minecraftforge.client.model.data.ModelData;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* Extension interface for {@link IForgeBakedModel}.
*/
@SuppressWarnings("deprecation")
public interface IForgeBakedModel {
private BakedModel self() {
return (BakedModel)this;
}
/**
* A null {@link RenderType} is used for the breaking overlay as well as non-standard rendering, so models should return all their quads.
*/
@NotNull
default List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData data, @Nullable RenderType renderType) {
return self().getQuads(state, side, rand);
}
default boolean useAmbientOcclusion(BlockState state) {
return self().useAmbientOcclusion();
}
default boolean useAmbientOcclusion(BlockState state, RenderType renderType) {
return self().useAmbientOcclusion(state);
}
/**
* Applies a transform for the given {@link ItemTransforms.TransformType} and {@code applyLeftHandTransform}, and
* returns the model to be rendered.
*/
default BakedModel applyTransform(ItemDisplayContext transformType, PoseStack poseStack, boolean applyLeftHandTransform) {
self().getTransforms().getTransform(transformType).apply(applyLeftHandTransform, poseStack);
return self();
}
default @NotNull ModelData getModelData(@NotNull BlockAndTintGetter level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull ModelData modelData) {
return modelData;
}
default TextureAtlasSprite getParticleIcon(@NotNull ModelData data) {
return self().getParticleIcon();
}
/**
* Gets the set of {@link RenderType render types} to use when drawing this block in the level.
* Supported types are those returned by {@link RenderType#chunkBufferLayers()}.
* <p>
* By default, defers query to {@link ItemBlockRenderTypes}.
*/
default ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data) {
return ItemBlockRenderTypes.getRenderLayers(state);
}
/**
* Gets an ordered list of {@link RenderType render types} to use when drawing this item.
* All render types using the {@link com.mojang.blaze3d.vertex.DefaultVertexFormat#NEW_ENTITY} format are supported.
* <p>
* This method will only be called on the models returned by {@link #getRenderPasses(ItemStack, boolean)}.
* <p>
* By default, defers query to {@link ItemBlockRenderTypes}.
*
* @see #getRenderPasses(ItemStack, boolean)
*/
/*
default List<RenderType> getRenderTypes(ItemStack itemStack, boolean fabulous) {
return List.of(RenderTypeHelper.getFallbackItemRenderType(itemStack, self()));
}
*/
/**
* Gets an ordered list of baked models used to render this model as an item.
* Each of those models' render types will be queried via {@link #getRenderTypes(ItemStack, boolean)}.
* <p>
* By default, returns the model itself.
*
* @see #getRenderTypes(ItemStack, boolean)
*/
/*
default List<BakedModel> getRenderPasses(ItemStack itemStack, boolean fabulous) {
return List.of(self());
}
*/
}
@@ -1,26 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.extensions;
import net.minecraft.core.Direction;
import net.minecraft.world.level.BlockAndTintGetter;
/**
* Extension interface for {@link BlockAndTintGetter}.
*/
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.getApproximateNearest(normalX, normalY, normalZ), shade);
}
}
@@ -0,0 +1,71 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.extensions;
import net.minecraft.client.renderer.ItemBlockRenderTypes;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.block.model.BlockModelPart;
import net.minecraft.client.renderer.block.model.BlockStateModel;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.core.BlockPos;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.client.ChunkRenderTypeSet;
import net.minecraftforge.client.model.data.ModelData;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.List;
@SuppressWarnings("deprecation")
public interface IForgeBlockStateModel {
private BlockStateModel self() {
return (BlockStateModel)this;
}
default @NotNull ModelData getModelData(@NotNull BlockAndTintGetter level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull ModelData modelData) {
return modelData;
}
default TextureAtlasSprite particleIcon(@NotNull ModelData data) {
return self().particleIcon();
}
/**
* Gets the set of {@link RenderType render types} to use when drawing this block in the level.
* Supported types are those returned by {@link RenderType#chunkBufferLayers()}.
* <p>
* By default, defers query to {@link ItemBlockRenderTypes}.
*/
@SuppressWarnings("removal")
default ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data) {
return ItemBlockRenderTypes.getRenderLayers(state);
}
/**
* Collects the parts of this model to render for the specified render type.
* Not all paths call this, or use a valid render type. So it is recommended to also implement a sane default in
* the normal {@link BlockStateModel#collectParts(RandomSource, List)} method.
*/
default List<BlockModelPart> collectParts(RandomSource random, ModelData data, @Nullable RenderType renderType) {
List<BlockModelPart> list = new ObjectArrayList<>();
this.collectParts(random, list, data, renderType);
return list;
}
/**
* Collects the parts of this model to render for the specified render type.
* Not all paths call this, or use a valid render type. So it is recommended to also implement a sane default in
* the normal {@link BlockStateModel#collectParts(RandomSource, List)} method.
*/
default void collectParts(RandomSource random, List<BlockModelPart> dest, ModelData data, @Nullable RenderType renderType) {
self().collectParts(random, dest);
}
}
@@ -0,0 +1,14 @@
package net.minecraftforge.client.extensions;
import com.mojang.blaze3d.textures.GpuTexture;
public interface IForgeGpuTexture {
@SuppressWarnings("unused")
private GpuTexture self() {
return (GpuTexture) this;
}
default boolean isStencilEnabled() {
return false;
}
}
@@ -5,7 +5,6 @@
package net.minecraftforge.client.extensions;
import com.google.common.collect.ImmutableList;
import com.mojang.blaze3d.vertex.VertexFormat;
import com.mojang.blaze3d.vertex.VertexFormatElement;
@@ -159,9 +159,9 @@ public class ModListScreen extends Screen {
}
@Override
protected void drawPanel(GuiGraphics guiGraphics, int entryRight, int relativeY, Tesselator tess, int mouseX, int mouseY) {
protected void drawPanel(GuiGraphics guiGraphics, int entryRight, int relativeY, int mouseX, int mouseY) {
if (logoPath != null) {
RenderSystem.enableBlend();
//RenderSystem.enableBlend();
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
// Draw the logo image inscribed in a rectangle with width entryWidth (minus some padding) and height 50
int headerHeight = 50;
@@ -171,9 +171,9 @@ public class ModListScreen extends Screen {
for (FormattedCharSequence line : lines) {
if (line != null) {
RenderSystem.enableBlend();
//RenderSystem.enableBlend();
guiGraphics.drawString(ModListScreen.this.font, line, left + PADDING, relativeY, 0xFFFFFF);
RenderSystem.disableBlend();
//RenderSystem.disableBlend();
}
relativeY += font.lineHeight;
}
@@ -409,7 +409,7 @@ public class ModListScreen extends Screen {
if (logo != null) {
var texture = new DynamicTexture(logo) {
var texture = new DynamicTexture(() -> logoFile, logo); /* {
@Override
public void upload() {
var pixels = this.getPixels();
@@ -420,6 +420,7 @@ public class ModListScreen extends Screen {
}
}
};
*/
tm.register(LOGO, texture);
var size = new Size2i(logo.getWidth(), logo.getHeight());
@@ -5,6 +5,8 @@
package net.minecraftforge.client.gui;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
@@ -29,7 +31,6 @@ import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.HoverEvent.Action;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.TextColor;
@@ -227,8 +228,16 @@ public class ModMismatchDisconnectedScreen extends Screen {
String modId = id.getNamespace();
String tooltipId = id.getPath().isEmpty() ? id.getNamespace() : id.toString();
return Component.literal(modName).withStyle(color % 2 == 0 ? ChatFormatting.GOLD : ChatFormatting.YELLOW)
.withStyle(s -> s.withHoverEvent(new HoverEvent(Action.SHOW_TEXT, Component.literal(tooltipId + (!presentModUrls.getOrDefault(modId, "").isEmpty() ? "\n" + ForgeI18n.parseMessage("fml.modmismatchscreen.homepage") : "")))))
.withStyle(s -> s.withClickEvent(!presentModUrls.getOrDefault(modId, "").isEmpty() ? new ClickEvent(ClickEvent.Action.OPEN_URL, presentModUrls.get(modId)) : null));
.withStyle(s -> s.withHoverEvent(new HoverEvent.ShowText(Component.literal(tooltipId + (!presentModUrls.getOrDefault(modId, "").isEmpty() ? "\n" + ForgeI18n.parseMessage("fml.modmismatchscreen.homepage") : "")))))
.withStyle(s -> s.withClickEvent(openUrl(presentModUrls.getOrDefault(modId, ""))));
}
private static ClickEvent.OpenUrl openUrl(String url) {
try {
return url.isEmpty() ? null : new ClickEvent.OpenUrl(new URI(url));
} catch (URISyntaxException e) {
return null;
}
}
@Override
@@ -242,7 +251,7 @@ public class ModMismatchDisconnectedScreen extends Screen {
}
@Override
protected void drawPanel(GuiGraphics guiGraphics, int entryRight, int relativeY, Tesselator tess, int mouseX, int mouseY) {
protected void drawPanel(GuiGraphics guiGraphics, int entryRight, int relativeY, int mouseX, int mouseY) {
int i = 0;
for (Pair<FormattedCharSequence, Pair<FormattedCharSequence, FormattedCharSequence>> line : lineTable) {
@@ -50,7 +50,7 @@ public enum VanillaGuiOverlay {
PORTAL("portal", (gui, guiGraphics, partialTick, screenWidth, screenHeight) -> {
float f1 = Mth.lerp(partialTick, gui.getMinecraft().player.oSpinningEffectIntensity, gui.getMinecraft().player.spinningEffectIntensity);
if (f1 > 0.0F && !gui.getMinecraft().player.hasEffect(MobEffects.CONFUSION)) {
if (f1 > 0.0F && !gui.getMinecraft().player.hasEffect(MobEffects.NAUSEA)) {
gui.setupOverlayRenderState(true, false);
gui.renderPortalOverlay(guiGraphics, f1);
}
@@ -5,20 +5,20 @@
package net.minecraftforge.client.gui.widget;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
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.renderer.CoreShaders;
import net.minecraft.client.renderer.RenderType;
import java.util.Collections;
import java.util.List;
/**
* Abstract scroll panel class.
* TODO: [Forge][Rendering] ScrollPanel could potentially be replaced by AbstractScrollArea
*/
public abstract class ScrollPanel extends AbstractContainerEventHandler implements Renderable, NarratableEntry {
private final Minecraft client;
@@ -145,7 +145,7 @@ public abstract class ScrollPanel extends AbstractContainerEventHandler implemen
/**
* Draws the background of the scroll panel. This runs AFTER Scissors are enabled.
*/
protected void drawBackground(GuiGraphics guiGraphics, Tesselator tess, float partialTick) {
protected void drawBackground(GuiGraphics guiGraphics, float partialTick) {
// BufferBuilder worldr = tess.getBuilder();
if (this.client.level != null) {
@@ -168,7 +168,7 @@ public abstract class ScrollPanel extends AbstractContainerEventHandler implemen
* Draw anything special on the screen. Scissor (RenderSystem.enableScissor) is enabled
* for anything that is rendered outside the view box. Do not mess with Scissor unless you support this.
*/
protected abstract void drawPanel(GuiGraphics guiGraphics, int entryRight, int relativeY, Tesselator tess, int mouseX, int mouseY);
protected abstract void drawPanel(GuiGraphics guiGraphics, int entryRight, int relativeY, int mouseX, int mouseY);
protected boolean clickPanel(double mouseX, double mouseY, int button) {
return false;
@@ -262,18 +262,14 @@ public abstract class ScrollPanel extends AbstractContainerEventHandler implemen
@Override
public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
Tesselator tess = Tesselator.getInstance();
guiGraphics.enableScissor(left, top, width, height);
double scale = client.getWindow().getGuiScale();
RenderSystem.enableScissor((int)(left * scale), (int)(client.getWindow().getHeight() - (bottom * scale)),
(int)(width * scale), (int)(height * scale));
this.drawBackground(guiGraphics, tess, partialTick);
this.drawBackground(guiGraphics, partialTick);
int baseY = this.top + border - (int)this.scrollDistance;
this.drawPanel(guiGraphics, right, baseY, tess, mouseX, mouseY);
this.drawPanel(guiGraphics, right, baseY, mouseX, mouseY);
RenderSystem.disableDepthTest();
guiGraphics.disableScissor();
int extraHeight = (this.getContentHeight() + border) - height;
if (extraHeight > 0) {
@@ -283,46 +279,25 @@ public abstract class ScrollPanel extends AbstractContainerEventHandler implemen
if (barTop < this.top)
barTop = this.top;
int barBgAlpha = this.barBgColor >> 24 & 0xff;
int barBgRed = this.barBgColor >> 16 & 0xff;
int barBgGreen = this.barBgColor >> 8 & 0xff;
int barBgBlue = this.barBgColor & 0xff;
var source = guiGraphics.getBufferSource();
var buf = source.getBuffer(RenderType.gui());
buf.addVertex(barLeft, this.bottom, 0.0F).setColor(barBgColor);
buf.addVertex(barLeft + barWidth, this.bottom, 0.0F).setColor(barBgColor);
buf.addVertex(barLeft + barWidth, this.top, 0.0F).setColor(barBgColor);
buf.addVertex(barLeft, this.top, 0.0F).setColor(barBgColor);
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);
worldr.addVertex(barLeft + barWidth, this.top, 0.0F).setColor(barBgRed, barBgGreen, barBgBlue, barBgAlpha);
worldr.addVertex(barLeft, this.top, 0.0F).setColor(barBgRed, barBgGreen, barBgBlue, barBgAlpha);
BufferUploader.drawWithShader(worldr.buildOrThrow());
buf = source.getBuffer(RenderType.gui());
buf.addVertex(barLeft, barTop + barHeight, 0.0F).setColor(barColor);
buf.addVertex(barLeft + barWidth, barTop + barHeight, 0.0F).setColor(barColor);
buf.addVertex(barLeft + barWidth, barTop, 0.0F).setColor(barColor);
buf.addVertex(barLeft, barTop, 0.0F).setColor(barColor);
int barAlpha = this.barColor >> 24 & 0xff;
int barRed = this.barColor >> 16 & 0xff;
int barGreen = this.barColor >> 8 & 0xff;
int barBlue = this.barColor & 0xff;
worldr = tess.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);
worldr.addVertex(barLeft, barTop + barHeight, 0.0F).setColor(barRed, barGreen, barBlue, barAlpha);
worldr.addVertex(barLeft + barWidth, barTop + barHeight, 0.0F).setColor(barRed, barGreen, barBlue, barAlpha);
worldr.addVertex(barLeft + barWidth, barTop, 0.0F).setColor(barRed, barGreen, barBlue, barAlpha);
worldr.addVertex(barLeft, barTop, 0.0F).setColor(barRed, barGreen, barBlue, barAlpha);
BufferUploader.drawWithShader(worldr.buildOrThrow());
int barBorderAlpha = this.barBorderColor >> 24 & 0xff;
int barBorderRed = this.barBorderColor >> 16 & 0xff;
int barBorderGreen = this.barBorderColor >> 8 & 0xff;
int barBorderBlue = this.barBorderColor & 0xff;
worldr = tess.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);
worldr.addVertex(barLeft, barTop + barHeight - 1, 0.0F).setColor(barBorderRed, barBorderGreen, barBorderBlue, barBorderAlpha);
worldr.addVertex(barLeft + barWidth - 1, barTop + barHeight - 1, 0.0F).setColor(barBorderRed, barBorderGreen, barBorderBlue, barBorderAlpha);
worldr.addVertex(barLeft + barWidth - 1, barTop, 0.0F).setColor(barBorderRed, barBorderGreen, barBorderBlue, barBorderAlpha);
worldr.addVertex(barLeft, barTop, 0.0F).setColor(barBorderRed, barBorderGreen, barBorderBlue, barBorderAlpha);
BufferUploader.drawWithShader(worldr.buildOrThrow());
buf = source.getBuffer(RenderType.gui());
buf.addVertex(barLeft, barTop + barHeight - 1, 0.0F).setColor(barBorderColor);
buf.addVertex(barLeft + barWidth - 1, barTop + barHeight - 1, 0.0F).setColor(barBorderColor);
buf.addVertex(barLeft + barWidth - 1, barTop, 0.0F).setColor(barBorderColor);
buf.addVertex(barLeft, barTop, 0.0F).setColor(barBorderColor);
}
RenderSystem.disableBlend();
RenderSystem.disableScissor();
}
protected void drawGradientRect(GuiGraphics guiGraphics, int left, int top, int right, int bottom, int color1, int color2) {
@@ -5,23 +5,18 @@
package net.minecraftforge.client.loading;
import com.mojang.blaze3d.platform.GlConst;
import com.mojang.blaze3d.opengl.GlTexture;
import com.mojang.blaze3d.systems.RenderSystem;
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 net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.LoadingOverlay;
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.client.ForgeRenderTypes;
import net.minecraftforge.fml.StartupMessageManager;
import net.minecraftforge.fml.earlydisplay.DisplayWindow;
import net.minecraftforge.fml.loading.progress.ProgressMeter;
import org.jetbrains.annotations.NotNull;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL30C;
@@ -38,18 +33,23 @@ import java.util.function.Supplier;
* It is somewhat a copy of the superclass render method.
*/
public class ForgeLoadingOverlay extends LoadingOverlay {
private static final boolean ENABLE = Boolean.parseBoolean("forge.enableForgeLoadingOverlay");
private final Minecraft minecraft;
private final ReloadInstance reload;
private final DisplayWindow displayWindow;
private final ProgressMeter progress;
private final RenderType earlyBuffer;
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.displayWindow = displayWindow;
displayWindow.addMojangTexture(mc.getTextureManager().getTexture(MOJANG_STUDIOS_LOGO_LOCATION).getId());
var texture = mc.getTextureManager().getTexture(MOJANG_STUDIOS_LOGO_LOCATION);
var glTexture = (GlTexture)texture.getTexture();
displayWindow.addMojangTexture(glTexture.glId());
this.progress = StartupMessageManager.prependProgressBar("Minecraft Progress", 100);
this.earlyBuffer = ForgeRenderTypes.getLoadingOverlay(displayWindow);
}
public static Supplier<LoadingOverlay> newInstance(Supplier<Minecraft> mc, Supplier<ReloadInstance> ri, Consumer<Optional<Throwable>> handler, DisplayWindow window) {
@@ -58,6 +58,8 @@ public class ForgeLoadingOverlay extends LoadingOverlay {
@Override
protected boolean renderContents(GuiGraphics gui, float fade) {
if (!ENABLE)
return true;
progress.setAbsolute(Mth.clamp((int)(this.reload.getActualProgress() * 100f), 0, 100));
int alpha = (int)(fade * 255);
@@ -72,18 +74,21 @@ public class ForgeLoadingOverlay extends LoadingOverlay {
RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, fade);
Matrix4f pos = gui.pose().last().pose();
/*
RenderSystem.enableBlend();
RenderSystem.blendFunc(GlConst.GL_SRC_ALPHA, GlConst.GL_ONE_MINUS_SRC_ALPHA);
RenderSystem.setShader(CoreShaders.POSITION_TEX_COLOR);
RenderSystem.setShaderTexture(0, displayWindow.getFramebufferTextureId());
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);
*/
var buf = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR);
var buf = gui.getBufferSource().getBuffer(earlyBuffer);
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.
@@ -95,8 +100,10 @@ public class ForgeLoadingOverlay extends LoadingOverlay {
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);
return false;
@@ -1,105 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.block.model.BakedQuad;
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.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.util.RandomSource;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.client.ChunkRenderTypeSet;
import net.minecraftforge.client.model.data.ModelData;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* Wrapper for {@link BakedModel} which delegates all operations to its parent.
* <p>
* Useful for creating wrapper baked models which only override certain properties.
*/
public abstract class BakedModelWrapper<T extends BakedModel> implements BakedModel {
protected final T originalModel;
public BakedModelWrapper(T originalModel) {
this.originalModel = originalModel;
}
@Override
public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand) {
return originalModel.getQuads(state, side, rand);
}
@Override
public boolean useAmbientOcclusion() {
return originalModel.useAmbientOcclusion();
}
@Override
public boolean useAmbientOcclusion(BlockState state) {
return originalModel.useAmbientOcclusion(state);
}
@Override
public boolean useAmbientOcclusion(BlockState state, RenderType renderType) {
return originalModel.useAmbientOcclusion(state, renderType);
}
@Override
public boolean isGui3d() {
return originalModel.isGui3d();
}
@Override
public boolean usesBlockLight() {
return originalModel.usesBlockLight();
}
@Override
public TextureAtlasSprite getParticleIcon() {
return originalModel.getParticleIcon();
}
@Override
public ItemTransforms getTransforms() {
return originalModel.getTransforms();
}
@Override
public BakedModel applyTransform(ItemDisplayContext cameraTransformType, PoseStack poseStack, boolean applyLeftHandTransform) {
return originalModel.applyTransform(cameraTransformType, poseStack, applyLeftHandTransform);
}
@Override
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) {
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) {
return originalModel.getModelData(level, pos, state, modelData);
}
@Override
public ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data) {
return originalModel.getRenderTypes(state, rand, data);
}
}
@@ -1,372 +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.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
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.ItemTransforms;
import net.minecraft.client.renderer.block.model.TextureSlots;
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.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.util.RandomSource;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.client.ChunkRenderTypeSet;
import net.minecraftforge.client.RenderTypeGroup;
import net.minecraftforge.client.model.data.ModelData;
import net.minecraftforge.client.model.data.ModelProperty;
import net.minecraftforge.client.model.geometry.IGeometryBakingContext;
import net.minecraftforge.client.model.geometry.IGeometryLoader;
import net.minecraftforge.client.model.geometry.IUnbakedGeometry;
import net.minecraftforge.client.model.geometry.UnbakedGeometryHelper;
import net.minecraftforge.common.util.ConcatenatedListView;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* A model composed of several named children.
* <p>
* 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> {
private final ImmutableMap<String, BlockModel> children;
private final 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, TextureSlots textures, ModelState modelState) {
var particle = baker.sprites().maybeMissing(textures, "particle");
var rootTransform = context.getRootTransform();
if (!rootTransform.isIdentity())
modelState = UnbakedGeometryHelper.composeRootTransformIntoModelState(modelState, rootTransform);
var bakedPartsBuilder = ImmutableMap.<String, BakedModel>builder();
for (var entry : children.entrySet()) {
var name = entry.getKey();
if (!context.isComponentVisible(name, true))
continue;
var model = entry.getValue();
bakedPartsBuilder.put(name, model.bake(textures, baker, modelState, model.getAmbientOcclusion(), model.getGuiLight().lightLikeBlock(), model.getTransforms()));
}
var bakedParts = bakedPartsBuilder.build();
var itemPassesBuilder = ImmutableList.<BakedModel>builder();
for (String name : this.itemPasses)
{
var model = bakedParts.get(name);
if (model == null)
throw new IllegalStateException("Specified \"" + name + "\" in \"item_render_order\", but that is not a child of this model.");
itemPassesBuilder.add(model);
}
return new Baked(context.isGui3d(), context.useBlockLight(), context.useAmbientOcclusion(), particle, context.getTransforms(), bakedParts, itemPassesBuilder.build());
}
@Override
public void resolveDependencies(UnbakedModel.Resolver resolver, IGeometryBakingContext context) {
children.values().forEach(child -> child.resolveDependencies(resolver));
}
@Override
public Set<String> getConfigurableComponentNames() {
return children.keySet();
}
public static class Baked implements IDynamicBakedModel {
private final boolean isAmbientOcclusion;
private final boolean isGui3d;
private final boolean isSideLit;
private final TextureAtlasSprite particle;
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, ImmutableMap<String, BakedModel> children, ImmutableList<BakedModel> itemPasses) {
this.children = children;
this.isAmbientOcclusion = isAmbientOcclusion;
this.isGui3d = isGui3d;
this.isSideLit = isSideLit;
this.particle = particle;
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) {
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))) {
quadLists.add(entry.getValue().getQuads(state, side, rand, CompositeModel.Data.resolve(data, entry.getKey()), renderType));
}
}
return ConcatenatedListView.of(quadLists);
}
@Override
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())));
return modelData.derive().with(Data.PROPERTY, builder.build()).build();
}
@Override
public boolean useAmbientOcclusion() {
return isAmbientOcclusion;
}
@Override
public boolean isGui3d() {
return isGui3d;
}
@Override
public boolean usesBlockLight() {
return isSideLit;
}
@Override
public TextureAtlasSprite getParticleIcon() {
return particle;
}
@Override
public ItemTransforms getTransforms() {
return transforms;
}
@Override
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())));
return ChunkRenderTypeSet.union(sets);
}
@Nullable
public BakedModel getPart(String name) {
return children.get(name);
}
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, ItemTransforms cameraTransforms) {
return new Builder(isAmbientOcclusion, isGui3d, isSideLit, particle, cameraTransforms);
}
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 ItemTransforms transforms;
private TextureAtlasSprite particle;
private RenderTypeGroup lastRenderTypes = RenderTypeGroup.EMPTY;
private RenderTypeGroup lastRenderTypesFast = RenderTypeGroup.EMPTY;
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.transforms = transforms;
}
public void addLayer(BakedModel model) {
flushQuads(RenderTypeGroup.EMPTY, RenderTypeGroup.EMPTY);
children.add(model);
}
private void addLayer(RenderTypeGroup renderTypes, List<BakedQuad> quads) {
this.addLayer(renderTypes, RenderTypeGroup.EMPTY, quads);
}
private void addLayer(RenderTypeGroup renderTypes, RenderTypeGroup renderTypesFast, List<BakedQuad> quads) {
var modelBuilder = IModelBuilder.of(isAmbientOcclusion, isSideLit, isGui3d, transforms, particle, renderTypes, renderTypesFast);
quads.forEach(modelBuilder::addUnculledFace);
children.add(modelBuilder.build());
}
private void flushQuads(RenderTypeGroup renderTypes) {
this.flushQuads(renderTypes, RenderTypeGroup.EMPTY);
}
private void flushQuads(RenderTypeGroup renderTypes, RenderTypeGroup renderTypesFast) {
if (!Objects.equals(renderTypes, lastRenderTypes)) {
if (!quads.isEmpty()) {
addLayer(lastRenderTypes, lastRenderTypesFast, quads);
quads.clear();
}
lastRenderTypes = renderTypes;
lastRenderTypesFast = renderTypesFast;
}
}
public Builder setParticle(TextureAtlasSprite particleSprite) {
this.particle = particleSprite;
return this;
}
public Builder addQuads(RenderTypeGroup renderTypes, BakedQuad... quadsToAdd) {
return this.addQuads(renderTypes, RenderTypeGroup.EMPTY, quadsToAdd);
}
public Builder addQuads(RenderTypeGroup renderTypes, RenderTypeGroup renderTypesFast, BakedQuad... quadsToAdd) {
flushQuads(renderTypes, renderTypesFast);
Collections.addAll(quads, quadsToAdd);
return this;
}
public Builder addQuads(RenderTypeGroup renderTypes, Collection<BakedQuad> quadsToAdd) {
return this.addQuads(renderTypes, RenderTypeGroup.EMPTY, quadsToAdd);
}
public Builder addQuads(RenderTypeGroup renderTypes, RenderTypeGroup renderTypesFast, Collection<BakedQuad> quadsToAdd) {
flushQuads(renderTypes, renderTypesFast);
quads.addAll(quadsToAdd);
return this;
}
public BakedModel build() {
if (!quads.isEmpty()) {
addLayer(lastRenderTypes, lastRenderTypesFast, quads);
}
var childrenBuilder = ImmutableMap.<String, BakedModel>builder();
var itemPassesBuilder = ImmutableList.<BakedModel>builder();
int i = 0;
for (var model : this.children) {
childrenBuilder.put("model_" + (i++), model);
itemPassesBuilder.add(model);
}
return new Baked(isGui3d, isSideLit, isAmbientOcclusion, particle, transforms, childrenBuilder.build(), itemPassesBuilder.build());
}
}
}
/**
* A model data container which stores data for child components.
*/
public static class Data {
public static final ModelProperty<Data> PROPERTY = new ModelProperty<>();
private final Map<String, ModelData> partData;
private Data(Map<String, ModelData> partData) {
this.partData = partData;
}
@Nullable
public ModelData get(String name) {
return partData.get(name);
}
/**
* Helper to get the data from a {@link ModelData} instance.
*
* @param modelData The object to get data from
* @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) {
var compositeData = modelData.get(PROPERTY);
if (compositeData == null)
return modelData;
var partData = compositeData.get(name);
return partData != null ? partData : modelData;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private final Map<String, ModelData> partData = new IdentityHashMap<>();
public Builder with(String name, ModelData data) {
partData.put(name, data);
return this;
}
public Data build() {
return new Data(partData);
}
}
}
public static final class Loader implements IGeometryLoader<CompositeModel> {
public static final Loader INSTANCE = new Loader();
private Loader() { }
@Override
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);
var children = childrenBuilder.build();
if (children.isEmpty())
throw new JsonParseException("Composite model requires a \"children\" element with at least one element.");
if (jsonObject.has("item_render_order")) {
itemPasses.clear();
for (var element : jsonObject.getAsJsonArray("item_render_order"))
{
var name = element.getAsString();
if (!children.containsKey(name))
throw new JsonParseException("Specified \"" + name + "\" in \"item_render_order\", but that is not a child of this model.");
itemPasses.add(name);
}
}
return new CompositeModel(children, ImmutableList.copyOf(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()) {
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,10 +12,12 @@ import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.block.model.TextureSlots;
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.ModelDebugName;
import net.minecraft.client.resources.model.ModelState;
import net.minecraft.client.resources.model.QuadCollection;
import net.minecraft.client.resources.model.UnbakedGeometry;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.level.material.Fluid;
@@ -25,7 +27,6 @@ import net.minecraftforge.client.RenderTypeGroup;
import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions;
import net.minecraftforge.client.model.geometry.IGeometryBakingContext;
import net.minecraftforge.client.model.geometry.IGeometryLoader;
import net.minecraftforge.client.model.geometry.IUnbakedGeometry;
import net.minecraftforge.client.model.geometry.StandaloneGeometryBakingContext;
import net.minecraftforge.client.model.geometry.UnbakedGeometryHelper;
import net.minecraftforge.registries.ForgeRegistries;
@@ -42,7 +43,7 @@ import org.joml.Vector3f;
*
* @see Colors
*/
public class DynamicFluidContainerModel implements IUnbakedGeometry<DynamicFluidContainerModel> {
public class DynamicFluidContainerModel implements UnbakedGeometry {
// 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());
@@ -63,6 +64,11 @@ public class DynamicFluidContainerModel implements IUnbakedGeometry<DynamicFluid
return new RenderTypeGroup(RenderType.translucent(), unlit ? ForgeRenderTypes.ITEM_UNSORTED_UNLIT_TRANSLUCENT.get() : ForgeRenderTypes.ITEM_UNSORTED_TRANSLUCENT.get());
}
@SuppressWarnings("deprecation")
private static Material getMaterial(ResourceLocation texture) {
return new Material(TextureAtlas.LOCATION_BLOCKS, texture);
}
/**
* Returns a new ModelDynBucket representing the given fluid, but with the same
* other properties (flipGas, tint, coverIsMask).
@@ -71,59 +77,59 @@ public class DynamicFluidContainerModel implements IUnbakedGeometry<DynamicFluid
return new DynamicFluidContainerModel(newFluid, flipGas, coverIsMask, applyFluidLuminosity);
}
@SuppressWarnings("deprecation")
@Override
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, TextureSlots textures, ModelState modelState) {
public QuadCollection bake(TextureSlots slots, ModelBaker baker, ModelState state, ModelDebugName name) {
return bake(slots, baker, state, name, StandaloneGeometryBakingContext.INSTANCE);
}
@Override
public QuadCollection bake(TextureSlots textures, ModelBaker baker, ModelState state, ModelDebugName name, IGeometryBakingContext context) {
Material fluidMaskLocation = textures.getMaterial("fluid");
Material stillMaterial = null;
if (fluid != Fluids.EMPTY) {
var stillTexture = IClientFluidTypeExtensions.of(fluid).getStillTexture();
stillMaterial = new Material(TextureAtlas.LOCATION_BLOCKS, stillTexture);
stillMaterial = getMaterial(stillTexture);
}
var sprites = baker.sprites();
var baseSprite = sprites.maybeMissing(textures, "base");
var fluidSprite = stillMaterial == null ? null : sprites.get(stillMaterial);
var coverSprite = sprites.maybeMissing(textures, "cover"); // (coverLocation != null && (!coverIsMask || baseLocation != null)) ? textures.apply(coverLocation) : null;
var particleSprite = sprites.maybeMissing(textures, "particle");
var baseSprite = sprites.resolveSlot(textures, "base", name);
var fluidSprite = stillMaterial == null ? null : sprites.get(stillMaterial, name);
var coverSprite = sprites.resolveSlot(textures, "cover", name);
/*
var particleSprite = sprites.resolveSlot(textures, "particle", name);
if (particleSprite == null) particleSprite = fluidSprite;
if (particleSprite == null) particleSprite = baseSprite;
if (particleSprite == null && !coverIsMask) particleSprite = coverSprite;
*/
var transformation = state.transformation();
// TODO: [Forge][Rendering] See if we can get rid of SimpleModelState and wrap transforms completely
// If the fluid is lighter than air, rotate 180deg to turn it upside down
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)));
}
if (flipGas && fluid != Fluids.EMPTY && fluid.getFluidType().isLighterThanAir())
transformation = transformation.compose(new Transformation(null, new Quaternionf(0, 0, 1, 0), null, null));
// We need to disable GUI 3D and block lighting for this to render properly
var itemContext = StandaloneGeometryBakingContext.builder(context).withGui3d(false).withUseBlockLight(false).build();
var modelBuilder = CompositeModel.Baked.builder(itemContext, particleSprite, /*new ContainedFluidOverrideHandler(baker, itemContext, this),*/ context.getTransforms());
var normalRenderTypes = getLayerRenderTypes(false);
var buf = new QuadCollection.Builder();
if (baseSprite != null) {
// Base texture
var unbaked = UnbakedGeometryHelper.createUnbakedItemElements(0, baseSprite.contents());
var quads = UnbakedGeometryHelper.bakeElements(unbaked, $ -> baseSprite, modelState);
modelBuilder.addQuads(normalRenderTypes, quads);
UnbakedGeometryHelper.bakeElements(unbaked, $ -> baseSprite, state, buf);
}
if (fluidMaskLocation != null && fluidSprite != null) {
TextureAtlasSprite templateSprite = sprites.get(fluidMaskLocation);
TextureAtlasSprite templateSprite = sprites.get(fluidMaskLocation, name);
if (templateSprite != null) {
// Fluid layer
var transformedState = new SimpleModelState(modelState.getRotation().compose(FLUID_TRANSFORM), modelState.isUvLocked());
var transformedState = new SimpleModelState(transformation.compose(FLUID_TRANSFORM));
var unbaked = UnbakedGeometryHelper.createUnbakedItemMaskElements(1, templateSprite.contents()); // Use template as mask
var quads = UnbakedGeometryHelper.bakeElements(unbaked, $ -> fluidSprite, transformedState); // Bake with fluid texture
var emissive = applyFluidLuminosity && fluid.getFluidType().getLightLevel() > 0;
var renderTypes = getLayerRenderTypes(emissive);
if (emissive) QuadTransformers.settingMaxEmissivity().processInPlace(quads);
var transformer = emissive ? QuadTransformers.settingMaxEmissivity() : QuadTransformers.empty();
modelBuilder.addQuads(renderTypes, quads);
UnbakedGeometryHelper.bakeElements(unbaked, $ -> fluidSprite, transformedState, transformer, buf); // Bake with fluid texture
}
}
@@ -131,29 +137,24 @@ public class DynamicFluidContainerModel implements IUnbakedGeometry<DynamicFluid
var sprite = coverIsMask ? baseSprite : coverSprite;
if (sprite != null) {
// Cover/overlay
var transformedState = new SimpleModelState(modelState.getRotation().compose(COVER_TRANSFORM), modelState.isUvLocked());
var transformedState = new SimpleModelState(transformation.compose(COVER_TRANSFORM));
var unbaked = UnbakedGeometryHelper.createUnbakedItemMaskElements(2, coverSprite.contents()); // Use cover as mask
var quads = UnbakedGeometryHelper.bakeElements(unbaked, $ -> sprite, transformedState); // Bake with selected texture
modelBuilder.addQuads(normalRenderTypes, quads);
UnbakedGeometryHelper.bakeElements(unbaked, $ -> sprite, transformedState, buf); // Bake with selected texture
}
}
modelBuilder.setParticle(particleSprite);
return modelBuilder.build();
return buf.build();
}
public static final class Loader implements IGeometryLoader<DynamicFluidContainerModel> {
public static final class Loader implements IGeometryLoader {
public static final Loader INSTANCE = new Loader();
private Loader() { }
@Override
public DynamicFluidContainerModel read(JsonObject jsonObject, JsonDeserializationContext deserializationContext) {
if (!jsonObject.has("fluid"))
throw new RuntimeException("Bucket model requires 'fluid' value.");
ResourceLocation fluidName = ResourceLocation.parse(jsonObject.get("fluid").getAsString());
public UnbakedGeometry read(JsonObject jsonObject, JsonDeserializationContext deserializationContext) {
var fluidName = ResourceLocation.parse(GsonHelper.getAsString(jsonObject, "fluid"));
Fluid fluid = ForgeRegistries.FLUIDS.getValue(fluidName);
@@ -1,79 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.renderer.block.model.BlockElement;
import net.minecraft.client.renderer.block.model.TextureSlots;
import net.minecraft.client.resources.model.ModelBaker;
import net.minecraft.client.resources.model.ModelState;
import net.minecraft.client.resources.model.SimpleBakedModel;
import net.minecraft.util.GsonHelper;
import net.minecraftforge.client.model.geometry.IGeometryBakingContext;
import net.minecraftforge.client.model.geometry.IGeometryLoader;
import net.minecraftforge.client.model.geometry.SimpleUnbakedGeometry;
import net.minecraftforge.client.model.geometry.UnbakedGeometryHelper;
/**
* A model composed of vanilla {@linkplain BlockElement block elements}.
*/
public class ElementsModel extends SimpleUnbakedGeometry<ElementsModel> {
private final List<BlockElement> elements;
public ElementsModel(List<BlockElement> elements) {
this.elements = elements;
}
@Override
protected void addQuads(IGeometryBakingContext context, IModelBuilder<?> modelBuilder, ModelBaker baker, TextureSlots textures, ModelState modelState) {
//protected void addQuads(IGeometryBakingContext context, IModelBuilder<?> modelBuilder, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState) {
// If there is a root transform, undo the ModelState transform, apply it, then re-apply the ModelState transform.
// This is necessary because of things like UV locking, which should only respond to the ModelState, and as such
// that is the only transform that should be applied during face bake.
var postTransform = QuadTransformers.empty();
var rootTransform = context.getRootTransform();
if (!rootTransform.isIdentity())
postTransform = UnbakedGeometryHelper.applyRootTransform(modelState, rootTransform);
var sprites = baker.sprites();
for (var element : elements) {
for (var direction : element.faces.keySet()) {
var face = element.faces.get(direction);
var sprite = sprites.maybeMissing(textures, face.texture());
var quad = SimpleBakedModel.bakeFace(element, face, sprite, direction, modelState);
postTransform.processInPlace(quad);
if (face.cullForDirection() == null)
modelBuilder.addUnculledFace(quad);
else
modelBuilder.addCulledFace(modelState.getRotation().rotateTransform(face.cullForDirection()), quad);
}
}
}
public static final class Loader implements IGeometryLoader<ElementsModel> {
public static final Loader INSTANCE = new Loader();
private Loader() { }
@Override
public ElementsModel read(JsonObject jsonObject, JsonDeserializationContext deserializationContext) throws JsonParseException {
if (!jsonObject.has("elements"))
throw new JsonParseException("An element model must have an \"elements\" member.");
List<BlockElement> elements = new ArrayList<>();
for (JsonElement element : GsonHelper.getAsJsonArray(jsonObject, "elements"))
elements.add(deserializationContext.deserialize(element, BlockElement.class));
return new ElementsModel(elements);
}
}
}
@@ -1,61 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model;
import java.util.List;
import java.util.Map;
import net.minecraft.client.renderer.block.model.ItemTransforms;
import net.minecraft.client.renderer.block.model.TextureSlots;
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.minecraftforge.client.RenderTypeGroup;
import net.minecraftforge.client.model.geometry.IGeometryBakingContext;
import net.minecraftforge.client.model.geometry.IGeometryLoader;
import net.minecraftforge.client.model.geometry.IUnbakedGeometry;
import net.minecraftforge.client.model.geometry.SimpleUnbakedGeometry;
import net.minecraftforge.client.textures.UnitTextureAtlasSprite;
/**
* A completely empty model with no quads or texture dependencies.
* <p>
* You can access it as a {@link BakedModel}, an {@link IUnbakedGeometry} or an {@link IGeometryLoader}.
*/
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() { }
@Override
protected void addQuads(IGeometryBakingContext owner, IModelBuilder<?> modelBuilder, ModelBaker baker, TextureSlots textures, ModelState modelTransform) {
// NO-OP
}
@Override
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, TextureSlots spriteGetter, ModelState modelState) {
return BAKED;
}
private static class Baked extends SimpleBakedModel {
private static final Material MISSING_TEXTURE = new Material(TextureAtlas.LOCATION_BLOCKS, MissingTextureAtlasSprite.getLocation());
public Baked() {
super(List.of(), Map.of(), false, false, false, UnitTextureAtlasSprite.INSTANCE, ItemTransforms.NO_TRANSFORMS, RenderTypeGroup.EMPTY, RenderTypeGroup.EMPTY);
}
@Override
public TextureAtlasSprite getParticleIcon() {
return MISSING_TEXTURE.sprite();
}
}
}
@@ -0,0 +1,47 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model;
import java.util.Map;
import java.util.Optional;
import com.mojang.math.Transformation;
import net.minecraft.resources.ResourceLocation;
public record ForgeBlockModelData(
Optional<Transformation> transform,
Optional<ResourceLocation> renderType,
Optional<ResourceLocation> renderTypeFast,
Optional<Map<String, Boolean>> visibility
) {
public ForgeBlockModelData() {
this(Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty());
}
public ForgeBlockModelData merge(ForgeBlockModelData other) {
if (other == null)
return this;
var vis = this.visibility();
if (this.visibility().isPresent() && other.visibility().isPresent()) {
var map = Map.copyOf(this.visibility().get());
map.putAll(other.visibility().get());
vis = Optional.of(map);
}
return new ForgeBlockModelData(
this.transform().isPresent() ? this.transform() : other.transform(),
this.renderType().isPresent() ? this.renderType() : other.renderType(),
this.renderTypeFast().isPresent() ? this.renderTypeFast() : other.renderTypeFast(),
vis.isPresent() ? vis : other.visibility()
);
}
public boolean full() {
return transform.isPresent() && renderType.isPresent() && renderTypeFast.isPresent() && visibility.isPresent();
}
}
@@ -18,11 +18,10 @@ import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.client.renderer.block.model.BlockElement;
import net.minecraft.client.renderer.block.model.BlockElementFace;
import net.minecraft.util.ExtraCodecs;
/**
* Holds extra data that may be injected into a face.<p>
* Used by {@link ItemLayerModel}, {@link BlockElement} and {@link BlockElementFace}
* Used by {@link ItemLayerGeometry}, {@link BlockElement} and {@link BlockElementFace}
*
* @param color Color in ARGB format
* @param blockLight Block Light for this face from 0-15 (inclusive)
@@ -1,34 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.core.Direction;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.client.extensions.IForgeBakedModel;
import net.minecraftforge.client.model.data.ModelData;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* Convenience interface with default implementation of {@link IForgeBakedModel#getQuads(BlockState, Direction, RandomSource, ModelData, RenderType)}.
*/
public interface IDynamicBakedModel extends BakedModel {
@Override
default @NotNull List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand) {
return getQuads(state, side, rand, ModelData.EMPTY, null);
}
// Force this to be overriden otherwise this introduces a default cycle between the two overloads.
@Override
@NotNull
List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData extraData, @Nullable RenderType renderType);
}
@@ -7,10 +7,13 @@ package net.minecraftforge.client.model;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.ItemTransforms;
import net.minecraft.client.renderer.block.model.SimpleModelWrapper;
import net.minecraft.client.renderer.item.EmptyModel;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.resources.model.SimpleBakedModel;
import net.minecraft.client.renderer.block.model.BlockModelPart;
import net.minecraft.client.resources.model.QuadCollection;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.RenderTypeGroup;
import java.util.List;
@@ -18,9 +21,12 @@ import java.util.List;
/**
* Base interface for any object that collects culled and unculled faces and bakes them into a model.
* <p>
* Provides a generic base implementation via {@link #of(boolean, boolean, boolean, ItemTransforms, ItemOverrides, TextureAtlasSprite)}
* Provides a generic base implementation via {@link #of(boolean, boolean, boolean, ItemTransforms, TextureAtlasSprite, RenderTypeGroup, RenderTypeGroup)}
* and a quad-collecting alternative via {@link #collecting(List)}.
*
* @deprecated Use {@link net.minecraft.client.resources.model.QuadCollection} instead.
*/
@Deprecated(forRemoval = true, since = "1.21.5")
public interface IModelBuilder<T extends IModelBuilder<T>> {
/**
* Creates a new model builder that uses the provided attributes in the final baked model.
@@ -70,10 +76,20 @@ public interface IModelBuilder<T extends IModelBuilder<T>> {
T addUnculledFace(BakedQuad quad);
BakedModel build();
BlockModelPart build();
class Simple implements IModelBuilder<Simple> {
private final SimpleBakedModel.Builder builder;
private final QuadCollection.Builder builder;
private final boolean hasAmbientOcclusion;
// TODO: [VEN] These are UNUSED, and this is GOING TO BREAK.
private final boolean usesBlockLight;
private final boolean isGui3d;
private final ItemTransforms transforms;
private final TextureAtlasSprite particle;
private final RenderTypeGroup renderTypes;
private final RenderTypeGroup renderTypesFast;
private Simple(
boolean hasAmbientOcclusion, boolean usesBlockLight, boolean isGui3d,
@@ -86,8 +102,14 @@ public interface IModelBuilder<T extends IModelBuilder<T>> {
boolean hasAmbientOcclusion, boolean usesBlockLight, boolean isGui3d,
ItemTransforms transforms, TextureAtlasSprite particle, RenderTypeGroup renderTypes, RenderTypeGroup renderTypesFast
) {
this.builder = new SimpleBakedModel.Builder(hasAmbientOcclusion, usesBlockLight, isGui3d, transforms).particle(particle);
this.builder.renderTypes(renderTypes, renderTypesFast);
this.builder = new QuadCollection.Builder();
this.hasAmbientOcclusion = hasAmbientOcclusion;
this.usesBlockLight = usesBlockLight;
this.isGui3d = isGui3d;
this.transforms = transforms;
this.particle = particle;
this.renderTypes = renderTypes;
this.renderTypesFast = renderTypesFast;
}
@Override
@@ -103,12 +125,15 @@ public interface IModelBuilder<T extends IModelBuilder<T>> {
}
@Override
public BakedModel build() {
return builder.build();
public BlockModelPart build() {
var quads = builder.build();
// TODO: [VEN] Models will NOT be complete here!!!!
return new SimpleModelWrapper(quads, hasAmbientOcclusion, particle);
}
}
class Collecting implements IModelBuilder<Collecting> {
private static final BlockModelPart EMPTY = new SimpleModelWrapper(QuadCollection.EMPTY, false, new TextureAtlasSprite(ResourceLocation.fromNamespaceAndPath("forge", "empty"), null, 0, 0, 0, 0) {});
private final List<BakedQuad> quads;
private Collecting(List<BakedQuad> quads) {
@@ -128,8 +153,8 @@ public interface IModelBuilder<T extends IModelBuilder<T>> {
}
@Override
public BakedModel build() {
return EmptyModel.BAKED;
public BlockModelPart build() {
return EMPTY;
}
}
}
@@ -8,8 +8,6 @@ package net.minecraftforge.client.model;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.VertexFormatElement;
import net.minecraft.client.renderer.block.model.BakedQuad;
import java.util.Arrays;
import java.util.List;
/**
@@ -17,6 +15,7 @@ import java.util.List;
*
* @see QuadTransformers
*/
@FunctionalInterface
public interface IQuadTransformer {
int STRIDE = DefaultVertexFormat.BLOCK.getVertexSize() / 4;
int POSITION = findOffset(VertexFormatElement.POSITION);
@@ -26,33 +25,14 @@ public interface IQuadTransformer {
int UV2 = findOffset(VertexFormatElement.UV2);
int NORMAL = findOffset(VertexFormatElement.NORMAL);
void processInPlace(BakedQuad quad);
default void processInPlace(List<BakedQuad> quads) {
for (BakedQuad quad : quads)
processInPlace(quad);
}
default BakedQuad process(BakedQuad quad) {
var copy = copy(quad);
processInPlace(copy);
return copy;
}
BakedQuad process(BakedQuad quad);
default List<BakedQuad> process(List<BakedQuad> inputs) {
return inputs.stream().map(IQuadTransformer::copy).peek(this::processInPlace).toList();
return inputs.stream().map(this::process).toList();
}
default IQuadTransformer andThen(IQuadTransformer other) {
return quad -> {
processInPlace(quad);
other.processInPlace(quad);
};
}
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.getLightEmission(), quad.hasAmbientOcclusion());
return quad -> other.process(process(quad));
}
private static int findOffset(VertexFormatElement element) {
@@ -10,14 +10,20 @@ import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMaps;
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.SimpleUnbakedGeometry;
import net.minecraft.client.renderer.block.model.TextureSlots;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.renderer.block.model.BlockElement;
import net.minecraft.client.renderer.block.model.BlockModelPart;
import net.minecraft.client.resources.model.Material;
import net.minecraft.client.resources.model.ModelBaker;
import net.minecraft.client.resources.model.ModelDebugName;
import net.minecraft.client.resources.model.ModelState;
import net.minecraft.client.resources.model.QuadCollection;
import net.minecraft.client.resources.model.UnbakedGeometry;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.ForgeRenderTypes;
import net.minecraftforge.client.RenderTypeGroup;
@@ -25,44 +31,48 @@ import net.minecraftforge.client.model.geometry.IGeometryBakingContext;
import net.minecraftforge.client.model.geometry.IGeometryLoader;
import net.minecraftforge.client.model.geometry.IUnbakedGeometry;
import net.minecraftforge.client.model.geometry.UnbakedGeometryHelper;
import java.util.ArrayList;
import java.util.List;
import org.jetbrains.annotations.Nullable;
/**
* Forge reimplementation of vanilla's {@link ItemModelGenerator}, i.e. builtin/generated models with some tweaks:
* - Represented as {@link IUnbakedGeometry} so it can be baked as usual instead of being special-cased
* Forge version of vanilla's {@link ItemModelGenerator}, i.e. builtin/generated models with some tweaks:
* - Represented as {@link UnbakedGeometry} so it can be used in multiple root models
* - Not limited to an arbitrary number of layers (5)
* - Support for per-layer render types
//* - Support for per-layer render types - Currently Doesn't work. TODO: [Forge][Model] Make a Model loader for this
*/
public class ItemLayerModel implements IUnbakedGeometry<ItemLayerModel> {
@Nullable
private ImmutableList<Material> textures;
@SuppressWarnings("unused")
public class ItemLayerGeometry implements UnbakedGeometry {
private static final ItemLayerGeometry INSTANCE = new ItemLayerGeometry(Int2ObjectMaps.emptyMap(), Int2ObjectMaps.emptyMap());
private final Int2ObjectMap<ResourceLocation> renderTypeNames;
private final Int2ObjectMap<ResourceLocation> renderTypeFastNames;
private ItemLayerModel(@Nullable ImmutableList<Material> textures, Int2ObjectMap<ResourceLocation> renderTypeNames) {
this(textures, renderTypeNames, new Int2ObjectOpenHashMap<>());
}
private ItemLayerModel(@Nullable ImmutableList<Material> textures, Int2ObjectMap<ResourceLocation> renderTypeNames, Int2ObjectMap<ResourceLocation> renderTypeFastNames) {
this.textures = textures;
private ItemLayerGeometry(Int2ObjectMap<ResourceLocation> renderTypeNames, Int2ObjectMap<ResourceLocation> renderTypeFastNames) {
this.renderTypeNames = renderTypeNames;
this.renderTypeFastNames = renderTypeFastNames;
}
@Override
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, TextureSlots spriteGetter, ModelState modelState) {
if (textures == null) {
ImmutableList.Builder<Material> builder = ImmutableList.builder();
int i = 0;
Material material;
while ((material = spriteGetter.getMaterial("layer" + i++)) != null) {
builder.add(material);
}
textures = builder.build();
public QuadCollection bake(TextureSlots textures, ModelBaker baker, ModelState state, ModelDebugName name) {
List<BlockElement> elements = new ArrayList<>();
int i = 0;
while (true) {
var layer = "layer" + i++;
var material = textures.getMaterial(layer);
if (material == null)
break;
var contents = baker.sprites().get(material, name).contents();
elements.addAll(ItemModelGenerator.processFrames(i, layer, contents));
}
return SimpleUnbakedGeometry.bake(elements, textures, baker.sprites(), state, name);
/*
Material particleMaterial = spriteGetter.getMaterial("particle");
var particle = baker.sprites().get(particleMaterial == null ? textures.get(0) : particleMaterial);
var particle = baker.sprites().get(particleMaterial == null ? textures.get(0) : particleMaterial, name);
var rootTransform = context.getRootTransform();
if (!rootTransform.isIdentity())
modelState = UnbakedGeometryHelper.composeRootTransformIntoModelState(modelState, rootTransform);
@@ -70,7 +80,7 @@ public class ItemLayerModel implements IUnbakedGeometry<ItemLayerModel> {
var normalRenderTypes = new RenderTypeGroup(RenderType.translucent(), ForgeRenderTypes.ITEM_UNSORTED_TRANSLUCENT.get());
var builder = CompositeModel.Baked.builder(context, particle, context.getTransforms());
for (int i = 0; i < textures.size(); i++) {
var sprite = baker.sprites().get(textures.get(i));
var sprite = baker.sprites().get(textures.get(i), name);
var unbaked = UnbakedGeometryHelper.createUnbakedItemElements(i, sprite.contents());
var quads = UnbakedGeometryHelper.bakeElements(unbaked, $ -> sprite, modelState);
var renderTypeName = renderTypeNames.get(i);
@@ -81,16 +91,20 @@ public class ItemLayerModel implements IUnbakedGeometry<ItemLayerModel> {
}
return builder.build();
*/
}
public static final class Loader implements IGeometryLoader<ItemLayerModel> {
public static final class Loader implements IGeometryLoader {
public static final Loader INSTANCE = new Loader();
@Override
public ItemLayerModel read(JsonObject jsonObject, JsonDeserializationContext deserializationContext) {
public UnbakedGeometry read(JsonObject jsonObject, JsonDeserializationContext deserializationContext) {
return ItemLayerGeometry.INSTANCE;
/*
var renderTypeNames = readRenderTypeNames(jsonObject, "render_types");
var renderTypeFastNames = readRenderTypeNames(jsonObject, "render_types_fast");
return new ItemLayerModel(null, renderTypeNames, renderTypeFastNames);
return new ItemLayerModel(renderTypeNames, renderTypeFastNames);
*/
}
private static Int2ObjectMap<ResourceLocation> readRenderTypeNames(JsonObject jsonObject, String key) {
@@ -107,18 +121,5 @@ public class ItemLayerModel implements IUnbakedGeometry<ItemLayerModel> {
return renderTypeNames;
}
@Deprecated(forRemoval = true, since = "1.21.4")
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()) {
int layer = Integer.parseInt(entry.getKey());
var data = ForgeFaceData.read(entry.getValue(), ForgeFaceData.DEFAULT);
layerData.put(layer, data);
}
}
}
}
@@ -21,8 +21,7 @@ import java.util.Arrays;
* @see IQuadTransformer
*/
public final class QuadTransformers {
private static final IQuadTransformer EMPTY = quad -> {};
private static final IQuadTransformer EMPTY = quad -> quad;
private static final IQuadTransformer[] EMISSIVE_TRANSFORMERS = Util.make(new IQuadTransformer[16], array -> {
Arrays.setAll(array, i -> applyingLightmap(LightTexture.pack(i, i)));
});
@@ -30,22 +29,20 @@ public final class QuadTransformers {
/**
* {@return a {@link BakedQuad} transformer that does nothing}
*/
public static IQuadTransformer empty()
{
public static IQuadTransformer empty() {
return EMPTY;
}
/**
* {@return a new {@link BakedQuad} transformer that applies the specified {@link Transformation}}
*/
public static IQuadTransformer applying(Transformation transform)
{
public static IQuadTransformer applying(Transformation transform) {
if (transform.isIdentity())
return empty();
return quad -> {
var vertices = quad.getVertices();
for (int i = 0; i < 4; i++)
{
var vertices = Arrays.copyOf(quad.vertices(), quad.vertices().length);
for (int i = 0; i < 4; i++) {
int offset = i * IQuadTransformer.STRIDE + IQuadTransformer.POSITION;
float x = Float.intBitsToFloat(vertices[offset]);
float y = Float.intBitsToFloat(vertices[offset + 1]);
@@ -60,12 +57,10 @@ public final class QuadTransformers {
vertices[offset + 2] = Float.floatToRawIntBits(pos.z());
}
for (int i = 0; i < 4; i++)
{
for (int i = 0; i < 4; i++) {
int offset = i * IQuadTransformer.STRIDE + IQuadTransformer.NORMAL;
int normalIn = vertices[offset];
if ((normalIn & 0x00FFFFFF) != 0) // The ignored byte is padding and may be filled with user data
{
if ((normalIn & 0x00FFFFFF) != 0) { // The ignored byte is padding and may be filled with user data
float x = ((byte) (normalIn & 0xFF)) / 127.0f;
float y = ((byte) ((normalIn >> 8) & 0xFF)) / 127.0f;
float z = ((byte) ((normalIn >> 16) & 0xFF)) / 127.0f;
@@ -79,34 +74,34 @@ public final class QuadTransformers {
(normalIn & 0xFF000000); // Restore padding, just in case
}
}
return new BakedQuad(vertices, quad.tintIndex(), quad.direction(), quad.sprite(), quad.shade(), quad.lightEmission(), quad.ambientOcclusion());
};
}
/**
* @return A new {@link BakedQuad} transformer that applies the specified packed light value.
*/
public static IQuadTransformer applyingLightmap(int packedLight)
{
public static IQuadTransformer applyingLightmap(int packedLight) {
return quad -> {
var vertices = quad.getVertices();
var vertices = Arrays.copyOf(quad.vertices(), quad.vertices().length);
for (int i = 0; i < 4; i++)
vertices[i * IQuadTransformer.STRIDE + IQuadTransformer.UV2] = packedLight;
return new BakedQuad(vertices, quad.tintIndex(), quad.direction(), quad.sprite(), quad.shade(), quad.lightEmission(), quad.ambientOcclusion());
};
}
/**
* @return A new {@link BakedQuad} transformer that applies the specified block and sky light values.
*/
public static IQuadTransformer applyingLightmap(int blockLight, int skyLight)
{
public static IQuadTransformer applyingLightmap(int blockLight, int skyLight) {
return applyingLightmap(LightTexture.pack(blockLight, skyLight));
}
/**
* @return A {@link BakedQuad} transformer that sets the lightmap to the given emissivity (0-15)
*/
public static IQuadTransformer settingEmissivity(int emissivity)
{
public static IQuadTransformer settingEmissivity(int emissivity) {
Preconditions.checkArgument(emissivity >= 0 && emissivity < 16, "Emissivity must be between 0 and 15.");
return EMISSIVE_TRANSFORMERS[emissivity];
}
@@ -114,8 +109,7 @@ public final class QuadTransformers {
/**
* @return A {@link BakedQuad} transformer that sets the lightmap to its max value
*/
public static IQuadTransformer settingMaxEmissivity()
{
public static IQuadTransformer settingMaxEmissivity() {
return EMISSIVE_TRANSFORMERS[15];
}
@@ -123,13 +117,15 @@ public final class QuadTransformers {
* @param color The color in ARGB format.
* @return A {@link BakedQuad} transformer that sets the color to the specified value.
*/
public static IQuadTransformer applyingColor(int color)
{
public static IQuadTransformer applyingColor(int color) {
final int fixedColor = toABGR(color);
return quad -> {
var vertices = quad.getVertices();
var vertices = Arrays.copyOf(quad.vertices(), quad.vertices().length);
for (int i = 0; i < 4; i++)
vertices[i * IQuadTransformer.STRIDE + IQuadTransformer.COLOR] = fixedColor;
return new BakedQuad(vertices, quad.tintIndex(), quad.direction(), quad.sprite(), quad.shade(), quad.lightEmission(), quad.ambientOcclusion());
};
}
@@ -140,8 +136,7 @@ public final class QuadTransformers {
* @param blue The blue value (0-255)
* @return A {@link BakedQuad} transformer that sets the color to the specified value.
*/
public static IQuadTransformer applyingColor(int red, int green, int blue)
{
public static IQuadTransformer applyingColor(int red, int green, int blue) {
return applyingColor(255, red, green, blue);
}
@@ -152,8 +147,7 @@ public final class QuadTransformers {
* @param blue The blue value (0-255)
* @return A {@link BakedQuad} transformer that sets the color to the specified value.
*/
public static IQuadTransformer applyingColor(int alpha, int red, int green, int blue)
{
public static IQuadTransformer applyingColor(int alpha, int red, int green, int blue) {
return applyingColor(alpha << 24 | red << 16 | green << 8 | blue);
}
@@ -163,14 +157,11 @@ public final class QuadTransformers {
* @param argb ARGB color
* @return ABGR color
*/
public static int toABGR(int argb)
{
public static int toABGR(int argb) {
return (argb & 0xFF00FF00) // alpha and green same spot
| ((argb >> 16) & 0x000000FF) // red moves to blue
| ((argb << 16) & 0x00FF0000); // blue moves to red
}
private QuadTransformers()
{
}
private QuadTransformers() { }
}
@@ -1,157 +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.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.mojang.blaze3d.vertex.PoseStack;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.ItemTransforms;
import net.minecraft.client.renderer.block.model.TextureSlots;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.model.BakedModel;
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.util.GsonHelper;
import net.minecraft.util.RandomSource;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.client.ChunkRenderTypeSet;
import net.minecraftforge.client.model.data.ModelData;
import net.minecraftforge.client.model.geometry.IGeometryBakingContext;
import net.minecraftforge.client.model.geometry.IGeometryLoader;
import net.minecraftforge.client.model.geometry.IUnbakedGeometry;
import org.jetbrains.annotations.NotNull;
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> {
private final BlockModel baseModel;
private final 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, TextureSlots textures, ModelState modelState) {
return new Baked(
context.useAmbientOcclusion(),
context.isGui3d(),
context.useBlockLight(),
baker.sprites().maybeMissing(textures, "particle"),
baseModel.bake(textures, baker, modelState),
ImmutableMap.copyOf(Maps.transformValues(perspectives, value -> {
return value.bake(textures, baker, modelState, context.useBlockLight(), value.getGuiLight().lightLikeBlock(), value.getTransforms());
}))
);
}
@Override
public void resolveDependencies(UnbakedModel.Resolver resolver, IGeometryBakingContext context) {
baseModel.resolveDependencies(resolver);
perspectives.values().forEach(model -> model.resolveDependencies(resolver));
}
public static class Baked implements IDynamicBakedModel {
private final boolean isAmbientOcclusion;
private final boolean isGui3d;
private final boolean isSideLit;
private final TextureAtlasSprite particle;
private final BakedModel baseModel;
private final 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.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) {
return baseModel.getQuads(state, side, rand, data, renderType);
}
@Override
public boolean useAmbientOcclusion() {
return isAmbientOcclusion;
}
@Override
public boolean isGui3d() {
return isGui3d;
}
@Override
public boolean usesBlockLight() {
return isSideLit;
}
@Override
public TextureAtlasSprite getParticleIcon() {
return particle;
}
@Override
public ItemTransforms getTransforms() {
return ItemTransforms.NO_TRANSFORMS;
}
@Override
public BakedModel applyTransform(ItemDisplayContext cameraTransformType, PoseStack poseStack, boolean applyLeftHandTransform) {
if (perspectives.containsKey(cameraTransformType)) {
BakedModel p = perspectives.get(cameraTransformType);
return p.applyTransform(cameraTransformType, poseStack, applyLeftHandTransform);
}
return baseModel.applyTransform(cameraTransformType, poseStack, applyLeftHandTransform);
}
@Override
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 Loader INSTANCE = new Loader();
private Loader() { }
@Override
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())) {
BlockModel perspectiveModel = deserializationContext.deserialize(GsonHelper.getAsJsonObject(perspectiveData, transform.getSerializedName()), BlockModel.class);
perspectives.put(transform, perspectiveModel);
}
}
return new SeparateTransformsModel(baseModel, ImmutableMap.copyOf(perspectives));
}
}
}
@@ -11,8 +11,4 @@ import net.minecraft.client.resources.model.ModelState;
/**
* Simple implementation of {@link ModelState}.
*/
public record SimpleModelState(Transformation getRotation, boolean isUvLocked) implements ModelState {
public SimpleModelState(Transformation transformation) {
this(transformation, false);
}
}
public record SimpleModelState(Transformation transformation) implements ModelState {}
@@ -6,14 +6,9 @@
package net.minecraftforge.client.model.data;
import com.google.common.base.Preconditions;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.core.BlockPos;
import net.minecraft.client.renderer.block.model.BlockModelPart;
import net.minecraft.core.Direction;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
@@ -23,15 +18,14 @@ import java.util.Map;
import java.util.Set;
/**
* A container for data to be passed to {@link BakedModel} instances.
* A container for data to be passed to {@link BlockModelPart} instances.
* <p>
* All objects stored in here <b>MUST BE IMMUTABLE OR THREAD-SAFE</b>.
* Properties will be accessed from another thread.
*
* @see ModelProperty
* @see BlockEntity#getModelData()
* @see BakedModel#getQuads(BlockState, Direction, RandomSource, ModelData, RenderType)
* @see BakedModel#getModelData(BlockAndTintGetter, BlockPos, BlockState, ModelData)
* @see BlockModelPart#getQuads(Direction)
*/
public final class ModelData {
public static final ModelData EMPTY = ModelData.builder().build();
@@ -5,7 +5,7 @@
package net.minecraftforge.client.model.data;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.renderer.block.model.BlockModelPart;
import org.jetbrains.annotations.Nullable;
import java.util.IdentityHashMap;
@@ -15,15 +15,15 @@ public class MultipartModelData
{
public static final ModelProperty<MultipartModelData> PROPERTY = new ModelProperty<>();
private final Map<BakedModel, ModelData> partData;
private final Map<BlockModelPart, ModelData> partData;
private MultipartModelData(Map<BakedModel, ModelData> partData)
private MultipartModelData(Map<BlockModelPart, ModelData> partData)
{
this.partData = partData;
}
@Nullable
public ModelData get(BakedModel model)
public ModelData get(BlockModelPart model)
{
return partData.get(model);
}
@@ -35,7 +35,7 @@ public class MultipartModelData
* @param model The model to get data for
* @return The data for the part, or the one passed in if not found
*/
public static ModelData resolve(ModelData modelData, BakedModel model)
public static ModelData resolve(ModelData modelData, BlockModelPart model)
{
var multipartData = modelData.get(PROPERTY);
if (multipartData == null)
@@ -51,9 +51,9 @@ public class MultipartModelData
public static final class Builder
{
private final Map<BakedModel, ModelData> partData = new IdentityHashMap<>();
private final Map<BlockModelPart, ModelData> partData = new IdentityHashMap<>();
public Builder with(BakedModel model, ModelData data)
public Builder with(BlockModelPart model, ModelData data)
{
partData.put(model, data);
return this;
@@ -16,7 +16,9 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ObjectArrays;
import com.google.gson.JsonObject;
import com.mojang.math.Quadrant;
import net.minecraft.client.resources.model.BlockModelRotation;
import net.minecraft.util.Mth;
import net.minecraftforge.client.model.generators.MultiPartBlockStateBuilder.PartBuilder;
import net.minecraftforge.client.model.generators.VariantBlockStateBuilder.PartialBlockstate;
import org.jetbrains.annotations.Nullable;
@@ -126,7 +128,17 @@ public final class ConfiguredModel {
}
static void checkRotation(int rotationX, int rotationY) {
Preconditions.checkArgument(BlockModelRotation.by(rotationX, rotationY) != null, "Invalid model rotation x=%d, y=%d", rotationX, rotationY);
Preconditions.checkArgument(quadrantFromDeg(rotationX) == null || quadrantFromDeg(rotationY) == null, "Invalid model rotation x=%d, y=%d", rotationX, rotationY);
}
static @Nullable Quadrant quadrantFromDeg(int degrees) {
return switch (Mth.positiveModulo(degrees, 360)) {
case 0 -> Quadrant.R0;
case 90 -> Quadrant.R90;
case 180 -> Quadrant.R180;
case 270 -> Quadrant.R270;
default -> null;
};
}
static void checkWeight(int weight) {
@@ -19,10 +19,10 @@ import com.google.common.base.Preconditions;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.mojang.math.Quadrant;
import com.mojang.math.Transformation;
import com.mojang.serialization.JsonOps;
import net.minecraft.client.renderer.block.model.BlockFaceUV;
import net.minecraft.client.renderer.block.model.BlockElement;
import net.minecraft.client.renderer.block.model.BlockElementFace;
import net.minecraft.client.renderer.block.model.BlockElementRotation;
@@ -40,6 +40,7 @@ import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.VisibleForTesting;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import org.joml.Vector3fc;
/**
* General purpose model builder, contains all the commonalities between item
@@ -313,18 +314,18 @@ public class ModelBuilder<T extends ModelBuilder<T>> extends ModelFile {
JsonObject transform = new JsonObject();
ItemTransform vec = e.getValue();
if (vec.equals(ItemTransform.NO_TRANSFORM)) continue;
var hasRightRotation = !vec.rightRotation.equals(ItemTransform.Deserializer.DEFAULT_ROTATION);
if (!vec.translation.equals(ItemTransform.Deserializer.DEFAULT_TRANSLATION)) {
transform.add("translation", serializeVector3f(e.getValue().translation));
var hasRightRotation = !vec.rightRotation().equals(ItemTransform.Deserializer.DEFAULT_ROTATION);
if (!vec.translation().equals(ItemTransform.Deserializer.DEFAULT_TRANSLATION)) {
transform.add("translation", serializeVector3f(e.getValue().translation()));
}
if (!vec.rotation.equals(ItemTransform.Deserializer.DEFAULT_ROTATION)) {
transform.add(hasRightRotation ? "left_rotation" : "rotation", serializeVector3f(vec.rotation));
if (!vec.rotation().equals(ItemTransform.Deserializer.DEFAULT_ROTATION)) {
transform.add(hasRightRotation ? "left_rotation" : "rotation", serializeVector3f(vec.rotation()));
}
if (!vec.scale.equals(ItemTransform.Deserializer.DEFAULT_SCALE)) {
transform.add("scale", serializeVector3f(e.getValue().scale));
if (!vec.scale().equals(ItemTransform.Deserializer.DEFAULT_SCALE)) {
transform.add("scale", serializeVector3f(e.getValue().scale()));
}
if (hasRightRotation) {
transform.add("right_rotation", serializeVector3f(vec.rightRotation));
transform.add("right_rotation", serializeVector3f(vec.rightRotation()));
}
display.add(e.getKey().getSerializedName(), transform);
}
@@ -343,44 +344,44 @@ public class ModelBuilder<T extends ModelBuilder<T>> extends ModelFile {
JsonArray elements = new JsonArray();
this.elements.stream().map(ElementBuilder::build).forEach(part -> {
JsonObject partObj = new JsonObject();
partObj.add("from", serializeVector3f(part.from));
partObj.add("to", serializeVector3f(part.to));
partObj.add("from", serializeVector3f(part.from()));
partObj.add("to", serializeVector3f(part.to()));
if (part.rotation != null) {
if (part.rotation() != null) {
JsonObject rotation = new JsonObject();
rotation.add("origin", serializeVector3f(part.rotation.origin()));
rotation.addProperty("axis", part.rotation.axis().getSerializedName());
rotation.addProperty("angle", part.rotation.angle());
if (part.rotation.rescale()) {
rotation.addProperty("rescale", part.rotation.rescale());
rotation.add("origin", serializeVector3f(part.rotation().origin()));
rotation.addProperty("axis", part.rotation().axis().getSerializedName());
rotation.addProperty("angle", part.rotation().angle());
if (part.rotation().rescale()) {
rotation.addProperty("rescale", part.rotation().rescale());
}
partObj.add("rotation", rotation);
}
if (!part.shade) {
partObj.addProperty("shade", part.shade);
if (!part.shade()) {
partObj.addProperty("shade", part.shade());
}
JsonObject faces = new JsonObject();
for (Direction dir : Direction.values()) {
BlockElementFace face = part.faces.get(dir);
BlockElementFace face = part.faces().get(dir);
if (face == null) continue;
JsonObject faceObj = new JsonObject();
faceObj.addProperty("texture", serializeLocOrKey(face.texture()));
if (!Arrays.equals(face.uv().uvs, part.uvsByFace(dir)))
faceObj.add("uv", new Gson().toJsonTree(face.uv().uvs));
if (!face.uvs().equals(part.faces().get(dir).uvs()))
faceObj.add("uv", new Gson().toJsonTree(new float[]{face.uvs().minU(), face.uvs().minV(), face.uvs().maxU(), face.uvs().maxV()}));
if (face.cullForDirection() != null)
faceObj.addProperty("cullface", face.cullForDirection().getSerializedName());
if (face.uv().rotation != 0)
faceObj.addProperty("rotation", face.uv().rotation);
if (face.rotation() != Quadrant.R0)
faceObj.addProperty("rotation", face.rotation().ordinal());
if (face.tintIndex() != -1)
faceObj.addProperty("tintindex", face.tintIndex());
if (face.data() != null && !ForgeFaceData.DEFAULT.equals(face.data()))
if (!ForgeFaceData.DEFAULT.equals(face.data()))
faceObj.add("forge_data", ForgeFaceData.CODEC.encodeStart(JsonOps.INSTANCE, face.data()).result().get());
faces.add(dir.getSerializedName(), faceObj);
}
if (!part.faces.isEmpty())
if (!part.faces().isEmpty())
partObj.add("faces", faces);
elements.add(partObj);
});
@@ -407,7 +408,7 @@ public class ModelBuilder<T extends ModelBuilder<T>> extends ModelFile {
return ResourceLocation.parse(tex).toString();
}
private JsonArray serializeVector3f(Vector3f vec) {
private JsonArray serializeVector3f(Vector3fc vec) {
JsonArray ret = new JsonArray();
ret.add(serializeFloat(vec.x()));
ret.add(serializeFloat(vec.y()));
@@ -734,7 +735,8 @@ public class ModelBuilder<T extends ModelBuilder<T>> extends ModelFile {
BlockElementFace build() {
if (this.texture == null)
throw new IllegalStateException("A model face must have a texture");
return new BlockElementFace(cullface, tintindex, texture, new BlockFaceUV(uvs, rotation.rotation), this.data);
// TODO: [Forge][Rendering[[VEN] This is probably wrong, but it was BLAZING FAST!!! to write!
return new BlockElementFace(cullface, tintindex, texture, new BlockElementFace.UVs(uvs[0], uvs[1], uvs[2], uvs[3]), Quadrant.values()[rotation.rotation], this.data);
}
public ElementBuilder end() { return ElementBuilder.this; }
@@ -1,173 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.geometry;
import com.mojang.math.Transformation;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import net.minecraft.client.renderer.block.model.BlockModel;
import net.minecraft.client.renderer.block.model.ItemTransforms;
import net.minecraft.client.renderer.block.model.TextureSlots;
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.resources.ResourceLocation;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
/**
* A {@linkplain IGeometryBakingContext geometry baking context} that is bound to a {@link BlockModel}.
* <p>
* Users should not be instantiating this themselves.
*/
public class BlockGeometryBakingContext implements IGeometryBakingContext {
public final BlockModel owner;
public final VisibilityData visibilityData = new VisibilityData();
@Nullable
private IUnbakedGeometry<?> customGeometry;
@Nullable
private Transformation rootTransform;
@Nullable
private ResourceLocation renderTypeHint;
@Nullable
private ResourceLocation renderTypeFastHint;
private boolean gui3d = true;
@ApiStatus.Internal
public BlockGeometryBakingContext(BlockModel owner) {
this.owner = owner;
}
public boolean hasCustomGeometry() {
return getCustomGeometry() != null;
}
private BlockGeometryBakingContext parentContext() {
return owner.parent instanceof BlockModel block ? block.customData : null;
}
@Nullable
public IUnbakedGeometry<?> getCustomGeometry() {
if (customGeometry != null)
return customGeometry;
var pctx = parentContext();
return pctx == null ? null : pctx.getCustomGeometry();
}
public void setCustomGeometry(IUnbakedGeometry<?> geometry) {
this.customGeometry = geometry;
}
@Override
public boolean isComponentVisible(String part, boolean fallback) {
var pctx = parentContext();
if (pctx == null || visibilityData.hasCustomVisibility(part))
return visibilityData.isVisible(part, fallback);
return pctx.isComponentVisible(part, fallback);
}
@Override
public boolean isGui3d() {
return gui3d;
}
@Override
public boolean useBlockLight() {
return owner.getGuiLight().lightLikeBlock();
}
@Override
public boolean useAmbientOcclusion() {
return owner.getAmbientOcclusion();
}
@Override
public ItemTransforms getTransforms() {
return owner.getTransforms();
}
@Override
public Transformation getRootTransform() {
if (rootTransform != null)
return rootTransform;
var pctx = parentContext();
return pctx == null ? Transformation.identity() : pctx.getRootTransform();
}
public void setRootTransform(Transformation rootTransform) {
this.rootTransform = rootTransform;
}
@Nullable
@Override
public ResourceLocation getRenderTypeHint() {
if (renderTypeHint != null)
return renderTypeHint;
var pctx = parentContext();
return pctx == null ? null: pctx.getRenderTypeHint();
}
@Nullable
@Override
public ResourceLocation getRenderTypeFastHint() {
if (renderTypeFastHint != null)
return renderTypeFastHint;
var pctx = parentContext();
return pctx == null ? null: pctx.getRenderTypeFastHint();
}
public void setRenderTypeHint(ResourceLocation renderTypeHint) {
this.renderTypeHint = renderTypeHint;
}
public void setRenderTypeFastHint(ResourceLocation renderTypeFastHint) {
this.renderTypeFastHint = renderTypeFastHint;
}
public void setGui3d(boolean gui3d) {
this.gui3d = gui3d;
}
public void copyFrom(BlockGeometryBakingContext other) {
this.customGeometry = other.customGeometry;
this.rootTransform = other.rootTransform;
this.visibilityData.copyFrom(other.visibilityData);
this.renderTypeHint = other.renderTypeHint;
this.renderTypeFastHint = other.renderTypeFastHint;
this.gui3d = other.gui3d;
}
public BakedModel bake(ModelBaker baker, TextureSlots textures, ModelState modelTransform) {
IUnbakedGeometry<?> geometry = getCustomGeometry();
if (geometry == null)
throw new IllegalStateException("Can not use custom baking without custom geometry");
return geometry.bake(this, baker, textures, modelTransform);
}
public static class VisibilityData {
private final Map<String, Boolean> data = new HashMap<>();
public boolean hasCustomVisibility(String part) {
return data.containsKey(part);
}
public boolean isVisible(String part, boolean fallback) {
return data.getOrDefault(part, fallback);
}
public void setVisibilityState(String partName, boolean type) {
data.put(partName, type);
}
public void copyFrom(VisibilityData visibilityData) {
data.clear();
data.putAll(visibilityData.data);
}
}
}
@@ -21,14 +21,14 @@ import java.util.stream.Collectors;
* Provides a lookup.
*/
public final class GeometryLoaderManager {
private static ImmutableMap<ResourceLocation, IGeometryLoader<?>> LOADERS;
private static ImmutableMap<ResourceLocation, IGeometryLoader> LOADERS;
private static String LOADER_LIST;
/**
* 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);
}
@@ -41,7 +41,7 @@ public final class GeometryLoaderManager {
@ApiStatus.Internal
public static void init() {
var loaders = new HashMap<ResourceLocation, IGeometryLoader<?>>();
var loaders = new HashMap<ResourceLocation, IGeometryLoader>();
var event = new ModelEvent.RegisterGeometryLoaders(loaders);
ModLoader.get().postEventWrapContainerInModOrder(event);
LOADERS = ImmutableMap.copyOf(loaders);
@@ -19,7 +19,6 @@ import org.jetbrains.annotations.Nullable;
* {@linkplain RenderTypeGroup render types}.
*
* @see StandaloneGeometryBakingContext
* @see BlockGeometryBakingContext
*/
public interface IGeometryBakingContext {
/**
@@ -8,12 +8,14 @@ package net.minecraftforge.client.model.geometry;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import net.minecraft.client.resources.model.UnbakedGeometry;
import net.minecraft.server.packs.resources.ResourceManagerReloadListener;
import net.minecraftforge.client.event.ModelEvent.RegisterGeometryLoaders;
import net.minecraftforge.client.event.RegisterClientReloadListenersEvent;
/**
* A loader for custom {@linkplain IUnbakedGeometry model geometries}.
* A loader for custom {@linkplain UnbakedGeometry model geometries}.
* <p>
* If you do any caching, you should implement {@link ResourceManagerReloadListener} and register it with
* {@link RegisterClientReloadListenersEvent}.
@@ -21,6 +23,6 @@ import net.minecraftforge.client.event.RegisterClientReloadListenersEvent;
* @see RegisterGeometryLoaders
* @see RegisterClientReloadListenersEvent
*/
public interface IGeometryLoader<T extends IUnbakedGeometry<T>> {
T read(JsonObject jsonObject, JsonDeserializationContext deserializationContext) throws JsonParseException;
public interface IGeometryLoader {
UnbakedGeometry read(JsonObject jsonObject, JsonDeserializationContext deserializationContext) throws JsonParseException;
}
@@ -6,13 +6,13 @@
package net.minecraftforge.client.model.geometry;
import java.util.Set;
import java.util.function.Function;
import net.minecraft.client.renderer.block.model.BlockModel;
import net.minecraft.client.renderer.block.model.TextureSlots;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.renderer.block.model.BlockModelPart;
import net.minecraft.client.resources.model.ModelBaker;
import net.minecraft.client.resources.model.ModelState;
import net.minecraft.client.resources.model.ResolvableModel;
import net.minecraft.client.resources.model.UnbakedModel;
/**
@@ -24,14 +24,14 @@ import net.minecraft.client.resources.model.UnbakedModel;
* @see IGeometryBakingContext
*/
public interface IUnbakedGeometry<T extends IUnbakedGeometry<T>> {
BakedModel bake(IGeometryBakingContext context, ModelBaker baker, TextureSlots spriteGetter, ModelState modelState);
BlockModelPart bake(IGeometryBakingContext context, ModelBaker baker, TextureSlots spriteGetter, ModelState modelState);
/**
* Resolve parents of nested {@link BlockModel}s which are later used in
* {@link IUnbakedGeometry#bake(IGeometryBakingContext, ModelBaker, TextureSlots, ModelState)}
* via {@link BlockModel#resolveParents(Function)}
*/
default void resolveDependencies(UnbakedModel.Resolver resolver, IGeometryBakingContext context) { }
default void resolveDependencies(ResolvableModel.Resolver resolver, IGeometryBakingContext context) { }
/**
* {@return a set of all the components whose visibility may be configured via {@link IGeometryBakingContext}}
@@ -0,0 +1,89 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.geometry;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import com.mojang.math.Transformation;
import net.minecraft.client.renderer.block.model.BlockModel;
import net.minecraft.client.renderer.block.model.ItemTransforms;
import net.minecraft.client.resources.model.ModelDiscovery.ModelWrapper;
import net.minecraft.client.resources.model.ResolvedModel;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.model.ForgeBlockModelData;
@ApiStatus.Internal
public record ModelContext(
ResolvedModel self,
ResolvedModel parent,
@Nullable ForgeBlockModelData data,
boolean gui3d
) implements IGeometryBakingContext {
public ModelContext(ResolvedModel self) {
this(self, self.parent(), makeData(self, self.parent()), true);
}
private static ForgeBlockModelData makeData(ResolvedModel self, ResolvedModel parent) {
var data = self.wrapped() instanceof BlockModel block ? block.forgeData() : null;
var p = parent;
while (p != null && (data == null || !data.full())) {
if (p.wrapped() instanceof BlockModel block) {
if (data == null)
data = block.forgeData();
else
data = data.merge(block.forgeData());
}
p = (ModelWrapper)p.parent();
}
return data;
}
@Override
public boolean isGui3d() {
return gui3d;
}
public ModelContext withGui3d(boolean value) {
return new ModelContext(self, parent, data, value);
}
@Override
public boolean useBlockLight() {
var value = self.wrapped().guiLight();
return value != null && value.lightLikeBlock();
}
@Override
public boolean useAmbientOcclusion() {
return Boolean.TRUE.equals(self.wrapped().ambientOcclusion());
}
@Override
public ItemTransforms getTransforms() {
return self.wrapped().transforms();
}
@Override
public Transformation getRootTransform() {
return data == null ? Transformation.identity() : data.transform().orElse(Transformation.identity());
}
@Override
public @Nullable ResourceLocation getRenderTypeHint() {
return data == null ? null : data.renderType().orElse(null);
}
@Override
public boolean isComponentVisible(String component, boolean fallback) {
if (data == null || data.visibility().isEmpty())
return fallback;
return data.visibility().get().getOrDefault(component, fallback);
}
}
@@ -1,34 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.geometry;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.TextureSlots;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.resources.model.ModelBaker;
import net.minecraft.client.resources.model.ModelState;
import net.minecraftforge.client.RenderTypeGroup;
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> {
@Override
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, TextureSlots textures, ModelState modelState) {
var particle = baker.sprites().maybeMissing(textures, "particle");
IModelBuilder<?> builder = IModelBuilder.of(context.useAmbientOcclusion(), context.useBlockLight(), context.isGui3d(),
context.getTransforms(), particle, context.getRenderType(), context.getRenderTypeFast());
addQuads(context, builder, baker, textures, modelState);
return builder.build();
}
protected abstract void addQuads(IGeometryBakingContext owner, IModelBuilder<?> modelBuilder, ModelBaker baker, TextureSlots textures, ModelState modelTransform);
}
@@ -5,12 +5,12 @@
package net.minecraftforge.client.model.geometry;
import com.mojang.math.Quadrant;
import com.mojang.math.Transformation;
import net.minecraft.Util;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.BlockElement;
import net.minecraft.client.renderer.block.model.BlockElementFace;
import net.minecraft.client.renderer.block.model.BlockFaceUV;
import net.minecraft.client.renderer.block.model.FaceBakery;
import net.minecraft.client.renderer.block.model.ItemModelGenerator;
import net.minecraft.client.renderer.block.model.TextureSlots;
@@ -20,10 +20,9 @@ import net.minecraft.client.renderer.texture.TextureAtlas;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.model.Material;
import net.minecraft.client.resources.model.ModelState;
import net.minecraft.client.resources.model.QuadCollection;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.inventory.InventoryMenu;
import net.minecraftforge.client.model.IModelBuilder;
import net.minecraftforge.client.model.IQuadTransformer;
import net.minecraftforge.client.model.QuadTransformers;
import net.minecraftforge.client.model.SimpleModelState;
@@ -32,9 +31,7 @@ import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import org.joml.Vector3f;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Matcher;
@@ -45,8 +42,6 @@ import java.util.regex.Pattern;
*/
@ApiStatus.Internal
public class UnbakedGeometryHelper {
private static final FaceBakery FACE_BAKERY = new FaceBakery();
/**
* Explanation:
* This takes anything that looks like a valid resourcepack texture location, and tries to extract a resourcelocation out of it.
@@ -64,14 +59,17 @@ public class UnbakedGeometryHelper {
private static final Pattern FILESYSTEM_PATH_TO_RESLOC =
Pattern.compile("(?:.*[\\\\/]assets[\\\\/](?<namespace>[a-z_-]+)[\\\\/]textures[\\\\/])?(?<path>[a-z_\\\\/-]+)\\.png");
private static final Material MISSING_MATERIAL = getMaterial(MissingTextureAtlasSprite.getLocation().toString());
/**
* 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 InventoryMenu#BLOCK_ATLAS}.
* The target atlas will always be {@link TextureAtlas#LOCATION_BLOCKS}.
*/
public static Material resolveDirtyMaterial(@Nullable String tex, TextureSlots textures) {
if (tex == null)
return new Material(TextureAtlas.LOCATION_BLOCKS, MissingTextureAtlasSprite.getLocation());
return MISSING_MATERIAL;
if (tex.startsWith("#"))
return textures.getMaterial(tex);
@@ -84,10 +82,9 @@ public class UnbakedGeometryHelper {
tex = namespace != null ? namespace + ":" + path : path;
}
return new Material(TextureAtlas.LOCATION_BLOCKS, ResourceLocation.parse(tex));
return getMaterial(tex);
}
private static final ItemModelGenerator ITEM_MODEL_GENERATOR = new ItemModelGenerator();
/**
* Creates a list of {@linkplain BlockElement block elements} in the shape of the specified sprite contents.
* These can later be baked using the same, or another texture.
@@ -95,7 +92,7 @@ public class UnbakedGeometryHelper {
* 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);
return ItemModelGenerator.processFrames(layerIndex, "layer" + layerIndex, spriteContents);
}
/**
@@ -146,12 +143,9 @@ public class UnbakedGeometryHelper {
// Create element
elements.add(new BlockElement(
new Vector3f(16 * xStart / (float) width, 16 - 16 * yEnd / (float) height, 7.5F),
new Vector3f(16 * x / (float) width, 16 - 16 * y / (float) height, 8.5F),
Util.make(new HashMap<>(), map -> {
for (Direction direction : Direction.values())
map.put(direction, new BlockElementFace(null, layerIndex, "layer" + layerIndex, new BlockFaceUV(null, 0)));
})
new Vector3f(16 * xStart / (float) width, 16 - 16 * yEnd / (float) height, 7.5F),
new Vector3f(16 * x / (float) width, 16 - 16 * y / (float) height, 8.5F),
Util.makeEnumMap(Direction.class, dir -> new BlockElementFace(dir, layerIndex, "layer" + layerIndex, new BlockElementFace.UVs(0F, 0F, 16F, 16F), Quadrant.R0))
));
// Reset xStart
@@ -163,37 +157,54 @@ public class UnbakedGeometryHelper {
}
/**
* Bakes a list of {@linkplain BlockElement block elements} and feeds the baked quads to a {@linkplain IModelBuilder model builder}.
* Bakes a list of {@linkplain BlockElement block elements} and returns a {@link QuadCollection}.
*/
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, element.lightEmission);
public static QuadCollection bakeElements(List<BlockElement> elements, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState) {
return bakeElements(elements, spriteGetter, modelState, QuadTransformers.empty());
}
/**
* Bakes a list of {@linkplain BlockElement block elements} and returns a {@link QuadCollection}.
*/
public static QuadCollection bakeElements(List<BlockElement> elements, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, IQuadTransformer transformer) {
var builder = new QuadCollection.Builder();
bakeElements(elements, spriteGetter, modelState, builder);
return builder.build();
}
/**
* Adds a list of {@linkplain BlockElement block elements} int a {@link QuadCollection.Builder}.
*/
public static void bakeElements(List<BlockElement> elements, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, QuadCollection.Builder builder) {
bakeElements(elements, spriteGetter, modelState, QuadTransformers.empty(), builder);
}
/**
* Adds a list of {@linkplain BlockElement block elements} int a {@link QuadCollection.Builder}.
*/
public static void bakeElements(List<BlockElement> elements, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, IQuadTransformer transformer, QuadCollection.Builder builder) {
for (var element : elements) {
element.faces().forEach((side, face) -> {
var sprite = spriteGetter.apply(getMaterial(face.texture()));
var quad = bakeElementFace(element, face, sprite, side, modelState, element.lightEmission());
if (face.cullForDirection() == null)
builder.addUnculledFace(quad);
else
builder.addCulledFace(Direction.rotate(modelState.getRotation().getMatrix(), face.cullForDirection()), quad);
builder.addCulledFace(Direction.rotate(modelState.transformation().getMatrix(), face.cullForDirection()), quad);
});
}
}
/**
* 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) {
if (elements.isEmpty())
return List.of();
var list = new ArrayList<BakedQuad>();
bakeElements(IModelBuilder.collecting(list), elements, spriteGetter, modelState);
return list;
@SuppressWarnings("deprecation")
private static Material getMaterial(String texture) {
return new Material(TextureAtlas.LOCATION_BLOCKS, ResourceLocation.parse(texture));
}
/**
* Turns a single {@link BlockElementFace} into a {@link BakedQuad}.
*/
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);
return FaceBakery.bakeQuad(element.from(), element.to(), face, sprite, direction, state, element.rotation(), element.shade(), lightEmission);
}
/**
@@ -208,7 +219,7 @@ public class UnbakedGeometryHelper {
// 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
Transformation transform = modelState.getRotation().applyOrigin(new Vector3f(.5F, .5F, .5F));
Transformation transform = modelState.transformation().applyOrigin(new Vector3f(.5F, .5F, .5F));
return QuadTransformers.applying(transform.compose(rootTransform).compose(transform.inverse()));
}
@@ -219,6 +230,6 @@ public class UnbakedGeometryHelper {
// 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));
return new SimpleModelState(modelState.getRotation().compose(rootTransform), modelState.isUvLocked());
return new SimpleModelState(modelState.transformation().compose(rootTransform));
}
}
@@ -1,76 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.lighting;
import net.minecraft.client.color.block.BlockColors;
import net.minecraft.client.renderer.LevelRenderer;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
/**
* Implementation of {@link QuadLighter} that lights {@link BakedQuad quads} with flat lighting.
*/
public class FlatQuadLighter extends QuadLighter
{
private static final Direction[] SIDES = Direction.values();
private static final float MAX_POSITION = 1f - 1e-2f;
private static final byte MAX_NORMAL = 127;
private boolean isFullCube;
private final int[] packedLight = new int[7];
public FlatQuadLighter(BlockColors colors)
{
super(colors);
}
@Override
protected void computeLightingAt(BlockAndTintGetter level, BlockPos pos, BlockState state)
{
isFullCube = Block.isShapeFullBlock(state.getCollisionShape(level, pos));
for (Direction side : SIDES)
{
packedLight[side.ordinal()] = LevelRenderer.getLightColor(level, state, pos.relative(side));
}
//Note: We can just use the LevelRenderer method as we know the state is the state at the given position
packedLight[6] = LevelRenderer.getLightColor(level, state, pos);
}
@Override
protected float calculateBrightness(float[] position)
{
return 1.0f; // No shading in flat lighting
}
@Override
protected int calculateLightmap(float[] position, byte[] normal)
{
if ((isFullCube || position[1] < -MAX_POSITION) && normal[1] <= -MAX_NORMAL)
return packedLight[Direction.DOWN.ordinal()];
if ((isFullCube || position[1] > MAX_POSITION) && normal[1] >= MAX_NORMAL)
return packedLight[Direction.UP.ordinal()];
if ((isFullCube || position[2] < -MAX_POSITION) && normal[2] <= -MAX_NORMAL)
return packedLight[Direction.NORTH.ordinal()];
if ((isFullCube || position[2] > MAX_POSITION) && normal[2] >= MAX_NORMAL)
return packedLight[Direction.SOUTH.ordinal()];
if ((isFullCube || position[0] < -MAX_POSITION) && normal[0] <= -MAX_NORMAL)
return packedLight[Direction.WEST.ordinal()];
if ((isFullCube || position[0] > MAX_POSITION) && normal[0] >= MAX_NORMAL)
return packedLight[Direction.EAST.ordinal()];
return packedLight[6];
}
}
@@ -1,115 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.lighting;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.color.block.BlockColors;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.block.ModelBlockRenderer;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.client.model.data.ModelData;
import net.minecraftforge.common.ForgeConfig;
import java.util.List;
/**
* Wrapper around {@link ModelBlockRenderer} to allow rendering blocks via Forge's lighting pipeline.
*/
public class ForgeModelBlockRenderer extends ModelBlockRenderer {
private static final Direction[] SIDES = Direction.values();
private final ThreadLocal<QuadLighter> flatLighter, smoothLighter;
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) {
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) {
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) {
ForgeModelBlockRenderer renderer = (ForgeModelBlockRenderer)Minecraft.getInstance().getBlockRenderer().getModelRenderer();
var pose = poseStack.last();
var empty = true;
var smoothLighter = lighter instanceof SmoothQuadLighter;
QuadLighter flatLighter = null;
rand.setSeed(seed);
List<BakedQuad> quads = model.getQuads(state, null, rand, modelData, renderType);
if (!quads.isEmpty()) {
empty = false;
lighter.setup(level, pos, state);
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 {
lighter.process(vertexConsumer, pose, quad, packedOverlay);
}
}
}
var mutable = pos.mutable();
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) {
empty = false;
lighter.setup(level, pos, state);
}
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 {
lighter.process(vertexConsumer, pose, quad, packedOverlay);
}
}
}
}
lighter.reset();
if (flatLighter != null)
flatLighter.reset();
return !empty;
}
}
@@ -1,155 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.lighting;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import net.minecraft.client.color.block.BlockColors;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.LightLayer;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.client.model.IQuadTransformer;
import org.joml.Vector3f;
import java.util.Objects;
/**
* Base class for all quad lighting providers.
* <p>
* Contains all the shared elements needed for {@link BakedQuad} processing and defers lighting logic to inheritors.
*
* @see FlatQuadLighter
* @see SmoothQuadLighter
*/
public abstract class QuadLighter
{
private static final float[] WHITE = new float[] { 1.0f, 1.0f, 1.0f };
private final BlockColors colors;
private int currentHash = 0;
private BlockAndTintGetter level;
private BlockPos pos;
private BlockState state;
private int cachedTintIndex = -1;
private final float[] cachedTintColor = new float[3];
// Arrays used for quad processing, initialized once and then used repeatedly to avoid GC pressure
private final float[] brightness = new float[4];
private final int[] lightmap = new int[4];
private final float[][] positions = new float[4][3];
private final byte[][] normals = new byte[4][3];
private final int[] packedLightmaps = new int[4];
protected QuadLighter(BlockColors colors)
{
this.colors = colors;
}
protected abstract void computeLightingAt(BlockAndTintGetter level, BlockPos pos, BlockState state);
protected abstract float calculateBrightness(float[] position);
protected abstract int calculateLightmap(float[] position, byte[] normal);
public final void setup(BlockAndTintGetter level, BlockPos pos, BlockState state)
{
var hash = Objects.hash(level, pos, state);
if (this.level != null && this.currentHash == hash)
{
return; // If we are drawing a block at the same position as before, don't re-compute anything
}
this.currentHash = hash;
this.level = level;
this.pos = pos;
this.state = state;
this.cachedTintIndex = -1;
computeLightingAt(level, pos, state);
}
public final void reset()
{
this.level = null; // Invalidates part of the state to force a re-computation
}
public final void process(VertexConsumer consumer, PoseStack.Pose pose, BakedQuad quad, int overlay)
{
var vertices = quad.getVertices();
for (int i = 0; i < 4; i++)
{
int offset = i * IQuadTransformer.STRIDE;
positions[i][0] = Float.intBitsToFloat(vertices[offset + IQuadTransformer.POSITION]);
positions[i][1] = Float.intBitsToFloat(vertices[offset + IQuadTransformer.POSITION + 1]);
positions[i][2] = Float.intBitsToFloat(vertices[offset + IQuadTransformer.POSITION + 2]);
int packedNormal = vertices[offset + IQuadTransformer.NORMAL];
normals[i][0] = (byte) (packedNormal & 0xFF);
normals[i][1] = (byte) ((packedNormal >> 8) & 0xFF);
normals[i][2] = (byte) ((packedNormal >> 16) & 0xFF);
packedLightmaps[i] = vertices[offset + IQuadTransformer.UV2];
}
if (normals[0][0] == 0 && normals[0][1] == 0 && normals[0][2] == 0)
{
Vector3f a = new Vector3f(positions[0]);
Vector3f ab = new Vector3f(positions[1]);
Vector3f ac = new Vector3f(positions[2]);
ac.sub(a);
ab.sub(a);
ab.cross(ac);
ab.normalize();
for (int v = 0; v < 4; v++)
{
normals[v][0] = (byte) (ab.x() * 127);
normals[v][1] = (byte) (ab.y() * 127);
normals[v][2] = (byte) (ab.z() * 127);
}
}
for (int i = 0; i < 4; i++)
{
var position = positions[i];
var normal = normals[i];
int packedLightmap = packedLightmaps[i];
var adjustedPosition = new float[] {
position[0] - 0.5f + ((normal[0] / 127f) * 0.5f),
position[1] - 0.5f + ((normal[1] / 127f) * 0.5f),
position[2] - 0.5f + ((normal[2] / 127f) * 0.5f)
};
var shade = level.getShade(normals[i][0] / 127f, normals[i][1] / 127f, normals[i][2] / 127f, quad.isShade());
brightness[i] = calculateBrightness(adjustedPosition) * shade;
int newLightmap = calculateLightmap(adjustedPosition, normal);
lightmap[i] = Math.max(packedLightmap & 0xFFFF, newLightmap & 0xFFFF) |
(Math.max((packedLightmap >> 16) & 0xFFFF, (newLightmap >> 16) & 0xFFFF) << 16);
}
var color = quad.isTinted() ? getColorFast(quad.getTintIndex()) : WHITE;
consumer.putBulkData(pose, quad, brightness, color[0], color[1], color[2], 1.0f, lightmap, overlay, true);
}
private float[] getColorFast(int tintIndex)
{
if (tintIndex != cachedTintIndex)
{
var packedColor = colors.getColor(state, level, pos, tintIndex);
cachedTintIndex = tintIndex;
cachedTintColor[0] = ((packedColor >> 16) & 0xFF) / 255F;
cachedTintColor[1] = ((packedColor >> 8) & 0xFF) / 255F;
cachedTintColor[2] = (packedColor & 0xFF) / 255F;
}
return cachedTintColor;
}
public static float calculateShade(float normalX, float normalY, float normalZ, boolean constantAmbientLight)
{
float yFactor = constantAmbientLight ? 0.9F : ((3.0F + normalY) / 4.0F);
return Math.min(normalX * normalX * 0.6F + normalY * normalY * yFactor + normalZ * normalZ * 0.8F, 1.0F);
}
}
@@ -1,231 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.lighting;
import net.minecraft.client.color.block.BlockColors;
import net.minecraft.client.renderer.LevelRenderer;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.util.Mth;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
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 {
private static final Direction[] SIDES = Direction.values();
private final BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
private final boolean[][][] t = new boolean[3][3][3];
private final int[][][] s = new int[3][3][3];
private final int[][][] b = new int[3][3][3];
private final float[][][][] skyLight = new float[3][2][2][2];
private final float[][][][] blockLight = new float[3][2][2][2];
private final float[][][] ao = new float[3][3][3];
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++) {
pos.setWithOffset(origin, x - 1, y - 1, z - 1);
BlockState neighborState = level.getBlockState(pos);
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);
ao[x][y][z] = neighborState.getShadeBrightness(level, pos);
}
}
}
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() == 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;
s[x][y][z] = Math.max(s[1][1][1] - 1, s[x][y][z]);
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++) {
int x1 = x * 2;
int y1 = y * 2;
int z1 = z * 2;
int sxyz = s[x1][y1][z1];
int bxyz = b[x1][y1][z1];
boolean txyz = t[x1][y1][z1];
int sxz = s[x1][1][z1], sxy = s[x1][y1][1], syz = s[1][y1][z1];
int bxz = b[x1][1][z1], bxy = b[x1][y1][1], byz = b[1][y1][z1];
boolean txz = t[x1][1][z1], txy = t[x1][y1][1], tyz = t[1][y1][z1];
int sx = s[x1][1][1], sy = s[1][y1][1], sz = s[1][1][z1];
int bx = b[x1][1][1], by = b[1][y1][1], bz = b[1][1][z1];
boolean tx = t[x1][1][1], ty = t[1][y1][1], tz = t[1][1][z1];
skyLight[0][x][y][z] = combine(sx, sxz, sxy, txz || txy ? sxyz : sx,
tx, txz, txy, txz || txy ? txyz : tx);
blockLight[0][x][y][z] = combine(bx, bxz, bxy, txz || txy ? bxyz : bx,
tx, txz, txy, txz || txy ? txyz : tx);
skyLight[1][x][y][z] = combine(sy, sxy, syz, txy || tyz ? sxyz : sy,
ty, txy, tyz, txy || tyz ? txyz : ty);
blockLight[1][x][y][z] = combine(by, bxy, byz, txy || tyz ? bxyz : by,
ty, txy, tyz, txy || tyz ? txyz : ty);
skyLight[2][x][y][z] = combine(sz, syz, sxz, tyz || txz ? sxyz : sz,
tz, tyz, txz, tyz || txz ? txyz : tz);
blockLight[2][x][y][z] = combine(bz, byz, bxz, tyz || txz ? bxyz : bz,
tz, tyz, txz, tyz || txz ? txyz : tz);
}
}
}
}
@Override
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;
int sz = z < 0 ? 1 : 2;
if (x < 0) x++;
if (y < 0) y++;
if (z < 0) z++;
float a = 0;
a += ao[sx - 1][sy - 1][sz - 1] * (1 - x) * (1 - y) * (1 - z);
a += ao[sx - 1][sy - 1][sz - 0] * (1 - x) * (1 - y) * (0 + z);
a += ao[sx - 1][sy - 0][sz - 1] * (1 - x) * (0 + y) * (1 - z);
a += ao[sx - 1][sy - 0][sz - 0] * (1 - x) * (0 + y) * (0 + z);
a += ao[sx - 0][sy - 1][sz - 1] * (0 + x) * (1 - y) * (1 - z);
a += ao[sx - 0][sy - 1][sz - 0] * (0 + x) * (1 - y) * (0 + z);
a += ao[sx - 0][sy - 0][sz - 1] * (0 + x) * (0 + y) * (1 - z);
a += ao[sx - 0][sy - 0][sz - 0] * (0 + x) * (0 + y) * (0 + z);
a = Mth.clamp(a, 0, 1);
return a;
}
@Override
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) {
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);
if (s3 == 0 && !t3) s3 = Math.max(0, Math.max(s1, s2) - 1);
return (c + s1 + s2 + s3) / (0xF * 4f);
}
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) {
float s = (float) Math.sqrt((6 - 2e-2f) / l2);
x *= s;
y *= s;
z *= s;
}
float ax = x > 0 ? x : -x;
float ay = y > 0 ? y : -y;
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) {
float s = (3f - 1e-4f) / (ay + az);
y *= s;
z *= s;
} 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) {
float s = (3f - 1e-4f) / (ax + ay);
x *= s;
y *= s;
} else if (ax + ay + az > 4 - 1e-4f) {
float s = (4 - 1e-4f) / (ax + ay + az);
x *= s;
y *= s;
z *= s;
}
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++) {
float vx = x * (1 - ix * 2);
float vy = y * (1 - iy * 2);
float vz = z * (1 - iz * 2);
float s3 = vx + vy + vz + 4;
float sx = vy + vz + 3;
float sy = vz + vx + 3;
float sz = vx + vy + 3;
float bx = (2 * vx + vy + vz + 6) / (s3 * sy * sz * (vx + 2));
s += bx;
l += bx * light[0][ix][iy][iz];
float by = (2 * vy + vz + vx + 6) / (s3 * sz * sx * (vy + 2));
s += by;
l += by * light[1][ix][iy][iz];
float bz = (2 * vz + vx + vy + 6) / (s3 * sx * sy * (vz + 2));
s += bz;
l += bz * light[2][ix][iy][iz];
}
}
}
l /= s;
l = Mth.clamp(l, 0, 1);
return l;
}
}
@@ -10,12 +10,21 @@ import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.TextureSlots;
import net.minecraft.client.resources.model.ModelBaker;
import net.minecraft.client.resources.model.ModelDebugName;
import net.minecraft.client.resources.model.ModelState;
import net.minecraft.client.resources.model.QuadCollection;
import net.minecraft.client.resources.model.UnbakedGeometry;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.ResourceManagerReloadListener;
import net.minecraft.util.GsonHelper;
import net.minecraftforge.client.model.IModelBuilder;
import net.minecraftforge.client.model.geometry.IGeometryBakingContext;
import net.minecraftforge.client.model.geometry.IGeometryLoader;
import net.minecraftforge.client.model.geometry.StandaloneGeometryBakingContext;
import java.io.FileNotFoundException;
import java.util.Map;
@@ -26,8 +35,7 @@ import java.util.Map;
* Allows the user to enable automatic face culling, toggle quad shading, flip UVs, render emissively and specify a
* {@link ObjMaterialLibrary material library} override.
*/
public class ObjLoader implements IGeometryLoader<ObjModel>, ResourceManagerReloadListener
{
public class ObjLoader implements IGeometryLoader, ResourceManagerReloadListener {
public static ObjLoader INSTANCE = new ObjLoader();
private final Map<ObjModel.ModelSettings, ObjModel> modelCache = Maps.newConcurrentMap();
@@ -36,61 +44,72 @@ public class ObjLoader implements IGeometryLoader<ObjModel>, ResourceManagerRelo
private ResourceManager manager = Minecraft.getInstance().getResourceManager();
@Override
public void onResourceManagerReload(ResourceManager resourceManager)
{
public void onResourceManagerReload(ResourceManager resourceManager) {
modelCache.clear();
materialCache.clear();
manager = resourceManager;
}
@Override
public ObjModel read(JsonObject jsonObject, JsonDeserializationContext deserializationContext)
{
if (!jsonObject.has("model"))
throw new JsonParseException("OBJ Loader requires a 'model' key that points to a valid .OBJ model.");
public UnbakedGeometry read(JsonObject json, JsonDeserializationContext deserializationContext) {
var location = ResourceLocation.parse(GsonHelper.getAsString(json, "model"));
String modelLocation = jsonObject.get("model").getAsString();
boolean automaticCulling = GsonHelper.getAsBoolean(json, "automatic_culling", true);
boolean shadeQuads = GsonHelper.getAsBoolean(json, "shade_quads", true);
boolean flipV = GsonHelper.getAsBoolean(json, "flip_v", false);
boolean emissiveAmbient = GsonHelper.getAsBoolean(json, "emissive_ambient", true);
String mtlOverride = GsonHelper.getAsString(json, "mtl_override", null);
boolean automaticCulling = GsonHelper.getAsBoolean(jsonObject, "automatic_culling", true);
boolean shadeQuads = GsonHelper.getAsBoolean(jsonObject, "shade_quads", true);
boolean flipV = GsonHelper.getAsBoolean(jsonObject, "flip_v", false);
boolean emissiveAmbient = GsonHelper.getAsBoolean(jsonObject, "emissive_ambient", true);
String mtlOverride = GsonHelper.getAsString(jsonObject, "mtl_override", null);
var settings = new ObjModel.ModelSettings(location, automaticCulling, shadeQuads, flipV, emissiveAmbient, mtlOverride);
var model = loadModel(settings);
return loadModel(new ObjModel.ModelSettings(ResourceLocation.parse(modelLocation), automaticCulling, shadeQuads, flipV, emissiveAmbient, mtlOverride));
return new ObjGeometry(model);
}
public ObjModel loadModel(ObjModel.ModelSettings settings)
{
public ObjModel loadModel(ObjModel.ModelSettings settings) {
return modelCache.computeIfAbsent(settings, (data) -> {
Resource resource = manager.getResource(settings.modelLocation()).orElseThrow();
try (ObjTokenizer tokenizer = new ObjTokenizer(resource.open()))
{
try (ObjTokenizer tokenizer = new ObjTokenizer(resource.open())) {
return ObjModel.parse(tokenizer, settings);
} catch (FileNotFoundException e)
{
throw new RuntimeException("Could not find OBJ model", e);
} catch (Exception e)
{
} catch (Exception e) {
throw new RuntimeException("Could not read OBJ model", e);
}
});
}
public ObjMaterialLibrary loadMaterialLibrary(ResourceLocation materialLocation)
{
public ObjMaterialLibrary loadMaterialLibrary(ResourceLocation materialLocation) {
return materialCache.computeIfAbsent(materialLocation, (location) -> {
Resource resource = manager.getResource(location).orElseThrow();
try (ObjTokenizer rdr = new ObjTokenizer(resource.open()))
{
try (ObjTokenizer rdr = new ObjTokenizer(resource.open())) {
return new ObjMaterialLibrary(rdr);
} catch (FileNotFoundException e)
{
throw new RuntimeException("Could not find OBJ material library", e);
} catch (Exception e)
{
} catch (Exception e) {
throw new RuntimeException("Could not read OBJ material library", e);
}
});
}
private static class ObjGeometry implements UnbakedGeometry {
private final ObjModel model;
public ObjGeometry(ObjModel model) {
this.model = model;
}
@Override
public QuadCollection bake(TextureSlots slots, ModelBaker baker, ModelState state, ModelDebugName name) {
return bake(slots, baker, state, name, StandaloneGeometryBakingContext.INSTANCE);
}
@Override
public QuadCollection bake(TextureSlots slots, ModelBaker baker, ModelState state, ModelDebugName name, IGeometryBakingContext context) {
var builder = new QuadCollection.Builder();
for (var part : model.getParts().values()) {
if (context.isComponentVisible(part.name(), true))
part.bake(slots, baker, state, name, context, builder);
}
return builder.build();
}
}
}
@@ -6,6 +6,7 @@
package net.minecraftforge.client.model.obj;
import com.google.common.collect.Maps;
import net.minecraft.client.resources.model.ModelDebugName;
import org.joml.Vector4f;
import java.io.IOException;
@@ -15,14 +15,15 @@ import net.minecraft.client.renderer.block.model.TextureSlots;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.model.Material;
import net.minecraft.client.resources.model.ModelBaker;
import net.minecraft.client.resources.model.ModelDebugName;
import net.minecraft.client.resources.model.ModelState;
import net.minecraft.client.resources.model.QuadCollection;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.Mth;
import net.minecraft.world.phys.Vec2;
import net.minecraftforge.client.model.IModelBuilder;
import net.minecraftforge.client.model.geometry.IGeometryBakingContext;
import net.minecraftforge.client.model.geometry.SimpleUnbakedGeometry;
import net.minecraftforge.client.model.geometry.UnbakedGeometryHelper;
import net.minecraftforge.client.model.pipeline.QuadBakingVertexConsumer;
import net.minecraftforge.client.model.renderable.CompositeRenderable;
@@ -51,7 +52,7 @@ import java.util.stream.Collectors;
* Supports positions, texture coordinates, normals and colors. The {@link ObjMaterialLibrary material library}
* has support for numerous features, including support for {@link ResourceLocation} textures (non-standard).
*/
public class ObjModel extends SimpleUnbakedGeometry<ObjModel> {
public class ObjModel {
private static final Vector4f COLOR_WHITE = new Vector4f(1, 1, 1, 1);
private static final Vec2[] DEFAULT_COORDS = {
new Vec2(0, 0),
@@ -61,6 +62,7 @@ public class ObjModel extends SimpleUnbakedGeometry<ObjModel> {
};
private final Map<String, ModelGroup> parts = Maps.newLinkedHashMap();
private final Map<String, ModelGroup> partsView = Collections.unmodifiableMap(parts);
private final Set<String> rootComponentNames = Collections.unmodifiableSet(parts.keySet());
private Set<String> allComponentNames;
@@ -87,6 +89,10 @@ public class ObjModel extends SimpleUnbakedGeometry<ObjModel> {
this.mtlOverride = settings.mtlOverride;
}
public Map<String, ModelGroup> getParts() {
return partsView;
}
public static ObjModel parse(ObjTokenizer tokenizer, ModelSettings settings) throws IOException {
var modelLocation = settings.modelLocation;
var materialLibraryOverrideLocation = settings.mtlOverride;
@@ -269,19 +275,10 @@ public class ObjModel extends SimpleUnbakedGeometry<ObjModel> {
};
}
@Override
protected void addQuads(IGeometryBakingContext owner, IModelBuilder<?> modelBuilder, ModelBaker baker, TextureSlots textures, ModelState modelTransform) {
for (var part : parts.values()) {
if (owner.isComponentVisible(part.name(), true))
part.addQuads(owner, modelBuilder, baker, textures, modelTransform, modelLocation);
}
}
public Set<String> getRootComponentNames() {
return rootComponentNames;
}
@Override
public Set<String> getConfigurableComponentNames() {
if (allComponentNames != null)
return allComponentNames;
@@ -428,7 +425,7 @@ public class ObjModel extends SimpleUnbakedGeometry<ObjModel> {
return builder.get();
}
private class ModelObject {
public class ModelObject {
public final String name;
List<ModelMesh> meshes = Lists.newArrayList();
@@ -441,9 +438,9 @@ public class ObjModel extends SimpleUnbakedGeometry<ObjModel> {
return name;
}
protected void addQuads(IGeometryBakingContext owner, IModelBuilder<?> modelBuilder, ModelBaker baker, TextureSlots textures, ModelState modelTransform, ResourceLocation modelLocation) {
public void bake(TextureSlots slots, ModelBaker baker, ModelState state, ModelDebugName name, IGeometryBakingContext context, QuadCollection.Builder builder) {
for (var mesh : meshes)
mesh.addQuads(owner, modelBuilder, baker, textures, modelTransform, modelLocation);
mesh.bake(slots, baker, state, name, context, builder);
}
protected void bake(CompositeRenderable.PartBuilder<?> builder, TextureSlots textures) {
@@ -465,7 +462,7 @@ public class ObjModel extends SimpleUnbakedGeometry<ObjModel> {
}
}
private class ModelGroup extends ModelObject {
public class ModelGroup extends ModelObject {
final Map<String, ModelObject> parts = Maps.newLinkedHashMap();
ModelGroup(String name) {
@@ -473,12 +470,12 @@ public class ObjModel extends SimpleUnbakedGeometry<ObjModel> {
}
@Override
public void addQuads(IGeometryBakingContext owner, IModelBuilder<?> modelBuilder, ModelBaker baker, TextureSlots spriteGetter, ModelState modelTransform, ResourceLocation modelLocation) {
super.addQuads(owner, modelBuilder, baker, spriteGetter, modelTransform, modelLocation);
public void bake(TextureSlots slots, ModelBaker baker, ModelState state, ModelDebugName name, IGeometryBakingContext context, QuadCollection.Builder builder) {
super.bake(slots, baker, state, name, context, builder);
for (var part : parts.values()) {
if (owner.isComponentVisible(part.name(), true))
part.addQuads(owner, modelBuilder, baker, spriteGetter, modelTransform, modelLocation);
if (context.isComponentVisible(part.name(), true))
part.bake(slots, baker, state, name, context, builder);
}
}
@@ -522,22 +519,25 @@ public class ObjModel extends SimpleUnbakedGeometry<ObjModel> {
this.smoothingGroup = currentSmoothingGroup;
}
protected void addQuads(IGeometryBakingContext owner, IModelBuilder<?> modelBuilder, ModelBaker baker, TextureSlots textures, ModelState modelTransform, ResourceLocation modelLocation) {
protected void bake(TextureSlots slots, ModelBaker baker, ModelState state, ModelDebugName name, IGeometryBakingContext context, QuadCollection.Builder builder) {
if (mat == null)
return;
var material = UnbakedGeometryHelper.resolveDirtyMaterial(mat.diffuseColorMap, textures);
var texture = baker.sprites().get(material);
var material = UnbakedGeometryHelper.resolveDirtyMaterial(mat.diffuseColorMap, slots);
var texture = baker.sprites().get(material, name);
int tintIndex = mat.diffuseTintIndex;
Vector4f colorTint = mat.diffuseColor;
var rootTransform = owner.getRootTransform();
var transform = rootTransform.isIdentity() ? modelTransform.getRotation() : modelTransform.getRotation().compose(rootTransform);
// TODO: [Forge][Rendering] Models contains the transforms so we shouldnt care about them here.
//var rootTransform = context.getRootTransform();
//var transform = rootTransform.isIdentity() ? modelTransform.transformation() : modelTransform.transformation().compose(rootTransform);
var transform = Transformation.identity();
for (int[][] face : faces) {
Pair<BakedQuad, Direction> quad = makeQuad(face, tintIndex, colorTint, mat.ambientColor, texture, transform);
if (quad.getRight() == null)
modelBuilder.addUnculledFace(quad.getLeft());
builder.addUnculledFace(quad.getLeft());
else
modelBuilder.addCulledFace(quad.getRight(), quad.getLeft());
builder.addCulledFace(quad.getRight(), quad.getLeft());
}
}
@@ -8,10 +8,9 @@ package net.minecraftforge.client.model.renderable;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.BlockModelPart;
import net.minecraft.client.renderer.block.model.BlockStateModel;
import net.minecraft.client.renderer.texture.TextureAtlas;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.core.Direction;
import net.minecraft.util.RandomSource;
import net.minecraft.util.Unit;
@@ -20,6 +19,7 @@ import net.minecraftforge.client.model.data.ModelData;
import org.jetbrains.annotations.Nullable;
import org.joml.Vector4f;
import java.util.ArrayList;
import java.util.Arrays;
/**
@@ -37,33 +37,39 @@ public class BakedModelRenderable implements IRenderable<BakedModelRenderable.Co
*
* @see net.minecraftforge.client.event.ModelEvent.RegisterModelStateDefinitions
*/
public static BakedModelRenderable of(ModelResourceLocation model) {
return of(Minecraft.getInstance().getModelManager().getModel(model));
public static BakedModelRenderable of(BlockState state) {
return of(Minecraft.getInstance().getModelManager().getBlockModelShaper().getBlockModel(state));
}
/**
* Constructs a {@link BakedModelRenderable} from the given baked model.
*/
public static BakedModelRenderable of(BakedModel model) {
public static BakedModelRenderable of(BlockStateModel model) {
return new BakedModelRenderable(model);
}
private final BakedModel model;
private final BlockStateModel model;
private BakedModelRenderable(BakedModel model) {
private BakedModelRenderable(BlockStateModel model) {
this.model = model;
}
@Override
public void render(PoseStack poseStack, MultiBufferSource bufferSource, ITextureRenderTypeLookup textureRenderTypeLookup, int lightmap, int overlay, float partialTick, Context context) {
@SuppressWarnings("deprecation")
var buffer = bufferSource.getBuffer(textureRenderTypeLookup.get(TextureAtlas.LOCATION_BLOCKS));
var tint = context.tint();
var randomSource = context.randomSource();
for (var direction : context.faces()) {
randomSource.setSeed(context.seed());
// Given the lack of context, the requested render type has to be null to ensure the model renders all of its geometry
for (BakedQuad quad : model.getQuads(context.state(), direction, randomSource, context.data(), null))
buffer.putBulkData(poseStack.last(), quad, tint.x(), tint.y(), tint.z(), tint.w(), lightmap, overlay, true);
randomSource.setSeed(context.seed());
// Given the lack of context, the requested render type has to be null to ensure the model renders all of its geometry
var parts = new ArrayList<BlockModelPart>();
model.collectParts(randomSource, parts, context.data(), null);
for (var part : parts) {
for (var direction : Direction.valuesView()) {
for (var quad : part.getQuads(direction)) {
buffer.putBulkData(poseStack.last(), quad, tint.x(), tint.y(), tint.z(), tint.w(), lightmap, overlay, true);
}
}
}
}
@@ -23,42 +23,33 @@ import java.util.List;
*
* @see Builder
*/
public class CompositeRenderable implements IRenderable<CompositeRenderable.Transforms>
{
public class CompositeRenderable implements IRenderable<CompositeRenderable.Transforms> {
private final List<Component> components = new ArrayList<>();
private CompositeRenderable()
{
}
private CompositeRenderable() { }
@Override
public void render(PoseStack poseStack, MultiBufferSource bufferSource, ITextureRenderTypeLookup textureRenderTypeLookup, int lightmap, int overlay, float partialTick, Transforms context)
{
public void render(PoseStack poseStack, MultiBufferSource bufferSource, ITextureRenderTypeLookup textureRenderTypeLookup, int lightmap, int overlay, float partialTick, Transforms context) {
for (var component : components)
component.render(poseStack, bufferSource, textureRenderTypeLookup, lightmap, overlay, context);
}
public static Builder builder()
{
public static Builder builder() {
return new Builder();
}
private static class Component
{
private static class Component {
private final String name;
private final List<Component> children = new ArrayList<>();
private final List<Mesh> meshes = new ArrayList<>();
public Component(String name)
{
public Component(String name) {
this.name = name;
}
public void render(PoseStack poseStack, MultiBufferSource bufferSource, ITextureRenderTypeLookup textureRenderTypeLookup, int lightmap, int overlay, Transforms context)
{
public void render(PoseStack poseStack, MultiBufferSource bufferSource, ITextureRenderTypeLookup textureRenderTypeLookup, int lightmap, int overlay, Transforms context) {
Matrix4f matrix = context.getTransform(name);
if (matrix != null)
{
if (matrix != null) {
poseStack.pushPose();
poseStack.mulPose(matrix);
}
@@ -74,75 +65,60 @@ public class CompositeRenderable implements IRenderable<CompositeRenderable.Tran
}
}
private static class Mesh
{
private static class Mesh {
private final ResourceLocation texture;
private final List<BakedQuad> quads = new ArrayList<>();
public Mesh(ResourceLocation texture)
{
public Mesh(ResourceLocation texture) {
this.texture = texture;
}
public void render(PoseStack poseStack, MultiBufferSource bufferSource, ITextureRenderTypeLookup textureRenderTypeLookup, int lightmap, int overlay)
{
public void render(PoseStack poseStack, MultiBufferSource bufferSource, ITextureRenderTypeLookup textureRenderTypeLookup, int lightmap, int overlay) {
var consumer = bufferSource.getBuffer(textureRenderTypeLookup.get(texture));
for (var quad : quads)
{
consumer.putBulkData(poseStack.last(), quad, 1, 1, 1, 1, lightmap, overlay, true);
}
}
}
public static class Builder
{
public static class Builder {
private final CompositeRenderable renderable = new CompositeRenderable();
private Builder()
{
}
private Builder() { }
public PartBuilder<Builder> child(String name)
{
public PartBuilder<Builder> child(String name) {
var child = new Component(name);
renderable.components.add(child);
return new PartBuilder<>(this, child);
}
public CompositeRenderable get()
{
public CompositeRenderable get() {
return renderable;
}
}
public static class PartBuilder<T>
{
public static class PartBuilder<T> {
private final T parent;
private final Component component;
private PartBuilder(T parent, Component component)
{
private PartBuilder(T parent, Component component) {
this.parent = parent;
this.component = component;
}
public PartBuilder<PartBuilder<T>> child(String name)
{
public PartBuilder<PartBuilder<T>> child(String name) {
var child = new Component(component.name + "/" + name);
this.component.children.add(child);
return new PartBuilder<>(this, child);
}
public PartBuilder<T> addMesh(ResourceLocation texture, List<BakedQuad> quads)
{
public PartBuilder<T> addMesh(ResourceLocation texture, List<BakedQuad> quads) {
var mesh = new Mesh(texture);
mesh.quads.addAll(quads);
component.meshes.add(mesh);
return this;
}
public T end()
{
public T end() {
return parent;
}
}
@@ -150,8 +126,7 @@ public class CompositeRenderable implements IRenderable<CompositeRenderable.Tran
/**
* A context value that provides {@link Matrix4f} transforms for certain parts of the model.
*/
public static class Transforms
{
public static class Transforms {
/**
* A default instance that has no transforms specified.
*/
@@ -160,21 +135,18 @@ public class CompositeRenderable implements IRenderable<CompositeRenderable.Tran
/**
* Builds a MultipartTransforms object with the given mapping.
*/
public static Transforms of(ImmutableMap<String, Matrix4f> parts)
{
public static Transforms of(ImmutableMap<String, Matrix4f> parts) {
return new Transforms(parts);
}
private final ImmutableMap<String, Matrix4f> parts;
private Transforms(ImmutableMap<String, Matrix4f> parts)
{
private Transforms(ImmutableMap<String, Matrix4f> parts) {
this.parts = parts;
}
@Nullable
public Matrix4f getTransform(String part)
{
public Matrix4f getTransform(String part) {
return parts.get(part);
}
}
@@ -6,17 +6,17 @@
package net.minecraftforge.common;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import net.minecraft.util.RandomSource;
import net.minecraft.util.random.WeightedEntry;
import net.minecraft.util.random.WeightedRandom;
import net.minecraft.util.random.WeightedList;
import net.minecraft.world.entity.EntityType;
public class DungeonHooks
{
private static ArrayList<DungeonMob> dungeonMobs = new ArrayList<DungeonMob>();
public class DungeonHooks {
private static WeightedList<EntityType<?>> dungeonMobs = WeightedList.<EntityType<?>>builder()
.add(EntityType.SKELETON, 100)
.add(EntityType.ZOMBIE, 200)
.add(EntityType.SPIDER, 100)
.build();
/**
* Adds a mob to the possible list of creatures the spawner will create.
@@ -35,23 +35,20 @@ public class DungeonHooks
public static float addDungeonMob(EntityType<?> type, int rarity)
{
if (rarity <= 0)
{
throw new IllegalArgumentException("Rarity must be greater then zero");
}
Iterator<DungeonMob> itr = dungeonMobs.iterator();
while (itr.hasNext())
{
DungeonMob mob = itr.next();
if (type == mob.type)
{
var list = new ArrayList<>(dungeonMobs.unwrap());
var itr = list.iterator();
while (itr.hasNext()) {
var mob = itr.next();
if (type == mob.value()) {
itr.remove();
rarity = mob.getWeight().asInt() + rarity;
rarity = mob.weight() + rarity;
break;
}
}
dungeonMobs.add(new DungeonMob(rarity, type));
dungeonMobs = WeightedList.<EntityType<?>>builder().addAll(list).add(type, rarity).build();
return rarity;
}
@@ -61,16 +58,16 @@ public class DungeonHooks
* @param name The name of the mob to remove
* @return The rarity of the removed mob, prior to being removed.
*/
public static int removeDungeonMob(EntityType<?> name)
{
for (DungeonMob mob : dungeonMobs)
{
if (name == mob.type)
{
dungeonMobs.remove(mob);
return mob.getWeight().asInt();
}
public static int removeDungeonMob(EntityType<?> name) {
var list = new ArrayList<>(dungeonMobs.unwrap());
for (var mob : list) {
if (mob.value() != name) continue;
list.remove(mob);
dungeonMobs = WeightedList.<EntityType<?>>builder().addAll(list).build();
return mob.weight();
}
return 0;
}
@@ -79,33 +76,7 @@ public class DungeonHooks
* @param rand World generation random number generator
* @return The mob name
*/
public static EntityType<?> getRandomDungeonMob(RandomSource rand)
{
DungeonMob mob = WeightedRandom.getRandomItem(rand, dungeonMobs).orElseThrow();
return mob.type;
}
public static class DungeonMob extends WeightedEntry.IntrusiveBase
{
public final EntityType<?> type;
public DungeonMob(int weight, EntityType<?> type)
{
super(weight);
this.type = type;
}
@Override
public boolean equals(Object target)
{
return target instanceof DungeonMob && type.equals(((DungeonMob)target).type);
}
}
static
{
addDungeonMob(EntityType.SKELETON, 100);
addDungeonMob(EntityType.ZOMBIE, 200);
addDungeonMob(EntityType.SPIDER, 100);
public static EntityType<?> getRandomDungeonMob(RandomSource rand) {
return dungeonMobs.getRandomOrThrow(rand);
}
}
@@ -94,8 +94,6 @@ public class ForgeConfig {
* Client specific configuration - only loaded clientside from forge-client.toml
*/
public static class Client {
public final BooleanValue experimentalForgeLightPipelineEnabled;
public final BooleanValue showLoadWarnings;
public final BooleanValue allowMipmapLowering;
@@ -104,11 +102,6 @@ public class ForgeConfig {
builder.comment("Client only settings, mostly things related to rendering")
.push("client");
experimentalForgeLightPipelineEnabled = builder
.comment("EXPERIMENTAL: Enable the Forge block rendering pipeline - fixes the lighting of custom models.")
.translation("forge.configgui.forgeLightPipelineEnabled")
.define("experimentalForgeLightPipelineEnabled", false);
showLoadWarnings = builder
.comment("When enabled, Forge will show any warnings that occurred during loading.")
.translation("forge.configgui.showLoadWarnings")
@@ -10,7 +10,6 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
@@ -675,6 +674,7 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfi
public void clearComment() { comment.clear(); }
public boolean hasComment() { return !this.comment.isEmpty(); }
@SuppressWarnings("unused")
public String buildComment() { return buildComment(List.of("unknown", "unknown")); }
public String buildComment(final List<String> path) {
if (comment.stream().allMatch(String::isBlank)) {
@@ -356,10 +356,12 @@ public final class ForgeHooks {
lastEnd = end;
String url = string.substring(start, end);
MutableComponent link = Component.literal(url);
URI uri = null;
try {
// Add schema so client doesn't crash.
if ((new URI(url)).getScheme() == null) {
uri = new URI(url);
if (uri.getScheme() == null) {
if (!allowMissingHeader) {
if (ichat == null)
ichat = Component.literal(url);
@@ -368,6 +370,7 @@ public final class ForgeHooks {
continue;
}
url = "http://" + url;
uri = new URI(url);
}
} catch (URISyntaxException e) {
// Bad syntax bail out!
@@ -377,7 +380,7 @@ public final class ForgeHooks {
}
// Set the click event and append the link.
ClickEvent click = new ClickEvent(ClickEvent.Action.OPEN_URL, url);
ClickEvent click = new ClickEvent.OpenUrl(uri);
link.setStyle(link.getStyle().withClickEvent(click).withUnderlined(true).withColor(TextColor.fromLegacyFormat(ChatFormatting.BLUE)));
if (ichat == null)
ichat = Component.literal("");
@@ -406,7 +409,7 @@ public final class ForgeHooks {
// Logic from tryHarvestBlock for pre-canceling the event
boolean preCancelEvent = false;
ItemStack itemstack = entityPlayer.getMainHandItem();
if (!itemstack.isEmpty() && !itemstack.getItem().canAttackBlock(level.getBlockState(pos), level, pos, entityPlayer)) {
if (!itemstack.isEmpty() && !itemstack.canDestroyBlock(level.getBlockState(pos), level, pos, entityPlayer)) {
preCancelEvent = true;
}
@@ -693,7 +696,7 @@ public final class ForgeHooks {
return modId;
}
public static boolean onFarmlandTrample(ServerLevel level, BlockPos pos, BlockState state, float fallDistance, Entity entity) {
public static boolean onFarmlandTrample(ServerLevel level, BlockPos pos, BlockState state, double fallDistance, Entity entity) {
if (entity.canTrample(level, state, pos, fallDistance))
return !ForgeEventFactory.fireFarmlandTrampleEvent(level, pos, state, fallDistance, entity);
return false;
@@ -742,7 +745,7 @@ public final class ForgeHooks {
*
* <p>All loot-table generated loot should be passed to this function.</p>
*
* @param lootTableId The ID of the loot table currently being queried
* @param table The loot table currently being queried
* @param generatedLoot The loot generated by the loot table
* @param context The loot context that generated the loot, unmodified
* @return The modified list of drops
@@ -816,27 +819,27 @@ public final class ForgeHooks {
CompoundTag tag = null;
try {
CompoundTag rootTag = access.getDataTagRaw(false);
tag = rootTag.getCompound("fml");
tag = rootTag.getCompoundOrEmpty("fml");
} catch (IOException e) {
try {
CompoundTag rootTag = access.getDataTagRaw(true);
tag = rootTag.getCompound("fml");
tag = rootTag.getCompoundOrEmpty("fml");
} catch (IOException e2) {
LOGGER.error(WORLDPERSISTENCE, "Failed to read level data.. ", e2);
return;
}
}
if (tag.contains("LoadingModList")) {
ListTag modList = tag.getList("LoadingModList", net.minecraft.nbt.Tag.TAG_COMPOUND);
ListTag modList = tag.getListOrEmpty("LoadingModList");
Map<String, ArtifactVersion> mismatchedVersions = new HashMap<>(modList.size());
Map<String, ArtifactVersion> missingVersions = new HashMap<>(modList.size());
for (int i = 0; i < modList.size(); i++) {
CompoundTag mod = modList.getCompound(i);
String modId = mod.getString("ModId");
CompoundTag mod = modList.getCompoundOrEmpty(i);
String modId = mod.getStringOr("ModId", null);
if (Objects.equals("minecraft", modId))
continue;
String modVersion = mod.getString("ModVersion");
String modVersion = mod.getStringOr("ModVersion", null);
final var previousVersion = new DefaultArtifactVersion(modVersion);
ModList.get().getModContainerById(modId).ifPresentOrElse(container -> {
final var loadingVersion = container.getModInfo().getVersion();
@@ -899,9 +902,9 @@ public final class ForgeHooks {
if (tag.contains("Registries")) {
Map<ResourceLocation, ForgeRegistry.Snapshot> snapshot = new HashMap<>();
CompoundTag regs = tag.getCompound("Registries");
for (String key : regs.getAllKeys())
snapshot.put(ResourceLocation.parse(key), ForgeRegistry.Snapshot.read(regs.getCompound(key)));
CompoundTag regs = tag.getCompoundOrEmpty("Registries");
for (String key : regs.keySet())
snapshot.put(ResourceLocation.parse(key), ForgeRegistry.Snapshot.read(regs.getCompoundOrEmpty(key)));
failedElements = GameData.injectSnapshot(snapshot, true, true);
}
@@ -993,7 +996,7 @@ public final class ForgeHooks {
/**
* Handles living entities being under water. This fires the {@link LivingBreatheEvent} and if the entity's air supply
* is less than or equal to zero also the {@link LivingDrownEvent}. Additionally when the entity is under water it will
* dismount if {@link IForgeEntity#canBeRiddenUnderFluidType(FluidType, Entity)} returns false.
* dismount if {@link net.minecraftforge.common.extensions.IForgeEntity#canBeRiddenUnderFluidType(FluidType, Entity)} returns false.
*
* @param entity The living entity which is currently updated
* @param consumeAirAmount The amount of air to consume when the entity is unable to breathe
@@ -8,6 +8,7 @@ package net.minecraftforge.common;
import com.google.common.collect.Sets;
import net.minecraftforge.common.extensions.IForgeBlock;
import net.minecraftforge.common.extensions.IForgeItem;
import org.jetbrains.annotations.ApiStatus;
import java.util.Set;
import java.util.stream.Collectors;
@@ -97,7 +98,10 @@ public class ToolActions
/**
* A tool action corresponding to the 'block' action of shields.
*
* @deprecated Completely overshadowed by {@link net.minecraft.core.component.DataComponents#BLOCKS_ATTACKS}
*/
@Deprecated(forRemoval = true, since = "1.21.5")
public static final ToolAction SHIELD_BLOCK = ToolAction.get("shield_block");
/**
@@ -109,9 +113,15 @@ public class ToolActions
public static final Set<ToolAction> DEFAULT_AXE_ACTIONS = of(AXE_DIG, AXE_STRIP, AXE_SCRAPE, AXE_WAX_OFF);
public static final Set<ToolAction> DEFAULT_HOE_ACTIONS = of(HOE_DIG, HOE_TILL);
public static final Set<ToolAction> DEFAULT_SHOVEL_ACTIONS = of(SHOVEL_DIG, SHOVEL_FLATTEN);
/** @deprecated See {@link #PICKAXE_DIG} for details */
@Deprecated(forRemoval = true, since = "1.21.5")
public static final Set<ToolAction> DEFAULT_PICKAXE_ACTIONS = of(PICKAXE_DIG);
/** @deprecated See {@link #SWORD_DIG} and {@link #SWORD_SWEEP} for details */
@Deprecated(forRemoval = true, since = "1.21.5")
public static final Set<ToolAction> DEFAULT_SWORD_ACTIONS = of(SWORD_DIG, SWORD_SWEEP);
public static final Set<ToolAction> DEFAULT_SHEARS_ACTIONS = of(SHEARS_DIG, SHEARS_HARVEST, SHEARS_CARVE, SHEARS_DISARM);
/** @deprecated See {@link #SHIELD_BLOCK} for details */
@Deprecated(forRemoval = true, since = "1.21.5")
public static final Set<ToolAction> DEFAULT_SHIELD_ACTIONS = of(SHIELD_BLOCK);
public static final Set<ToolAction> DEFAULT_FISHING_ROD_ACTIONS = of(FISHING_ROD_CAST);
@@ -5,6 +5,7 @@
package net.minecraftforge.common;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
@@ -12,6 +13,7 @@ import java.util.Map;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.entity.npc.VillagerProfession;
import net.minecraft.world.entity.npc.VillagerTrades;
import net.minecraft.world.entity.npc.VillagerTrades.ItemListing;
@@ -20,15 +22,13 @@ import net.minecraftforge.event.village.VillagerTradesEvent;
import net.minecraftforge.event.village.WandererTradesEvent;
import net.minecraftforge.event.server.ServerAboutToStartEvent;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.commons.lang3.tuple.Pair;
public class VillagerTradingManager
{
public class VillagerTradingManager {
private static final Map<ResourceKey<VillagerProfession>, Int2ObjectMap<ItemListing[]>> VANILLA_TRADES = new HashMap<>();
private static final List<Pair<ItemListing[], Integer>> WANDERER_TRADES = new ArrayList<>();
private static final Map<VillagerProfession, Int2ObjectMap<ItemListing[]>> VANILLA_TRADES = new HashMap<>();
private static final Int2ObjectMap<ItemListing[]> WANDERER_TRADES = new Int2ObjectOpenHashMap<>();
static
{
static {
VillagerTrades.TRADES.forEach((key, value) -> {
Int2ObjectMap<ItemListing[]> copy = new Int2ObjectOpenHashMap<>();
for (var ent : value.int2ObjectEntrySet()) {
@@ -36,50 +36,40 @@ public class VillagerTradingManager
}
VANILLA_TRADES.put(key, copy);
});
VillagerTrades.WANDERING_TRADER_TRADES.int2ObjectEntrySet().forEach(e -> WANDERER_TRADES.put(e.getIntKey(), Arrays.copyOf(e.getValue(), e.getValue().length)));
WANDERER_TRADES.addAll(VillagerTrades.WANDERING_TRADER_TRADES);
}
static void loadTrades(ServerAboutToStartEvent e)
{
static void loadTrades(ServerAboutToStartEvent e) {
postWandererEvent();
postVillagerEvents();
}
/**
* Posts the WandererTradesEvent.
*/
private static void postWandererEvent()
{
List<ItemListing> generic = NonNullList.create();
List<ItemListing> rare = NonNullList.create();
Arrays.stream(WANDERER_TRADES.get(1)).forEach(generic::add);
Arrays.stream(WANDERER_TRADES.get(2)).forEach(rare::add);
MinecraftForge.EVENT_BUS.post(new WandererTradesEvent(generic, rare));
VillagerTrades.WANDERING_TRADER_TRADES.put(1, generic.toArray(new ItemListing[0]));
VillagerTrades.WANDERING_TRADER_TRADES.put(2, rare.toArray(new ItemListing[0]));
/** Posts the WandererTradesEvent. */
private static void postWandererEvent() {
var event = MinecraftForge.EVENT_BUS.fire(new WandererTradesEvent(WANDERER_TRADES));
VillagerTrades.WANDERING_TRADER_TRADES.clear();
for (var pool : event.getPools())
VillagerTrades.WANDERING_TRADER_TRADES.add(Pair.of(pool.getEntries().toArray(ItemListing[]::new), pool.getRolls()));
}
/**
* Posts a VillagerTradesEvent for each registered profession.
*/
private static void postVillagerEvents()
{
for (VillagerProfession prof : ForgeRegistries.VILLAGER_PROFESSIONS)
{
/** Posts a VillagerTradesEvent for each registered profession. */
private static void postVillagerEvents() {
// TODO [VillagerType][1.21.5] Villager Professions are stored as keys in vanilla now? Re-evaluate this.
for (VillagerProfession value : ForgeRegistries.VILLAGER_PROFESSIONS) {
var prof = ForgeRegistries.VILLAGER_PROFESSIONS.getResourceKey(value).orElseThrow();
Int2ObjectMap<ItemListing[]> trades = VANILLA_TRADES.getOrDefault(prof, new Int2ObjectOpenHashMap<>());
Int2ObjectMap<List<ItemListing>> mutableTrades = new Int2ObjectOpenHashMap<>();
for (int i = 1; i < 6; i++)
{
mutableTrades.put(i, NonNullList.create());
}
for (var entry : trades.int2ObjectEntrySet()) {
for (var entry : trades.int2ObjectEntrySet())
Arrays.stream(entry.getValue()).forEach(mutableTrades.get(entry.getIntKey())::add);
}
MinecraftForge.EVENT_BUS.post(new VillagerTradesEvent(mutableTrades, prof));
Int2ObjectMap<ItemListing[]> newTrades = new Int2ObjectOpenHashMap<>();
for (var entry : mutableTrades.int2ObjectEntrySet()) {
for (var entry : mutableTrades.int2ObjectEntrySet())
newTrades.put(entry.getIntKey(), entry.getValue().toArray(new ItemListing[0]));
}
VillagerTrades.TRADES.put(prof, newTrades);
}
}
@@ -5,6 +5,7 @@
package net.minecraftforge.common.brewing;
/*
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -12,7 +13,6 @@ import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.core.NonNullList;
/*
public class BrewingRecipeRegistry {
/**
@@ -11,10 +11,8 @@ import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.commands.arguments.selector.EntitySelector;
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Allows modders to register custom entity selectors by assigning an {@link IEntitySelectorType} to a String token. <br>
@@ -9,14 +9,12 @@ import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.serialization.JsonOps;
import net.minecraft.advancements.Advancement;
import net.minecraft.advancements.AdvancementHolder;
import net.minecraft.core.HolderLookup;
import net.minecraft.resources.RegistryOps;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.common.crafting.conditions.ICondition;
@@ -92,7 +92,7 @@ public class PartialNBTIngredient extends AbstractIngredient {
public static final MapCodec<PartialNBTIngredient> CODEC = RecordCodecBuilder.mapCodec(builder ->
builder.group(
Ingredient.NON_AIR_HOLDER_SET_CODEC.fieldOf("items").forGetter(i -> i.values),
TagParser.AS_CODEC.fieldOf("nbt").forGetter(i -> i.nbt)
TagParser.FLATTENED_CODEC.fieldOf("nbt").forGetter(i -> i.nbt)
).apply(builder, PartialNBTIngredient::new)
);
@@ -8,9 +8,7 @@ package net.minecraftforge.common.data;
import net.minecraft.core.HolderLookup;
import net.minecraft.data.PackOutput;
import net.minecraft.data.tags.FluidTagsProvider;
import net.minecraft.data.tags.IntrinsicHolderTagsProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.BlockTags;
import net.minecraft.tags.FluidTags;
import net.minecraft.tags.TagKey;
import net.minecraft.world.level.material.Fluid;
@@ -18,8 +16,6 @@ import net.minecraftforge.common.ForgeMod;
import org.jetbrains.annotations.ApiStatus;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import static net.minecraftforge.common.Tags.Fluids.*;
@ApiStatus.Internal
@@ -587,8 +587,11 @@ public interface IForgeBlock {
* @param pos Block position in level
* @param direction The direction that the fire is coming from
* @param igniter The entity that lit the fire
* @return {@code true} if the block <strong>SHOULD BE REMOVED</strong>
*/
default void onCaughtFire(BlockState state, Level level, BlockPos pos, @Nullable Direction direction, @Nullable LivingEntity igniter) {}
default boolean onCaughtFire(BlockState state, Level level, BlockPos pos, @Nullable Direction direction, @Nullable LivingEntity igniter) {
return false;
}
/**
* Called when fire is updating on a neighbor block.
@@ -5,7 +5,6 @@
package net.minecraftforge.common.extensions;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
import net.minecraft.world.entity.player.Player;
@@ -31,19 +30,16 @@ public interface IForgeBlockEntity extends ICapabilityProvider {
}
/**
* Called when you receive a TileEntityData packet for the location this
* TileEntity is currently in. On the client, the NetworkManager will always
* be the remote server. On the server, it will be whomever is responsible for
* Called when you receive a TileEntityData packet for the location this TileEntity is currently in. On the client,
* the NetworkManager will always be the remote server. On the server, it will be whomever is responsible for
* sending the packet.
*
* @param net The NetworkManager the packet originated from
* @param pkt The data packet
* @param connection The Connection the packet originated from
* @param pkt The data packet
* @param lookup The holder lookup provider
*/
default void onDataPacket(Connection connection, ClientboundBlockEntityDataPacket pkt, HolderLookup.Provider lookup) {
CompoundTag compoundtag = pkt.getTag();
if (compoundtag != null) {
self().loadWithComponents(compoundtag, lookup);
}
this.self().loadWithComponents(pkt.getTag(), lookup);
}
/**
@@ -460,9 +460,10 @@ public interface IForgeBlockState {
* @param pos Block position in level
* @param face The face that the fire is coming from
* @param igniter The entity that lit the fire
* @return {@code true} if the block <strong>SHOULD BE REMOVED</strong>
*/
default void onCaughtFire(Level level, BlockPos pos, @Nullable Direction face, @Nullable LivingEntity igniter) {
self().getBlock().onCaughtFire(self(), level, pos, face, igniter);
default boolean onCaughtFire(Level level, BlockPos pos, @Nullable Direction face, @Nullable LivingEntity igniter) {
return self().getBlock().onCaughtFire(self(), level, pos, face, igniter);
}
/**
@@ -98,7 +98,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag> {
* @param fallDistance The fall distance
* @return {@code true} if this entity can trample, {@code false} otherwise
*/
boolean canTrample(ServerLevel level, BlockState state, BlockPos pos, float fallDistance);
boolean canTrample(ServerLevel level, BlockState state, BlockPos pos, double fallDistance);
/**
* Returns The classification of this entity
@@ -9,6 +9,7 @@ import java.util.Arrays;
import java.util.Objects;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import net.minecraft.core.Registry;
@@ -49,6 +50,12 @@ public interface IForgeGameTestHelper {
return (GameTestHelper) this;
}
int getTickAsInt();
default GameTestAssertException throwing(String message) {
return new GameTestAssertException(Component.literal(message), this.getTickAsInt());
}
default void say(String message) {
this.say(message, Style.EMPTY);
}
@@ -73,14 +80,22 @@ public interface IForgeGameTestHelper {
return ForgeI18n.getPattern(message) != null ? Component.translatable(message) : Component.literal(message);
}
default void assertTrue(boolean value, String message) {
this.assertTrue(value, () -> message);
}
default void assertTrue(boolean value, Supplier<String> message) {
if (!value)
throw new GameTestAssertException(message.get());
throw new GameTestAssertException(Component.literal(message.get()), this.getTickAsInt());
}
default void assertFalse(boolean value, String message) {
this.assertFalse(value, () -> message);
}
default void assertFalse(boolean value, Supplier<String> message) {
if (value)
throw new GameTestAssertException(message.get());
throw new GameTestAssertException(Component.literal(message.get()), this.getTickAsInt());
}
default <N> void assertValueEqual(N expected, N actual, String name, String message) {
@@ -89,7 +104,7 @@ public interface IForgeGameTestHelper {
default <N> void assertValueEqual(N expected, N actual, String name, Supplier<String> message) {
if (!Objects.equals(expected, actual))
throw new GameTestAssertException("%s -- Expected %s to be %s, but was %s".formatted(message.get(), name, expected, actual));
throw this.throwing("%s -- Expected %s to be %s, but was %s".formatted(message.get(), name, expected, actual));
}
default <N> void assertValueEqual(N[] expected, N[] actual, String name, String message) {
@@ -98,7 +113,7 @@ public interface IForgeGameTestHelper {
default <N> void assertValueEqual(N[] expected, N[] actual, String name, Supplier<String> message) {
if (!Objects.deepEquals(expected, actual))
throw new GameTestAssertException("%s -- Expected %s to be %s, but was %s".formatted(message.get(), name, Arrays.toString(expected), Arrays.toString(actual)));
throw this.throwing("%s -- Expected %s to be %s, but was %s".formatted(message.get(), name, Arrays.toString(expected), Arrays.toString(actual)));
}
default <N> void assertValueNotEqual(N expected, N actual, String name, String message) {
@@ -107,7 +122,7 @@ public interface IForgeGameTestHelper {
default <N> void assertValueNotEqual(N expected, N actual, String name, Supplier<String> message) {
if (Objects.equals(expected, actual))
throw new GameTestAssertException("%s -- Expected %s to NOT be %s, but was".formatted(message.get(), name, expected));
throw this.throwing("%s -- Expected %s to NOT be %s, but was".formatted(message.get(), name, expected));
}
default <N> void assertValueNotEqual(N[] expected, N[] actual, String name, String message) {
@@ -116,7 +131,7 @@ public interface IForgeGameTestHelper {
default <N> void assertValueNotEqual(N[] expected, N[] actual, String name, Supplier<String> message) {
if (!Objects.deepEquals(expected, actual))
throw new GameTestAssertException("%s -- Expected %s to NOT be %s, but was".formatted(message.get(), name, Arrays.toString(expected)));
throw this.throwing("%s -- Expected %s to NOT be %s, but was".formatted(message.get(), name, Arrays.toString(expected)));
}
default <E> Registry<E> registryLookup(ResourceKey<? extends Registry<? extends E>> registryKey) {
@@ -145,7 +160,7 @@ public interface IForgeGameTestHelper {
var server = level.getServer();
var listener = new ServerGamePacketListenerImpl(server, connection, player, cookie);
var info = GameProtocols.SERVERBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(server.registryAccess()));
var info = GameProtocols.SERVERBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(server.registryAccess()), listener);
connection.setupInboundProtocol(info, listener);
return player;
}
@@ -258,13 +273,26 @@ public interface IForgeGameTestHelper {
return new BoolFlag(name);
}
default void fail(String message) {
self().fail(Component.literal(message));
}
public static class Flag<T> {
private final String name;
@Nullable
protected T value = null;
private final Function<String, ? extends RuntimeException> thrower;
protected @Nullable T value = null;
public Flag(String name) {
this(name, RuntimeException::new);
}
public Flag(String name, Function<String, ? extends RuntimeException> thrower) {
this.name = name;
this.thrower = thrower;
}
protected final RuntimeException throwing(String message) {
return this.thrower.apply(message);
}
public void set(T value) {
@@ -287,7 +315,7 @@ public interface IForgeGameTestHelper {
public void assertUnset(Supplier<String> message) {
if (this.value != null) {
String s = message != null ? message.get() + " -- " : "";
throw new GameTestAssertException(s + "Expected " + name + " to be null, but was " + this.value);
throw this.throwing(s + "Expected " + name + " to be null, but was " + this.value);
}
}
@@ -302,7 +330,7 @@ public interface IForgeGameTestHelper {
public void assertSet(Supplier<String> message) {
if (this.value == null) {
String s = message != null ? message.get() + " -- " : "";
throw new GameTestAssertException(s + "Flag " + name + " was never set");
throw this.throwing(s + "Flag " + name + " was never set");
}
}
@@ -318,7 +346,7 @@ public interface IForgeGameTestHelper {
assertSet(message);
if (expected != null && !expected.equals(this.value)) {
String s = message != null ? message.get() + " -- " : "";
throw new GameTestAssertException(s + "Expected " + name + " to be " + expected + ", but was " + this.value);
throw this.throwing(s + "Expected " + name + " to be " + expected + ", but was " + this.value);
}
}
}
@@ -228,18 +228,11 @@ public interface IForgeItem {
}
/**
* Called to tick this items in a players inventory, the indexes are the global slot index.
* Called to tick this items in a entitie's inventory, the slotIndex may be -1 for non player entities as they may not have a slot index.
* See {@link EntityEquipment#tick(Entity)}
*/
default void onInventoryTick(ItemStack stack, Level level, Player player, int slotIndex, int selectedIndex) {
// For compatibility reasons we have to use non-local index values, I think this is a vanilla bug but lets maintain compatibility
var inv = player.getInventory();
int vanillaIndex = slotIndex;
if (slotIndex >= inv.items.size()) {
vanillaIndex -= inv.items.size();
if (vanillaIndex >= inv.armor.size())
vanillaIndex -= inv.armor.size();
}
stack.inventoryTick(level, player, vanillaIndex, selectedIndex == vanillaIndex);
default void inventoryTick(ItemStack stack, Level level, Entity entity, @Nullable EquipmentSlot slot, int slotIndex) {
stack.inventoryTick(level, entity, slot);
}
/**
@@ -460,9 +453,11 @@ public interface IForgeItem {
* @param entity The LivingEntity holding the shield
* @param attacker The LivingEntity holding the ItemStack
* @return True if this ItemStack can disable the shield in question.
* @deprecated Overriding this does nothing! Use {@link net.minecraft.core.component.DataComponents#WEAPON}.
*/
@Deprecated(forRemoval = true, since = "1.21.5")
default boolean canDisableShield(ItemStack stack, ItemStack shield, LivingEntity entity, LivingEntity attacker) {
return attacker.canDisableShield();
return attacker.getSecondsToDisableBlocking() > 0.0F;
}
/**
@@ -223,13 +223,13 @@ public interface IForgeItemStack {
}
/**
* Called to tick this items in a players inventory, the indexes are the global slot index.
* Called to tick this items in a entitie's inventory, the slotIndex may be -1 for non player entities as they may not have a slot index.
* See {@link EntityEquipment#tick(Entity)}
*/
default void onInventoryTick(Level level, Player player, int slotIndex, int selectedIndex) {
self().getItem().onInventoryTick(self(), level, player, slotIndex, selectedIndex);
default void inventoryTick(Level level, Entity entity, @Nullable EquipmentSlot slot, int slotIndex) {
self().getItem().inventoryTick(self(), level, entity, slot, slotIndex);
}
/**
* Called every tick from {@code Horse#playGallopSound(SoundEvent)} on the item in the
* armor slot.
@@ -91,7 +91,7 @@ public interface IForgeTransformation {
Transformation transform = self();
if (transform.isIdentity()) return Transformation.identity();
Matrix4f ret = transform.getMatrix();
Matrix4f ret = transform.getMatrixCopy();
Matrix4f tmp = new Matrix4f().translation(origin.x(), origin.y(), origin.z());
tmp.mul(ret, ret);
tmp.translation(-origin.x(), -origin.y(), -origin.z());
@@ -0,0 +1,89 @@
package net.minecraftforge.common.extensions;
import net.minecraft.util.random.Weighted;
import net.minecraft.util.random.WeightedList;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.function.Predicate;
public interface IForgeWeightedList<E> {
private WeightedList<E> self() {
return (WeightedList<E>) this;
}
/**
* Removes any existing elements from this list. If removal takes place, this will create a new list.
* <p>To check if the builder elements have changed, simply check if the old and new lists are equal.</p>
* {@snippet :
* private static void test() {
* var list = WeightedList.<String>builder().add("Hello, World!", 1).build();
*
* // if builder has no removals
* assert list == list.removeIf(String::isEmpty);
*
* // if builder has removals
* assert list != list.removeIf(s -> s.equals("Hello, World!"));
* }
*}
*
* @param predicate The predicate to remove elements with
* @return The builder
* @apiNote This is an <strong>expensive operation</strong> and primarily exists to help port legacy systems that
* used older list-based systems from 1.21.4 and older.
* @see java.util.List#removeIf(Predicate)
*/
default WeightedList<E> removeIf(Predicate<E> predicate) {
var list = new ArrayList<>(this.self().unwrap());
return list.removeIf(w -> predicate.test(w.value()))
? WeightedList.<E>builder().addAll(list).build()
: this.self();
}
interface Builder<E> {
private WeightedList.Builder<E> self() {
return (WeightedList.Builder<E>) this;
}
/** @see com.google.common.collect.ImmutableList.Builder#addAll(Iterable) */
default WeightedList.Builder<E> addAll(Iterable<Weighted<E>> iterable) {
for (var w : iterable) this.self().add(w.value(), w.weight());
return this.self();
}
/** @see com.google.common.collect.ImmutableList.Builder#addAll(Iterator) */
default WeightedList.Builder<E> addAll(Iterator<Weighted<E>> iterator) {
return this.addAll(() -> iterator);
}
/**
* Removes any existing elements from the builder. If removal takes place, this will create a new builder.
* <p>To check if the builder elements have changed, simply check if the old and new builders are equal.</p>
* {@snippet :
* private static void test() {
* var builder = WeightedList.<String>builder();
* builder.add("Hello, World!", 1);
*
* // if builder has no removals
* assert builder == builder.removeIf(String::isEmpty);
*
* // if builder has removals
* assert builder != builder.removeIf(s -> s.equals("Hello, World!"));
* }
*}
*
* @param predicate The predicate to remove elements with
* @return The builder
* @apiNote This is an <strong>expensive operation</strong> and primarily exists to help port legacy systems
* that used the older arraylist-based building from 1.21.4 and older.
* @see IForgeWeightedList#removeIf(Predicate)
* @see java.util.List#removeIf(Predicate)
*/
default WeightedList.Builder<E> removeIf(Predicate<E> predicate) {
var list = new ArrayList<>(this.self().build().unwrap());
return list.removeIf(w -> predicate.test(w.value()))
? WeightedList.<E>builder().addAll(list)
: this.self();
}
}
}
@@ -8,7 +8,9 @@ package net.minecraftforge.common.util;
import java.util.List;
import java.util.UUID;
import net.minecraft.core.UUIDUtil;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.nbt.Tag;
public interface INBTBuilder {
@@ -63,9 +65,14 @@ public interface INBTBuilder {
return this;
}
/** @deprecated Use {@link #putByteArray(String, byte...)} */
@Deprecated(forRemoval = true, since = "1.21.5")
public Builder putByteArray(String key, List<Byte> value) {
tag.putByteArray(key, value);
return this;
var array = new byte[value.size()];
for (var i = 0; i < value.size(); i++)
array[i] = value.get(i);
return this.putByteArray(key, array);
}
public Builder putIntArray(String key, int... value) {
@@ -73,9 +80,14 @@ public interface INBTBuilder {
return this;
}
/** @deprecated Use {@link #putIntArray(String, int...)} */
@Deprecated(forRemoval = true, since = "1.21.5")
public Builder putIntArray(String key, List<Integer> value) {
tag.putIntArray(key, value);
return this;
var array = new int[value.size()];
for (var i = 0; i < value.size(); i++)
array[i] = value.get(i);
return this.putIntArray(key, array);
}
public Builder putLongArray(String key, long... value) {
@@ -83,9 +95,14 @@ public interface INBTBuilder {
return this;
}
/** @deprecated Use {@link #putLongArray(String, long...)} */
@Deprecated(forRemoval = true, since = "1.21.5")
public Builder putLongArray(String key, List<Long> value) {
tag.putLongArray(key, value);
return this;
var array = new long[value.size()];
for (var i = 0; i < value.size(); i++)
array[i] = value.get(i);
return this.putLongArray(key, array);
}
public Builder put(String key, boolean value) {
@@ -99,7 +116,7 @@ public interface INBTBuilder {
}
public Builder put(String key, UUID value) {
tag.putUUID(key, value);
tag.putIntArray(key, UUIDUtil.uuidToIntArray(value));
return this;
}
}
@@ -24,20 +24,19 @@ import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.serialization.JsonOps;
import net.minecraft.nbt.TagParser;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.util.GsonHelper;
import org.jetbrains.annotations.Nullable;
public class JsonUtils
{
public class JsonUtils {
// http://stackoverflow.com/questions/7706772/deserializing-immutablelist-using-gson/21677349#21677349
public enum ImmutableListTypeAdapter implements JsonDeserializer<ImmutableList<?>>, JsonSerializer<ImmutableList<?>>
{
public enum ImmutableListTypeAdapter implements JsonDeserializer<ImmutableList<?>>, JsonSerializer<ImmutableList<?>> {
INSTANCE;
@Override
public ImmutableList<?> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException
{
public ImmutableList<?> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
final Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments();
final Type parametrizedType = listOf(typeArguments[0]).getType();
final List<?> list = context.deserialize(json, parametrizedType);
@@ -45,8 +44,7 @@ public class JsonUtils
}
@Override
public JsonElement serialize(ImmutableList<?> src, Type type, JsonSerializationContext context)
{
public JsonElement serialize(ImmutableList<?> src, Type type, JsonSerializationContext context) {
final Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments();
final Type parametrizedType = listOf(typeArguments[0]).getType();
return context.serialize(src, parametrizedType);
@@ -54,18 +52,15 @@ public class JsonUtils
}
@SuppressWarnings({ "serial", "unchecked" })
private static <E> TypeToken<List<E>> listOf(final Type arg)
{
private static <E> TypeToken<List<E>> listOf(final Type arg) {
return new TypeToken<List<E>>() {}.where(new TypeParameter<E>() {}, (TypeToken<E>) TypeToken.of(arg));
}
public enum ImmutableMapTypeAdapter implements JsonDeserializer<ImmutableMap<String, ?>>, JsonSerializer<ImmutableMap<String, ?>>
{
public enum ImmutableMapTypeAdapter implements JsonDeserializer<ImmutableMap<String, ?>>, JsonSerializer<ImmutableMap<String, ?>> {
INSTANCE;
@Override
public ImmutableMap<String, ?> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException
{
public ImmutableMap<String, ?> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
final Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments();
final Type parameterizedType = mapOf(typeArguments[1]).getType();
final Map<String, ?> map = context.deserialize(json, parameterizedType);
@@ -73,8 +68,7 @@ public class JsonUtils
}
@Override
public JsonElement serialize(ImmutableMap<String, ?> src, Type type, JsonSerializationContext context)
{
public JsonElement serialize(ImmutableMap<String, ?> src, Type type, JsonSerializationContext context) {
final Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments();
final Type parameterizedType = mapOf(typeArguments[1]).getType();
return context.serialize(src, parameterizedType);
@@ -82,20 +76,14 @@ public class JsonUtils
}
@Nullable
public static CompoundTag readNBT(JsonObject json, String key)
{
if (net.minecraft.util.GsonHelper.isValidNode(json, key))
{
try
{
return TagParser.parseTag(net.minecraft.util.GsonHelper.getAsString(json, key));
} catch (CommandSyntaxException e)
{
throw new JsonSyntaxException("Malformed NBT tag", e);
}
} else
{
public static CompoundTag readNBT(JsonObject json, String key) {
if (!net.minecraft.util.GsonHelper.isValidNode(json, key))
return null;
try {
return TagParser.parseCompoundFully(GsonHelper.getAsString(json, key));
} catch (CommandSyntaxException e) {
throw new JsonSyntaxException("Malformed NBT tag", e);
}
}
@@ -0,0 +1,105 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.util;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.function.Function;
/**
* Proxy object for a value that is calculated on first access
* @param <T> The type of the value
*/
public sealed interface LazyFunction<T, R> extends Function<T, R> permits LazyFunction.Fast, LazyFunction.Concurrent {
/**
* Constructs a lazy-initialized object
* @param function The function for the value, to be called the first time the value is needed.
*/
static <T, R> LazyFunction<T, R> of(@NotNull Function<T, R> function) {
return new LazyFunction.Fast<>(function);
}
/**
* Constructs a thread-safe lazy-initialized object
* @param function The function for the value, to be called the first time the value is needed.
*/
static <T, R> LazyFunction<T, R> concurrentOf(@NotNull Function<T, R> function) {
return new LazyFunction.Concurrent<>(function);
}
R get() throws IllegalStateException;
/** Non-thread-safe implementation. */
final class Fast<T, R> implements LazyFunction<T, R> {
private Function<T, R> function;
private R instance;
private Fast(Function<T, R> function) {
this.function = function;
}
@Override
public @Nullable R apply(T t) {
if (function != null) {
instance = function.apply(t);
function = null;
}
return instance;
}
@Override
public R get() throws IllegalStateException {
if (function != null)
throw new IllegalStateException("Cannot call get() before apply()");
return instance;
}
}
/** Thread-safe implementation. */
final class Concurrent<T, R> implements LazyFunction<T, R> {
private volatile Object lock = new Object();
private volatile Function<T, R> function;
private volatile R instance;
private Concurrent(Function<T, R> function)
{
this.function = function;
}
@Override
public @Nullable R apply(T t) {
// Copy the lock to a local variable to prevent NPEs if the lock field is set to null between the
// null-check and the synchronization
Object localLock = this.lock;
if (function != null)
{
// localLock is not null here because supplier was non-null after we copied the lock and both of them
// are volatile
synchronized (localLock)
{
if (function != null)
{
instance = function.apply(t);
function = null;
this.lock = null;
}
}
}
return instance;
}
@Override
public R get() throws IllegalStateException {
if (function != null)
throw new IllegalStateException("Cannot call get() before apply()");
return instance;
}
}
}
@@ -5,47 +5,47 @@
package net.minecraftforge.common.util;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.level.saveddata.SavedData;
import net.minecraft.world.level.storage.DimensionDataStorage;
import net.minecraft.world.level.saveddata.SavedDataType;
import org.jetbrains.annotations.Nullable;
import com.mojang.serialization.codecs.RecordCodecBuilder;
@SuppressWarnings("deprecation")
public class LevelCapabilityData extends SavedData {
public static final String ID = "capabilities";
public static final SavedDataType<LevelCapabilityData> TYPE = new SavedDataType<LevelCapabilityData>(
"capabilities",
LevelCapabilityData::new,
ctx ->
RecordCodecBuilder.create(b ->
b.group(
CompoundTag.CODEC.fieldOf("data").forGetter(i -> {
if (i.serializable == null)
return new CompoundTag();
return i.serializable.serializeNBT(ctx.levelOrThrow().registryAccess());
})
).apply(b, nbt -> new LevelCapabilityData(ctx, nbt))
),
null
);
@Nullable
private final INBTSerializable<CompoundTag> serializable;
private CompoundTag capNBT = null;
public LevelCapabilityData(@Nullable INBTSerializable<CompoundTag> serializable) {
this.serializable = serializable;
private LevelCapabilityData(SavedData.Context ctx) {
this.serializable = ctx.levelOrThrow().getCapabilityDispatcher();
}
@Override
public CompoundTag save(CompoundTag nbt, HolderLookup.Provider provider) {
if (serializable != null)
nbt = serializable.serializeNBT(provider);
return nbt;
private LevelCapabilityData(SavedData.Context ctx, CompoundTag data) {
this(ctx);
if (this.serializable != null)
this.serializable.deserializeNBT(ctx.levelOrThrow().registryAccess(), data);
}
@Override
public boolean isDirty() {
return true;
}
public static LevelCapabilityData compute(DimensionDataStorage data, @Nullable INBTSerializable<CompoundTag> caps) {
var factory = new Factory<>(
() -> new LevelCapabilityData(caps),
(tag, lookup) -> {
var ret = new LevelCapabilityData(caps);
if (caps != null)
caps.deserializeNBT(lookup, tag);
return ret;
},
null
);
return data.computeIfAbsent(factory, ID);
}
}
@@ -10,7 +10,7 @@ import java.util.Optional;
import net.minecraft.core.Holder;
import net.minecraft.sounds.Music;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.util.random.SimpleWeightedRandomList;
import net.minecraft.util.random.WeightedList;
import net.minecraft.world.level.biome.AmbientAdditionsSettings;
import net.minecraft.world.level.biome.AmbientMoodSettings;
import net.minecraft.world.level.biome.AmbientParticleSettings;
@@ -90,7 +90,7 @@ public class BiomeSpecialEffectsBuilder extends BiomeSpecialEffects.Builder {
return this.ambientAdditionsSettings;
}
public Optional<SimpleWeightedRandomList<Music>> getBackgroundMusic() {
public Optional<WeightedList<Music>> getBackgroundMusic() {
return this.backgroundMusic;
}
}
@@ -13,11 +13,15 @@ import java.util.function.Function;
import com.mojang.datafixers.util.Either;
import com.mojang.serialization.Codec;
import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.ListCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.Util;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet;
import net.minecraft.core.RegistryCodecs;
import net.minecraft.util.random.Weighted;
import net.minecraft.util.random.WeightedList;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.level.biome.Biome;
@@ -155,15 +159,12 @@ public final class ForgeBiomeModifiers {
* @param biomes Biomes to add mob spawns to.
* @param spawners List of SpawnerDatas specifying EntityType, weight, and pack size.
*/
public record AddSpawnsBiomeModifier(HolderSet<Biome> biomes, List<SpawnerData> spawners) implements BiomeModifier {
public record AddSpawnsBiomeModifier(HolderSet<Biome> biomes, WeightedList<SpawnerData> spawners) implements BiomeModifier {
public static final MapCodec<AddSpawnsBiomeModifier> CODEC = RecordCodecBuilder.mapCodec(builder ->
builder.group(
Biome.LIST_CODEC.fieldOf("biomes").forGetter(AddSpawnsBiomeModifier::biomes),
// Allow either a list or single spawner, attempting to decode the list format first.
Codec.either(SpawnerData.CODEC.listOf(), SpawnerData.CODEC).xmap(
either -> either.map(Function.identity(), List::of), // convert list/singleton to list when decoding
list -> list.size() == 1 ? Either.right(list.get(0)) : Either.left(list) // convert list to singleton/list when encoding
).fieldOf("spawners").forGetter(AddSpawnsBiomeModifier::spawners)
WeightedList.codec(SpawnerData.CODEC).fieldOf("spawners").forGetter(AddSpawnsBiomeModifier::spawners)
).apply(builder, AddSpawnsBiomeModifier::new));
/**
@@ -172,16 +173,18 @@ public final class ForgeBiomeModifiers {
* @param spawner SpawnerData specifying EntityTYpe, weight, and pack size.
* @return AddSpawnsBiomeModifier that adds a single spawn entry to the specified biomes.
*/
public static AddSpawnsBiomeModifier singleSpawn(HolderSet<Biome> biomes, SpawnerData spawner) {
return new AddSpawnsBiomeModifier(biomes, List.of(spawner));
public static AddSpawnsBiomeModifier singleSpawn(HolderSet<Biome> biomes, int weight, SpawnerData spawner) {
return new AddSpawnsBiomeModifier(biomes, WeightedList.of(List.of(new Weighted<>(spawner, weight))));
}
@Override
public void modify(Holder<Biome> biome, Phase phase, Builder builder) {
if (phase == Phase.ADD && this.biomes.contains(biome)) {
var spawns = builder.getMobSpawnSettings();
for (var spawner : this.spawners)
spawns.addSpawn(spawner.type.getCategory(), spawner);
for (var weighted : this.spawners.unwrap()) {
var spawner = weighted.value();
spawns.addSpawn(spawner.type().getCategory(), weighted.weight(), spawner);
}
}
}
@@ -216,7 +219,7 @@ public final class ForgeBiomeModifiers {
if (phase == Phase.REMOVE && this.biomes.contains(biome)) {
var spawns = builder.getMobSpawnSettings();
for (var category : MobCategory.values())
spawns.getSpawner(category).removeIf(data -> this.entityTypes.contains(ForgeRegistries.ENTITY_TYPES.getHolder(data.type).get()));
spawns.getSpawner(category).removeIf(data -> this.entityTypes.contains(ForgeRegistries.ENTITY_TYPES.getHolder(data.type()).orElseThrow()));
}
}
@@ -6,563 +6,73 @@
package net.minecraftforge.common.world;
import com.mojang.datafixers.util.Pair;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import it.unimi.dsi.fastutil.longs.LongSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Function;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.world.entity.Entity;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.ForcedChunksSavedData;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.TicketType;
import net.minecraftforge.fml.ModList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.Unmodifiable;
@ParametersAreNonnullByDefault
public class ForgeChunkManager
{
private static final Logger LOGGER = LogManager.getLogger();
private static final TicketType<TicketOwner<BlockPos>> BLOCK = TicketType.create("forge:block", Comparator.comparing(info -> info));
private static final TicketType<TicketOwner<BlockPos>> BLOCK_TICKING = TicketType.create("forge:block_ticking", Comparator.comparing(info -> info));
private static final TicketType<TicketOwner<UUID>> ENTITY = TicketType.create("forge:entity", Comparator.comparing(info -> info));
private static final TicketType<TicketOwner<UUID>> ENTITY_TICKING = TicketType.create("forge:entity_ticking", Comparator.comparing(info -> info));
private static final Map<String, LoadingValidationCallback> callbacks = new HashMap<>();
/**
* Sets the forced chunk loading validation callback for the given mod. This allows for validating and removing no longer valid tickets on level load.
*
* @apiNote This method should be called from a {@link net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent} using one of the {@link
* net.minecraftforge.fml.event.lifecycle.ParallelDispatchEvent} enqueueWork methods.
*/
public static void setForcedChunkLoadingCallback(String modId, LoadingValidationCallback callback)
{
if (ModList.get().isLoaded(modId))
callbacks.put(modId, callback);
else
LOGGER.warn("A mod attempted to set the forced chunk validation loading callback for an unloaded mod of id: {}", modId);
/** @deprecated Vanilla now handles all forced chunks using its new {@link TicketType} system. */
@Deprecated(forRemoval = true, since = "1.21.5")
public class ForgeChunkManager {
private static <T> T error() {
throw new UnsupportedOperationException("Mod used ForgeChnkManager when they should use vanilla's TicketType system, see Level.getChunkSource().addTicketWithRadius");
}
/**
* Checks if a level has any forced chunks. Mainly used for seeing if a level should continue ticking with no players in it.
*/
public static boolean hasForcedChunks(ServerLevel level)
{
ForcedChunksSavedData data = level.getDataStorage().get(ForcedChunksSavedData.factory(), "chunks");
if (data == null) return false;
return !data.getChunks().isEmpty() || !data.getBlockForcedChunks().isEmpty() || !data.getEntityForcedChunks().isEmpty();
}
/** @deprecated Use Vanilla's {@link TicketType} system */
public static void setForcedChunkLoadingCallback(String modId, LoadingValidationCallback callback) { error(); }
/**
* Forces a chunk to be loaded for the given mod with the "owner" of the ticket being a given block position.
*
* @param add {@code true} to force the chunk, {@code false} to unforce the chunk.
* @param ticking {@code true} to make the chunk receive full chunk ticks even if there is no player nearby.
*/
public static boolean forceChunk(ServerLevel level, String modId, BlockPos owner, int chunkX, int chunkZ, boolean add, boolean ticking)
{
return forceChunk(level, modId, owner, chunkX, chunkZ, add, ticking, ticking ? BLOCK_TICKING : BLOCK, ForcedChunksSavedData::getBlockForcedChunks);
}
/** @deprecated Use Vanilla's {@link TicketType} system */
public static boolean hasForcedChunks(ServerLevel level) { return error(); }
/**
* Forces a chunk to be loaded for the given mod with the "owner" of the ticket being the UUID of the given entity.
*
* @param add {@code true} to force the chunk, {@code false} to unforce the chunk.
* @param ticking {@code true} to make the chunk receive full chunk ticks even if there is no player nearby.
*/
public static boolean forceChunk(ServerLevel level, String modId, Entity owner, int chunkX, int chunkZ, boolean add, boolean ticking)
{
return forceChunk(level, modId, owner.getUUID(), chunkX, chunkZ, add, ticking);
}
/** @deprecated Use Vanilla's {@link TicketType} system */
public static boolean forceChunk(ServerLevel level, String modId, BlockPos owner, int chunkX, int chunkZ, boolean add, boolean ticking) { return error(); }
/**
* Forces a chunk to be loaded for the given mod with the "owner" of the ticket being a given UUID.
*
* @param add {@code true} to force the chunk, {@code false} to unforce the chunk.
* @param ticking {@code true} to make the chunk receive full chunk ticks even if there is no player nearby.
*/
public static boolean forceChunk(ServerLevel level, String modId, UUID owner, int chunkX, int chunkZ, boolean add, boolean ticking)
{
return forceChunk(level, modId, owner, chunkX, chunkZ, add, ticking, ticking ? ENTITY_TICKING : ENTITY, ForcedChunksSavedData::getEntityForcedChunks);
}
/** @deprecated Use Vanilla's {@link TicketType} system */
public static boolean forceChunk(ServerLevel level, String modId, Entity owner, int chunkX, int chunkZ, boolean add, boolean ticking) { return error(); }
/**
* Forces a chunk to be loaded for the given mod with the given "owner".
*
* @param add {@code true} to force the chunk, {@code false} to unforce the chunk.
*
* @implNote Based on {@link ServerLevel#setChunkForced(int, int, boolean)}
*/
private static <T extends Comparable<? super T>> boolean forceChunk(ServerLevel level, String modId, T owner, int chunkX, int chunkZ, boolean add, boolean ticking,
TicketType<TicketOwner<T>> type, Function<ForcedChunksSavedData, TicketTracker<T>> ticketGetter)
{
if (!ModList.get().isLoaded(modId))
{
LOGGER.warn("A mod attempted to force a chunk for an unloaded mod of id: {}", modId);
return false;
}
ForcedChunksSavedData saveData = level.getDataStorage().computeIfAbsent(ForcedChunksSavedData.factory(), "chunks");
ChunkPos pos = new ChunkPos(chunkX, chunkZ);
long chunk = pos.toLong();
TicketTracker<T> tickets = ticketGetter.apply(saveData);
TicketOwner<T> ticketOwner = new TicketOwner<>(modId, owner);
boolean success;
if (add)
{
success = tickets.add(ticketOwner, chunk, ticking);
if (success)
level.getChunk(chunkX, chunkZ);
}
else
{
success = tickets.remove(ticketOwner, chunk, ticking);
}
if (success)
{
saveData.setDirty(true);
forceChunk(level, pos, type, ticketOwner, add, ticking);
}
return success;
}
/**
* Adds/Removes a ticket from the level's chunk provider with the proper levels to match the forced chunks.
*
* @param add {@code true} to force the chunk, {@code false} to unforce the chunk.
* @param ticking {@code true} to make the chunk receive full chunk ticks even if there is no player nearby.
*
* @implNote We use distance 2 for what we pass, as when using register/releaseTicket the ticket's level is set to 33 - distance and the level that forced chunks use
* is 31.
*/
private static <T extends Comparable<? super T>> void forceChunk(ServerLevel level, ChunkPos pos, TicketType<TicketOwner<T>> type, TicketOwner<T> owner, boolean add,
boolean ticking)
{
if (add)
level.getChunkSource().addRegionTicket(type, pos, 2, owner, ticking);
else
level.getChunkSource().removeRegionTicket(type, pos, 2, owner, ticking);
}
/**
* Reinstates forge's forced chunks when vanilla initially loads a level and reinstates their forced chunks. This method also will validate all of forge's forced
* chunks using and registered {@link LoadingValidationCallback}.
*
* @apiNote Internal
*/
public static void reinstatePersistentChunks(ServerLevel level, ForcedChunksSavedData saveData)
{
if (!callbacks.isEmpty())
{
//If we have any callbacks, gather all owned tickets by modid for both blocks and entities
Map<String, Map<BlockPos, Pair<LongSet, LongSet>>> blockTickets = gatherTicketsByModId(saveData.getBlockForcedChunks());
Map<String, Map<UUID, Pair<LongSet, LongSet>>> entityTickets = gatherTicketsByModId(saveData.getEntityForcedChunks());
//Fire the callbacks allowing them to remove any tickets they don't want anymore
for (Map.Entry<String, LoadingValidationCallback> entry : callbacks.entrySet())
{
String modId = entry.getKey();
boolean hasBlockTicket = blockTickets.containsKey(modId);
boolean hasEntityTicket = entityTickets.containsKey(modId);
if (hasBlockTicket || hasEntityTicket)
{
Map<BlockPos, Pair<LongSet, LongSet>> ownedBlockTickets = hasBlockTicket ? Collections.unmodifiableMap(blockTickets.get(modId)) : Collections.emptyMap();
Map<UUID, Pair<LongSet, LongSet>> ownedEntityTickets = hasEntityTicket ? Collections.unmodifiableMap(entityTickets.get(modId)) : Collections.emptyMap();
entry.getValue().validateTickets(level, new TicketHelper(saveData, modId, ownedBlockTickets, ownedEntityTickets));
}
}
}
//Reinstate the chunks that we want to load
reinstatePersistentChunks(level, BLOCK, saveData.getBlockForcedChunks().chunks, false);
reinstatePersistentChunks(level, BLOCK_TICKING, saveData.getBlockForcedChunks().tickingChunks, true);
reinstatePersistentChunks(level, ENTITY, saveData.getEntityForcedChunks().chunks, false);
reinstatePersistentChunks(level, ENTITY_TICKING, saveData.getEntityForcedChunks().tickingChunks, true);
}
/**
* Gathers tickets into a mod filtered map for use in providing all tickets a mod has registered to its {@link LoadingValidationCallback}.
*/
private static <T extends Comparable<? super T>> Map<String, Map<T, Pair<LongSet, LongSet>>> gatherTicketsByModId(TicketTracker<T> tickets)
{
Map<String, Map<T, Pair<LongSet, LongSet>>> modSortedOwnedChunks = new HashMap<>();
gatherTicketsByModId(tickets.chunks, Pair::getFirst, modSortedOwnedChunks);
gatherTicketsByModId(tickets.tickingChunks, Pair::getSecond, modSortedOwnedChunks);
return modSortedOwnedChunks;
}
/**
* Gathers tickets into a mod filtered map for use in providing all tickets a mod has registered to its {@link LoadingValidationCallback}.
*/
private static <T extends Comparable<? super T>> void gatherTicketsByModId(Map<TicketOwner<T>, LongSet> tickets, Function<Pair<LongSet, LongSet>, LongSet> typeGetter,
Map<String, Map<T, Pair<LongSet, LongSet>>> modSortedOwnedChunks)
{
for (Map.Entry<TicketOwner<T>, LongSet> entry : tickets.entrySet())
{
Pair<LongSet, LongSet> pair = modSortedOwnedChunks.computeIfAbsent(entry.getKey().modId, modId -> new HashMap<>())
.computeIfAbsent(entry.getKey().owner, owner -> new Pair<>(new LongOpenHashSet(), new LongOpenHashSet()));
typeGetter.apply(pair).addAll(entry.getValue());
}
}
/**
* Adds back any persistent forced chunks to the level's chunk provider.
*/
private static <T extends Comparable<? super T>> void reinstatePersistentChunks(ServerLevel level, TicketType<TicketOwner<T>> type,
Map<TicketOwner<T>, LongSet> tickets, boolean ticking)
{
for (Map.Entry<TicketOwner<T>, LongSet> entry : tickets.entrySet())
{
for (long chunk : entry.getValue())
{
forceChunk(level, new ChunkPos(chunk), type, entry.getKey(), true, ticking);
}
}
}
/**
* Writes the forge forced chunks into the NBT compound. Format is List{modid, List{ChunkPos, List{BlockPos}, List{UUID}}}
*
* @apiNote Internal
*/
public static void writeForgeForcedChunks(CompoundTag nbt, TicketTracker<BlockPos> blockForcedChunks, TicketTracker<UUID> entityForcedChunks)
{
if (!blockForcedChunks.isEmpty() || !entityForcedChunks.isEmpty())
{
Map<String, Long2ObjectMap<CompoundTag>> forcedEntries = new HashMap<>();
writeForcedChunkOwners(forcedEntries, blockForcedChunks, "Blocks", Tag.TAG_COMPOUND, (pos, forcedBlocks) -> forcedBlocks.add(NbtUtils.writeBlockPos(pos)));
writeForcedChunkOwners(forcedEntries, entityForcedChunks, "Entities", Tag.TAG_INT_ARRAY, (uuid, forcedEntities) -> forcedEntities.add(NbtUtils.createUUID(uuid)));
ListTag forcedChunks = new ListTag();
for (Map.Entry<String, Long2ObjectMap<CompoundTag>> entry : forcedEntries.entrySet())
{
CompoundTag forcedEntry = new CompoundTag();
forcedEntry.putString("Mod", entry.getKey());
ListTag modForced = new ListTag();
modForced.addAll(entry.getValue().values());
forcedEntry.put("ModForced", modForced);
forcedChunks.add(forcedEntry);
}
nbt.put("ForgeForced", forcedChunks);
}
}
private static <T extends Comparable<? super T>> void writeForcedChunkOwners(Map<String, Long2ObjectMap<CompoundTag>> forcedEntries, TicketTracker<T> tracker,
String listKey, int listType, BiConsumer<T, ListTag> ownerWriter)
{
writeForcedChunkOwners(forcedEntries, tracker.chunks, listKey,listType, ownerWriter);
writeForcedChunkOwners(forcedEntries, tracker.tickingChunks, "Ticking" + listKey, listType, ownerWriter);
}
private static <T extends Comparable<? super T>> void writeForcedChunkOwners(Map<String, Long2ObjectMap<CompoundTag>> forcedEntries,
Map<TicketOwner<T>, LongSet> forcedChunks, String listKey, int listType, BiConsumer<T, ListTag> ownerWriter)
{
for (Map.Entry<TicketOwner<T>, LongSet> entry : forcedChunks.entrySet())
{
Long2ObjectMap<CompoundTag> modForced = forcedEntries.computeIfAbsent(entry.getKey().modId, modId -> new Long2ObjectOpenHashMap<>());
for (long chunk : entry.getValue())
{
CompoundTag modEntry = modForced.computeIfAbsent(chunk, chunkPos -> {
CompoundTag baseEntry = new CompoundTag();
baseEntry.putLong("Chunk", chunkPos);
return baseEntry;
});
ListTag ownerList = modEntry.getList(listKey, listType);
ownerWriter.accept(entry.getKey().owner, ownerList);
//Note: As getList returns a new list in the case the data is of the wrong type,
// we need to mimic was vanilla does in various places and put our list back in
// the CompoundNBT regardless.
modEntry.put(listKey, ownerList);
}
}
}
/**
* Reads the forge forced chunks from the NBT compound. Format is List{modid, List{ChunkPos, List{BlockPos}, List{UUID}}}
*
* @apiNote Internal
*/
public static void readForgeForcedChunks(CompoundTag nbt, TicketTracker<BlockPos> blockForcedChunks, TicketTracker<UUID> entityForcedChunks)
{
ListTag forcedChunks = nbt.getList("ForgeForced", Tag.TAG_COMPOUND);
for (int i = 0; i < forcedChunks.size(); i++)
{
CompoundTag forcedEntry = forcedChunks.getCompound(i);
String modId = forcedEntry.getString("Mod");
if (ModList.get().isLoaded(modId))
{
ListTag modForced = forcedEntry.getList("ModForced", Tag.TAG_COMPOUND);
for (int j = 0; j < modForced.size(); j++)
{
CompoundTag modEntry = modForced.getCompound(j);
long chunkPos = modEntry.getLong("Chunk");
readBlockForcedChunks(modId, chunkPos, modEntry, "Blocks", blockForcedChunks.chunks);
readBlockForcedChunks(modId, chunkPos, modEntry, "TickingBlocks", blockForcedChunks.tickingChunks);
readEntityForcedChunks(modId, chunkPos, modEntry, "Entities", entityForcedChunks.chunks);
readEntityForcedChunks(modId, chunkPos, modEntry, "TickingEntities", entityForcedChunks.tickingChunks);
}
}
else
{
LOGGER.warn("Found chunk loading data for mod {} which is currently not available or active - it will be removed from the level save.", modId);
}
}
}
/**
* Reads the forge block forced chunks.
*/
private static void readBlockForcedChunks(String modId, long chunkPos, CompoundTag modEntry, String key, Map<TicketOwner<BlockPos>, LongSet> blockForcedChunks)
{
ListTag forcedBlocks = modEntry.getList(key, Tag.TAG_INT_ARRAY);
for (int k = 0; k < forcedBlocks.size(); k++)
{
var aint = forcedBlocks.getIntArray(k);
var pos = aint.length == 3 ? new BlockPos(aint[0], aint[1], aint[2]) : BlockPos.ZERO;
blockForcedChunks.computeIfAbsent(new TicketOwner<>(modId, pos), owner -> new LongOpenHashSet()).add(chunkPos);
}
}
/**
* Reads the forge entity forced chunks.
*/
private static void readEntityForcedChunks(String modId, long chunkPos, CompoundTag modEntry, String key, Map<TicketOwner<UUID>, LongSet> entityForcedChunks)
{
ListTag forcedEntities = modEntry.getList(key, Tag.TAG_INT_ARRAY);
for (Tag uuid : forcedEntities)
{
entityForcedChunks.computeIfAbsent(new TicketOwner<>(modId, NbtUtils.loadUUID(uuid)), owner -> new LongOpenHashSet()).add(chunkPos);
}
}
/** @deprecated Use Vanilla's {@link TicketType} system */
public static boolean forceChunk(ServerLevel level, String modId, UUID owner, int chunkX, int chunkZ, boolean add, boolean ticking) { return error(); }
/** @deprecated Use Vanilla's {@link TicketType} system */
@FunctionalInterface
@Deprecated(forRemoval = true, since = "1.21.5")
public interface LoadingValidationCallback {
/**
* Called back when tickets are about to be loaded and reinstated to allow mods to invalidate and remove specific tickets that may no longer be valid.
*
* @param level The level
* @param ticketHelper Ticket helper to remove any invalid tickets.
*/
void validateTickets(ServerLevel level, TicketHelper ticketHelper);
}
/**
* Class to help mods remove no longer valid tickets.
*/
public static class TicketHelper
{
private final Map<BlockPos, Pair<LongSet, LongSet>> blockTickets;
private final Map<UUID, Pair<LongSet, LongSet>> entityTickets;
private final ForcedChunksSavedData saveData;
private final String modId;
private TicketHelper(ForcedChunksSavedData saveData, String modId, Map<BlockPos, Pair<LongSet, LongSet>> blockTickets, Map<UUID, Pair<LongSet, LongSet>> entityTickets)
{
this.saveData = saveData;
this.modId = modId;
this.blockTickets = blockTickets;
this.entityTickets = entityTickets;
}
/**
* Gets all "BLOCK" tickets this mod had registered and which block positions are forcing which chunks. First element of the pair is the non-fully ticking
* tickets, second element is the fully ticking tickets.
*
* @apiNote This map is unmodifiable and does not update to reflect removed tickets so it is safe to call the remove methods while iterating it.
*/
public Map<BlockPos, Pair<LongSet, LongSet>> getBlockTickets()
{
return blockTickets;
}
/**
* Gets all "ENTITY" tickets this mod had registered and which entity (UUID) is forcing which chunks. First element of the pair is the non-fully ticking
* tickets, second element is the fully ticking tickets.
*
* @apiNote This map is unmodifiable and does not update to reflect removed tickets so it is safe to call the remove methods while iterating it.
*/
public Map<UUID, Pair<LongSet, LongSet>> getEntityTickets()
{
return entityTickets;
}
/**
* Removes all tickets that a given block was responsible for; both ticking and not ticking.
*
* @param owner Block that was responsible.
*/
public void removeAllTickets(BlockPos owner)
{
removeAllTickets(saveData.getBlockForcedChunks(), owner);
}
/**
* Removes all tickets that a given entity (UUID) was responsible for; both ticking and not ticking.
*
* @param owner Entity (UUID) that was responsible.
*/
public void removeAllTickets(UUID owner)
{
removeAllTickets(saveData.getEntityForcedChunks(), owner);
}
/**
* Removes all tickets that a given owner was responsible for; both ticking and not ticking.
*/
private <T extends Comparable<? super T>> void removeAllTickets(TicketTracker<T> tickets, T owner)
{
TicketOwner<T> ticketOwner = new TicketOwner<>(modId, owner);
if (tickets.chunks.containsKey(ticketOwner) || tickets.tickingChunks.containsKey(ticketOwner))
{
tickets.chunks.remove(ticketOwner);
tickets.tickingChunks.remove(ticketOwner);
saveData.setDirty(true);
}
}
/**
* Removes the ticket for the given chunk that a given block was responsible for.
*
* @param owner Block that was responsible.
* @param chunk Chunk to remove ticket of.
* @param ticking Whether or not the ticket to remove represents a ticking set of tickets or not.
*/
public void removeTicket(BlockPos owner, long chunk, boolean ticking)
{
removeTicket(saveData.getBlockForcedChunks(), owner, chunk, ticking);
}
/**
* Removes the ticket for the given chunk that a given entity (UUID) was responsible for.
*
* @param owner Entity (UUID) that was responsible.
* @param chunk Chunk to remove ticket of.
* @param ticking Whether or not the ticket to remove represents a ticking set of tickets or not.
*/
public void removeTicket(UUID owner, long chunk, boolean ticking)
{
removeTicket(saveData.getEntityForcedChunks(), owner, chunk, ticking);
}
private <T extends Comparable<? super T>> void removeTicket(TicketTracker<T> tickets, T owner, long chunk, boolean ticking)
{
if (tickets.remove(new TicketOwner<>(modId, owner), chunk, ticking))
saveData.setDirty(true);
}
/** @deprecated Use Vanilla's {@link TicketType} system */
@Deprecated(forRemoval = true, since = "1.21.5")
public static class TicketHelper {
private TicketHelper() { }
/** @deprecated Use Vanilla's {@link TicketType} system */
public @Unmodifiable Map<BlockPos, Pair<LongSet, LongSet>> getBlockTickets() { return error(); }
/** @deprecated Use Vanilla's {@link TicketType} system */
public @Unmodifiable Map<UUID, Pair<LongSet, LongSet>> getEntityTickets() { return error(); }
/** @deprecated Use Vanilla's {@link TicketType} system */
public void removeAllTickets(BlockPos owner) { error(); }
/** @deprecated Use Vanilla's {@link TicketType} system */
public void removeAllTickets(UUID owner) { error(); }
/** @deprecated Use Vanilla's {@link TicketType} system */
public void removeTicket(BlockPos owner, long chunk, boolean ticking) { error(); }
/** @deprecated Use Vanilla's {@link TicketType} system */
public void removeTicket(UUID owner, long chunk, boolean ticking) { error(); }
}
/**
* Helper class to keep track of a ticket owner by modid and owner object
*/
public static class TicketOwner<T extends Comparable<? super T>> implements Comparable<TicketOwner<T>>
{
private final String modId;
private final T owner;
private TicketOwner(String modId, T owner)
{
this.modId = modId;
this.owner = owner;
}
@Override
public int compareTo(TicketOwner<T> other)
{
int res = modId.compareTo(other.modId);
return res == 0 ? owner.compareTo(other.owner) : res;
}
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TicketOwner<?> that = (TicketOwner<?>) o;
return Objects.equals(modId, that.modId) && Objects.equals(owner, that.owner);
}
@Override
public int hashCode()
{
return Objects.hash(modId, owner);
}
/** @deprecated Use Vanilla's {@link TicketType} system */
@Deprecated(forRemoval = true, since = "1.21.5")
public static class TicketOwner implements Comparable<TicketOwner> {
private TicketOwner() { }
@Override public int compareTo(TicketOwner o) { return error(); }
}
/**
* Helper class to manage tracking and handling loaded tickets.
*/
public static class TicketTracker<T extends Comparable<? super T>>
{
private final Map<TicketOwner<T>, LongSet> chunks = new HashMap<>();
private final Map<TicketOwner<T>, LongSet> tickingChunks = new HashMap<>();
/**
* Gets an unmodifiable view of the tracked chunks.
*/
public Map<TicketOwner<T>, LongSet> getChunks()
{
return Collections.unmodifiableMap(chunks);
}
/**
* Gets an unmodifiable view of the tracked fully ticking chunks.
*/
public Map<TicketOwner<T>, LongSet> getTickingChunks()
{
return Collections.unmodifiableMap(tickingChunks);
}
/**
* Checks if this tracker is empty.
*
* @return {@code true} if there are no chunks or ticking chunks being tracked.
*/
public boolean isEmpty()
{
return chunks.isEmpty() && tickingChunks.isEmpty();
}
private Map<TicketOwner<T>, LongSet> getTickets(boolean ticking)
{
return ticking ? tickingChunks : chunks;
}
/**
* @return {@code true} if the state changed.
*/
private boolean remove(TicketOwner<T> owner, long chunk, boolean ticking)
{
Map<TicketOwner<T>, LongSet> tickets = getTickets(ticking);
if (tickets.containsKey(owner))
{
LongSet ticketChunks = tickets.get(owner);
if (ticketChunks.remove(chunk))
{
if (ticketChunks.isEmpty())
tickets.remove(owner);
return true;
}
}
return false;
}
/**
* @return {@code true} if the state changed.
*/
private boolean add(TicketOwner<T> owner, long chunk, boolean ticking)
{
return getTickets(ticking).computeIfAbsent(owner, o -> new LongOpenHashSet()).add(chunk);
}
/** @deprecated Use Vanilla's {@link TicketType} system */
@Deprecated(forRemoval = true, since = "1.21.5")
public static class TicketTracker {
public Map<TicketOwner, LongSet> getChunks() { return error(); }
public boolean isEmpty() { return error(); }
}
}
@@ -9,54 +9,48 @@ import java.util.Collections;
import java.util.List;
import java.util.Set;
import net.minecraft.Util;
import net.minecraft.util.random.WeightedList;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.level.biome.MobSpawnSettings;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Unmodifiable;
public class MobSpawnSettingsBuilder extends MobSpawnSettings.Builder
{
public class MobSpawnSettingsBuilder extends MobSpawnSettings.Builder {
private final Set<MobCategory> typesView = Collections.unmodifiableSet(this.spawners.keySet());
private final Set<EntityType<?>> costView = Collections.unmodifiableSet(this.mobSpawnCosts.keySet());
public MobSpawnSettingsBuilder(MobSpawnSettings orig)
{
orig.getSpawnerTypes().forEach(k -> {
spawners.get(k).clear();
spawners.get(k).addAll(orig.getMobs(k).unwrap());
});
public MobSpawnSettingsBuilder(MobSpawnSettings orig) {
orig.getSpawnerTypes().forEach(k ->
spawners.put(k, WeightedList.<MobSpawnSettings.SpawnerData>builder().addAll(orig.getMobs(k).unwrap()))
);
orig.getEntityTypes().forEach(k -> mobSpawnCosts.put(k, orig.getMobSpawnCost(k)));
creatureGenerationProbability = orig.getCreatureProbability();
}
public Set<MobCategory> getSpawnerTypes()
{
public Set<MobCategory> getSpawnerTypes() {
return this.typesView;
}
public List<MobSpawnSettings.SpawnerData> getSpawner(MobCategory type)
{
public WeightedList.Builder<MobSpawnSettings.SpawnerData> getSpawner(MobCategory type) {
return this.spawners.get(type);
}
public Set<EntityType<?>> getEntityTypes()
{
public Set<EntityType<?>> getEntityTypes() {
return this.costView;
}
@Nullable
public MobSpawnSettings.MobSpawnCost getCost(EntityType<?> type)
{
public MobSpawnSettings.MobSpawnCost getCost(EntityType<?> type) {
return this.mobSpawnCosts.get(type);
}
public float getProbability()
{
public float getProbability() {
return this.creatureGenerationProbability;
}
public MobSpawnSettingsBuilder disablePlayerSpawn()
{
public MobSpawnSettingsBuilder disablePlayerSpawn() {
return this;
}
}
@@ -9,9 +9,11 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import net.minecraft.core.HolderSet;
import net.minecraft.util.random.WeightedRandomList;
import net.minecraft.util.random.Weighted;
import net.minecraft.util.random.WeightedList;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.MobSpawnSettings;
@@ -20,9 +22,9 @@ import net.minecraft.world.level.levelgen.structure.Structure.StructureSettings;
import net.minecraft.world.level.levelgen.structure.StructureSpawnOverride;
import net.minecraft.world.level.levelgen.structure.TerrainAdjustment;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.UnmodifiableView;
public class StructureSettingsBuilder
{
public class StructureSettingsBuilder {
private HolderSet<Biome> biomes;
private final Map<MobCategory, StructureSpawnOverrideBuilder> spawnOverrides;
private GenerationStep.Decoration step;
@@ -32,13 +34,11 @@ public class StructureSettingsBuilder
* @param settings Existing StructureSettings.
* @return A new builder with a copy of that StructureSettings's values.
*/
public static StructureSettingsBuilder copyOf(StructureSettings settings)
{
public static StructureSettingsBuilder copyOf(StructureSettings settings) {
return new StructureSettingsBuilder(settings.biomes(), settings.spawnOverrides(), settings.step(), settings.terrainAdaptation());
}
private StructureSettingsBuilder(HolderSet<Biome> biomes, Map<MobCategory, StructureSpawnOverride> spawnOverrides, GenerationStep.Decoration step, TerrainAdjustment terrainAdaptation)
{
private StructureSettingsBuilder(HolderSet<Biome> biomes, Map<MobCategory, StructureSpawnOverride> spawnOverrides, GenerationStep.Decoration step, TerrainAdjustment terrainAdaptation) {
this.biomes = biomes;
this.spawnOverrides = spawnOverrides.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> StructureSpawnOverrideBuilder.copyOf(entry.getValue())));
this.step = step;
@@ -48,21 +48,18 @@ public class StructureSettingsBuilder
/**
* @return A new StructureSettings with the finalized values.
*/
public StructureSettings build()
{
public StructureSettings build() {
Map<MobCategory, StructureSpawnOverride> overrides = Collections.unmodifiableMap(
this.spawnOverrides.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().build()))
);
return new StructureSettings(this.biomes, overrides, this.step, this.terrainAdaptation);
}
public HolderSet<Biome> getBiomes()
{
public HolderSet<Biome> getBiomes() {
return biomes;
}
public void setBiomes(HolderSet<Biome> biomes)
{
public void setBiomes(HolderSet<Biome> biomes) {
this.biomes = biomes;
}
@@ -70,9 +67,7 @@ public class StructureSettingsBuilder
* Gets a mutable builder for the spawn overrides of a given mob category or {@code null} if no overrides are defined for that category.
* @param category Mob category
*/
@Nullable
public StructureSpawnOverrideBuilder getSpawnOverrides(MobCategory category)
{
public @Nullable StructureSpawnOverrideBuilder getSpawnOverrides(MobCategory category) {
return spawnOverrides.get(category);
}
@@ -80,8 +75,7 @@ public class StructureSettingsBuilder
* Gets or creates a mutable builder for the spawn overrides of a given mob category. If the override needed to be created it will default to piece bounding.
* @param category Mob category
*/
public StructureSpawnOverrideBuilder getOrAddSpawnOverrides(MobCategory category)
{
public StructureSpawnOverrideBuilder getOrAddSpawnOverrides(MobCategory category) {
return spawnOverrides.computeIfAbsent(category, c -> new StructureSpawnOverrideBuilder(StructureSpawnOverride.BoundingBoxType.PIECE, Collections.emptyList()));
}
@@ -89,32 +83,28 @@ public class StructureSettingsBuilder
* Removes the spawn overrides for the given mob category.
* @param category Mob category
*/
public void removeSpawnOverrides(MobCategory category)
{
public void removeSpawnOverrides(MobCategory category) {
this.spawnOverrides.remove(category);
}
/**
* Gets the world generation decoration step the structure spawns during.
*/
public GenerationStep.Decoration getDecorationStep()
{
public GenerationStep.Decoration getDecorationStep() {
return step;
}
/**
* Sets the world generation decoration step the structure spawns during.
*/
public void setDecorationStep(GenerationStep.Decoration step)
{
public void setDecorationStep(GenerationStep.Decoration step) {
this.step = step;
}
/**
* Gets the way the structure adapts to the terrain during generation.
*/
public TerrainAdjustment getTerrainAdaptation()
{
public TerrainAdjustment getTerrainAdaptation() {
return terrainAdaptation;
}
@@ -122,28 +112,24 @@ public class StructureSettingsBuilder
* Sets the way the structure adapts to the terrain during generation.
* @param terrainAdaptation New terrain adjustment
*/
public void setTerrainAdaptation(TerrainAdjustment terrainAdaptation)
{
public void setTerrainAdaptation(TerrainAdjustment terrainAdaptation) {
this.terrainAdaptation = terrainAdaptation;
}
public static class StructureSpawnOverrideBuilder
{
public static class StructureSpawnOverrideBuilder {
private StructureSpawnOverride.BoundingBoxType boundingBox;
private final List<MobSpawnSettings.SpawnerData> spawns;
private final List<MobSpawnSettings.SpawnerData> spawnsView;
private final List<Weighted<MobSpawnSettings.SpawnerData>> spawns;
private final List<Weighted<MobSpawnSettings.SpawnerData>> spawnsView;
/**
* @param override Existing spawn override data.
* @return A new builder with a copy of that StructureSpawnOverride's values.
*/
public static StructureSpawnOverrideBuilder copyOf(StructureSpawnOverride override)
{
public static StructureSpawnOverrideBuilder copyOf(StructureSpawnOverride override) {
return new StructureSpawnOverrideBuilder(override.boundingBox(), override.spawns().unwrap());
}
private StructureSpawnOverrideBuilder(StructureSpawnOverride.BoundingBoxType boundingBox, List<MobSpawnSettings.SpawnerData> spawns)
{
private StructureSpawnOverrideBuilder(StructureSpawnOverride.BoundingBoxType boundingBox, List<Weighted<MobSpawnSettings.SpawnerData>> spawns) {
this.boundingBox = boundingBox;
this.spawns = new ArrayList<>(spawns);
this.spawnsView = Collections.unmodifiableList(this.spawns);
@@ -152,49 +138,45 @@ public class StructureSettingsBuilder
/**
* Gets the type of bounding box for this structures spawn overrides.
*/
public StructureSpawnOverride.BoundingBoxType getBoundingBox()
{
return boundingBox;
public StructureSpawnOverride.BoundingBoxType getBoundingBox() {
return this.boundingBox;
}
/**
* Sets the way the structure checks for spawn overrides. Whether it is on a piece by piece basis or within the bounds of the overall structure.
* Sets the way the structure checks for spawn overrides. Whether it is on a piece by piece basis or within the
* bounds of the overall structure.
*/
public void setBoundingBox(StructureSpawnOverride.BoundingBoxType boundingBox)
{
public void setBoundingBox(StructureSpawnOverride.BoundingBoxType boundingBox) {
this.boundingBox = boundingBox;
}
/**
* Unmodifiable view of the possible spawns.
*/
public List<MobSpawnSettings.SpawnerData> getSpawns()
{
return spawnsView;
/** @return An {@linkplain Collections#unmodifiableList(List) Unmodifiable view} of the possible spawns. */
@UnmodifiableView
public List<Weighted<MobSpawnSettings.SpawnerData>> getSpawns() {
return this.spawnsView;
}
/** Adds a spawn to the overrides with a default weight of {@code 1}. */
public void addSpawn(MobSpawnSettings.SpawnerData spawn) {
this.addSpawn(spawn, 1);
}
/** Adds a spawn to the overrides. */
public void addSpawn(MobSpawnSettings.SpawnerData spawn, int weight) {
this.spawns.add(new Weighted<>(Objects.requireNonNull(spawn), weight));
}
/**
* Adds a spawn to the overrides.
* Removes all instances of a given spawn from the list of overrides. Use {@link #getSpawns()} to get instances
* of spawn data to remove.
*/
public void addSpawn(MobSpawnSettings.SpawnerData spawn)
{
this.spawns.add(spawn);
public void removeSpawn(MobSpawnSettings.SpawnerData spawn) {
this.spawns.removeIf(s -> s.value().equals(spawn));
}
/**
* Removes a given spawn from the list of overrides. Use {@link #getSpawns()} to get instances of spawn data to remove.
*/
public void removeSpawn(MobSpawnSettings.SpawnerData spawn)
{
this.spawns.remove(spawn);
}
/**
* @return A new StructureSpawnOverride with the finalized values.
*/
public StructureSpawnOverride build()
{
return new StructureSpawnOverride(boundingBox, WeightedRandomList.create(spawns));
/** @return A new StructureSpawnOverride with the finalized values. */
public StructureSpawnOverride build() {
return new StructureSpawnOverride(this.boundingBox, WeightedList.of(this.spawns));
}
}
}
@@ -91,8 +91,6 @@ public class EnergyStorage implements IEnergyStorage, INBTSerializable<Tag> {
@Override
public void deserializeNBT(HolderLookup.Provider registryAccess, Tag nbt) {
if (!(nbt instanceof IntTag intNbt))
throw new IllegalArgumentException("Can not deserialize to an instance that isn't the default implementation");
this.energy = intNbt.getAsInt();
this.energy = nbt.asInt().orElseThrow(() -> new IllegalArgumentException("Can not deserialize to an instance that isn't the default implementation"));
}
}
@@ -15,9 +15,8 @@ import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.LayeredRegistryAccess;
import net.minecraft.core.component.DataComponentMap;
import net.minecraft.server.RegistryLayer;
import net.minecraft.util.random.WeightedList;
import net.minecraft.world.entity.*;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.chunk.storage.SerializableChunkData;
@@ -62,7 +61,6 @@ import net.minecraft.server.players.PlayerList;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.RandomSource;
import net.minecraft.util.random.WeightedRandomList;
import net.minecraft.world.Container;
import net.minecraft.world.Difficulty;
import net.minecraft.world.DifficultyInstance;
@@ -293,7 +291,7 @@ public final class ForgeEventFactory {
/**
* Specialized variant of {@link #checkSpawnPosition} for spawners, as they have slightly different checks.
* @see #CheckSpawnPosition
* @see #checkSpawnPosition(Mob, ServerLevelAccessor, EntitySpawnReason)
* @implNote See in-line comments about custom spawn rules.
*/
public static boolean checkSpawnPositionSpawner(Mob mob, ServerLevelAccessor level, EntitySpawnReason spawnType, SpawnData spawnData, BaseSpawner spawner) {
@@ -331,7 +329,7 @@ public final class ForgeEventFactory {
* The only code that changes is the {@link Mob#finalizeSpawn} call.
* @return The SpawnGroupData from this event, or null if it was canceled. The return value of this method has no bearing on if the entity will be spawned.
* @see MobSpawnEvent.FinalizeSpawn
* @see Mob#finalizeSpawn(ServerLevelAccessor, DifficultyInstance, MobSpawnType, SpawnGroupData, CompoundTag)
* @see Mob#finalizeSpawn(ServerLevelAccessor, DifficultyInstance, EntitySpawnReason, SpawnGroupData)
* @apiNote Callers do not need to check if the entity's spawn was cancelled, as the spawn will be blocked by Forge.
* @implNote Changes to the signature of this method must be reflected in the method redirector coremod.
*/
@@ -507,7 +505,7 @@ public final class ForgeEventFactory {
boolean isCanceled = post(new EntityMountEvent(entityMounting, entityBeingMounted, entityMounting.level(), isMounting));
if(isCanceled) {
entityMounting.absMoveTo(entityMounting.getX(), entityMounting.getY(), entityMounting.getZ(), entityMounting.yRotO, entityMounting.xRotO);
entityMounting.absSnapTo(entityMounting.getX(), entityMounting.getY(), entityMounting.getZ(), entityMounting.yRotO, entityMounting.xRotO);
return false;
} else
return true;
@@ -533,8 +531,8 @@ public final class ForgeEventFactory {
post(new PlayerFlyableFallEvent(player, distance, multiplier));
}
public static boolean onPlayerSpawnSet(Player player, ResourceKey<Level> levelKey, BlockPos pos, boolean forced) {
return post(new PlayerSetSpawnEvent(player, levelKey, pos, forced));
public static boolean onPlayerSpawnSet(ServerPlayer player, ServerPlayer.RespawnConfig config) {
return post(new PlayerSetSpawnEvent(player, config));
}
public static PlayerSpawnPhantomsEvent onPlayerSpawnPhantom(Player player, int phantomsToSpawn) {
@@ -623,7 +621,7 @@ public final class ForgeEventFactory {
var canContinueSleep = evt.getResult();
if (canContinueSleep == Result.DEFAULT)
return !player.level().isDay();
return !player.level().isBrightOutside();
else
return canContinueSleep == Result.ALLOW;
}
@@ -829,12 +827,12 @@ public final class ForgeEventFactory {
post(new TickEvent.ServerTickEvent.Post(haveTime, server));
}
public static WeightedRandomList<MobSpawnSettings.SpawnerData> getPotentialSpawns(LevelAccessor level, MobCategory category, BlockPos pos, WeightedRandomList<MobSpawnSettings.SpawnerData> oldList) {
public static WeightedList<MobSpawnSettings.SpawnerData> getPotentialSpawns(LevelAccessor level, MobCategory category, BlockPos pos, WeightedList<MobSpawnSettings.SpawnerData> oldList) {
LevelEvent.PotentialSpawns event = new LevelEvent.PotentialSpawns(level, category, pos, oldList);
if (post(event))
return WeightedRandomList.create();
return WeightedList.of();
//System.out.println("List: " + oldList.unwrap() + " " + event.getSpawnerDataList());
return WeightedRandomList.create(event.getSpawnerDataList());
return WeightedList.of(event.getSpawnerDataList());
}
public static void onAdvancementEarned(Player player, AdvancementHolder holder) {
@@ -913,8 +911,8 @@ public final class ForgeEventFactory {
return fire(new LivingSwapItemsEvent.Hands(entity));
}
public static ShieldBlockEvent onShieldBlock(LivingEntity blocker, DamageSource source, float blocked) {
return fire(new ShieldBlockEvent(blocker, source, blocked));
public static ShieldBlockEvent onShieldBlock(LivingEntity blocker, DamageSource source, float blocked, ItemStack blockedWith) {
return fire(new ShieldBlockEvent(blocker, source, blocked, blockedWith));
}
public static void onEntityEnterSection(Entity entity, long packedOldPos, long packedNewPos) {
@@ -925,7 +923,7 @@ public final class ForgeEventFactory {
return post(new LivingEvent.LivingTickEvent(entity));
}
public static LivingFallEvent onLivingFall(LivingEntity entity, float distance, float damageMultiplier) {
public static LivingFallEvent onLivingFall(LivingEntity entity, double distance, float damageMultiplier) {
return fire(new LivingFallEvent(entity, distance, damageMultiplier));
}
@@ -1090,7 +1088,7 @@ public final class ForgeEventFactory {
return fire(new LootingLevelEvent(target, cause, level));
}
public static boolean fireFarmlandTrampleEvent(ServerLevel level, BlockPos pos, BlockState state, float fallDistance, Entity entity) {
public static boolean fireFarmlandTrampleEvent(ServerLevel level, BlockPos pos, BlockState state, double fallDistance, Entity entity) {
return post(new BlockEvent.FarmlandTrampleEvent(level, pos, state, fallDistance, entity));
}
}
@@ -1,55 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.event;
import net.minecraft.gametest.framework.GameTest;
import net.minecraft.gametest.framework.GameTestGenerator;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.gametest.ForgeGameTestHooks;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;
/**
* Game tests are registered on client or server startup.
* It is only run once for a given instance of the game if {@link ForgeGameTestHooks#isGametestEnabled} returns true.
* This is the preferred way to register your game tests.
* <p>
* Fired on the Mod bus, see {@link IModBusEvent}.
*/
public class RegisterGameTestsEvent extends Event implements IModBusEvent {
private final Set<Method> gameTestMethods;
public RegisterGameTestsEvent(Set<Method> gameTestMethods) {
this.gameTestMethods = gameTestMethods;
}
/**
* Registers an entire class to the game test registry.
* All methods annotated with {@link GameTest} or {@link GameTestGenerator} will be registered.
* If the set of enabled batches is non-empty, a method will only be registered if its
* {@link GameTest#batch() batch} is listed.
*
* @param testClass the test class to register to the game test registry
*/
public void register(Class<?> testClass) {
Arrays.stream(testClass.getDeclaredMethods()).forEach(this::register);
}
/**
* Registers a single method to the game test registry.
* The method will only be registered if it is annotated with {@link GameTest} or {@link GameTestGenerator}.
* If the set of enabled batches is non-empty, the method will only be registered if its
* {@link GameTest#batch() batch} is listed.
*
* @param testMethod the test method to register to the game test registry
*/
public void register(Method testMethod) {
this.gameTestMethods.add(testMethod);
}
}
@@ -14,9 +14,9 @@ import net.minecraft.world.entity.LivingEntity;
/**
* LivingFallEvent is fired when an Entity is set to be falling.<br>
* This event is fired whenever an Entity is set to fall in
* {@link LivingEntity#causeFallDamage(float, float, DamageSource)}.<br>
* {@link LivingEntity#causeFallDamage(double, float, DamageSource)}.<br>
* <br>
* This event is fired via the {@link ForgeHooks#onLivingFall(LivingEntity, float, float)}.<br>
* This event is fired via the {@link net.minecraftforge.event.ForgeEventFactory#onLivingFall(LivingEntity, double, float)}.<br>
* <br>
* {@link #distance} contains the distance the Entity is to fall. If this event is canceled, this value is set to 0.0F.
* <br>
@@ -28,19 +28,18 @@ import net.minecraft.world.entity.LivingEntity;
* This event is fired on the {@link MinecraftForge#EVENT_BUS}.
**/
@Cancelable
public class LivingFallEvent extends LivingEvent
{
private float distance;
public class LivingFallEvent extends LivingEvent {
private double distance;
private float damageMultiplier;
public LivingFallEvent(LivingEntity entity, float distance, float damageMultiplier)
{
public LivingFallEvent(LivingEntity entity, double distance, float damageMultiplier) {
super(entity);
this.setDistance(distance);
this.setDamageMultiplier(damageMultiplier);
this.distance = distance;
this.damageMultiplier = damageMultiplier;
}
public float getDistance() { return distance; }
public void setDistance(float distance) { this.distance = distance; }
public double getDistance() { return this.distance; }
public void setDistance(double distance) { this.distance = distance; }
public float getDamageMultiplier() { return damageMultiplier; }
public void setDamageMultiplier(float damageMultiplier) { this.damageMultiplier = damageMultiplier; }
}
@@ -8,6 +8,7 @@ package net.minecraftforge.event.entity.living;
import net.minecraft.util.Mth;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.eventbus.api.Cancelable;
/**
@@ -18,70 +19,56 @@ import net.minecraftforge.eventbus.api.Cancelable;
* at least for players.
*/
@Cancelable
public class ShieldBlockEvent extends LivingEvent
{
public class ShieldBlockEvent extends LivingEvent {
private final DamageSource source;
private final float originalBlocked;
private float dmgBlocked;
private boolean shieldTakesDamage = true;
private final ItemStack blockedWith;
public ShieldBlockEvent(LivingEntity blocker, DamageSource source, float blocked)
{
public ShieldBlockEvent(LivingEntity blocker, DamageSource source, float blocked, ItemStack blockedWith) {
super(blocker);
this.source = source;
this.originalBlocked = blocked;
this.dmgBlocked = blocked;
this.blockedWith = blockedWith;
}
/**
* @return The damage source.
*/
public DamageSource getDamageSource()
{
/** @return The damage source. */
public DamageSource getDamageSource() {
return this.source;
}
/**
* @return The original amount of damage blocked, which is the same as the original
* incoming damage value.
*/
public float getOriginalBlockedDamage()
{
/** @return The original amount of damage blocked, which is the same as the original incoming damage value. */
public float getOriginalBlockedDamage() {
return this.originalBlocked;
}
/**
* @return The current amount of damage blocked, as a result of this event.
*/
public float getBlockedDamage()
{
/** @return The current amount of damage blocked, as a result of this event. */
public float getBlockedDamage() {
return this.dmgBlocked;
}
/**
* Controls if {@link LivingEntity#hurtCurrentlyUsedShield} is called.
* @return If the shield item will take durability damage or not.
*/
public boolean shieldTakesDamage()
{
/** @return If the shield item will take durability damage or not. */
public boolean shieldTakesDamage() {
return this.shieldTakesDamage;
}
/**
* Set how much damage is blocked by this action.<br>
* Note that initially the blocked amount is the entire attack.<br>
* Sets how much damage is blocked by this action.
* <p>Note that initially the blocked amount is the entire attack.</p>
*/
public void setBlockedDamage(float blocked)
{
public void setBlockedDamage(float blocked) {
this.dmgBlocked = Mth.clamp(blocked, 0, this.originalBlocked);
}
/**
* Set if the shield will take durability damage or not.
*/
public void setShieldTakesDamage(boolean damage)
{
/** Sets if the shield will take durability damage or not. */
public void setShieldTakesDamage(boolean damage) {
this.shieldTakesDamage = damage;
}
/** @return The item that was used to block damage. */
public ItemStack getBlockedWith() {
return this.blockedWith;
}
}
@@ -6,48 +6,67 @@
package net.minecraftforge.event.entity.player;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.Level;
import net.minecraft.world.entity.player.Player;
import net.minecraft.core.BlockPos;
import net.minecraftforge.eventbus.api.Cancelable;
import org.jetbrains.annotations.Nullable;
/**
* This event is fired when a player's spawn point is set or reset.<br>
* This event is fired when a player's spawn point is set or reset.
* <p>
* The event can be canceled, which will prevent the spawn point from being changed.
*/
@Cancelable
public class PlayerSetSpawnEvent extends PlayerEvent
{
private final ResourceKey<Level> spawnLevel;
private final boolean forced;
@Nullable
private final BlockPos newSpawn;
public class PlayerSetSpawnEvent extends PlayerEvent {
private final @Nullable ServerPlayer.RespawnConfig config;
public PlayerSetSpawnEvent(Player player, ResourceKey<Level> spawnLevel, @Nullable BlockPos newSpawn, boolean forced)
{
@Deprecated(forRemoval = true, since = "1.21.5")
private final ResourceKey<Level> spawnLevel;
@Deprecated(forRemoval = true, since = "1.21.5")
private final boolean forced;
@Deprecated(forRemoval = true, since = "1.21.5")
private final @Nullable BlockPos newSpawn;
public PlayerSetSpawnEvent(ServerPlayer player, @Nullable ServerPlayer.RespawnConfig config) {
super(player);
this.spawnLevel = spawnLevel;
this.newSpawn = newSpawn;
this.forced = forced;
this.config = config;
boolean hasConfig = config != null;
this.forced = hasConfig && config.forced();
this.spawnLevel = hasConfig ? config.dimension() : Level.OVERWORLD;
this.newSpawn = hasConfig ? config.pos() : null;
}
public boolean isForced()
{
return forced;
/** @return The config for the player respawn */
public @Nullable ServerPlayer.RespawnConfig getConfig() {
return this.config;
}
/**
* The new spawn position, or null if the spawn position is being reset.
* @return If the new spawn point is forced
* @deprecated Use {@link ServerPlayer.RespawnConfig#forced()} via {@link #getConfig()}
*/
@Nullable
public BlockPos getNewSpawn()
{
return newSpawn;
@Deprecated(forRemoval = true, since = "1.21.5")
public boolean isForced() {
return this.forced;
}
public ResourceKey<Level> getSpawnLevel()
{
return spawnLevel;
/**
* @return The new spawn position, or {@code null} if the spawn position is being reset
* @deprecated Use {@link ServerPlayer.RespawnConfig#pos()} via {@link #getConfig()}
*/
@Deprecated(forRemoval = true, since = "1.21.5")
public @Nullable BlockPos getNewSpawn() {
return this.newSpawn;
}
/**
* @return The new spawn dimension, defaulting to {@link Level#OVERWORLD} if it is {@code null}
* @deprecated Use {@link ServerPlayer.RespawnConfig#dimension()} via {@link #getConfig()}
*/
@Deprecated(forRemoval = true, since = "1.21.5")
public ResourceKey<Level> getSpawnLevel() {
return this.spawnLevel;
}
}
@@ -337,9 +337,9 @@ public class BlockEvent extends Event {
@Cancelable
public static class FarmlandTrampleEvent extends BlockEvent {
private final Entity entity;
private final float fallDistance;
private final double fallDistance;
public FarmlandTrampleEvent(ServerLevel level, BlockPos pos, BlockState state, float fallDistance, Entity entity) {
public FarmlandTrampleEvent(ServerLevel level, BlockPos pos, BlockState state, double fallDistance, Entity entity) {
super(level, pos, state);
this.entity = entity;
this.fallDistance = fallDistance;
@@ -349,7 +349,7 @@ public class BlockEvent extends Event {
return entity;
}
public float getFallDistance() {
public double getFallDistance() {
return fallDistance;
}
@@ -10,42 +10,44 @@ import java.util.Collections;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.ReceivingLevelScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.ProgressListener;
import net.minecraft.util.random.WeightedRandomList;
import net.minecraft.util.random.Weighted;
import net.minecraft.util.random.WeightedList;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.StructureManager;
import net.minecraft.world.level.biome.MobSpawnSettings;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.storage.ServerLevelData;
import net.minecraftforge.common.ForgeInternalHandler;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.Cancelable;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.LogicalSide;
import org.jetbrains.annotations.UnmodifiableView;
/**
* This event is fired whenever an event involving a {@link LevelAccessor} occurs.
* <p>
* All children of this event are fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}.
*/
public class LevelEvent extends Event
{
public class LevelEvent extends Event {
private final LevelAccessor level;
public LevelEvent(LevelAccessor level)
{
public LevelEvent(LevelAccessor level) {
this.level = level;
}
/**
* {@return the level this event is affecting}
*/
public LevelAccessor getLevel()
{
public LevelAccessor getLevel() {
return level;
}
@@ -59,26 +61,23 @@ public class LevelEvent extends Event
* This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}
* on both logical sides.
**/
public static class Load extends LevelEvent
{
public static class Load extends LevelEvent {
public Load(LevelAccessor level) { super(level); }
}
/**
* This event is fired whenever a level unloads.
* This event is fired whenever a level unloads in
* {@link Minecraft#setLevel(ClientLevel)},
* {@link Minecraft#setLevel(ClientLevel, ReceivingLevelScreen.Reason)},
* {@link MinecraftServer#stopServer()},
* {@link Minecraft#clearLevel(Screen)}, and
* {@link ForgeInternalHandler#onDimensionUnload(Unload)}.
* {@link Minecraft#clearClientLevel(Screen)}.
* <p>
* This event is not {@linkplain Cancelable cancellable} and does not {@linkplain HasResult have a result}.
* <p>
* This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}
* on both logical sides.
**/
public static class Unload extends LevelEvent
{
public static class Unload extends LevelEvent {
public Unload(LevelAccessor level) { super(level); }
}
@@ -92,8 +91,7 @@ public class LevelEvent extends Event
* This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}
* only on the {@linkplain LogicalSide#SERVER logical server}.
**/
public static class Save extends LevelEvent
{
public static class Save extends LevelEvent {
public Save(LevelAccessor level) { super(level); }
}
@@ -110,18 +108,15 @@ public class LevelEvent extends Event
* @see ServerLevelData#isInitialized()
*/
@Cancelable
public static class CreateSpawnPosition extends LevelEvent
{
public static class CreateSpawnPosition extends LevelEvent {
private final ServerLevelData settings;
public CreateSpawnPosition(LevelAccessor level, ServerLevelData settings)
{
public CreateSpawnPosition(LevelAccessor level, ServerLevelData settings) {
super(level);
this.settings = settings;
}
public ServerLevelData getSettings()
{
public ServerLevelData getSettings() {
return settings;
}
}
@@ -131,22 +126,20 @@ public class LevelEvent extends Event
*
* <p>If an entry is added to the list, it needs to be a globally unique instance.</p>
*
* The event is called in {@link net.minecraft.world.level.NaturalSpawner#mobsAt(ServerLevel,
* StructureManager, ChunkGenerator, MobCategory, RandomSource, BlockPos)}.</p>
* The event is called in {@link net.minecraft.world.level.NaturalSpawner#mobsAt(ServerLevel, StructureManager,
* ChunkGenerator, MobCategory, BlockPos, Holder)}.</p>
*
* <p>This event is {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.
* Canceling the event will result in an empty list, meaning no entity will be spawned.</p>
*/
@Cancelable
public static class PotentialSpawns extends LevelEvent
{
public static class PotentialSpawns extends LevelEvent {
private final MobCategory mobcategory;
private final BlockPos pos;
private final List<MobSpawnSettings.SpawnerData> list;
private final List<MobSpawnSettings.SpawnerData> view;
private final List<Weighted<MobSpawnSettings.SpawnerData>> list;
private final @UnmodifiableView List<Weighted<MobSpawnSettings.SpawnerData>> view;
public PotentialSpawns(LevelAccessor level, MobCategory category, BlockPos pos, WeightedRandomList<MobSpawnSettings.SpawnerData> oldList)
{
public PotentialSpawns(LevelAccessor level, MobCategory category, BlockPos pos, WeightedList<MobSpawnSettings.SpawnerData> oldList) {
super(level);
this.pos = pos;
this.mobcategory = category;
@@ -158,50 +151,39 @@ public class LevelEvent extends Event
this.view = Collections.unmodifiableList(list);
}
/**
* {@return the category of the mobs in the spawn list.}
*/
public MobCategory getMobCategory()
{
return mobcategory;
/** @return the category of the mobs in the spawn list. */
public MobCategory getMobCategory() {
return this.mobcategory;
}
/**
* {@return the block position where the chosen mob will be spawned.}
*/
public BlockPos getPos()
{
return pos;
/** @return the block position where the chosen mob will be spawned. */
public BlockPos getPos() {
return this.pos;
}
/**
* {@return the list of mobs that can potentially be spawned.}
*/
public List<MobSpawnSettings.SpawnerData> getSpawnerDataList()
{
return view;
/** @return the list of mobs that can potentially be spawned. */
public @UnmodifiableView List<Weighted<MobSpawnSettings.SpawnerData>> getSpawnerDataList() {
return this.view;
}
/**
* Appends a SpawnerData entry to the spawn list.
*
* @param data SpawnerData entry to be appended to the spawn list.
* @param data SpawnerData entry to be appended to the spawn list.
* @param weight The weight for the data entry to have in the list.
*/
public void addSpawnerData(MobSpawnSettings.SpawnerData data)
{
list.add(data);
public void addSpawnerData(MobSpawnSettings.SpawnerData data, int weight) {
this.list.add(new Weighted<>(data, weight));
}
/**
* Removes a SpawnerData entry from the spawn list.
* Removes all entries of the given SpawnerData from the spawn list.
*
* @param data SpawnerData entry to be removed from the spawn list.
*
* {@return {@code true} if the spawn list contained the specified element.}
* @return {@code true} if the spawn list contained the specified element.
*/
public boolean removeSpawnerData(MobSpawnSettings.SpawnerData data)
{
return list.remove(data);
public boolean removeSpawnerData(MobSpawnSettings.SpawnerData data) {
return this.list.removeIf(weighted -> weighted.value().equals(data));
}
}
}
@@ -8,6 +8,7 @@ package net.minecraftforge.event.village;
import java.util.List;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.entity.npc.VillagerData;
import net.minecraft.world.entity.npc.VillagerProfession;
import net.minecraft.world.entity.npc.VillagerTrades.ItemListing;
@@ -16,35 +17,29 @@ import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.event.server.ServerAboutToStartEvent;
/**
* VillagerTradesEvent is fired during the {@link ServerAboutToStartEvent}. It is used to gather the trade lists for each profession.
* It is fired on the {@link MinecraftForge#EVENT_BUS}.
* It is fired once for each registered villager profession.
* Villagers pick two trades from their trade map, based on their level.
* Villager level is increased by successful trades.
* The map is populated for levels 1-5 (inclusive), so Map#get will never return null for those keys.
* Levels outside of this range do nothing, as specified by {@link VillagerData#canLevelUp(int)} which is called before attempting to level up.
* To add trades to the merchant, simply add new trades to the list. {@link BasicItemListing} provides a default implementation.
* VillagerTradesEvent is fired during the {@link ServerAboutToStartEvent}. It is used to gather the trade lists for each profession.
* <p>It is fired on the {@link MinecraftForge#EVENT_BUS}.</p>
* <p>It is fired once for each registered villager profession.</p>
* <p>Villagers pick two trades from their trade map, based on their level.</p>
* <p>Villager level is increased by successful trades.</p>
* <p>The map is populated for levels 1-5 (inclusive), so getting a value will never return null for those keys.</p>
* <p>Levels outside of this range do nothing, as specified by {@link VillagerData#canLevelUp(int)} which is called before attempting to level up.</p>
* <p>To add trades to the merchant, simply add new trades to the list.</p>
*/
public class VillagerTradesEvent extends Event
{
public class VillagerTradesEvent extends Event {
protected Int2ObjectMap<List<ItemListing>> trades;
protected VillagerProfession type;
protected ResourceKey<VillagerProfession> type;
public VillagerTradesEvent(Int2ObjectMap<List<ItemListing>> trades, VillagerProfession type)
{
public VillagerTradesEvent(Int2ObjectMap<List<ItemListing>> trades, ResourceKey<VillagerProfession> type) {
this.trades = trades;
this.type = type;
}
public Int2ObjectMap<List<ItemListing>> getTrades()
{
return trades;
public Int2ObjectMap<List<ItemListing>> getTrades() {
return this.trades;
}
public VillagerProfession getType()
{
return type;
public ResourceKey<VillagerProfession> getType() {
return this.type;
}
}
@@ -5,8 +5,13 @@
package net.minecraftforge.event.village;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import net.minecraft.Util;
import net.minecraft.world.entity.npc.VillagerTrades.ItemListing;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.Event;
@@ -15,28 +20,39 @@ import net.minecraftforge.event.server.ServerAboutToStartEvent;
/**
* WandererTradesEvent is fired during the {@link ServerAboutToStartEvent}. It is used to gather the trade lists for the wandering merchant.
* It is fired on the {@link MinecraftForge#EVENT_BUS}.
* The wandering merchant picks a few trades from {@code generic} and a single trade from {@code rare}.
* The wandering merchant picks {@link Pool#rolls} from each {@link Pool}
* To add trades to the merchant, simply add new trades to the list. {@link BasicItemListing} provides a default implementation.
*/
public class WandererTradesEvent extends Event
{
public class WandererTradesEvent extends Event {
protected List<Pool> pools;
protected List<ItemListing> generic;
protected List<ItemListing> rare;
public WandererTradesEvent(List<ItemListing> generic, List<ItemListing> rare)
{
this.generic = generic;
this.rare = rare;
public WandererTradesEvent(List<Pair<ItemListing[], Integer>> pools) {
this.pools = pools.stream().map(Pool::new).collect(Util.toMutableList());
}
public List<ItemListing> getGenericTrades()
{
return generic;
public List<Pool> getPools() {
return pools;
}
public List<ItemListing> getRareTrades()
{
return rare;
public static class Pool {
private int rolls;
private List<ItemListing> entries;
public Pool(Pair<ItemListing[], Integer> data) {
this.rolls = data.getRight();
this.entries = new ArrayList<>(Arrays.asList(data.getLeft()));
}
public int getRolls() {
return this.rolls;
}
public void setRolls(int value) {
this.rolls = value;
}
public List<ItemListing> getEntries() {
return this.entries;
}
}
}
@@ -22,7 +22,9 @@ import net.minecraftforge.registries.ForgeRegistries;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
import java.util.Optional;
/**
@@ -33,8 +35,7 @@ import java.util.Optional;
* equal.
*
*/
public class FluidStack
{
public class FluidStack {
private static final Logger LOGGER = LogManager.getLogger();
public static final FluidStack EMPTY = new FluidStack(Fluids.EMPTY, 0);
@@ -53,18 +54,14 @@ public class FluidStack
private boolean isEmpty;
private int amount;
private CompoundTag tag;
private Holder.Reference<Fluid> fluidDelegate;
private @Nullable CompoundTag tag;
private final Holder.Reference<Fluid> fluidDelegate;
public FluidStack(Fluid fluid, int amount)
{
if (fluid == null)
{
public FluidStack(Fluid fluid, int amount) {
if (fluid == null) {
LOGGER.fatal("Null fluid supplied to fluidstack. Did you try and create a stack for an unregistered fluid?");
throw new IllegalArgumentException("Cannot create a fluidstack from a null fluid");
}
else if (ForgeRegistries.FLUIDS.getKey(fluid) == null)
{
} else if (ForgeRegistries.FLUIDS.getKey(fluid) == null) {
LOGGER.fatal("Failed attempt to create a FluidStack for an unregistered Fluid {} (type {})", ForgeRegistries.FLUIDS.getKey(fluid), fluid.getClass().getName());
throw new IllegalArgumentException("Cannot create a fluidstack from an unregistered fluid");
}
@@ -74,18 +71,14 @@ public class FluidStack
updateEmpty();
}
public FluidStack(Fluid fluid, int amount, CompoundTag nbt)
{
public FluidStack(Fluid fluid, int amount, CompoundTag nbt) {
this(fluid, amount);
if (nbt != null)
{
tag = nbt.copy();
}
}
public FluidStack(FluidStack stack, int amount)
{
public FluidStack(FluidStack stack, int amount) {
this(stack.getFluid(), amount, stack.tag);
}
@@ -93,51 +86,39 @@ public class FluidStack
* This provides a safe method for retrieving a FluidStack - if the Fluid is invalid, the stack
* will return as null.
*/
public static FluidStack loadFluidStackFromNBT(CompoundTag nbt)
{
public static FluidStack loadFluidStackFromNBT(CompoundTag nbt) {
if (nbt == null)
{
return EMPTY;
}
if (!nbt.contains("FluidName", Tag.TAG_STRING))
{
return EMPTY;
}
ResourceLocation fluidName = ResourceLocation.parse(nbt.getString("FluidName"));
var fluidNameString = nbt.getString("FluidName");
if (fluidNameString.isEmpty())
return EMPTY;
ResourceLocation fluidName = ResourceLocation.parse(fluidNameString.get());
Fluid fluid = ForgeRegistries.FLUIDS.getValue(fluidName);
if (fluid == null)
{
return EMPTY;
}
FluidStack stack = new FluidStack(fluid, nbt.getInt("Amount"));
if (nbt.contains("Tag", Tag.TAG_COMPOUND))
{
stack.tag = nbt.getCompound("Tag");
}
FluidStack stack = new FluidStack(fluid, nbt.getIntOr("Amount", 0));
nbt.getCompound("Tag").ifPresent(tag -> stack.tag = tag);
return stack;
}
public CompoundTag writeToNBT(CompoundTag nbt)
{
public CompoundTag writeToNBT(CompoundTag nbt) {
nbt.putString("FluidName", ForgeRegistries.FLUIDS.getKey(getFluid()).toString());
nbt.putInt("Amount", amount);
if (tag != null)
{
nbt.put("Tag", tag);
}
return nbt;
}
public final Fluid getFluid()
{
public final Fluid getFluid() {
return isEmpty ? Fluids.EMPTY : fluidDelegate.get();
}
public final Fluid getRawFluid()
{
public final Fluid getRawFluid() {
return fluidDelegate.get();
}
@@ -149,13 +130,11 @@ public class FluidStack
isEmpty = getRawFluid() == Fluids.EMPTY || amount <= 0;
}
public int getAmount()
{
public int getAmount() {
return isEmpty ? 0 : amount ;
}
public void setAmount(int amount)
{
public void setAmount(int amount) {
if (getRawFluid() == Fluids.EMPTY) throw new IllegalStateException("Can't modify the empty stack.");
this.amount = amount;
updateEmpty();
@@ -169,68 +148,60 @@ public class FluidStack
setAmount(this.amount - amount);
}
public boolean hasTag()
{
public boolean hasTag() {
return tag != null;
}
public CompoundTag getTag()
{
public CompoundTag getTag() {
return tag;
}
public void setTag(CompoundTag tag)
{
public void setTag(CompoundTag tag) {
if (getRawFluid() == Fluids.EMPTY) throw new IllegalStateException("Can't modify the empty stack.");
this.tag = tag;
}
public CompoundTag getOrCreateTag()
{
public CompoundTag getOrCreateTag() {
if (tag == null)
setTag(new CompoundTag());
return tag;
}
public CompoundTag getChildTag(String childName)
{
public @Nullable CompoundTag getChildTag(String childName) {
if (tag == null)
return null;
return tag.getCompound(childName);
return tag.getCompoundOrEmpty(childName);
}
public CompoundTag getOrCreateChildTag(String childName)
{
public CompoundTag getOrCreateChildTag(String childName) {
getOrCreateTag();
CompoundTag child = tag.getCompound(childName);
if (!tag.contains(childName, Tag.TAG_COMPOUND))
{
var optional = tag.getCompound(childName);
if (optional.isEmpty()) {
var child = new CompoundTag();
tag.put(childName, child);
return child;
}
return child;
return optional.get();
}
public void removeChildTag(String childName)
{
public void removeChildTag(String childName) {
if (tag != null)
tag.remove(childName);
}
public Component getDisplayName()
{
public Component getDisplayName() {
return this.getFluid().getFluidType().getDescription(this);
}
public String getTranslationKey()
{
public String getTranslationKey() {
return this.getFluid().getFluidType().getDescriptionId(this);
}
/**
* @return A copy of this FluidStack
*/
public FluidStack copy()
{
public FluidStack copy() {
return new FluidStack(getFluid(), amount, tag);
}
@@ -241,21 +212,18 @@ public class FluidStack
* The FluidStack for comparison
* @return true if the Fluids (IDs and NBT Tags) are the same
*/
public boolean isFluidEqual(@NotNull FluidStack other)
{
public boolean isFluidEqual(@NotNull FluidStack other) {
return getFluid() == other.getFluid() && isFluidStackTagEqual(other);
}
private boolean isFluidStackTagEqual(FluidStack other)
{
private boolean isFluidStackTagEqual(FluidStack other) {
return tag == null ? other.tag == null : other.tag != null && tag.equals(other.tag);
}
/**
* Determines if the NBT Tags are equal. Useful if the FluidIDs are known to be equal.
*/
public static boolean areFluidStackTagsEqual(@NotNull FluidStack stack1, @NotNull FluidStack stack2)
{
public static boolean areFluidStackTagsEqual(@NotNull FluidStack stack1, @NotNull FluidStack stack2) {
return stack1.isFluidStackTagEqual(stack2);
}
@@ -264,8 +232,7 @@ public class FluidStack
*
* @return true if this FluidStack contains the other FluidStack (same fluid and >= amount)
*/
public boolean containsFluid(@NotNull FluidStack other)
{
public boolean containsFluid(@NotNull FluidStack other) {
return isFluidEqual(other) && amount >= other.amount;
}
@@ -276,8 +243,7 @@ public class FluidStack
* - the FluidStack for comparison
* @return true if the two FluidStacks are exactly the same
*/
public boolean isFluidStackIdentical(FluidStack other)
{
public boolean isFluidStackIdentical(FluidStack other) {
return isFluidEqual(other) && amount == other.amount;
}
@@ -289,14 +255,12 @@ public class FluidStack
* The ItemStack for comparison
* @return true if the Fluids (IDs and NBT Tags) are the same
*/
public boolean isFluidEqual(@NotNull ItemStack other)
{
public boolean isFluidEqual(@NotNull ItemStack other) {
return FluidUtil.getFluidContained(other).map(this::isFluidEqual).orElse(false);
}
@Override
public final int hashCode()
{
public final int hashCode() {
int code = 1;
code = 31*code + getFluid().hashCode();
if (tag != null)
@@ -310,12 +274,7 @@ public class FluidStack
* This is included for use in data structures.
*/
@Override
public final boolean equals(Object o)
{
if (!(o instanceof FluidStack))
{
return false;
}
return isFluidEqual((FluidStack) o);
public final boolean equals(Object o) {
return o instanceof FluidStack stack && isFluidEqual(stack);
}
}
@@ -456,14 +456,14 @@ public class FluidType {
* Returns a sound to play when a certain action is performed at a
* position. If no sound is present, then the sound will be {@code null}.
*
* @param player the player listening to the sound
* @param entity the entity listening to the sound
* @param getter the getter which can get the fluid
* @param pos the position of the fluid
* @param action the action being performed
* @return the sound to play when performing the action
*/
@Nullable
public SoundEvent getSound(@Nullable Player player, BlockGetter getter, BlockPos pos, SoundAction action) {
public SoundEvent getSound(@Nullable LivingEntity entity, BlockGetter getter, BlockPos pos, SoundAction action) {
return this.getSound(action);
}
@@ -784,7 +784,7 @@ public class FluidType {
* @param stack the stack holding the fluid being placed
* @return {@code true} if this fluid should be vaporized on placement, {@code false} otherwise
*
* @see BucketItem#emptyContents(Player, Level, BlockPos, BlockHitResult)
* @see BucketItem#emptyContents(LivingEntity, Level, BlockPos, BlockHitResult)
*/
public boolean isVaporizedOnPlacement(Level level, BlockPos pos, FluidStack stack) {
if (level.dimensionType().ultraWarm()) {
@@ -798,16 +798,16 @@ public class FluidType {
*
* <p>Note: The fluid will already have been drained from the stack.
*
* @param player the player placing the fluid, may be {@code null} for blocks like dispensers
* @param entity the player placing the fluid, may be {@code null} for blocks like dispensers
* @param level the level the fluid is vaporized in
* @param pos the position the fluid is vaporized at
* @param stack the stack holding the fluid being vaporized
*
* @see BucketItem#emptyContents(Player, Level, BlockPos, BlockHitResult)
* @see BucketItem#emptyContents(LivingEntity, Level, BlockPos, BlockHitResult)
*/
public void onVaporize(@Nullable Player player, Level level, BlockPos pos, FluidStack stack) {
SoundEvent sound = this.getSound(player, level, pos, SoundActions.FLUID_VAPORIZE);
level.playSound(player, pos, sound != null ? sound : SoundEvents.FIRE_EXTINGUISH, SoundSource.BLOCKS, 0.5F, 2.6F + (level.random.nextFloat() - level.random.nextFloat()) * 0.8F);
public void onVaporize(@Nullable LivingEntity entity, Level level, BlockPos pos, FluidStack stack) {
SoundEvent sound = this.getSound(entity, level, pos, SoundActions.FLUID_VAPORIZE);
level.playSound(entity, pos, sound != null ? sound : SoundEvents.FIRE_EXTINGUISH, SoundSource.BLOCKS, 0.5F, 2.6F + (level.random.nextFloat() - level.random.nextFloat()) * 0.8F);
for (int l = 0; l < 8; ++l)
level.addAlwaysVisibleParticle(ParticleTypes.LARGE_SMOKE, (double) pos.getX() + Math.random(), (double) pos.getY() + Math.random(), (double) pos.getZ() + Math.random(), 0.0D, 0.0D, 0.0D);
@@ -6,10 +6,12 @@
package net.minecraftforge.gametest;
import net.minecraft.SharedConstants;
import net.minecraft.gametest.framework.GameTest;
import net.minecraft.gametest.framework.GameTestRegistry;
import net.minecraft.gametest.framework.TestFunction;
import net.minecraftforge.event.RegisterGameTestsEvent;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.gametest.framework.GameTestHelper;
import net.minecraft.gametest.framework.GameTestInstance;
import net.minecraft.gametest.framework.TestData;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.ModLoader;
import net.minecraftforge.fml.common.Mod;
@@ -17,6 +19,7 @@ import net.minecraftforge.fml.loading.FMLLoader;
import net.minecraftforge.fml.util.ObfuscationReflectionHelper;
import net.minecraftforge.forgespi.language.ModFileScanData;
import net.minecraftforge.forgespi.language.ModFileScanData.AnnotationData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.ApiStatus;
@@ -24,23 +27,25 @@ import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.Type;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Internal class used to glue mods into the game test framework.
* Modders should use the supplied annotations and {@link RegisterGameTestsEvent}
* Modders should use the supplied annotations and DeferredRegister
*/
@SuppressWarnings("unused")
@ApiStatus.Internal
public class ForgeGameTestHooks {
private static boolean registeredGametests = false;
private static final Logger LOGGER = LogManager.getLogger();
private static final Type GAME_TEST_HOLDER = Type.getType(GameTestHolder.class);
private static final String DEFAULT_BATCH = getDefaultBatch();
public static boolean isGametestEnabled() {
return !FMLLoader.isProduction() && (SharedConstants.IS_RUNNING_IN_IDE || isGametestServer() || Boolean.getBoolean("forge.enableGameTest"));
@@ -50,6 +55,7 @@ public class ForgeGameTestHooks {
return !FMLLoader.isProduction() && Boolean.getBoolean("forge.gameTestServer");
}
/*
@SuppressWarnings("deprecation")
public static void registerGametests() {
if (!registeredGametests && isGametestEnabled() && ModLoader.isLoadingStateValid()) {
@@ -112,6 +118,10 @@ public class ForgeGameTestHooks {
if (!shouldPrefix)
return null;
return getPrefix(cls);
}
private static String getPrefix(Class<?> cls) {
var prefix = cls.getAnnotation(GameTestPrefix.class);
if (prefix != null)
return prefix.value();
@@ -120,73 +130,70 @@ public class ForgeGameTestHooks {
if (holder != null && !holder.value().isEmpty())
return holder.value();
var mod = method.getDeclaringClass().getAnnotation(Mod.class);
var mod = cls.getAnnotation(Mod.class);
if (mod != null)
return mod.value();
return cls.getSimpleName().toLowerCase(Locale.ENGLISH);
}
public static String getTestTemplate(Method method, GameTest meta, String testName) {
// If we have a ':' assume we specified the exact template path
if (meta.template().indexOf(':') != -1)
return meta.template();
String template = null;
if (meta.template().isEmpty())
template = testName;
else
template = getPrefixed(method, meta.template());
var cls = method.getDeclaringClass();
var holder = cls.getAnnotation(GameTestHolder.class);
if (holder != null && !holder.namespace().isEmpty())
return holder.namespace() + ':' + template;
var mod = cls.getAnnotation(Mod.class);
if (mod != null)
return mod.value() + ':' + template;
return template;
private static ResourceLocation key(String namespace, String path) {
return path.indexOf(':') == -1 ? ResourceLocation.parse(path) : ResourceLocation.fromNamespaceAndPath(namespace, path);
}
private static String getDefaultBatch() {
try {
return (String)ObfuscationReflectionHelper.findMethod(GameTest.class, "m_177043" + '_').getDefaultValue();
} catch (Exception e) {
e.printStackTrace(); // Should never happen, but just in case.
return "defaultBatch";
public static Map<ResourceLocation, GameTestInstance> gatherTests(Class<?> root) {
String prefix = getPrefix(root);
var seen = new HashSet<ResourceLocation>();
Class<?> cls = root;
while (cls != Object.class) {
for (var method : cls.getDeclaredMethods()) {
if (cls != root && Modifier.isStatic(method.getModifiers()))
continue;
var gametest = method.getAnnotation(GameTest.class);
if (gametest == null)
continue;
var owner = method.getDeclaringClass().getName() + "." + method.getName();
if (method.getParameterCount() != 1 || method.getParameterTypes()[0] != GameTestHelper.class)
throw new IllegalStateException("Invalid @GameTest function " + owner + " incorrect arguments");
var testName = key(prefix, gametest.name().isEmpty() ? method.getName() : gametest.name());
if (!seen.add(testName)) {
if (!Modifier.isStatic(method.getModifiers()))
continue;
throw new IllegalStateException("Failed to register test, already seen " + testName + ", for " + owner);
}
if (gametest.type() == GameTest.Type.FUNCTION) {
var funcName = key(prefix, gametest.function());
var func = BuiltInRegistries.TEST_FUNCTION.get(funcName).orElse(null);
if (func == null)
throw new IllegalStateException("Could not find referenced function `" + funcName + "` for " + owner);
var data = getTestData(prefix, owner, gametest.data());
} else if (gametest.type() == GameTest.Type.BLOCK) {
} else {
throw new IllegalStateException("Could not determine GameTest type for " + root.getName() + " -> " + gametest.type());
}
}
cls = cls.getSuperclass();
}
}
public static String getTestBatch(Method method, GameTest gametest) {
var batch = gametest.batch();
if (DEFAULT_BATCH.equals(batch)) {
var prefix = getPrefix(method);
return prefix == null ? batch : prefix;
}
return getPrefixed(method, batch.toLowerCase(Locale.ENGLISH));
}
public static void addTest(Collection<TestFunction> functions, Set<String> classes, Set<String> filters, TestFunction func) {
boolean allowed = filters.isEmpty() || filters.stream().anyMatch(f -> f.equals(func.batchName()) || func.batchName().startsWith(f + '.'));
if (!allowed)
return;
functions.add(func);
var batch = func.batchName();
classes.add(batch);
int idx = batch.lastIndexOf('.');
while (idx != -1) {
batch = batch.substring(0, idx);
idx = batch.lastIndexOf('.');
classes.add(batch);
}
private static TestData<?> getTestData(String prefix, String owner, GameTest.Data data) {
var envName = key(prefix, data.environment());
var env = BuiltInRegistries.TEST_ENVIRONMENT
}
*/
}
@@ -0,0 +1,44 @@
package net.minecraftforge.gametest;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import net.minecraft.world.level.block.Rotation;
@Retention(RUNTIME)
@Target(METHOD)
public @interface GameTest {
String name() default "";
String function() default "";
Type type() default Type.BLOCK;
Data data() default @Data;
int rotationSteps() default 0;
public enum Type {
BLOCK,
FUNCTION;
}
/**
* Annotation definitions for {@link net.minecraft.gametest.framework.TestData}
*/
public @interface Data {
String environment() default "";
String structure() default "forge:empty3x3";
int maxTicks() default Integer.MAX_VALUE;
int setupTicks() default 0;
boolean required() default false;
Rotation rotation() default Rotation.NONE;
boolean manualOnly() default false;
int maxAttempts() default 1;
int requiredSuccesses() default 1;
boolean skyAccess() default false;
}
}
@@ -5,9 +5,6 @@
package net.minecraftforge.gametest;
import net.minecraft.gametest.framework.GameTest;
import net.minecraft.gametest.framework.GameTestGenerator;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
Loaded 100 of 548 files, more files were not shown because too many files have changed in this diff. Show more