[1.19.x] Fluid API Overhaul (#8695)

This commit is contained in:
ChampionAsh5357 authored and GitHub committed 2022-06-14 23:07:51 +01:00
1 parent e386229b66
commit 2a05c7c01d
67 files changed
+3856 -740

No files matched your search

@@ -17,7 +17,7 @@ public class FluidContainerColorer implements ItemColor
{
if (tintIndex != 1) return 0xFFFFFFFF;
return FluidUtil.getFluidContained(stack)
.map(fstack -> fstack.getFluid().getAttributes().getColor(fstack))
.map(fstack -> RenderProperties.get(fstack.getFluid()).getColorTint(fstack))
.orElse(0xFFFFFFFF);
}
}
@@ -383,8 +383,28 @@ public class ForgeHooksClient
MinecraftForge.EVENT_BUS.post(new ScreenEvent.DrawScreenEvent.Post(screen, poseStack, mouseX, mouseY, partialTick));
}
public static void onFogRender(FogType type, Camera camera, float partialTick, float nearDistance, float farDistance, FogShape shape)
public static Vector3f getFogColor(Camera camera, float partialTick, ClientLevel level, int renderDistance, float darkenWorldAmount, float fogRed, float fogGreen, float fogBlue)
{
// Modify fog color depending on the fluid
FluidState state = level.getFluidState(camera.getBlockPosition());
Vector3f fluidFogColor = new Vector3f(fogRed, fogGreen, fogBlue);
if (camera.getPosition().y < (double)((float)camera.getBlockPosition().getY() + state.getHeight(level, camera.getBlockPosition())))
fluidFogColor = RenderProperties.get(state).modifyFogColor(camera, partialTick, level, renderDistance, darkenWorldAmount, fluidFogColor);
EntityViewRenderEvent.FogColors event = new net.minecraftforge.client.event.EntityViewRenderEvent.FogColors(camera, partialTick, fluidFogColor.x(), fluidFogColor.y(), fluidFogColor.z());
MinecraftForge.EVENT_BUS.post(event);
fluidFogColor.set(event.getRed(), event.getGreen(), event.getBlue());
return fluidFogColor;
}
public static void onFogRender(FogRenderer.FogMode mode, FogType type, Camera camera, float partialTick, float renderDistance, float nearDistance, float farDistance, FogShape shape)
{
// Modify fog rendering depending on the fluid
FluidState state = camera.getEntity().level.getFluidState(camera.getBlockPosition());
if (camera.getPosition().y < (double)((float)camera.getBlockPosition().getY() + state.getHeight(camera.getEntity().level, camera.getBlockPosition())))
RenderProperties.get(state).modifyFogRender(camera, mode, renderDistance, partialTick, nearDistance, farDistance, shape);
EntityViewRenderEvent.RenderFogEvent event = new EntityViewRenderEvent.RenderFogEvent(type, camera, partialTick, nearDistance, farDistance, shape);
if (MinecraftForge.EVENT_BUS.post(event))
{
@@ -441,10 +461,11 @@ public class ForgeHooksClient
@SuppressWarnings("deprecation")
public static TextureAtlasSprite[] getFluidSprites(BlockAndTintGetter level, BlockPos pos, FluidState fluidStateIn)
{
ResourceLocation overlayTexture = fluidStateIn.getType().getAttributes().getOverlayTexture();
IFluidTypeRenderProperties props = RenderProperties.get(fluidStateIn);
ResourceLocation overlayTexture = props.getOverlayTexture(fluidStateIn, level, pos);
return new TextureAtlasSprite[] {
Minecraft.getInstance().getTextureAtlas(TextureAtlas.LOCATION_BLOCKS).apply(fluidStateIn.getType().getAttributes().getStillTexture(level, pos)),
Minecraft.getInstance().getTextureAtlas(TextureAtlas.LOCATION_BLOCKS).apply(fluidStateIn.getType().getAttributes().getFlowingTexture(level, pos)),
Minecraft.getInstance().getTextureAtlas(TextureAtlas.LOCATION_BLOCKS).apply(props.getStillTexture(fluidStateIn, level, pos)),
Minecraft.getInstance().getTextureAtlas(TextureAtlas.LOCATION_BLOCKS).apply(props.getFlowingTexture(fluidStateIn, level, pos)),
overlayTexture == null ? null : Minecraft.getInstance().getTextureAtlas(TextureAtlas.LOCATION_BLOCKS).apply(overlayTexture),
};
}
@@ -458,7 +479,7 @@ public class ForgeHooksClient
public static Stream<Material> getFluidMaterials(Fluid fluid)
{
return fluid.getAttributes().getTextures()
return RenderProperties.get(fluid).getTextures()
.filter(Objects::nonNull)
.map(ForgeHooksClient::getBlockMaterial);
}
@@ -0,0 +1,373 @@
package net.minecraftforge.client;
import com.mojang.blaze3d.shaders.FogShape;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.BufferUploader;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.Tesselator;
import com.mojang.blaze3d.vertex.VertexFormat;
import com.mojang.math.Matrix4f;
import com.mojang.math.Vector3f;
import net.minecraft.client.Camera;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.renderer.FogRenderer;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.ItemBlockRenderTypes;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.core.BlockPos;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids;
import net.minecraftforge.client.model.FluidModel;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidType;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
import java.util.stream.Stream;
/**
* An interface which defines properties relating to how a {@link FluidType}
* should render.
*
* <p>Note: This does not define any data regarding {@link RenderType}s as those
* are specified by the Fluid via {@link ItemBlockRenderTypes#setRenderLayer(Fluid, RenderType)}
* in the {@link FMLClientSetupEvent}.
*/
public interface IFluidTypeRenderProperties
{
/**
* A dummy instance returned when no render properties are specified.
*/
IFluidTypeRenderProperties DUMMY = new IFluidTypeRenderProperties()
{
};
/* Default Accessors */
/**
* Returns the tint applied to the fluid's textures.
*
* <p>The result represents a 32-bit integer where each 8-bits represent
* the alpha, red, green, and blue channel respectively.
*
* @return the tint applied to the fluid's textures in ARGB format
*/
default int getColorTint()
{
return 0xFFFFFFFF;
}
/**
* Returns the reference of the texture to apply to a source fluid.
*
* <p>This should return a reference to the texture and not the actual
* texture itself (e.g. {@code minecraft:block/water_still} will point to
* {@code assets/minecraft/textures/block/water_still.png}).
*
* <p>Important: This method should only return {@code null} for {@link Fluids#EMPTY}.
* All other implementations must define this property.
*
* @return the reference of the texture to apply to a source fluid
*/
default ResourceLocation getStillTexture()
{
return null;
}
/**
* Returns the reference of the texture to apply to a flowing fluid.
*
* <p>This should return a reference to the texture and not the actual
* texture itself (e.g. {@code minecraft:block/water_flow} will point to
* {@code assets/minecraft/textures/block/water_flow.png}).
*
* <p>Important: This method should only return {@code null} for {@link Fluids#EMPTY}.
* All other implementations must define this property.
*
* @return the reference of the texture to apply to a flowing fluid
*/
default ResourceLocation getFlowingTexture()
{
return null;
}
/**
* Returns the reference of the texture to apply to a fluid directly touching
* a non-opaque block other than air. If no reference is specified, either
* {@code #getStillTexture} or {@code #getFlowingTexture} will be applied
* instead.
*
* <p>This should return a reference to the texture and not the actual
* texture itself (e.g. {@code minecraft:block/water_overlay} will point to
* {@code assets/minecraft/textures/block/water_overlay.png}).
*
* @return the reference of the texture to apply to a fluid directly touching
* a non-opaque block
*/
@Nullable
default ResourceLocation getOverlayTexture()
{
return null;
}
/**
* Returns a stream of textures applied to a fluid.
*
* <p>This is used by the {@link FluidModel} to load in all textures that
* can be applied on reload.
*
* @return a stream of textures applied to a fluid
*/
default Stream<ResourceLocation> getTextures()
{
return Stream.of(this.getStillTexture(), this.getFlowingTexture(), this.getOverlayTexture())
.filter(Objects::nonNull);
}
/**
* Returns the location of the texture to apply to the camera when it is
* within the fluid. If no location is specified, no overlay will be applied.
*
* <p>This should return a location to the texture and not a reference
* (e.g. {@code minecraft:textures/misc/underwater.png} will use the texture
* at {@code assets/minecraft/textures/misc/underwater.png}).
*
* @param mc the client instance
* @return the location of the texture to apply to the camera when it is
* within the fluid
*/
@Nullable
default ResourceLocation getRenderOverlayTexture(Minecraft mc)
{
return null;
}
/**
* Renders {@code #getRenderOverlayTexture} onto the camera when within
* the fluid.
*
* @param mc the client instance
* @param stack the transformations representing the current rendering position
*/
default void renderOverlay(Minecraft mc, PoseStack stack)
{
ResourceLocation texture = this.getRenderOverlayTexture(mc);
if (texture == null) return;
RenderSystem.setShader(GameRenderer::getPositionTexShader);
RenderSystem.enableTexture();
RenderSystem.setShaderTexture(0, texture);
BufferBuilder buffer = Tesselator.getInstance().getBuilder();
BlockPos playerEyePos = new BlockPos(mc.player.getX(), mc.player.getEyeY(), mc.player.getZ());
float brightness = LightTexture.getBrightness(mc.player.level.dimensionType(), mc.player.level.getMaxLocalRawBrightness(playerEyePos));
RenderSystem.enableBlend();
RenderSystem.defaultBlendFunc();
RenderSystem.setShaderColor(brightness, brightness, brightness, 0.1F);
float uOffset = -mc.player.getYRot() / 64.0F;
float vOffset = mc.player.getXRot() / 64.0F;
Matrix4f pose = stack.last().pose();
buffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX);
buffer.vertex(pose, -1.0F, -1.0F, -0.5F).uv(4.0F + uOffset, 4.0F + vOffset).endVertex();
buffer.vertex(pose, 1.0F, -1.0F, -0.5F).uv(uOffset, 4.0F + vOffset).endVertex();
buffer.vertex(pose, 1.0F, 1.0F, -0.5F).uv(uOffset, vOffset).endVertex();
buffer.vertex(pose, -1.0F, 1.0F, -0.5F).uv(4.0F + uOffset, vOffset).endVertex();
BufferUploader.drawWithShader(buffer.end());
RenderSystem.disableBlend();
}
/**
* Modifies the color of the fog when the camera is within the fluid.
*
* <p>The result expects a three float vector representing the red, green,
* and blue channels respectively. Each channel should be between [0,1].
*
* @param camera the camera instance
* @param partialTick the delta time of where the current frame is within a tick
* @param level the level the camera is located in
* @param renderDistance the render distance of the client
* @param darkenWorldAmount the amount to darken the world by
* @param fluidFogColor the current color of the fog
* @return the color of the fog
*/
@NotNull
default Vector3f modifyFogColor(Camera camera, float partialTick, ClientLevel level, int renderDistance, float darkenWorldAmount, Vector3f fluidFogColor)
{
return fluidFogColor;
}
/**
* Modifies how the fog is currently being rendered when the camera is
* within a fluid.
*
* @param camera the camera instance
* @param mode the type of fog being rendered
* @param renderDistance the render distance of the client
* @param partialTick the delta time of where the current frame is within a tick
* @param nearDistance the near plane of where the fog starts to render
* @param farDistance the far plane of where the fog ends rendering
* @param shape the shape of the fog being rendered
*/
default void modifyFogRender(Camera camera, FogRenderer.FogMode mode, float renderDistance, float partialTick, float nearDistance, float farDistance, FogShape shape)
{
}
/* Level-Based Accessors */
/**
* Returns the reference of the texture to apply to a source fluid.
*
* <p>This should return a reference to the texture and not the actual
* texture itself (e.g. {@code minecraft:block/water_still} will point to
* {@code assets/minecraft/textures/block/water_still.png}).
*
* <p>Important: This method should only return {@code null} for {@link Fluids#EMPTY}.
* All other implementations must define this property.
*
* @param state the state of the fluid
* @param getter the getter the fluid can be obtained from
* @param pos the position of the fluid
* @return the reference of the texture to apply to a source fluid
*/
default ResourceLocation getStillTexture(FluidState state, BlockAndTintGetter getter, BlockPos pos)
{
return this.getStillTexture();
}
/**
* Returns the reference of the texture to apply to a flowing fluid.
*
* <p>This should return a reference to the texture and not the actual
* texture itself (e.g. {@code minecraft:block/water_flow} will point to
* {@code assets/minecraft/textures/block/water_flow.png}).
*
* <p>Important: This method should only return {@code null} for {@link Fluids#EMPTY}.
* All other implementations must define this property.
*
* @param state the state of the fluid
* @param getter the getter the fluid can be obtained from
* @param pos the position of the fluid
* @return the reference of the texture to apply to a flowing fluid
*/
default ResourceLocation getFlowingTexture(FluidState state, BlockAndTintGetter getter, BlockPos pos)
{
return this.getFlowingTexture();
}
/**
* Returns the reference of the texture to apply to a fluid directly touching
* a non-opaque block other than air. If no reference is specified, either
* {@code #getStillTexture} or {@code #getFlowingTexture} will be applied
* instead.
*
* <p>This should return a reference to the texture and not the actual
* texture itself (e.g. {@code minecraft:block/water_overlay} will point to
* {@code assets/minecraft/textures/block/water_overlay.png}).
*
* @param state the state of the fluid
* @param getter the getter the fluid can be obtained from
* @param pos the position of the fluid
* @return the reference of the texture to apply to a fluid directly touching
* a non-opaque block
*/
default ResourceLocation getOverlayTexture(FluidState state, BlockAndTintGetter getter, BlockPos pos)
{
return this.getOverlayTexture();
}
/**
* Returns the tint applied to the fluid's textures.
*
* <p>The result represents a 32-bit integer where each 8-bits represent
* the alpha, red, green, and blue channel respectively.
*
* @param state the state of the fluid
* @param getter the getter the fluid can be obtained from
* @param pos the position of the fluid
* @return the tint applied to the fluid's textures in ARGB format
*/
default int getColorTint(FluidState state, BlockAndTintGetter getter, BlockPos pos)
{
return this.getColorTint();
}
/* Stack-Based Accessors */
/**
* Returns the tint applied to the fluid's textures.
*
* <p>The result represents a 32-bit integer where each 8-bits represent
* the alpha, red, green, and blue channel respectively.
*
* @param stack the stack the fluid is in
* @return the tint applied to the fluid's textures in ARGB format
*/
default int getColorTint(FluidStack stack)
{
return this.getColorTint();
}
/**
* Returns the reference of the texture to apply to a source fluid.
*
* <p>This should return a reference to the texture and not the actual
* texture itself (e.g. {@code minecraft:block/water_still} will point to
* {@code assets/minecraft/textures/block/water_still.png}).
*
* <p>Important: This method should only return {@code null} for {@link Fluids#EMPTY}.
* All other implementations must define this property.
*
* @param stack the stack the fluid is in
* @return the reference of the texture to apply to a source fluid
*/
default ResourceLocation getStillTexture(FluidStack stack)
{
return this.getStillTexture();
}
/**
* Returns the reference of the texture to apply to a flowing fluid.
*
* <p>This should return a reference to the texture and not the actual
* texture itself (e.g. {@code minecraft:block/water_flow} will point to
* {@code assets/minecraft/textures/block/water_flow.png}).
*
* <p>Important: This method should only return {@code null} for {@link Fluids#EMPTY}.
* All other implementations must define this property.
*
* @param stack the stack the fluid is in
* @return the reference of the texture to apply to a flowing fluid
*/
default ResourceLocation getFlowingTexture(FluidStack stack)
{
return this.getFlowingTexture();
}
/**
* Returns the reference of the texture to apply to a fluid directly touching
* a non-opaque block other than air. If no reference is specified, either
* {@code #getStillTexture} or {@code #getFlowingTexture} will be applied
* instead.
*
* <p>This should return a reference to the texture and not the actual
* texture itself (e.g. {@code minecraft:block/water_overlay} will point to
* {@code assets/minecraft/textures/block/water_overlay.png}).
*
* @param stack the stack the fluid is in
* @return the reference of the texture to apply to a fluid directly touching
* a non-opaque block
*/
default ResourceLocation getOverlayTexture(FluidStack stack)
{
return this.getOverlayTexture();
}
}
@@ -11,6 +11,9 @@ import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.FluidState;
import net.minecraftforge.fluids.FluidType;
public class RenderProperties
{
@@ -44,6 +47,21 @@ public class RenderProperties
return block.getRenderPropertiesInternal() instanceof IBlockRenderProperties props ? props : IBlockRenderProperties.DUMMY;
}
public static IFluidTypeRenderProperties get(FluidState state)
{
return get(state.getFluidType());
}
public static IFluidTypeRenderProperties get(Fluid fluid)
{
return get(fluid.getFluidType());
}
public static IFluidTypeRenderProperties get(FluidType type)
{
return type.getRenderPropertiesInternal() instanceof IFluidTypeRenderProperties props ? props : IFluidTypeRenderProperties.DUMMY;
}
private RenderProperties()
{
// Not instantiable.
@@ -41,6 +41,7 @@ import net.minecraft.world.level.GameType;
import net.minecraftforge.client.RenderProperties;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType;
import net.minecraftforge.common.ForgeMod;
import net.minecraftforge.common.MinecraftForge;
import org.apache.logging.log4j.LogManager;
@@ -469,7 +470,7 @@ public class ForgeIngameGui extends Gui
int top = height - right_height;
int air = player.getAirSupply();
if (player.isEyeInFluid(FluidTags.WATER) || air < 300)
if (player.isEyeInFluidType(ForgeMod.WATER_TYPE.get()) || air < 300)
{
int full = Mth.ceil((double)(air - 2) * 10.0D / 300.0D);
int partial = Mth.ceil((double)air * 10.0D / 300.0D) - full;
@@ -22,6 +22,7 @@ import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.RenderProperties;
import net.minecraftforge.client.model.geometry.IModelGeometry;
import net.minecraftforge.fluids.FluidUtil;
import net.minecraftforge.registries.ForgeRegistries;
@@ -93,7 +94,7 @@ public final class DynamicBucketModel implements IModelGeometry<DynamicBucketMod
ModelState transformsFromModel = owner.getCombinedTransform();
TextureAtlasSprite fluidSprite = fluid != Fluids.EMPTY ? spriteGetter.apply(ForgeHooksClient.getBlockMaterial(fluid.getAttributes().getStillTexture())) : null;
TextureAtlasSprite fluidSprite = fluid != Fluids.EMPTY ? spriteGetter.apply(ForgeHooksClient.getBlockMaterial(RenderProperties.get(fluid).getStillTexture())) : null;
TextureAtlasSprite coverSprite = (coverLocation != null && (!coverIsMask || baseLocation != null)) ? spriteGetter.apply(coverLocation) : null;
ImmutableMap<TransformType, Transformation> transformMap =
@@ -105,7 +106,7 @@ public final class DynamicBucketModel implements IModelGeometry<DynamicBucketMod
if (particleSprite == null && !coverIsMask) particleSprite = coverSprite;
// if the fluid is lighter than air, will manipulate the initial state to be rotated 180deg to turn it upside down
if (flipGas && fluid != Fluids.EMPTY && fluid.getAttributes().isLighterThanAir())
if (flipGas && fluid != Fluids.EMPTY && fluid.getFluidType().isLighterThanAir())
{
modelTransform = new SimpleModelState(
modelTransform.getRotation().blockCornerToCenter().compose(
@@ -128,8 +129,8 @@ public final class DynamicBucketModel implements IModelGeometry<DynamicBucketMod
if (templateSprite != null)
{
// build liquid layer (inside)
int luminosity = applyFluidLuminosity ? fluid.getAttributes().getLuminosity() : 0;
int color = tint ? fluid.getAttributes().getColor() : 0xFFFFFFFF;
int luminosity = applyFluidLuminosity ? fluid.getFluidType().getLightLevel() : 0;
int color = tint ? RenderProperties.get(fluid).getColorTint() : 0xFFFFFFFF;
builder.addQuads(ItemLayerModel.getLayerRenderType(luminosity > 0), ItemTextureQuadConverter.convertTexture(transform, templateSprite, fluidSprite, NORTH_Z_FLUID, Direction.NORTH, color, 1, luminosity));
builder.addQuads(ItemLayerModel.getLayerRenderType(luminosity > 0), ItemTextureQuadConverter.convertTexture(transform, templateSprite, fluidSprite, SOUTH_Z_FLUID, Direction.SOUTH, color, 1, luminosity));
}
@@ -28,12 +28,13 @@ import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.Mth;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.IFluidTypeRenderProperties;
import net.minecraftforge.client.RenderProperties;
import net.minecraftforge.client.model.data.IModelData;
import net.minecraftforge.client.model.geometry.IModelGeometry;
import net.minecraftforge.client.model.pipeline.BakedQuadBuilder;
import net.minecraftforge.client.model.pipeline.IVertexConsumer;
import net.minecraftforge.client.model.pipeline.TRSRTransformer;
import net.minecraftforge.fluids.FluidAttributes;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
@@ -72,16 +73,16 @@ public final class FluidModel implements IModelGeometry<FluidModel>
@Override
public BakedModel bake(IModelConfiguration owner, ModelBakery bakery, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelTransform, ItemOverrides overrides, ResourceLocation modelLocation)
{
FluidAttributes attrs = fluid.getAttributes();
IFluidTypeRenderProperties props = RenderProperties.get(fluid);
return new CachingBakedFluid(
modelTransform.getRotation(),
PerspectiveMapWrapper.getTransforms(modelTransform),
modelLocation,
attrs.getColor(),
spriteGetter.apply(ForgeHooksClient.getBlockMaterial(attrs.getStillTexture())),
spriteGetter.apply(ForgeHooksClient.getBlockMaterial(attrs.getFlowingTexture())),
Optional.ofNullable(attrs.getOverlayTexture()).map(ForgeHooksClient::getBlockMaterial).map(spriteGetter),
attrs.isLighterThanAir(),
props.getColorTint(),
spriteGetter.apply(ForgeHooksClient.getBlockMaterial(props.getStillTexture())),
spriteGetter.apply(ForgeHooksClient.getBlockMaterial(props.getFlowingTexture())),
Optional.ofNullable(props.getOverlayTexture()).map(ForgeHooksClient::getBlockMaterial).map(spriteGetter),
fluid.getFluidType().isLighterThanAir(),
null
);
}
@@ -51,6 +51,7 @@ import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.gameevent.GameEvent;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.level.storage.WorldData;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootTable;
@@ -139,7 +140,7 @@ import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.event.world.NoteBlockEvent;
import net.minecraftforge.eventbus.api.Event.Result;
import net.minecraftforge.fluids.FluidAttributes;
import net.minecraftforge.fluids.FluidType;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.ModLoader;
@@ -803,30 +804,24 @@ public class ForgeHooks
return ret;
}
public static FluidAttributes createVanillaFluidAttributes(Fluid fluid)
/**
* Returns a vanilla fluid type for the given fluid.
*
* @param fluid the fluid looking for its type
* @return the type of the fluid if vanilla
* @throws RuntimeException if the fluid is not a vanilla one
*/
public static FluidType getVanillaFluidType(Fluid fluid)
{
if (fluid instanceof EmptyFluid)
return net.minecraftforge.fluids.FluidAttributes.builder(null, null)
.translationKey("block.minecraft.air")
.color(0).density(0).temperature(0).luminosity(0).viscosity(0).build(fluid);
if (fluid instanceof WaterFluid)
return net.minecraftforge.fluids.FluidAttributes.Water.builder(
new ResourceLocation("block/water_still"),
new ResourceLocation("block/water_flow"))
.overlay(new ResourceLocation("block/water_overlay"))
.translationKey("block.minecraft.water")
.color(0xFF3F76E4)
.sound(SoundEvents.BUCKET_FILL, SoundEvents.BUCKET_EMPTY)
.build(fluid);
if (fluid instanceof LavaFluid)
return net.minecraftforge.fluids.FluidAttributes.builder(
new ResourceLocation("block/lava_still"),
new ResourceLocation("block/lava_flow"))
.translationKey("block.minecraft.lava")
.luminosity(15).density(3000).viscosity(6000).temperature(1300)
.sound(SoundEvents.BUCKET_FILL_LAVA, SoundEvents.BUCKET_EMPTY_LAVA)
.build(fluid);
throw new RuntimeException("Mod fluids must override createAttributes.");
if (fluid == Fluids.EMPTY)
return ForgeMod.EMPTY_TYPE.get();
if (fluid == Fluids.WATER || fluid == Fluids.FLOWING_WATER)
return ForgeMod.WATER_TYPE.get();
if (fluid == Fluids.LAVA || fluid == Fluids.FLOWING_LAVA)
return ForgeMod.LAVA_TYPE.get();
if (ForgeMod.MILK.filter(milk -> milk == fluid).isPresent() || ForgeMod.FLOWING_MILK.filter(milk -> milk == fluid).isPresent())
return ForgeMod.MILK_TYPE.get();
throw new RuntimeException("Mod fluids must override getFluidType.");
}
public static String getDefaultWorldPreset()
@@ -5,19 +5,30 @@
package net.minecraftforge.common;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BiomeColors;
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
import net.minecraft.commands.synchronization.ArgumentTypeInfos;
import net.minecraft.commands.synchronization.SingletonArgumentInfo;
import net.minecraft.core.BlockPos;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.RangedAttribute;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.item.Items;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.core.Registry;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.pathfinder.BlockPathTypes;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.IFluidTypeRenderProperties;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent;
import net.minecraftforge.common.crafting.PartialNBTIngredient;
@@ -35,7 +46,7 @@ import net.minecraftforge.common.world.NoneBiomeModifier;
import net.minecraftforge.common.world.NoneStructureModifier;
import net.minecraftforge.common.world.StructureModifier;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fluids.FluidAttributes;
import net.minecraftforge.fluids.FluidType;
import net.minecraftforge.fluids.ForgeFlowingFluid;
import net.minecraftforge.fml.*;
import net.minecraftforge.fml.config.ModConfig;
@@ -82,8 +93,10 @@ import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import com.mojang.serialization.Codec;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.function.Consumer;
@Mod("forge")
public class ForgeMod
@@ -133,13 +146,153 @@ public class ForgeMod
* Noop biome modifier. Can be used in a biome modifier json with "type": "forge:none".
*/
public static final RegistryObject<Codec<NoneBiomeModifier>> NONE_BIOME_MODIFIER_TYPE = BIOME_MODIFIER_SERIALIZERS.register("none", () -> Codec.unit(NoneBiomeModifier.INSTANCE));
/**
* Noop structure modifier. Can be used in a structure modifier json with "type": "forge:none".
*/
public static final RegistryObject<Codec<NoneStructureModifier>> NONE_STRUCTURE_MODIFIER_TYPE = STRUCTURE_MODIFIER_SERIALIZERS.register("none", () -> Codec.unit(NoneStructureModifier.INSTANCE));
private static final DeferredRegister<FluidType> VANILLA_FLUID_TYPES = DeferredRegister.create(ForgeRegistries.Keys.FLUID_TYPES, "minecraft");
public static final RegistryObject<FluidType> EMPTY_TYPE = VANILLA_FLUID_TYPES.register("empty", () ->
new FluidType(FluidType.Properties.create()
.descriptionId("block.minecraft.air")
.motionScale(1D)
.canPushEntity(false)
.canSwim(false)
.canDrown(false)
.fallDistanceModifier(1F)
.pathType(null)
.adjacentPathType(null)
.density(0)
.temperature(0)
.viscosity(0))
{
@Override
public void setItemMovement(ItemEntity entity)
{
if (!entity.isNoGravity()) entity.setDeltaMovement(entity.getDeltaMovement().add(0.0D, -0.04D, 0.0D));
}
});
public static final RegistryObject<FluidType> WATER_TYPE = VANILLA_FLUID_TYPES.register("water", () ->
new FluidType(FluidType.Properties.create()
.descriptionId("block.minecraft.water")
.fallDistanceModifier(0F)
.canExtinguish(true)
.canConvertToSource(true)
.supportsBoating(true)
.sound(SoundActions.BUCKET_FILL, SoundEvents.BUCKET_FILL)
.sound(SoundActions.BUCKET_EMPTY, SoundEvents.BUCKET_EMPTY)
.sound(SoundActions.FLUID_VAPORIZE, SoundEvents.FIRE_EXTINGUISH)
.canHydrate(true))
{
@Override
public @Nullable BlockPathTypes getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog)
{
return canFluidLog ? super.getBlockPathType(state, level, pos, mob, true) : null;
}
@Override
public void initializeClient(Consumer<IFluidTypeRenderProperties> consumer)
{
consumer.accept(new IFluidTypeRenderProperties()
{
private static final ResourceLocation UNDERWATER_LOCATION = new ResourceLocation("textures/misc/underwater.png"),
WATER_STILL = new ResourceLocation("block/water_still"),
WATER_FLOW = new ResourceLocation("block/water_flow"),
WATER_OVERLAY = new ResourceLocation("block/water_overlay");
@Override
public ResourceLocation getStillTexture()
{
return WATER_STILL;
}
@Override
public ResourceLocation getFlowingTexture()
{
return WATER_FLOW;
}
@Nullable
@Override
public ResourceLocation getOverlayTexture()
{
return WATER_OVERLAY;
}
@Override
public ResourceLocation getRenderOverlayTexture(Minecraft mc)
{
return UNDERWATER_LOCATION;
}
@Override
public int getColorTint()
{
return 0xFF3F76E4;
}
@Override
public int getColorTint(FluidState state, BlockAndTintGetter getter, BlockPos pos)
{
return BiomeColors.getAverageWaterColor(getter, pos) | 0xFF000000;
}
});
}
});
public static final RegistryObject<FluidType> LAVA_TYPE = VANILLA_FLUID_TYPES.register("lava", () ->
new FluidType(FluidType.Properties.create()
.descriptionId("block.minecraft.lava")
.canSwim(false)
.canDrown(false)
.pathType(BlockPathTypes.LAVA)
.adjacentPathType(null)
.sound(SoundActions.BUCKET_FILL, SoundEvents.BUCKET_FILL_LAVA)
.sound(SoundActions.BUCKET_EMPTY, SoundEvents.BUCKET_EMPTY_LAVA)
.lightLevel(15)
.density(3000)
.viscosity(6000)
.temperature(1300))
{
@Override
public double motionScale(Entity entity)
{
return entity.level.dimensionType().ultraWarm() ? 0.007D : 0.0023333333333333335D;
}
@Override
public void setItemMovement(ItemEntity entity)
{
Vec3 vec3 = entity.getDeltaMovement();
entity.setDeltaMovement(vec3.x * (double)0.95F, vec3.y + (double)(vec3.y < (double)0.06F ? 5.0E-4F : 0.0F), vec3.z * (double)0.95F);
}
@Override
public void initializeClient(Consumer<IFluidTypeRenderProperties> consumer)
{
consumer.accept(new IFluidTypeRenderProperties()
{
private static final ResourceLocation LAVA_STILL = new ResourceLocation("block/lava_still"),
LAVA_FLOW = new ResourceLocation("block/lava_flow");
@Override
public ResourceLocation getStillTexture()
{
return LAVA_STILL;
}
@Override
public ResourceLocation getFlowingTexture()
{
return LAVA_FLOW;
}
});
}
});
private static boolean enableMilkFluid = false;
public static final RegistryObject<FluidType> MILK_TYPE = RegistryObject.createOptional(new ResourceLocation("milk"), ForgeRegistries.Keys.FLUID_TYPES.location(), "minecraft");
public static final RegistryObject<Fluid> MILK = RegistryObject.create(new ResourceLocation("milk"), ForgeRegistries.FLUIDS);
public static final RegistryObject<Fluid> FLOWING_MILK = RegistryObject.create(new ResourceLocation("flowing_milk"), ForgeRegistries.FLUIDS);
@@ -185,6 +338,7 @@ public class ForgeMod
COMMAND_ARGUMENT_TYPES.register(modEventBus);
BIOME_MODIFIER_SERIALIZERS.register(modEventBus);
STRUCTURE_MODIFIER_SERIALIZERS.register(modEventBus);
VANILLA_FLUID_TYPES.register(modEventBus);
MinecraftForge.EVENT_BUS.addListener(this::serverStopping);
MinecraftForge.EVENT_BUS.addListener(this::missingSoundMapping);
ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, ForgeConfig.clientSpec);
@@ -274,14 +428,42 @@ public class ForgeMod
// done in an event instead of deferred to only enable if a mod requests it
public void registerFluids(RegisterEvent event)
{
if (enableMilkFluid && event.getRegistryKey().equals(ForgeRegistries.Keys.FLUIDS))
if (enableMilkFluid)
{
// set up attributes
FluidAttributes.Builder attributesBuilder = FluidAttributes.builder(new ResourceLocation("forge", "block/milk_still"), new ResourceLocation("forge", "block/milk_flowing")).density(1024).viscosity(1024);
ForgeFlowingFluid.Properties properties = new ForgeFlowingFluid.Properties(MILK, FLOWING_MILK, attributesBuilder).bucket(() -> Items.MILK_BUCKET);
// register fluid type
event.register(ForgeRegistries.Keys.FLUID_TYPES, helper -> helper.register(MILK_TYPE.getId(), new FluidType(FluidType.Properties.create().density(1024).viscosity(1024))
{
@Override
public void initializeClient(Consumer<IFluidTypeRenderProperties> consumer)
{
consumer.accept(new IFluidTypeRenderProperties()
{
private static final ResourceLocation MILK_STILL = new ResourceLocation("forge", "block/milk_still"),
MILK_FLOW = new ResourceLocation("forge", "block/milk_flowing");
@Override
public ResourceLocation getStillTexture()
{
return MILK_STILL;
}
@Override
public ResourceLocation getFlowingTexture()
{
return MILK_FLOW;
}
});
}
}));
// register fluids
event.register(ForgeRegistries.Keys.FLUIDS, MILK.getId(), () -> new ForgeFlowingFluid.Source(properties));
event.register(ForgeRegistries.Keys.FLUIDS, FLOWING_MILK.getId(), () -> new ForgeFlowingFluid.Flowing(properties));
event.register(ForgeRegistries.Keys.FLUIDS, helper -> {
// set up properties
ForgeFlowingFluid.Properties properties = new ForgeFlowingFluid.Properties(MILK_TYPE, MILK, FLOWING_MILK).bucket(() -> Items.MILK_BUCKET);
helper.register(MILK.getId(), new ForgeFlowingFluid.Source(properties));
helper.register(FLOWING_MILK.getId(), new ForgeFlowingFluid.Flowing(properties));
});
}
}
@@ -0,0 +1,45 @@
package net.minecraftforge.common;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Defines an action which produces a sound.
*/
@SuppressWarnings("ClassCanBeRecord")
public final class SoundAction
{
private static final Map<String, SoundAction> ACTIONS = new ConcurrentHashMap<>();
/**
* Gets or creates a new {@code SoundAction} for the given name.
*
* @param name the name of the action
* @return the existing {@code SoundAction}, or a new one if not present
*/
public static SoundAction get(String name)
{
return ACTIONS.computeIfAbsent(name, SoundAction::new);
}
private final String name;
private SoundAction(final String name)
{
this.name = name;
}
/**
* Returns the name of the action.
*
* @return the name of the action
*/
public String name() {
return this.name;
}
@Override
public String toString() {
return "SoundAction[" + this.name + "]";
}
}
@@ -0,0 +1,27 @@
package net.minecraftforge.common;
/**
* A utility holding common sound actions.
*/
public final class SoundActions
{
private SoundActions()
{
throw new AssertionError("SoundActions should not be instantiated.");
}
/**
* When a bucket is being filled by a fluid.
*/
public static final SoundAction BUCKET_FILL = SoundAction.get("bucket_fill");
/**
* When a bucket is emptying a fluid.
*/
public static final SoundAction BUCKET_EMPTY = SoundAction.get("bucket_empty");
/**
* When the fluid is being vaporized.
*/
public static final SoundAction FLUID_VAPORIZE = SoundAction.get("fluid_vaporize");
}
@@ -405,7 +405,14 @@ public class Tags
{
private static void init() {}
/**
* Holds all fluids related to milk.
*/
public static final TagKey<Fluid> MILK = tag("milk");
/**
* Holds all fluids that are gaseous at room temperature.
*/
public static final TagKey<Fluid> GASEOUS = tag("gaseous");
private static TagKey<Fluid> tag(String name)
{
@@ -28,6 +28,7 @@ import net.minecraft.world.level.pathfinder.BlockPathTypes;
import net.minecraft.tags.BlockTags;
import net.minecraft.core.Direction;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.pathfinder.WalkNodeEvaluator;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraft.server.level.ServerLevel;
@@ -480,16 +481,43 @@ public interface IForgeBlock
}
/**
* Get the {@code PathNodeType} for this block. Return {@code null} for vanilla behavior.
* Gets the path type of this block when an entity is pathfinding. When
* {@code null}, uses vanilla behavior.
*
* @return the PathNodeType
* @param state the state of the block
* @param level the level which contains this block
* @param pos the position of the block
* @param mob the mob currently pathfinding, may be {@code null}
* @return the path type of this block
*/
@Nullable
default BlockPathTypes getAiPathNodeType(BlockState state, BlockGetter level, BlockPos pos, @Nullable Mob entity)
default BlockPathTypes getBlockPathType(BlockState state, BlockGetter level, BlockPos pos, @Nullable Mob mob)
{
return state.getBlock() == Blocks.LAVA ? BlockPathTypes.LAVA : state.isBurning(level, pos) ? BlockPathTypes.DAMAGE_FIRE : null;
}
/**
* Gets the path type of the adjacent block to a pathfinding entity.
* Path types with a negative malus are not traversable for the entity.
* Pathfinding entities will favor paths consisting of a lower malus.
* When {@code null}, uses vanilla behavior.
*
* @param state the state of the block
* @param level the level which contains this block
* @param pos the position of the block
* @param mob the mob currently pathfinding, may be {@code null}
* @param originalType the path type of the source the entity is on
* @return the path type of this block
*/
@Nullable
default BlockPathTypes getAdjacentBlockPathType(BlockState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, BlockPathTypes originalType)
{
if (state.is(Blocks.CACTUS)) return BlockPathTypes.DANGER_CACTUS;
else if (state.is(Blocks.SWEET_BERRY_BUSH)) return BlockPathTypes.DANGER_OTHER;
else if (WalkNodeEvaluator.isBurningBlock(state)) return BlockPathTypes.DANGER_FIRE;
else return null;
}
/**
* @param state The state
* @return true if the block is sticky block which used for pull or push adjacent blocks (use by piston)
@@ -816,4 +844,26 @@ public interface IForgeBlock
}
return true;
}
/**
* Returns whether the block can be hydrated by a fluid.
*
* <p>Hydration is an arbitrary word which depends on the block.
* <ul>
* <li>A farmland has moisture</li>
* <li>A sponge can soak up the liquid</li>
* <li>A coral can live</li>
* </ul>
*
* @param state the state of the block being hydrated
* @param getter the getter which can get the block
* @param pos the position of the block being hydrated
* @param fluid the state of the fluid
* @param fluidPos the position of the fluid
* @return {@code true} if the block can be hydrated, {@code false} otherwise
*/
default boolean canBeHydrated(BlockState state, BlockGetter getter, BlockPos pos, FluidState fluid, BlockPos fluidPos)
{
return fluid.canHydrate(getter, fluidPos, state, pos);
}
}
@@ -541,25 +541,36 @@ public interface IForgeBlockState
}
/**
* Get the {@code BlockPathTypes} for this block. Return {@code null} for vanilla behavior.
* Gets the path type of this block when an entity is pathfinding. When
* {@code null}, uses vanilla behavior.
*
* @return the PathNodeType
*/
@Nullable
default BlockPathTypes getBlockPathType(BlockGetter level, BlockPos pos)
{
return getBlockPathType(level, pos, null);
}
/**
* Get the {@code PathNodeType} for this block. Return {@code null} for vanilla behavior.
*
* @return the PathNodeType
* @param level the level which contains this block
* @param pos the position of the block
* @param mob the mob currently pathfinding, may be {@code null}
* @return the path type of this block
*/
@Nullable
default BlockPathTypes getBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob)
{
return self().getBlock().getAiPathNodeType(self(), level, pos, mob);
return self().getBlock().getBlockPathType(self(), level, pos, mob);
}
/**
* Gets the path type of the adjacent block to a pathfinding entity.
* Path types with a negative malus are not traversable for the entity.
* Pathfinding entities will favor paths consisting of a lower malus.
* When {@code null}, uses vanilla behavior.
*
* @param level the level which contains this block
* @param pos the position of the block
* @param mob the mob currently pathfinding, may be {@code null}
* @param originalType the path type of the source the entity is on
* @return the path type of this block
*/
@Nullable
default BlockPathTypes getAdjacentBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob, BlockPathTypes originalType)
{
return self().getBlock().getAdjacentBlockPathType(self(), level, pos, mob, originalType);
}
/**
@@ -676,4 +687,25 @@ public interface IForgeBlockState
{
return self().getBlock().supportsExternalFaceHiding(self());
}
/**
* Returns whether the block can be hydrated by a fluid.
*
* <p>Hydration is an arbitrary word which depends on the block.
* <ul>
* <li>A farmland has moisture</li>
* <li>A sponge can soak up the liquid</li>
* <li>A coral can live</li>
* </ul>
*
* @param getter the getter which can get the block
* @param pos the position of the block being hydrated
* @param fluid the state of the fluid
* @param fluidPos the position of the fluid
* @return {@code true} if the block can be hydrated, {@code false} otherwise
*/
default boolean canBeHydrated(BlockGetter getter, BlockPos pos, FluidState fluid, BlockPos fluidPos)
{
return self().getBlock().canBeHydrated(self(), getter, pos, fluid, fluidPos);
}
}
@@ -0,0 +1,35 @@
package net.minecraftforge.common.extensions;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.level.material.FluidState;
import net.minecraftforge.fluids.FluidType;
public interface IForgeBoat
{
private Boat self()
{
return (Boat) this;
}
/**
* Returns whether the boat can be used on the fluid.
*
* @param state the state of the fluid
* @return {@code true} if the boat can be used, {@code false} otherwise
*/
default boolean canBoatInFluid(FluidState state)
{
return state.supportsBoating(self());
}
/**
* Returns whether the boat can be used on the fluid.
*
* @param type the type of the fluid
* @return {@code true} if the boat can be used, {@code false} otherwise
*/
default boolean canBoatInFluid(FluidType type)
{
return type.supportsBoating(self());
}
}
@@ -6,7 +6,9 @@
package net.minecraftforge.common.extensions;
import java.util.Collection;
import java.util.function.BiPredicate;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.boss.enderdragon.EnderDragon;
@@ -19,11 +21,14 @@ import net.minecraft.world.item.SpawnEggItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.phys.HitResult;
import net.minecraftforge.common.ForgeMod;
import net.minecraftforge.common.ForgeSpawnEggItem;
import net.minecraftforge.common.SoundAction;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.entity.PartEntity;
import net.minecraftforge.fluids.FluidType;
import org.jetbrains.annotations.Nullable;
public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
@@ -101,14 +106,16 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
}
/**
* Checks if this entity can continue to be ridden while it is underwater.
* Returns whether the entity can ride in this vehicle under the fluid.
*
* @param rider The entity that is riding this entity
* @return {@code true} if the entity can continue to ride underwater. {@code false} otherwise.
* @param type the type of the fluid
* @param rider the entity riding the vehicle
* @return {@code true} if the vehicle can be ridden in under this fluid,
* {@code false} otherwise
*/
default boolean canBeRiddenInWater(Entity rider)
default boolean canBeRiddenUnderFluidType(FluidType type, Entity rider)
{
return self().rideableUnderWater();
return type.canRideVehicleUnder(self(), rider);
}
/**
@@ -212,4 +219,195 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
}
return vanillaStep;
}
/**
* Returns the height of the fluid type in relation to the bounding box of
* the entity. If the entity is not in the fluid type, then {@code 0}
* is returned.
*
* @param type the type of the fluid
* @return the height of the fluid compared to the entity
*/
double getFluidTypeHeight(FluidType type);
/**
* Returns the fluid type which is the highest on the bounding box of
* the entity.
*
* @return the fluid type which is the highest on the bounding box of
* the entity
*/
FluidType getMaxHeightFluidType();
/**
* Returns whether the entity is within the fluid type of the state.
*
* @param state the state of the fluid
* @return {@code true} if the entity is within the fluid type of the
* state, {@code false} otherwise
*/
default boolean isInFluidType(FluidState state)
{
return this.isInFluidType(state.getFluidType());
}
/**
* Returns whether the entity is within the fluid type.
*
* @param type the type of the fluid
* @return {@code true} if the entity is within the fluid type,
* {@code false} otherwise
*/
default boolean isInFluidType(FluidType type)
{
return this.getFluidTypeHeight(type) > 0.0D;
}
/**
* Returns whether any fluid type the entity is currently in matches
* the specified condition.
*
* @param predicate a test taking in the fluid type and its height
* @return {@code true} if a fluid type meets the condition, {@code false}
* otherwise
*/
default boolean isInFluidType(BiPredicate<FluidType, Double> predicate)
{
return isInFluidType(predicate, false);
}
/**
* Returns whether the fluid type the entity is currently in matches
* the specified condition.
*
* @param predicate a test taking in the fluid type and its height
* @param forAllTypes {@code true} if all fluid types should match the
* condition instead of at least one
* @return {@code true} if a fluid type meets the condition, {@code false}
* otherwise
*/
boolean isInFluidType(BiPredicate<FluidType, Double> predicate, boolean forAllTypes);
/**
* Returns whether the entity is in a fluid.
*
* @return {@code true} if the entity is in a fluid, {@code false} otherwise
*/
boolean isInFluidType();
/**
* Returns the fluid that is on the entity's eyes.
*
* @return the fluid that is on the entity's eyes
*/
FluidType getEyeInFluidType();
/**
* Returns whether the fluid is on the entity's eyes.
*
* @return {@code true} if the fluid is on the entity's eyes, {@code false} otherwise
*/
default boolean isEyeInFluidType(FluidType type)
{
return type == this.getEyeInFluidType();
}
/**
* Returns whether the entity can start swimming in the fluid.
*
* @return {@code true} if the entity can start swimming, {@code false} otherwise
*/
default boolean canStartSwimming()
{
return !this.getEyeInFluidType().isAir() && this.canSwimInFluidType(this.getEyeInFluidType());
}
/**
* Returns how much the velocity of the fluid should be scaled by
* when applied to an entity.
*
* @param type the type of the fluid
* @return a scalar to multiply to the fluid velocity
*/
default double getFluidMotionScale(FluidType type)
{
return type.motionScale(self());
}
/**
* Returns whether the fluid can push an entity.
*
* @param type the type of the fluid
* @return {@code true} if the entity can be pushed by the fluid, {@code false} otherwise
*/
default boolean isPushedByFluid(FluidType type)
{
return self().isPushedByFluid() && type.canPushEntity(self());
}
/**
* Returns whether the entity can swim in the fluid.
*
* @param type the type of the fluid
* @return {@code true} if the entity can swim in the fluid, {@code false} otherwise
*/
default boolean canSwimInFluidType(FluidType type)
{
return type.canSwim(self());
}
/**
* Returns whether the entity can be extinguished by this fluid.
*
* @param type the type of the fluid
* @return {@code true} if the entity can be extinguished, {@code false} otherwise
*/
default boolean canFluidExtinguish(FluidType type)
{
return type.canExtinguish(self());
}
/**
* Returns how much the fluid should scale the damage done to a falling
* entity when hitting the ground per tick.
*
* <p>Implementation: If the entity is in many fluids, the smallest modifier
* is applied.
*
* @param type the type of the fluid
* @return a scalar to multiply to the fall damage
*/
default float getFluidFallDistanceModifier(FluidType type)
{
return type.getFallDistanceModifier(self());
}
/**
* Returns whether the entity can be hydrated by this fluid.
*
* <p>Hydration is an arbitrary word which depends on the entity.
*
* @param type the type of the fluid
* @return {@code true} if the entity can be hydrated, {@code false}
* otherwise
*/
default boolean canHydrateInFluidType(FluidType type)
{
return type.canHydrate(self());
}
/**
* Returns a sound to play when a certain action is performed by the
* entity in the fluid. If no sound is present, then the sound will be
* {@code null}.
*
* @param type the type of the fluid
* @param action the action being performed
* @return the sound to play when performing the action
*/
@Nullable
default SoundEvent getSoundFromFluidType(FluidType type, SoundAction action)
{
return type.getSound(self(), action);
}
}
@@ -5,74 +5,36 @@
package net.minecraftforge.common.extensions;
import net.minecraft.core.HolderSet;
import net.minecraft.world.level.material.Material;
import net.minecraft.world.entity.Entity;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.phys.AABB;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.LevelReader;
import net.minecraftforge.fluids.FluidAttributes;
import net.minecraft.world.level.pathfinder.BlockPathTypes;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.fluids.FluidType;
import org.jetbrains.annotations.Nullable;
public interface IForgeFluid
{
/**
* Called when the entity is inside this block, may be used to determined if the entity can breathing,
* display material overlays, or if the entity can swim inside a block.
*
* @param level that is being tested.
* @param pos position thats being tested.
* @param entity that is being tested.
* @param yToTest, primarily for testingHead, which sends the the eye level of the entity, other wise it sends a y that can be tested vs liquid height.
* @param tag Fluid category
* @param testingHead when true, its testing the entities head for vision, breathing ect... otherwise its testing the body, for swimming and movement adjustment.
*/
default boolean isEntityInside(FluidState state, LevelReader level, BlockPos pos, Entity entity, double yToTest, HolderSet<Fluid> tag, boolean testingHead)
private Fluid self()
{
return state.is(tag) && yToTest < (double)(pos.getY() + state.getHeight(level, pos) + 0.11111111F);
return (Fluid) this;
}
/**
* Called when boats or fishing hooks are inside the block to check if they are inside
* the material requested.
* Returns the explosion resistance of the fluid.
*
* @param level level that is being tested.
* @param pos block thats being tested.
* @param boundingBox box to test, generally the bounds of an entity that are besting tested.
* @param materialIn to check for.
* @return null for default behavior, true if the box is within the material, false if it was not.
*/
@Nullable
default Boolean isAABBInsideMaterial(FluidState state, LevelReader level, BlockPos pos, AABB boundingBox, Material materialIn)
{
return null;
}
/**
* Called when entities are moving to check if they are inside a liquid
*
* @param level level that is being tested.
* @param pos block thats being tested.
* @param boundingBox box to test, generally the bounds of an entity that are besting tested.
* @return null for default behavior, true if the box is within the material, false if it was not.
*/
@Nullable
default Boolean isAABBInsideLiquid(FluidState state, LevelReader level, BlockPos pos, AABB boundingBox)
{
return null;
}
/**
* Location sensitive version of getExplosionResistance
*
* @param level The current level
* @param pos Block position in level
* @param explosion The explosion
* @return The amount of the explosion absorbed.
* @param state the state of the fluid
* @param level the level the fluid is in
* @param pos the position of the fluid
* @param explosion the explosion the fluid is absorbing
* @return the amount of the explosion the fluid can absorb
*/
@SuppressWarnings("deprecation")
default float getExplosionResistance(FluidState state, BlockGetter level, BlockPos pos, Explosion explosion)
@@ -81,17 +43,125 @@ public interface IForgeFluid
}
/**
* Queries if this fluid should render in a given layer.
* A custom {@link IBakedModel} can use {@link net.minecraftforge.client.MinecraftForgeClient#getRenderType()} to alter the model based on layer.
* Returns the type of this fluid.
*
* <p>Important: This MUST be overridden on your fluid, otherwise an
* error will be thrown.
*
* @return the type of this fluid
*/
/* TODO: reimplement
default boolean canRenderInLayer(IFluidState state, BlockRenderLayer layer)
{
return this.getFluid().getRenderLayer() == layer;
}*/
FluidType getFluidType();
/**
* Retrieves the non-vanilla fluid attributes, including localized name.
* Performs how an entity moves when within the fluid. If using custom
* movement logic, the method should return {@code true}. Otherwise, the
* movement logic will default to water.
*
* @param state the state of the fluid
* @param entity the entity moving within the fluid
* @param movementVector the velocity of how the entity wants to move
* @param gravity the gravity to apply to the entity
* @return {@code true} if custom movement logic is performed, {@code false} otherwise
*/
FluidAttributes getAttributes();
default boolean move(FluidState state, LivingEntity entity, Vec3 movementVector, double gravity)
{
return getFluidType().move(state, entity, movementVector, gravity);
}
/**
* Returns whether the fluid can create a source.
*
* @param state the state of the fluid
* @param reader the reader that can get the fluid
* @param pos the location of the fluid
* @return {@code true} if the fluid can create a source, {@code false} otherwise
*/
default boolean canConvertToSource(FluidState state, LevelReader reader, BlockPos pos)
{
return getFluidType().canConvertToSource(state, reader, pos);
}
/**
* Returns whether the boat can be used on the fluid.
*
* @param state the state of the fluid
* @param boat the boat trying to be used on the fluid
* @return {@code true} if the boat can be used, {@code false} otherwise
*/
default boolean supportsBoating(FluidState state, Boat boat)
{
return getFluidType().supportsBoating(state, boat);
}
/**
* Gets the path type of this fluid when an entity is pathfinding. When
* {@code null}, uses vanilla behavior.
*
* @param state the state of the fluid
* @param level the level which contains this fluid
* @param pos the position of the fluid
* @param mob the mob currently pathfinding, may be {@code null}
* @param canFluidLog {@code true} if the path is being applied for fluids that can log blocks,
* should be checked against if the fluid can log a block
* @return the path type of this fluid
*/
@Nullable
default BlockPathTypes getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @org.jetbrains.annotations.Nullable Mob mob, boolean canFluidLog)
{
return getFluidType().getBlockPathType(state, level, pos, mob, canFluidLog);
}
/**
* Gets the path type of the adjacent fluid to a pathfinding entity.
* Path types with a negative malus are not traversable for the entity.
* Pathfinding entities will favor paths consisting of a lower malus.
* When {@code null}, uses vanilla behavior.
*
* @param state the state of the fluid
* @param level the level which contains this fluid
* @param pos the position of the fluid
* @param mob the mob currently pathfinding, may be {@code null}
* @param originalType the path type of the source the entity is on
* @return the path type of this fluid
*/
@Nullable
default BlockPathTypes getAdjacentBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @org.jetbrains.annotations.Nullable Mob mob, BlockPathTypes originalType)
{
return getFluidType().getAdjacentBlockPathType(state, level, pos, mob, originalType);
}
/**
* Returns whether the block can be hydrated by a fluid.
*
* <p>Hydration is an arbitrary word which depends on the block.
* <ul>
* <li>A farmland has moisture</li>
* <li>A sponge can soak up the liquid</li>
* <li>A coral can live</li>
* </ul>
*
* @param state the state of the fluid
* @param getter the getter which can get the fluid
* @param pos the position of the fluid
* @param source the state of the block being hydrated
* @param sourcePos the position of the block being hydrated
* @return {@code true} if the block can be hydrated, {@code false} otherwise
*/
default boolean canHydrate(FluidState state, BlockGetter getter, BlockPos pos, BlockState source, BlockPos sourcePos)
{
return getFluidType().canHydrate(state, getter, pos, source, sourcePos);
}
/**
* Returns whether the block can be extinguished by this fluid.
*
* @param state the state of the fluid
* @param getter the getter which can get the fluid
* @param pos the position of the fluid
* @return {@code true} if the block can be extinguished, {@code false} otherwise
*/
default boolean canExtinguish(FluidState state, BlockGetter getter, BlockPos pos)
{
return getFluidType().canExtinguish(state, getter, pos);
}
}
@@ -5,50 +5,153 @@
package net.minecraftforge.common.extensions;
import net.minecraft.core.HolderSet;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.pathfinder.BlockPathTypes;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.fluids.FluidType;
import org.jetbrains.annotations.Nullable;
public interface IForgeFluidState
{
private FluidState self()
{
return (FluidState)this;
return (FluidState) this;
}
/**
* Called when the entity is inside this block, may be used to determined if the entity can breathing,
* display material overlays, or if the entity can swim inside a block.
* Returns the explosion resistance of the fluid.
*
* @param level that is being tested.
* @param pos position thats being tested.
* @param entity that is being tested.
* @param yToTest, primarily for testingHead, which sends the the eye level of the entity, other wise it sends a y that can be tested vs liquid height.
* @param tag to test for.
* @param testingHead when true, its testing the entities head for vision, breathing ect... otherwise its testing the body, for swimming and movement adjustment.
*/
default boolean isEntityInside(LevelReader level, BlockPos pos, Entity entity, double yToTest, HolderSet<Fluid> tag, boolean testingHead)
{
// return ifluidstate.isTagged(p_213290_1_) && d0 < (double)((float)blockpos.getY() + ifluidstate.getActualHeight(this.level, blockpos) + 0.11111111F);
return self().getType().isEntityInside(self(), level, pos, entity, yToTest, tag, testingHead);
}
/**
* Location sensitive version of getExplosionResistance
*
* @param level The current level
* @param pos Block position in level
* @param explosion The explosion
* @return The amount of the explosion absorbed.
* @param level the level the fluid is in
* @param pos the position of the fluid
* @param explosion the explosion the fluid is absorbing
* @return the amount of the explosion the fluid can absorb
*/
default float getExplosionResistance(BlockGetter level, BlockPos pos, Explosion explosion)
{
return self().getType().getExplosionResistance(self(), level, pos, explosion);
}
/**
* Returns the type of this fluid.
*
* @return the type of this fluid
*/
default FluidType getFluidType()
{
return self().getType().getFluidType();
}
/**
* Performs how an entity moves when within the fluid. If using custom
* movement logic, the method should return {@code true}. Otherwise, the
* movement logic will default to water.
*
* @param entity the entity moving within the fluid
* @param movementVector the velocity of how the entity wants to move
* @param gravity the gravity to apply to the entity
* @return {@code true} if custom movement logic is performed, {@code false} otherwise
*/
default boolean move(LivingEntity entity, Vec3 movementVector, double gravity)
{
return self().getType().move(self(), entity, movementVector, gravity);
}
/**
* Returns whether the fluid can create a source.
*
* @param reader the reader that can get the fluid
* @param pos the location of the fluid
* @return {@code true} if the fluid can create a source, {@code false} otherwise
*/
default boolean canConvertToSource(LevelReader reader, BlockPos pos)
{
return self().getType().canConvertToSource(self(), reader, pos);
}
/**
* Returns whether the boat can be used on the fluid.
*
* @param boat the boat trying to be used on the fluid
* @return {@code true} if the boat can be used, {@code false} otherwise
*/
default boolean supportsBoating(Boat boat)
{
return self().getType().supportsBoating(self(), boat);
}
/**
* Gets the path type of this fluid when an entity is pathfinding. When
* {@code null}, uses vanilla behavior.
*
* @param level the level which contains this fluid
* @param pos the position of the fluid
* @param mob the mob currently pathfinding, may be {@code null}
* @param canFluidLog {@code true} if the path is being applied for fluids that can log blocks,
* should be checked against if the fluid can log a block
* @return the path type of this fluid
*/
@Nullable
default BlockPathTypes getBlockPathType(BlockGetter level, BlockPos pos, @org.jetbrains.annotations.Nullable Mob mob, boolean canFluidLog)
{
return self().getType().getBlockPathType(self(), level, pos, mob, canFluidLog);
}
/**
* Gets the path type of the adjacent fluid to a pathfinding entity.
* Path types with a negative malus are not traversable for the entity.
* Pathfinding entities will favor paths consisting of a lower malus.
* When {@code null}, uses vanilla behavior.
*
* @param level the level which contains this fluid
* @param pos the position of the fluid
* @param mob the mob currently pathfinding, may be {@code null}
* @param originalType the path type of the source the entity is on
* @return the path type of this fluid
*/
@Nullable
default BlockPathTypes getAdjacentBlockPathType(BlockGetter level, BlockPos pos, @org.jetbrains.annotations.Nullable Mob mob, BlockPathTypes originalType)
{
return self().getType().getAdjacentBlockPathType(self(), level, pos, mob, originalType);
}
/**
* Returns whether the block can be hydrated by a fluid.
*
* <p>Hydration is an arbitrary word which depends on the block.
* <ul>
* <li>A farmland has moisture</li>
* <li>A sponge can soak up the liquid</li>
* <li>A coral can live</li>
* </ul>
*
* @param getter the getter which can get the fluid
* @param pos the position of the fluid
* @param source the state of the block being hydrated
* @param sourcePos the position of the block being hydrated
* @return {@code true} if the block can be hydrated, {@code false} otherwise
*/
default boolean canHydrate(BlockGetter getter, BlockPos pos, BlockState source, BlockPos sourcePos)
{
return self().getType().canHydrate(self(), getter, pos, source, sourcePos);
}
/**
* Returns whether the block can be extinguished by this fluid.
*
* @param getter the getter which can get the fluid
* @param pos the position of the fluid
* @return {@code true} if the block can be extinguished, {@code false} otherwise
*/
default boolean canExtinguish(BlockGetter getter, BlockPos pos)
{
return self().getType().canExtinguish(self(), getter, pos);
}
}
@@ -0,0 +1,69 @@
package net.minecraftforge.common.extensions;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.common.ForgeMod;
import net.minecraftforge.fluids.FluidType;
public interface IForgeLivingEntity extends IForgeEntity
{
default LivingEntity self()
{
return (LivingEntity) this;
}
@Override
default boolean canSwimInFluidType(FluidType type)
{
if (type == ForgeMod.WATER_TYPE.get()) return !self().isSensitiveToWater();
else return IForgeEntity.super.canSwimInFluidType(type);
}
/**
* Performs what to do when an entity attempts to go up or "jump" in a fluid.
*
* @param type the type of the fluid
*/
default void jumpInFluid(FluidType type)
{
self().setDeltaMovement(self().getDeltaMovement().add(0.0D, (double)0.04F * self().getAttributeValue(ForgeMod.SWIM_SPEED.get()), 0.0D));
}
/**
* Performs what to do when an entity attempts to go down or "sink" in a fluid.
*
* @param type the type of the fluid
*/
default void sinkInFluid(FluidType type)
{
self().setDeltaMovement(self().getDeltaMovement().add(0.0D, (double)-0.04F * self().getAttributeValue(ForgeMod.SWIM_SPEED.get()), 0.0D));
}
/**
* Returns whether the entity can drown in the fluid.
*
* @param type the type of the fluid
* @return {@code true} if the entity can drown in the fluid, {@code false} otherwise
*/
default boolean canDrownInFluidType(FluidType type)
{
if (type == ForgeMod.WATER_TYPE.get()) return !self().canBreatheUnderwater();
return type.canDrownIn(self());
}
/**
* Performs how an entity moves when within the fluid. If using custom
* movement logic, the method should return {@code true}. Otherwise, the
* movement logic will default to water.
*
* @param state the state of the fluid
* @param movementVector the velocity of how the entity wants to move
* @param gravity the gravity to apply to the entity
* @return {@code true} if custom movement logic is performed, {@code false} otherwise
*/
default boolean moveInFluid(FluidState state, Vec3 movementVector, double gravity)
{
return state.move(self(), movementVector, gravity);
}
}
@@ -94,7 +94,7 @@ public class DispenseFluidContainer extends DefaultDispenseItemBehavior
return super.execute(source, stack);
}
FluidStack fluidStack = fluidHandler.drain(FluidAttributes.BUCKET_VOLUME, IFluidHandler.FluidAction.EXECUTE);
FluidStack fluidStack = fluidHandler.drain(FluidType.BUCKET_VOLUME, IFluidHandler.FluidAction.EXECUTE);
Direction dispenserFacing = source.getBlockState().getValue(DispenserBlock.FACING);
BlockPos blockpos = source.getPos().relative(dispenserFacing);
FluidActionResult result = FluidUtil.tryPlaceFluid(null, source.getLevel(), InteractionHand.MAIN_HAND, blockpos, stack, fluidStack);
@@ -1,446 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.fluids;
import net.minecraft.world.item.BucketItem;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.item.ItemStack;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.network.chat.Component;
import net.minecraft.world.level.BlockAndTintGetter;
import java.util.function.BiFunction;
import java.util.stream.Stream;
import net.minecraft.world.entity.player.Player;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.item.Rarity;
import net.minecraft.client.renderer.BiomeColors;
import net.minecraft.Util;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraftforge.registries.ForgeRegistries;
import org.jetbrains.annotations.Nullable;
/**
* Minecraft Forge Fluid Implementation
*
* This class is a fluid (liquid or gas) equivalent to "Item." It describes the nature of a fluid
* and contains its general properties.
*
* These properties do not have inherent gameplay mechanics - they are provided so that mods may
* choose to take advantage of them.
*
* Fluid implementations are not required to actively use these properties, nor are objects
* interfacing with fluids required to make use of them, but it is encouraged.
*
* The default values can be used as a reference point for mods adding fluids such as oil or heavy
* water.
*
*/
public class FluidAttributes
{
public static final int BUCKET_VOLUME = 1000;
private String translationKey;
private final ResourceLocation stillTexture;
private final ResourceLocation flowingTexture;
@Nullable
private final ResourceLocation overlayTexture;
private final SoundEvent fillSound;
private final SoundEvent emptySound;
/**
* The light level emitted by this fluid.
*
* Default value is 0, as most fluids do not actively emit light.
*/
private final int luminosity;
/**
* Density of the fluid - completely arbitrary; negative density indicates that the fluid is
* lighter than air.
*
* Default value is approximately the real-life density of water in kg/m^3.
*/
private final int density;
/**
* Temperature of the fluid - completely arbitrary; higher temperature indicates that the fluid is
* hotter than air.
*
* Default value is approximately the real-life room temperature of water in degrees Kelvin.
*/
private final int temperature;
/**
* Viscosity ("thickness") of the fluid - completely arbitrary; negative values are not
* permissible.
*
* Default value is approximately the real-life density of water in m/s^2 (x10^-3).
*
* Higher viscosity means that a fluid flows more slowly, like molasses.
* Lower viscosity means that a fluid flows more quickly, like helium.
*
*/
private final int viscosity;
/**
* This indicates if the fluid is gaseous.
*
* Generally this is associated with negative density fluids.
*/
private final boolean isGaseous;
/**
* The rarity of the fluid.
*
* Used primarily in tool tips.
*/
private final Rarity rarity;
/**
* Color used by universal bucket and the ModelFluid baked model.
* Note that this int includes the alpha so converting this to RGB with alpha would be
* float r = ((color >> 16) & 0xFF) / 255f; // red
* float g = ((color >> 8) & 0xFF) / 255f; // green
* float b = ((color >> 0) & 0xFF) / 255f; // blue
* float a = ((color >> 24) & 0xFF) / 255f; // alpha
*/
private final int color;
protected FluidAttributes(Builder builder, Fluid fluid)
{
this.translationKey = builder.translationKey != null ? builder.translationKey : Util.makeDescriptionId("fluid", ForgeRegistries.FLUIDS.getKey(fluid));
this.stillTexture = builder.stillTexture;
this.flowingTexture = builder.flowingTexture;
this.overlayTexture = builder.overlayTexture;
this.color = builder.color;
this.fillSound = builder.fillSound;
this.emptySound = builder.emptySound;
this.luminosity = builder.luminosity;
this.temperature = builder.temperature;
this.viscosity = builder.viscosity;
this.density = builder.density;
this.isGaseous = builder.isGaseous;
this.rarity = builder.rarity;
}
public ItemStack getBucket(FluidStack stack)
{
return new ItemStack(stack.getFluid().getBucket());
}
public BlockState getBlock(BlockAndTintGetter reader, BlockPos pos, FluidState state)
{
return state.createLegacyBlock();
}
public FluidState getStateForPlacement(BlockAndTintGetter reader, BlockPos pos, FluidStack state)
{
return state.getFluid().defaultFluidState();
}
public final boolean canBePlacedInWorld(BlockAndTintGetter reader, BlockPos pos, FluidState state)
{
return !getBlock(reader, pos, state).isAir();
}
public final boolean canBePlacedInWorld(BlockAndTintGetter reader, BlockPos pos, FluidStack state)
{
return !getBlock(reader, pos, getStateForPlacement(reader, pos, state)).isAir();
}
public final boolean isLighterThanAir()
{
return this.density <= 0;
}
/**
* Determines if this fluid should vaporize in dimensions where water vaporizes when placed.
* To preserve the intentions of vanilla, fluids that can turn lava into obsidian should vaporize.
* This prevents players from making the nether safe with a single bucket.
* Based on {@link BucketItem#emptyContents(Player, Level, BlockPos, BlockHitResult)}
*
* @param fluidStack The fluidStack is trying to be placed.
* @return true if this fluid should vaporize in dimensions where water vaporizes when placed.
*/
public boolean doesVaporize(BlockAndTintGetter reader, BlockPos pos, FluidStack fluidStack)
{
BlockState blockstate = getBlock(reader, pos, getStateForPlacement(reader, pos, fluidStack));
if (blockstate == null)
return false;
return blockstate.getMaterial() == net.minecraft.world.level.material.Material.WATER;
}
/**
* Called instead of placing the fluid block if {@link DimensionType#ultraWarm()} and {@link #doesVaporize(BlockAndTintGetter, BlockPos, FluidStack)} are true.
* Override this to make your explosive liquid blow up instead of the default smoke, etc.
* Based on {@link BucketItem#emptyContents(Player, Level, BlockPos, BlockHitResult)}
*
* @param player Player who tried to place the fluid. May be null for blocks like dispensers.
* @param worldIn World to vaporize the fluid in.
* @param pos The position in the world the fluid block was going to be placed.
* @param fluidStack The fluidStack that was going to be placed.
*/
public void vaporize(@Nullable Player player, Level worldIn, BlockPos pos, FluidStack fluidStack)
{
worldIn.playSound(player, pos, SoundEvents.FIRE_EXTINGUISH, SoundSource.BLOCKS, 0.5F, 2.6F + (worldIn.random.nextFloat() - worldIn.random.nextFloat()) * 0.8F);
for (int l = 0; l < 8; ++l)
{
worldIn.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);
}
}
/**
* Returns the localized name of this fluid.
*/
public Component getDisplayName(FluidStack stack)
{
return Component.translatable(getTranslationKey(stack));
}
/**
* A FluidStack sensitive version of getTranslationKey
*/
public String getTranslationKey(FluidStack stack)
{
return this.getTranslationKey();
}
/**
* Returns the translation key of this fluid.
*/
public String getTranslationKey()
{
return this.translationKey;
}
/* Default Accessors */
public final int getLuminosity()
{
return this.luminosity;
}
public final int getDensity()
{
return this.density;
}
public final int getTemperature()
{
return this.temperature;
}
public final int getViscosity()
{
return this.viscosity;
}
public final boolean isGaseous()
{
return this.isGaseous;
}
public Rarity getRarity()
{
return rarity;
}
public int getColor()
{
return color;
}
public ResourceLocation getStillTexture()
{
return stillTexture;
}
public ResourceLocation getFlowingTexture()
{
return flowingTexture;
}
@Nullable
public ResourceLocation getOverlayTexture()
{
return overlayTexture;
}
public SoundEvent getFillSound()
{
return fillSound;
}
public SoundEvent getEmptySound()
{
return emptySound;
}
/* Stack-based Accessors */
public int getLuminosity(FluidStack stack){ return getLuminosity(); }
public int getDensity(FluidStack stack){ return getDensity(); }
public int getTemperature(FluidStack stack){ return getTemperature(); }
public int getViscosity(FluidStack stack){ return getViscosity(); }
public boolean isGaseous(FluidStack stack){ return isGaseous(); }
public Rarity getRarity(FluidStack stack){ return getRarity(); }
public int getColor(FluidStack stack){ return getColor(); }
public ResourceLocation getStillTexture(FluidStack stack) { return getStillTexture(); }
public ResourceLocation getFlowingTexture(FluidStack stack) { return getFlowingTexture(); }
public SoundEvent getFillSound(FluidStack stack) { return getFillSound(); }
public SoundEvent getEmptySound(FluidStack stack) { return getEmptySound(); }
/* World-based Accessors */
public int getLuminosity(BlockAndTintGetter level, BlockPos pos){ return getLuminosity(); }
public int getDensity(BlockAndTintGetter level, BlockPos pos){ return getDensity(); }
public int getTemperature(BlockAndTintGetter level, BlockPos pos){ return getTemperature(); }
public int getViscosity(BlockAndTintGetter level, BlockPos pos){ return getViscosity(); }
public boolean isGaseous(BlockAndTintGetter level, BlockPos pos){ return isGaseous(); }
public Rarity getRarity(BlockAndTintGetter level, BlockPos pos){ return getRarity(); }
public int getColor(BlockAndTintGetter level, BlockPos pos){ return getColor(); }
public ResourceLocation getStillTexture(BlockAndTintGetter level, BlockPos pos) { return getStillTexture(); }
public ResourceLocation getFlowingTexture(BlockAndTintGetter level, BlockPos pos) { return getFlowingTexture(); }
public SoundEvent getFillSound(BlockAndTintGetter level, BlockPos pos) { return getFillSound(); }
public SoundEvent getEmptySound(BlockAndTintGetter level, BlockPos pos) { return getEmptySound(); }
public static Builder builder(ResourceLocation stillTexture, ResourceLocation flowingTexture) {
return new Builder(stillTexture, flowingTexture, FluidAttributes::new);
}
public Stream<ResourceLocation> getTextures()
{
if (overlayTexture != null)
return Stream.of(stillTexture, flowingTexture, overlayTexture);
return Stream.of(stillTexture, flowingTexture);
}
public static class Builder
{
private final ResourceLocation stillTexture;
private final ResourceLocation flowingTexture;
private ResourceLocation overlayTexture;
private int color = 0xFFFFFFFF;
private String translationKey;
private SoundEvent fillSound;
private SoundEvent emptySound;
private int luminosity = 0;
private int density = 1000;
private int temperature = 300;
private int viscosity = 1000;
private boolean isGaseous;
private Rarity rarity = Rarity.COMMON;
private BiFunction<Builder,Fluid,FluidAttributes> factory;
protected Builder(ResourceLocation stillTexture, ResourceLocation flowingTexture, BiFunction<Builder,Fluid,FluidAttributes> factory) {
this.factory = factory;
this.stillTexture = stillTexture;
this.flowingTexture = flowingTexture;
}
public final Builder translationKey(String translationKey)
{
this.translationKey = translationKey;
return this;
}
public final Builder color(int color)
{
this.color = color;
return this;
}
public final Builder overlay(ResourceLocation texture)
{
overlayTexture = texture;
return this;
}
public final Builder luminosity(int luminosity)
{
this.luminosity = luminosity;
return this;
}
public final Builder density(int density)
{
this.density = density;
return this;
}
public final Builder temperature(int temperature)
{
this.temperature = temperature;
return this;
}
public final Builder viscosity(int viscosity)
{
this.viscosity = viscosity;
return this;
}
public final Builder gaseous()
{
isGaseous = true;
return this;
}
public final Builder rarity(Rarity rarity)
{
this.rarity = rarity;
return this;
}
public final Builder sound(SoundEvent sound)
{
this.fillSound = this.emptySound = sound;
return this;
}
public final Builder sound(SoundEvent fillSound, SoundEvent emptySound)
{
this.fillSound = fillSound;
this.emptySound = emptySound;
return this;
}
public FluidAttributes build(Fluid fluid)
{
return factory.apply(this, fluid);
}
}
public static class Water extends FluidAttributes
{
protected Water(Builder builder, Fluid fluid)
{
super(builder, fluid);
}
@Override
public int getColor(BlockAndTintGetter level, BlockPos pos)
{
return BiomeColors.getAverageWaterColor(level, pos) | 0xFF000000;
}
public static Builder builder(ResourceLocation stillTexture, ResourceLocation flowingTexture) {
return new Builder(stillTexture, flowingTexture, Water::new);
}
}
}
@@ -0,0 +1,184 @@
package net.minecraftforge.fluids;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.LiquidBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.FluidState;
import net.minecraftforge.common.ForgeMod;
import net.minecraftforge.event.ForgeEventFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
/**
* A registry which defines the interactions a source fluid can have with its
* surroundings. Each possible flow direction is checked for all interactions with
* the source.
*
* <p>Fluid interactions mimic the behavior of {@code LiquidBlock#shouldSpreadLiquid}.
* As such, all directions, besides {@link Direction#DOWN} is tested and then replaced.
* Any fluids which cause a change in the down interaction must be handled in
* {@code FlowingFluid#spreadTo} and not by this interaction manager.
*/
public final class FluidInteractionRegistry
{
private static final Map<FluidType, List<InteractionInformation>> INTERACTIONS = new HashMap<>();
/**
* Adds an interaction between a source and its surroundings.
*
* @param source the source of the interaction, this will be replaced if the interaction occurs
* @param interaction the interaction data to check and perform
*/
public static synchronized void addInteraction(FluidType source, InteractionInformation interaction)
{
INTERACTIONS.computeIfAbsent(source, s -> new ArrayList<>()).add(interaction);
}
/**
* Performs all potential fluid interactions at a given position.
*
* <p>Note: Only the first interaction check that succeeds will occur.
*
* @param level the level the interactions take place in
* @param pos the position of the source fluid
* @return {@code true} if an interaction took place, {@code false} otherwise
*/
public static boolean canInteract(Level level, BlockPos pos)
{
FluidState state = level.getFluidState(pos);
for (Direction direction : LiquidBlock.POSSIBLE_FLOW_DIRECTIONS)
{
BlockPos relativePos = pos.relative(direction.getOpposite());
List<InteractionInformation> interactions = INTERACTIONS.getOrDefault(state.getFluidType(), Collections.emptyList());
for (InteractionInformation interaction : interactions)
{
if (interaction.predicate().test(level, pos, relativePos, state))
{
interaction.interaction().interact(level, pos, relativePos, state);
return true;
}
}
}
return false;
}
static
{
// Lava + Water = Obsidian (Source Lava) / Cobblestone (Flowing Lava)
addInteraction(ForgeMod.LAVA_TYPE.get(), new InteractionInformation(
ForgeMod.WATER_TYPE.get(),
fluidState -> fluidState.isSource() ? Blocks.OBSIDIAN.defaultBlockState() : Blocks.COBBLESTONE.defaultBlockState()
));
// Lava + Soul Soil (Below) + Blue Ice = Basalt
addInteraction(ForgeMod.LAVA_TYPE.get(), new InteractionInformation(
(level, currentPos, relativePos, currentState) -> level.getBlockState(currentPos.below()).is(Blocks.SOUL_SOIL) && level.getBlockState(relativePos).is(Blocks.BLUE_ICE),
Blocks.BASALT.defaultBlockState()
));
}
/**
* Holds the interaction data for a given source type on when to succeed
* and what to perform.
*
* @param predicate a test to see whether an interaction can occur
* @param interaction the interaction to perform
*/
public record InteractionInformation(HasFluidInteraction predicate, FluidInteraction interaction)
{
/**
* Constructor which checks the surroundings fluids for a specific type
* and then transforms the source state into a block.
*
* @param type the type of the fluid that must be surrounding the source
* @param state the state of the block replacing the source
*/
public InteractionInformation(FluidType type, BlockState state)
{
this(type, fluidState -> state);
}
/**
* Constructor which transforms the source state into a block.
*
* @param predicate a test to see whether an interaction can occur
* @param state the state of the block replacing the source
*/
public InteractionInformation(HasFluidInteraction predicate, BlockState state)
{
this(predicate, fluidState -> state);
}
/**
* Constructor which checks the surroundings fluids for a specific type
* and then transforms the source state into a block.
*
* @param type the type of the fluid that must be surrounding the source
* @param getState a function to transform the source fluid into a block state
*/
public InteractionInformation(FluidType type, Function<FluidState, BlockState> getState)
{
this((level, currentPos, relativePos, currentState) -> level.getFluidState(relativePos).getFluidType() == type, getState);
}
/**
* Constructor which transforms the source state into a block.
*
* @param predicate a test to see whether an interaction can occur
* @param getState a function to transform the source fluid into a block state
*/
public InteractionInformation(HasFluidInteraction predicate, Function<FluidState, BlockState> getState)
{
this(predicate, (level, currentPos, relativePos, currentState) ->
{
level.setBlockAndUpdate(currentPos, ForgeEventFactory.fireFluidPlaceBlockEvent(level, currentPos, currentPos, getState.apply(currentState)));
level.levelEvent(1501, currentPos, 0);
});
}
}
/**
* An interface which tests whether a source fluid can interact with its
* surroundings.
*/
@FunctionalInterface
public interface HasFluidInteraction
{
/**
* Returns whether the interaction can occur.
*
* @param level the level the interaction takes place in
* @param currentPos the position of the source
* @param relativePos a position surrounding the source
* @param currentState the state of the fluid surrounding the source
* @return {@code true} if an interaction can occur, {@code false} otherwise
*/
boolean test(Level level, BlockPos currentPos, BlockPos relativePos, FluidState currentState);
}
/**
* An interface which performs an interaction for a source.
*/
@FunctionalInterface
public interface FluidInteraction
{
/**
* Performs the interaction between the source and the surrounding data.
*
* @param level the level the interaction takes place in
* @param currentPos the position of the source
* @param relativePos a position surrounding the source
* @param currentState the state of the fluid surrounding the source
*/
void interact(Level level, BlockPos currentPos, BlockPos relativePos, FluidState currentState);
}
}
@@ -234,12 +234,12 @@ public class FluidStack
public Component getDisplayName()
{
return this.getFluid().getAttributes().getDisplayName(this);
return this.getFluid().getFluidType().getDescription(this);
}
public String getTranslationKey()
{
return this.getFluid().getAttributes().getTranslationKey(this);
return this.getFluid().getFluidType().getDescriptionId(this);
}
/**
File diff suppressed because it is too large. Load diff
@@ -23,6 +23,7 @@ import net.minecraft.core.BlockPos;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.level.Level;
import net.minecraftforge.common.SoundActions;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandler;
@@ -137,7 +138,7 @@ public class FluidUtil
tryFluidTransfer(containerFluidHandler, fluidSource, maxAmount, true);
if (player != null)
{
SoundEvent soundevent = simulatedTransfer.getFluid().getAttributes().getFillSound(simulatedTransfer);
SoundEvent soundevent = simulatedTransfer.getFluid().getFluidType().getSound(simulatedTransfer, SoundActions.BUCKET_FILL);
player.level.playSound(null, player.getX(), player.getY() + 0.5, player.getZ(), soundevent, SoundSource.BLOCKS, 1.0F, 1.0F);
}
}
@@ -181,7 +182,7 @@ public class FluidUtil
if (doDrain && player != null)
{
SoundEvent soundevent = transfer.getFluid().getAttributes().getEmptySound(transfer);
SoundEvent soundevent = transfer.getFluid().getFluidType().getSound(transfer, SoundActions.BUCKET_EMPTY);
player.level.playSound(null, player.getX(), player.getY() + 0.5, player.getZ(), soundevent, SoundSource.BLOCKS, 1.0F, 1.0F);
}
@@ -546,7 +547,7 @@ public class FluidUtil
}
Fluid fluid = resource.getFluid();
if (fluid == Fluids.EMPTY || !fluid.getAttributes().canBePlacedInWorld(level, pos, resource))
if (fluid == Fluids.EMPTY || !fluid.getFluidType().canBePlacedInLevel(level, pos, resource))
{
return false;
}
@@ -569,12 +570,12 @@ public class FluidUtil
return false; // Non-air, solid, unreplacable block. We can't put fluid here.
}
if (level.dimensionType().ultraWarm() && fluid.getAttributes().doesVaporize(level, pos, resource))
if (fluid.getFluidType().isVaporizedOnPlacement(level, pos, resource))
{
FluidStack result = fluidSource.drain(resource, IFluidHandler.FluidAction.EXECUTE);
if (!result.isEmpty())
{
result.getFluid().getAttributes().vaporize(player, level, pos, result);
result.getFluid().getFluidType().onVaporize(player, level, pos, result);
return true;
}
}
@@ -593,7 +594,7 @@ public class FluidUtil
FluidStack result = tryFluidTransfer(handler, fluidSource, resource, true);
if (!result.isEmpty())
{
SoundEvent soundevent = resource.getFluid().getAttributes().getEmptySound(resource);
SoundEvent soundevent = resource.getFluid().getFluidType().getSound(resource, SoundActions.BUCKET_EMPTY);
level.playSound(player, pos, soundevent, SoundSource.BLOCKS, 1.0F, 1.0F);
return true;
}
@@ -609,7 +610,7 @@ public class FluidUtil
*/
private static IFluidHandler getFluidBlockHandler(Fluid fluid, Level level, BlockPos pos)
{
BlockState state = fluid.getAttributes().getBlock(level, pos, fluid.defaultFluidState());
BlockState state = fluid.getFluidType().getBlockForFluidState(level, pos, fluid.defaultFluidState());
return new BlockWrapper(state, level, pos);
}
@@ -660,6 +661,6 @@ public class FluidUtil
}
}
return fluid.getAttributes().getBucket(fluidStack);
return fluid.getFluidType().getBucket(fluidStack);
}
}
@@ -23,6 +23,7 @@ import net.minecraft.core.BlockPos;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.LevelReader;
import net.minecraftforge.common.SoundActions;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -30,14 +31,13 @@ import java.util.function.Supplier;
public abstract class ForgeFlowingFluid extends FlowingFluid
{
private final Supplier<? extends FluidType> fluidType;
private final Supplier<? extends Fluid> flowing;
private final Supplier<? extends Fluid> still;
@Nullable
private final Supplier<? extends Item> bucket;
@Nullable
private final Supplier<? extends LiquidBlock> block;
private final FluidAttributes.Builder builder;
private final boolean canMultiply;
private final int slopeFindDistance;
private final int levelDecreasePerBlock;
private final float explosionResistance;
@@ -45,10 +45,9 @@ public abstract class ForgeFlowingFluid extends FlowingFluid
protected ForgeFlowingFluid(Properties properties)
{
this.fluidType = properties.fluidType;
this.flowing = properties.flowing;
this.still = properties.still;
this.builder = properties.attributes;
this.canMultiply = properties.canMultiply;
this.bucket = properties.bucket;
this.block = properties.block;
this.slopeFindDistance = properties.slopeFindDistance;
@@ -57,6 +56,12 @@ public abstract class ForgeFlowingFluid extends FlowingFluid
this.tickRate = properties.tickRate;
}
@Override
public FluidType getFluidType()
{
return this.fluidType.get();
}
@Override
public Fluid getFlowing()
{
@@ -72,7 +77,13 @@ public abstract class ForgeFlowingFluid extends FlowingFluid
@Override
protected boolean canConvertToSource()
{
return canMultiply;
return false;
}
@Override
public boolean canConvertToSource(FluidState state, LevelReader reader, BlockPos pos)
{
return this.getFluidType().canConvertToSource(state, reader, pos);
}
@Override
@@ -136,13 +147,7 @@ public abstract class ForgeFlowingFluid extends FlowingFluid
@Override
public Optional<SoundEvent> getPickupSound()
{
return Optional.ofNullable(getAttributes().getFillSound());
}
@Override
protected FluidAttributes createAttributes()
{
return builder.build(this);
return Optional.ofNullable(getFluidType().getSound(SoundActions.BUCKET_FILL));
}
public static class Flowing extends ForgeFlowingFluid
@@ -185,10 +190,9 @@ public abstract class ForgeFlowingFluid extends FlowingFluid
public static class Properties
{
private Supplier<? extends FluidType> fluidType;
private Supplier<? extends Fluid> still;
private Supplier<? extends Fluid> flowing;
private FluidAttributes.Builder attributes;
private boolean canMultiply;
private Supplier<? extends Item> bucket;
private Supplier<? extends LiquidBlock> block;
private int slopeFindDistance = 4;
@@ -196,17 +200,11 @@ public abstract class ForgeFlowingFluid extends FlowingFluid
private float explosionResistance = 1;
private int tickRate = 5;
public Properties(Supplier<? extends Fluid> still, Supplier<? extends Fluid> flowing, FluidAttributes.Builder attributes)
public Properties(Supplier<? extends FluidType> fluidType, Supplier<? extends Fluid> still, Supplier<? extends Fluid> flowing)
{
this.fluidType = fluidType;
this.still = still;
this.flowing = flowing;
this.attributes = attributes;
}
public Properties canMultiply()
{
canMultiply = true;
return this;
}
public Properties bucket(Supplier<? extends Item> bucket)
@@ -13,14 +13,14 @@ import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.core.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fluids.FluidAttributes;
import net.minecraftforge.fluids.FluidType;
import net.minecraftforge.fluids.capability.templates.FluidTank;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class TileFluidHandler extends BlockEntity
{
protected FluidTank tank = new FluidTank(FluidAttributes.BUCKET_VOLUME);
protected FluidTank tank = new FluidTank(FluidType.BUCKET_VOLUME);
private final LazyOptional<IFluidHandler> holder = LazyOptional.of(() -> tank);
@@ -10,8 +10,8 @@ import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.LiquidBlockContainer;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraftforge.fluids.FluidAttributes;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidType;
import net.minecraftforge.fluids.FluidUtil;
import net.minecraftforge.fluids.capability.templates.VoidFluidHandler;
@@ -39,7 +39,7 @@ public class BlockWrapper extends VoidFluidHandler
public int fill(FluidStack resource, FluidAction action)
{
// NOTE: "Filling" means placement in this context!
if (resource.getAmount() < FluidAttributes.BUCKET_VOLUME)
if (resource.getAmount() < FluidType.BUCKET_VOLUME)
{
return 0;
}
@@ -48,7 +48,7 @@ public class BlockWrapper extends VoidFluidHandler
FluidUtil.destroyBlockOnFluidPlacement(world, blockPos);
world.setBlock(blockPos, state, Block.UPDATE_ALL_IMMEDIATE);
}
return FluidAttributes.BUCKET_VOLUME;
return FluidType.BUCKET_VOLUME;
}
public static class LiquidContainerBlockWrapper extends VoidFluidHandler
@@ -68,15 +68,15 @@ public class BlockWrapper extends VoidFluidHandler
public int fill(FluidStack resource, FluidAction action)
{
// NOTE: "Filling" means placement in this context!
if (resource.getAmount() >= FluidAttributes.BUCKET_VOLUME)
if (resource.getAmount() >= FluidType.BUCKET_VOLUME)
{
BlockState state = world.getBlockState(blockPos);
if (liquidContainer.canPlaceLiquid(world, blockPos, state, resource.getFluid()))
{
//If we are executing try to actually fill the container, if it failed return that we failed
if (action.simulate() || liquidContainer.placeLiquid(world, blockPos, state, resource.getFluid().getAttributes().getStateForPlacement(world, blockPos, resource)))
if (action.simulate() || liquidContainer.placeLiquid(world, blockPos, state, resource.getFluid().getFluidType().getStateForPlacement(world, blockPos, resource)))
{
return FluidAttributes.BUCKET_VOLUME;
return FluidType.BUCKET_VOLUME;
}
}
}
@@ -11,8 +11,8 @@ import net.minecraft.world.level.block.BucketPickup;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraftforge.fluids.FluidAttributes;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidType;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.logging.log4j.LogManager;
@@ -50,7 +50,7 @@ public class BucketPickupHandlerWrapper implements IFluidHandler
FluidState fluidState = world.getFluidState(blockPos);
if (!fluidState.isEmpty())
{
return new FluidStack(fluidState.getType(), FluidAttributes.BUCKET_VOLUME);
return new FluidStack(fluidState.getType(), FluidType.BUCKET_VOLUME);
}
}
return FluidStack.EMPTY;
@@ -59,7 +59,7 @@ public class BucketPickupHandlerWrapper implements IFluidHandler
@Override
public int getTankCapacity(int tank)
{
return FluidAttributes.BUCKET_VOLUME;
return FluidType.BUCKET_VOLUME;
}
@Override
@@ -78,7 +78,7 @@ public class BucketPickupHandlerWrapper implements IFluidHandler
@Override
public FluidStack drain(FluidStack resource, FluidAction action)
{
if (!resource.isEmpty() && FluidAttributes.BUCKET_VOLUME <= resource.getAmount())
if (!resource.isEmpty() && FluidType.BUCKET_VOLUME <= resource.getAmount())
{
FluidState fluidState = world.getFluidState(blockPos);
if (!fluidState.isEmpty() && resource.getFluid() == fluidState.getType())
@@ -88,7 +88,7 @@ public class BucketPickupHandlerWrapper implements IFluidHandler
ItemStack itemStack = bucketPickupHandler.pickupBlock(world, blockPos, world.getBlockState(blockPos));
if (itemStack != ItemStack.EMPTY && itemStack.getItem() instanceof BucketItem bucket)
{
FluidStack extracted = new FluidStack(bucket.getFluid(), FluidAttributes.BUCKET_VOLUME);
FluidStack extracted = new FluidStack(bucket.getFluid(), FluidType.BUCKET_VOLUME);
if (!resource.isFluidEqual(extracted))
{
//Be loud if something went wrong
@@ -101,7 +101,7 @@ public class BucketPickupHandlerWrapper implements IFluidHandler
}
else
{
FluidStack extracted = new FluidStack(fluidState.getType(), FluidAttributes.BUCKET_VOLUME);
FluidStack extracted = new FluidStack(fluidState.getType(), FluidType.BUCKET_VOLUME);
if (resource.isFluidEqual(extracted))
{
//Validate NBT matches
@@ -117,19 +117,19 @@ public class BucketPickupHandlerWrapper implements IFluidHandler
@Override
public FluidStack drain(int maxDrain, FluidAction action)
{
if (FluidAttributes.BUCKET_VOLUME <= maxDrain)
if (FluidType.BUCKET_VOLUME <= maxDrain)
{
FluidState fluidState = world.getFluidState(blockPos);
if (!fluidState.isEmpty())
{
if (action.simulate())
{
return new FluidStack(fluidState.getType(), FluidAttributes.BUCKET_VOLUME);
return new FluidStack(fluidState.getType(), FluidType.BUCKET_VOLUME);
}
ItemStack itemStack = bucketPickupHandler.pickupBlock(world, blockPos, world.getBlockState(blockPos));
if (itemStack != ItemStack.EMPTY && itemStack.getItem() instanceof BucketItem bucket)
{
return new FluidStack(bucket.getFluid(), FluidAttributes.BUCKET_VOLUME);
return new FluidStack(bucket.getFluid(), FluidType.BUCKET_VOLUME);
}
}
}
@@ -7,8 +7,8 @@ package net.minecraftforge.fluids.capability.wrappers;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraftforge.fluids.FluidAttributes;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidType;
import net.minecraftforge.fluids.IFluidBlock;
import net.minecraftforge.fluids.capability.IFluidHandler;
@@ -52,7 +52,7 @@ public class FluidBlockWrapper implements IFluidHandler
return (int) (stored.getAmount() / filledPercentage);
}
}
return FluidAttributes.BUCKET_VOLUME;
return FluidType.BUCKET_VOLUME;
}
@Override
@@ -11,8 +11,8 @@ import net.minecraftforge.common.ForgeMod;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fluids.FluidAttributes;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidType;
import net.minecraftforge.fluids.FluidUtil;
import net.minecraftforge.fluids.capability.IFluidHandlerItem;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
@@ -54,7 +54,7 @@ public class FluidBucketWrapper implements IFluidHandlerItem, ICapabilityProvide
{
return true;
}
return !fluid.getFluid().getAttributes().getBucket(fluid).isEmpty();
return !fluid.getFluid().getFluidType().getBucket(fluid).isEmpty();
}
@NotNull
@@ -63,11 +63,11 @@ public class FluidBucketWrapper implements IFluidHandlerItem, ICapabilityProvide
Item item = container.getItem();
if (item instanceof BucketItem)
{
return new FluidStack(((BucketItem)item).getFluid(), FluidAttributes.BUCKET_VOLUME);
return new FluidStack(((BucketItem)item).getFluid(), FluidType.BUCKET_VOLUME);
}
else if (item instanceof MilkBucketItem && ForgeMod.MILK.isPresent())
{
return new FluidStack(ForgeMod.MILK.get(), FluidAttributes.BUCKET_VOLUME);
return new FluidStack(ForgeMod.MILK.get(), FluidType.BUCKET_VOLUME);
}
else
{
@@ -99,7 +99,7 @@ public class FluidBucketWrapper implements IFluidHandlerItem, ICapabilityProvide
@Override
public int getTankCapacity(int tank) {
return FluidAttributes.BUCKET_VOLUME;
return FluidType.BUCKET_VOLUME;
}
@Override
@@ -111,7 +111,7 @@ public class FluidBucketWrapper implements IFluidHandlerItem, ICapabilityProvide
@Override
public int fill(FluidStack resource, FluidAction action)
{
if (container.getCount() != 1 || resource.getAmount() < FluidAttributes.BUCKET_VOLUME || container.getItem() instanceof MilkBucketItem || !getFluid().isEmpty() || !canFillFluidType(resource))
if (container.getCount() != 1 || resource.getAmount() < FluidType.BUCKET_VOLUME || container.getItem() instanceof MilkBucketItem || !getFluid().isEmpty() || !canFillFluidType(resource))
{
return 0;
}
@@ -121,14 +121,14 @@ public class FluidBucketWrapper implements IFluidHandlerItem, ICapabilityProvide
setFluid(resource);
}
return FluidAttributes.BUCKET_VOLUME;
return FluidType.BUCKET_VOLUME;
}
@NotNull
@Override
public FluidStack drain(FluidStack resource, FluidAction action)
{
if (container.getCount() != 1 || resource.getAmount() < FluidAttributes.BUCKET_VOLUME)
if (container.getCount() != 1 || resource.getAmount() < FluidType.BUCKET_VOLUME)
{
return FluidStack.EMPTY;
}
@@ -150,7 +150,7 @@ public class FluidBucketWrapper implements IFluidHandlerItem, ICapabilityProvide
@Override
public FluidStack drain(int maxDrain, FluidAction action)
{
if (container.getCount() != 1 || maxDrain < FluidAttributes.BUCKET_VOLUME)
if (container.getCount() != 1 || maxDrain < FluidType.BUCKET_VOLUME)
{
return FluidStack.EMPTY;
}
@@ -23,6 +23,7 @@ public class ForgeDeferredRegistriesSetup
ForgeRegistries.DEFERRED_LOOT_MODIFIER_SERIALIZERS.register(modEventBus);
ForgeRegistries.DEFERRED_WORLD_TYPES.register(modEventBus);
ForgeRegistries.DEFERRED_BIOME_MODIFIER_SERIALIZERS.register(modEventBus);
ForgeRegistries.DEFERRED_FLUID_TYPES.register(modEventBus);
ForgeRegistries.DEFERRED_BIOME_MODIFIERS.register(modEventBus);
ForgeRegistries.DEFERRED_STRUCTURE_MODIFIER_SERIALIZERS.register(modEventBus);
ForgeRegistries.DEFERRED_STRUCTURE_MODIFIERS.register(modEventBus);
@@ -44,6 +44,7 @@ import net.minecraftforge.common.Tags;
import net.minecraftforge.common.loot.GlobalLootModifierSerializer;
import net.minecraftforge.common.world.BiomeModifier;
import net.minecraftforge.common.world.ForgeWorldPreset;
import net.minecraftforge.fluids.FluidType;
import java.util.function.Supplier;
import net.minecraftforge.common.world.StructureModifier;
@@ -105,6 +106,8 @@ public class ForgeRegistries
public static final Supplier<IForgeRegistry<Codec<? extends BiomeModifier>>> BIOME_MODIFIER_SERIALIZERS = DEFERRED_BIOME_MODIFIER_SERIALIZERS.makeRegistry(() -> new RegistryBuilder<Codec<? extends BiomeModifier>>().disableSaving().disableSync());
static final DeferredRegister<Codec<? extends StructureModifier>> DEFERRED_STRUCTURE_MODIFIER_SERIALIZERS = DeferredRegister.create(Keys.STRUCTURE_MODIFIER_SERIALIZERS, Keys.STRUCTURE_MODIFIER_SERIALIZERS.location().getNamespace());
public static final Supplier<IForgeRegistry<Codec<? extends StructureModifier>>> STRUCTURE_MODIFIER_SERIALIZERS = DEFERRED_STRUCTURE_MODIFIER_SERIALIZERS.makeRegistry(() -> new RegistryBuilder<Codec<? extends StructureModifier>>().disableSaving().disableSync());
static final DeferredRegister<FluidType> DEFERRED_FLUID_TYPES = DeferredRegister.create(Keys.FLUID_TYPES, Keys.FLUID_TYPES.location().getNamespace());
public static final Supplier<IForgeRegistry<FluidType>> FLUID_TYPES = DEFERRED_FLUID_TYPES.makeRegistry(GameData::getFluidTypeRegistryBuilder);
// Custom forge datapack registries
static final DeferredRegister<BiomeModifier> DEFERRED_BIOME_MODIFIERS = DeferredRegister.create(Keys.BIOME_MODIFIERS, "forge");
@@ -152,6 +155,7 @@ public class ForgeRegistries
public static final ResourceKey<Registry<ForgeWorldPreset>> WORLD_TYPES = key("forge:world_types");
public static final ResourceKey<Registry<Codec<? extends BiomeModifier>>> BIOME_MODIFIER_SERIALIZERS = key("forge:biome_modifier_serializers");
public static final ResourceKey<Registry<Codec<? extends StructureModifier>>> STRUCTURE_MODIFIER_SERIALIZERS = key("forge:structure_modifier_serializers");
public static final ResourceKey<Registry<FluidType>> FLUID_TYPES = key("forge:fluid_type");
// Forge Dynamic
public static final ResourceKey<Registry<BiomeModifier>> BIOME_MODIFIERS = key("forge:biome_modifier");
@@ -40,6 +40,7 @@ import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.loot.GlobalLootModifierSerializer;
import net.minecraftforge.common.util.LogMessageAdapter;
import net.minecraftforge.common.world.ForgeWorldPreset;
import net.minecraftforge.fluids.FluidType;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.ModLoader;
import net.minecraftforge.fml.ModLoadingContext;
@@ -153,6 +154,11 @@ public class GameData
return makeRegistry(WORLD_TYPES).disableSaving().disableSync();
}
static RegistryBuilder<FluidType> getFluidTypeRegistryBuilder()
{
return makeRegistry(FLUID_TYPES).disableSaving();
}
private static <T> RegistryBuilder<T> makeRegistry(ResourceKey<? extends Registry<T>> key)
{
return new RegistryBuilder<T>().setName(key.location()).setMaxID(MAX_VARINT).hasWrapper();