Update to 1.14.2

This commit is contained in:
LexManos authored and cpw committed 2019-06-07 16:50:47 -04:00
1 parent d3e8804dbf
commit a7df63e1a1
1010 files changed
+15254 -19520

No files matched your search

@@ -28,7 +28,7 @@ import javax.annotation.Nullable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.init.Biomes;
import net.minecraft.world.biome.Biomes;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.biome.*;
import static net.minecraftforge.common.BiomeDictionary.Type.*;
@@ -25,7 +25,7 @@ import java.util.List;
import com.google.common.collect.ImmutableList;
import net.minecraft.init.Biomes;
import net.minecraft.world.biome.Biomes;
import net.minecraft.util.WeightedRandom;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.provider.BiomeProvider;
@@ -19,6 +19,7 @@
package net.minecraftforge.common;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
@@ -40,16 +41,18 @@ import com.google.common.collect.MapMaker;
import com.google.common.collect.Multiset;
import io.netty.buffer.Unpooled;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.ListNBT;
import net.minecraft.network.PacketBuffer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.registry.MutableRegistry;
import net.minecraft.world.World;
import net.minecraft.world.ServerWorldEventHandler;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldServerMulti;
import net.minecraft.world.chunk.ChunkStatus;
import net.minecraft.world.chunk.listener.IChunkStatusListener;
import net.minecraft.world.ServerWorld;
import net.minecraft.world.ServerMultiWorld;
import net.minecraft.world.dimension.DimensionType;
import net.minecraftforge.event.world.RegisterDimensionsEvent;
import net.minecraftforge.event.world.WorldEvent;
@@ -88,10 +91,10 @@ public class DimensionManager
* @param type Dimension Type.
* @param data Configuration data for this dimension, passed into
*/
public static DimensionType registerDimension(ResourceLocation name, ModDimension type, PacketBuffer data)
public static DimensionType registerDimension(ResourceLocation name, ModDimension type, PacketBuffer data, boolean hasSkyLight)
{
Validate.notNull(name, "Can not register a dimension with null name");
Validate.isTrue(!REGISTRY.func_212607_c(name), "Dimension: " + name + " Already registered");
Validate.isTrue(!REGISTRY.containsKey(name), "Dimension: " + name + " Already registered");
Validate.notNull(type, "Can not register a null dimension type");
int id = REGISTRY.getNextId();
@@ -103,8 +106,9 @@ public class DimensionManager
LOGGER.info(DIMMGR, "Changing ModDimension for '{}' from '{}' to '{}'", name.toString(), old.getType() == null ? null : old.getType().toString(), type.getRegistryName().toString());
savedEntries.remove(name);
}
DimensionType instance = new DimensionType(id, "", name.getNamespace() + "/" + name.getPath(), type.getFactory(), type, data);
REGISTRY.register(id, name, instance);
@SuppressWarnings("deprecation")
DimensionType instance = new DimensionType(id, "", name.getNamespace() + "/" + name.getPath(), type.getFactory(), hasSkyLight, type, data);
REGISTRY.func_218382_a(id, name, instance);
LOGGER.info(DIMMGR, "Registered dimension {} of type {} and id {}", name.toString(), type.getRegistryName().toString(), id);
return instance;
}
@@ -147,7 +151,7 @@ public class DimensionManager
* @return The world, null if unloaded and not loadable.
*/
@Nullable
public static WorldServer getWorld(MinecraftServer server, DimensionType dim, boolean resetUnloadDelay, boolean forceLoad)
public static ServerWorld getWorld(MinecraftServer server, DimensionType dim, boolean resetUnloadDelay, boolean forceLoad)
{
Validate.notNull(server, "Must provide server when creating world");
Validate.notNull(dim, "Dimension type must not be null");
@@ -161,7 +165,7 @@ public class DimensionManager
getData(dim).ticksWaited = 0;
@SuppressWarnings("deprecation")
WorldServer ret = server.forgeGetWorldMap().get(dim);
ServerWorld ret = server.forgeGetWorldMap().get(dim);
if (ret == null && forceLoad)
ret = initWorld(server, dim);
return ret;
@@ -177,47 +181,45 @@ public class DimensionManager
dimensions.remove(id);
}
public static DimensionType registerDimensionInternal(int id, ResourceLocation name, ModDimension type, PacketBuffer data)
public static DimensionType registerDimensionInternal(int id, ResourceLocation name, ModDimension type, PacketBuffer data, boolean hasSkyLight)
{
Validate.notNull(name, "Can not register a dimension with null name");
Validate.notNull(type, "Can not register a null dimension type");
Validate.isTrue(!REGISTRY.func_212607_c(name), "Dimension: " + name + " Already registered");
Validate.isTrue(REGISTRY.get(id) == null, "Dimension with id " + id + " already registered as name " + REGISTRY.getKey(REGISTRY.get(id)));
Validate.isTrue(!REGISTRY.containsKey(name), "Dimension: " + name + " Already registered");
Validate.isTrue(REGISTRY.getByValue(id) == null, "Dimension with id " + id + " already registered as name " + REGISTRY.getKey(REGISTRY.getByValue(id)));
DimensionType instance = new DimensionType(id, "", name.getNamespace() + "/" + name.getPath(), type.getFactory(), type, data);
REGISTRY.register(id, name, instance);
@SuppressWarnings("deprecation")
DimensionType instance = new DimensionType(id, "", name.getNamespace() + "/" + name.getPath(), type.getFactory(), hasSkyLight, type, data);
REGISTRY.func_218382_a(id, name, instance);
LOGGER.info(DIMMGR, "Registered dimension {} of type {} and id {}", name.toString(), type.getRegistryName().toString(), id);
return instance;
}
@SuppressWarnings("deprecation")
public static WorldServer initWorld(MinecraftServer server, DimensionType dim)
public static ServerWorld initWorld(MinecraftServer server, DimensionType dim)
{
Validate.isTrue(dim != DimensionType.OVERWORLD, "Can not hotload overworld. This must be loaded at all times by main Server.");
Validate.notNull(server, "Must provide server when creating world");
Validate.notNull(dim, "Must provide dimension when creating world");
WorldServer overworld = getWorld(server, DimensionType.OVERWORLD, false, false);
ServerWorld overworld = getWorld(server, DimensionType.OVERWORLD, false, false);
Validate.notNull(overworld, "Cannot Hotload Dim: Overworld is not Loaded!");
@SuppressWarnings("resource")
WorldServer world = new WorldServerMulti(server, overworld.getSaveHandler(), dim, overworld, server.profiler).func_212251_i__();
world.addEventListener(new ServerWorldEventHandler(server, world));
ServerWorld world = new ServerMultiWorld(overworld, server, server.func_213207_aT(), overworld.func_217485_w(), dim, server.func_213185_aS(), new NoopChunkStatusListener());
if (!server.isSinglePlayer())
world.getWorldInfo().setGameType(server.getGameType());
server.forgeGetWorldMap().put(dim, world);
MinecraftForge.EVENT_BUS.post(new WorldEvent.Load(world));
server.setDifficultyForAllWorlds(server.getDifficulty());
return world;
}
private static boolean canUnloadWorld(WorldServer world)
private static boolean canUnloadWorld(ServerWorld world)
{
return world.func_212412_ag().isEmpty()
&& world.playerEntities.isEmpty()
return world.func_217469_z().isEmpty()
&& world.func_217369_A().isEmpty()
//&& !world.dimension.getType().shouldLoadSpawn()
&& !getData(world.getDimension().getType()).keepLoaded;
}
@@ -226,7 +228,7 @@ public class DimensionManager
* Queues a dimension to unload, if it can be unloaded.
* @param id The id of the dimension
*/
public static void unloadWorld(WorldServer world)
public static void unloadWorld(ServerWorld world)
{
if (world == null || !canUnloadWorld(world))
return;
@@ -261,7 +263,7 @@ public class DimensionManager
queueIterator.remove();
WorldServer w = server.forgeGetWorldMap().get(dim);
ServerWorld w = server.forgeGetWorldMap().get(dim);
dimension.ticksWaited = 0;
// Don't unload the world if the status changed
@@ -272,7 +274,7 @@ public class DimensionManager
}
try
{
w.saveAllChunks(true, null);
w.func_217445_a(null, true, true);
}
catch (Exception e)
{
@@ -281,7 +283,11 @@ public class DimensionManager
finally
{
MinecraftForge.EVENT_BUS.post(new WorldEvent.Unload(w));
w.close();
try {
w.close();
} catch (IOException e) {
LOGGER.error("Exception closing the level", e);
}
server.forgeGetWorldMap().remove(dim);
}
}
@@ -304,22 +310,22 @@ public class DimensionManager
}
}
public static void writeRegistry(NBTTagCompound data)
public static void writeRegistry(CompoundNBT data)
{
data.setInt("version", 1);
data.putInt("version", 1);
List<SavedEntry> list = new ArrayList<>();
for (DimensionType type : REGISTRY)
list.add(new SavedEntry(type));
savedEntries.values().forEach(list::add);
Collections.sort(list, (a, b) -> a.id - b.id);
NBTTagList lst = new NBTTagList();
ListNBT lst = new ListNBT();
list.forEach(e -> lst.add(e.write()));
data.setTag("entries", lst);
data.func_218657_a("entries", lst);
}
public static void readRegistry(NBTTagCompound data)
public static void readRegistry(CompoundNBT data)
{
int version = data.getInt("version");
if (version != 1)
@@ -330,19 +336,19 @@ public class DimensionManager
REGISTRY.clear();
vanilla.forEach((key, value) -> {
LOGGER.debug(DIMMGR, "Registering vanilla entry ID: {} Name: {} Value: {}", value.getId() + 1, key.toString(), value.toString());
REGISTRY.register(value.getId() + 1, key, value);
REGISTRY.func_218382_a(value.getId() + 1, key, value);
});
savedEntries.clear();
boolean error = false;
NBTTagList list = data.getList("entries", 10);
ListNBT list = data.getList("entries", 10);
for (int x = 0; x < list.size(); x++)
{
SavedEntry entry = new SavedEntry(list.getCompound(x));
if (entry.type == null)
{
DimensionType type = REGISTRY.func_212608_b(entry.name);
DimensionType type = REGISTRY.getOrDefault(entry.name);
if (type == null)
{
LOGGER.error(DIMMGR, "Vanilla entry '{}' id {} in save file not found in registry.", entry.name.toString(), entry.id);
@@ -366,7 +372,7 @@ public class DimensionManager
savedEntries.put(entry.name, entry);
continue;
}
registerDimensionInternal(entry.id, entry.name, mod, entry.data == null ? null : new PacketBuffer(Unpooled.wrappedBuffer(entry.data)));
registerDimensionInternal(entry.id, entry.name, mod, entry.data == null ? null : new PacketBuffer(Unpooled.wrappedBuffer(entry.data)), entry.skyLight());
}
}
@@ -382,7 +388,7 @@ public class DimensionManager
}
@Deprecated //Forge: Internal use only.
public static IRegistry<DimensionType> getRegistry()
public static MutableRegistry<DimensionType> getRegistry()
{
return REGISTRY;
}
@@ -404,6 +410,7 @@ public class DimensionManager
ResourceLocation name;
ResourceLocation type;
byte[] data;
boolean skyLight;
public int getId()
{
@@ -427,12 +434,18 @@ public class DimensionManager
return data;
}
private SavedEntry(NBTTagCompound data)
public boolean skyLight()
{
return this.skyLight;
}
private SavedEntry(CompoundNBT data)
{
this.id = data.getInt("id");
this.name = new ResourceLocation(data.getString("name"));
this.type = data.contains("type", 8) ? new ResourceLocation(data.getString("type")) : null;
this.data = data.contains("data", 7) ? data.getByteArray("data") : null;
this.skyLight = data.contains("sky_light", 99) ? data.getByte("sky_light") == 0 : true;
}
private SavedEntry(DimensionType data)
@@ -443,18 +456,27 @@ public class DimensionManager
this.type = data.getModType().getRegistryName();
if (data.getData() != null)
this.data = data.getData().array();
this.skyLight = data.func_218272_d();
}
private NBTTagCompound write()
private CompoundNBT write()
{
NBTTagCompound ret = new NBTTagCompound();
ret.setInt("id", id);
ret.setString("name", name.toString());
CompoundNBT ret = new CompoundNBT();
ret.putInt("id", id);
ret.putString("name", name.toString());
if (type != null)
ret.setString("type", type.toString());
ret.putString("type", type.toString());
if (data != null)
ret.setByteArray("data", data);
ret.putByteArray("data", data);
ret.putByte("sky_light", (byte)(skyLight ? 1 : 0));
return ret;
}
}
private static class NoopChunkStatusListener implements IChunkStatusListener
{
@Override public void func_219509_a(ChunkPos p_219509_1_) { }
@Override public void func_219508_a(ChunkPos p_219508_1_, ChunkStatus p_219508_2_) { }
@Override public void func_219510_b() { }
}
}
@@ -20,6 +20,7 @@
package net.minecraftforge.common;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import net.minecraft.entity.EntityType;
@@ -50,11 +51,15 @@ public class DungeonHooks
throw new IllegalArgumentException("Rarity must be greater then zero");
}
for (DungeonMob mob : dungeonMobs)
Iterator<DungeonMob> itr = dungeonMobs.iterator();
while (itr.hasNext())
{
DungeonMob mob = itr.next();
if (type == mob.type)
{
return mob.itemWeight += rarity;
itr.remove();
rarity = mob.itemWeight + rarity;
break;
}
}
@@ -26,8 +26,7 @@ import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.IWorld;
import net.minecraft.world.IWorldReaderBase;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunk;
import net.minecraftforge.common.ticket.AABBTicket;
@@ -107,7 +106,7 @@ public class FarmlandWaterManager
* Tests if a block is in a region that is watered by blocks. This does not check vanilla water, see {@link net.minecraft.block.BlockFarmland#hasWater(World, BlockPos)}
* @return true if there is a ticket with an AABB that includes your block
*/
public static boolean hasBlockWaterTicket(IWorldReaderBase world, BlockPos pos)
public static boolean hasBlockWaterTicket(IWorldReader world, BlockPos pos)
{
ChunkTicketManager<Vec3d> ticketManager = getTicketManager(new ChunkPos(pos.getX() >> 4, pos.getZ() >> 4), world);
if (ticketManager != null)
@@ -133,7 +132,7 @@ public class FarmlandWaterManager
}
}
private static ChunkTicketManager<Vec3d> getTicketManager(ChunkPos pos, IWorldReaderBase world) {
private static ChunkTicketManager<Vec3d> getTicketManager(ChunkPos pos, IWorldReader world) {
Preconditions.checkArgument(!world.isRemote(), "Water region is only determined server-side");
Map<ChunkPos, ChunkTicketManager<Vec3d>> ticketMap = customWaterHandler.get(world.getDimension().getType().getId());
if (ticketMap == null)
@@ -22,17 +22,15 @@ package net.minecraftforge.common;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Throwables;
@@ -43,78 +41,78 @@ import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.minecraft.advancements.Advancement;
import net.minecraft.block.Block;
import net.minecraft.block.state.BlockWorldState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.CachedBlockInfo;
import net.minecraft.block.BlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.EntityMinecartContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.entity.MobEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.item.minecart.ContainerMinecartEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.fluid.IFluidState;
import net.minecraft.init.Blocks;
import net.minecraft.init.Fluids;
import net.minecraft.inventory.ContainerRepair;
import net.minecraft.block.Blocks;
import net.minecraft.fluid.Fluids;
import net.minecraft.inventory.container.RepairContainer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemAxe;
import net.minecraft.item.ItemBucket;
import net.minecraft.item.ItemEnchantedBook;
import net.minecraft.item.ItemPickaxe;
import net.minecraft.item.ItemPotion;
import net.minecraft.item.ItemSpade;
import net.minecraft.item.ItemSpawnEgg;
import net.minecraft.item.AxeItem;
import net.minecraft.item.BucketItem;
import net.minecraft.item.EnchantedBookItem;
import net.minecraft.item.PickaxeItem;
import net.minecraft.item.PotionItem;
import net.minecraft.item.ShovelItem;
import net.minecraft.item.SpawnEggItem;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTippedArrow;
import net.minecraft.item.TippedArrowItem;
import net.minecraft.item.ItemUseContext;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.network.Packet;
import net.minecraft.network.datasync.DataSerializer;
import net.minecraft.network.play.server.SPacketBlockChange;
import net.minecraft.potion.PotionType;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.ListNBT;
import net.minecraft.network.play.ServerPlayNetHandler;
import net.minecraft.network.IPacket;
import net.minecraft.network.datasync.IDataSerializer;
import net.minecraft.network.play.server.SChangeBlockPacket;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionUtils;
import net.minecraft.stats.StatList;
import net.minecraft.stats.Stats;
import net.minecraft.tags.Tag;
import net.minecraft.tileentity.MobSpawnerBaseLogic;
import net.minecraft.world.spawner.AbstractSpawner;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.IntIdentityHashBiMap;
import net.minecraft.util.JsonUtils;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.WeightedRandom;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.EntityRayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.Difficulty;
import net.minecraft.world.GameType;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IWorld;
import net.minecraft.world.storage.loot.LootEntry;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.storage.loot.LootTable;
import net.minecraft.world.storage.loot.LootTableManager;
import net.minecraft.world.storage.loot.conditions.LootCondition;
import net.minecraftforge.common.util.BlockSnapshot;
import net.minecraftforge.event.AnvilUpdateEvent;
import net.minecraftforge.event.DifficultyChangeEvent;
@@ -133,23 +131,19 @@ import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.event.entity.living.LivingKnockBackEvent;
import net.minecraftforge.event.entity.living.LivingSetAttackTargetEvent;
import net.minecraftforge.event.entity.living.LootingLevelEvent;
import net.minecraftforge.event.entity.player.AdvancementEvent;
import net.minecraftforge.event.entity.player.AnvilRepairEvent;
import net.minecraftforge.event.entity.player.AttackEntityEvent;
import net.minecraftforge.event.entity.player.CriticalHitEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.entity.player.AdvancementEvent;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.event.world.NoteBlockEvent;
import net.minecraftforge.eventbus.api.Event.Result;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.DataSerializerEntry;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.GameData;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
@@ -160,57 +154,6 @@ public class ForgeHooks
{
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker FORGEHOOKS = MarkerManager.getMarker("FORGEHOOKS");
//TODO: Remove in 1.14 as vanilla uses loot tables
public static class SeedEntry extends WeightedRandom.Item
{
@Nonnull
public final ItemStack seed;
public SeedEntry(@Nonnull ItemStack seed, int weight)
{
super(weight);
this.seed = seed;
}
@Nonnull
public ItemStack getStack(Random rand, int fortune)
{
return seed.copy();
}
}
public static class FortuneSeedEntry extends SeedEntry
{
private int min, factor;
public FortuneSeedEntry(@Nonnull ItemStack seed, int weight, int min, int factor)
{
super(seed, weight);
this.min = min;
this.factor = factor;
}
@Nonnull
public ItemStack getStack(Random rand, int fortune)
{
ItemStack ret = seed.copy();
ret.setCount(min + rand.nextInt(fortune * factor + 1));
return ret;
}
}
static final List<SeedEntry> seedList = new ArrayList<SeedEntry>();
@Nonnull
public static ItemStack getGrassSeed(Random rand, int fortune)
{
if (seedList.size() == 0)
{
return ItemStack.EMPTY; //Some bad mods hack in and empty our list, so lets not hard crash -.-
}
SeedEntry entry = WeightedRandom.getRandomItem(rand, seedList);
if (entry == null || entry.seed.isEmpty())
{
return ItemStack.EMPTY;
}
return entry.getStack(rand, fortune);
}
public static boolean canContinueUsing(@Nonnull ItemStack from, @Nonnull ItemStack to)
{
@@ -221,7 +164,7 @@ public class ForgeHooks
return false;
}
public static boolean canHarvestBlock(@Nonnull IBlockState state, @Nonnull EntityPlayer player, @Nonnull IBlockReader world, @Nonnull BlockPos pos)
public static boolean canHarvestBlock(@Nonnull BlockState state, @Nonnull PlayerEntity player, @Nonnull IBlockReader world, @Nonnull BlockPos pos)
{
//state = state.getActualState(world, pos);
if (state.getMaterial().isToolNotRequired())
@@ -247,7 +190,7 @@ public class ForgeHooks
public static boolean canToolHarvestBlock(IWorldReader world, BlockPos pos, @Nonnull ItemStack stack)
{
IBlockState state = world.getBlockState(pos);
BlockState state = world.getBlockState(pos);
//state = state.getActualState(world, pos);
ToolType tool = state.getHarvestTool();
if (stack.isEmpty() || tool == null) return false;
@@ -256,7 +199,7 @@ public class ForgeHooks
public static boolean isToolEffective(IWorldReader world, BlockPos pos, @Nonnull ItemStack stack)
{
IBlockState state = world.getBlockState(pos);
BlockState state = world.getBlockState(pos);
//state = state.getActualState(world, pos);
for (ToolType type : stack.getToolTypes())
{
@@ -273,11 +216,11 @@ public class ForgeHooks
return;
toolInit = true;
Set<Block> blocks = getPrivateValue(ItemPickaxe.class, null, 0);
Set<Block> blocks = getPrivateValue(PickaxeItem.class, null, 0);
blocks.forEach(block -> blockToolSetter.accept(block, ToolType.PICKAXE, 0));
blocks = getPrivateValue(ItemSpade.class, null, 0);
blocks = getPrivateValue(ShovelItem.class, null, 0);
blocks.forEach(block -> blockToolSetter.accept(block, ToolType.SHOVEL, 0));
blocks = getPrivateValue(ItemAxe.class, null, 0);
blocks = getPrivateValue(AxeItem.class, null, 0);
blocks.forEach(block -> blockToolSetter.accept(block, ToolType.AXE, 0));
//This is taken from ItemAxe, if that changes update here.
@@ -291,54 +234,53 @@ public class ForgeHooks
/**
* Called when a player uses 'pick block', calls new Entity and Block hooks.
*/
public static boolean onPickBlock(RayTraceResult target, EntityPlayer player, World world)
public static boolean onPickBlock(RayTraceResult target, PlayerEntity player, World world)
{
ItemStack result;
ItemStack result = ItemStack.EMPTY;
boolean isCreative = player.abilities.isCreativeMode;
TileEntity te = null;
if (target.type == RayTraceResult.Type.BLOCK)
if (target.func_216346_c() == RayTraceResult.Type.BLOCK)
{
IBlockState state = world.getBlockState(target.getBlockPos());
BlockPos pos = ((BlockRayTraceResult)target).func_216350_a();
BlockState state = world.getBlockState(pos);
if (state.isAir(world, target.getBlockPos()))
if (state.isAir(world, pos))
return false;
if (isCreative && GuiScreen.isCtrlKeyDown() && state.hasTileEntity())
te = world.getTileEntity(target.getBlockPos());
if (isCreative && Screen.hasControlDown() && state.hasTileEntity())
te = world.getTileEntity(pos);
result = state.getBlock().getPickBlock(state, target, world, target.getBlockPos(), player);
result = state.getBlock().getPickBlock(state, target, world, pos, player);
if (result.isEmpty())
LOGGER.warn("Picking on: [{}] {} gave null item", target.func_216346_c(), state.getBlock().getRegistryName());
}
else
else if (target.func_216346_c() == RayTraceResult.Type.ENTITY)
{
if (target.type != RayTraceResult.Type.ENTITY || target.entity == null || !isCreative)
{
return false;
}
Entity entity = ((EntityRayTraceResult)target).func_216348_a();
result = entity.getPickedResult(target);
result = target.entity.getPickedResult(target);
if (result.isEmpty())
LOGGER.warn("Picking on: [{}] {} gave null item", target.func_216346_c(), entity.getType().getRegistryName());
}
if (result.isEmpty())
{
return false;
}
if (te != null)
{
Minecraft.getInstance().storeTEInStack(result, te);
}
if (isCreative)
{
player.inventory.setPickedItemStack(result);
Minecraft.getInstance().playerController.sendSlotPacket(player.getHeldItem(EnumHand.MAIN_HAND), 36 + player.inventory.currentItem);
Minecraft.getInstance().playerController.sendSlotPacket(player.getHeldItem(Hand.MAIN_HAND), 36 + player.inventory.currentItem);
return true;
}
int slot = player.inventory.getSlotFor(result);
if (slot != -1)
{
if (InventoryPlayer.isHotbar(slot))
if (PlayerInventory.isHotbar(slot))
player.inventory.currentItem = slot;
else
Minecraft.getInstance().playerController.pickItem(slot);
@@ -347,7 +289,7 @@ public class ForgeHooks
return false;
}
public static void onDifficultyChange(EnumDifficulty difficulty, EnumDifficulty oldDifficulty)
public static void onDifficultyChange(Difficulty difficulty, Difficulty oldDifficulty)
{
MinecraftForge.EVENT_BUS.post(new DifficultyChangeEvent(difficulty, oldDifficulty));
}
@@ -355,57 +297,57 @@ public class ForgeHooks
//Optifine Helper Functions u.u, these are here specifically for Optifine
//Note: When using Optifine, these methods are invoked using reflection, which
//incurs a major performance penalty.
public static void onLivingSetAttackTarget(EntityLivingBase entity, EntityLivingBase target)
public static void onLivingSetAttackTarget(LivingEntity entity, LivingEntity target)
{
MinecraftForge.EVENT_BUS.post(new LivingSetAttackTargetEvent(entity, target));
}
public static boolean onLivingUpdate(EntityLivingBase entity)
public static boolean onLivingUpdate(LivingEntity entity)
{
return MinecraftForge.EVENT_BUS.post(new LivingUpdateEvent(entity));
}
public static boolean onLivingAttack(EntityLivingBase entity, DamageSource src, float amount)
public static boolean onLivingAttack(LivingEntity entity, DamageSource src, float amount)
{
return entity instanceof EntityPlayer || !MinecraftForge.EVENT_BUS.post(new LivingAttackEvent(entity, src, amount));
return entity instanceof PlayerEntity || !MinecraftForge.EVENT_BUS.post(new LivingAttackEvent(entity, src, amount));
}
public static boolean onPlayerAttack(EntityLivingBase entity, DamageSource src, float amount)
public static boolean onPlayerAttack(LivingEntity entity, DamageSource src, float amount)
{
return !MinecraftForge.EVENT_BUS.post(new LivingAttackEvent(entity, src, amount));
}
public static LivingKnockBackEvent onLivingKnockBack(EntityLivingBase target, Entity attacker, float strength, double ratioX, double ratioZ)
public static LivingKnockBackEvent onLivingKnockBack(LivingEntity target, Entity attacker, float strength, double ratioX, double ratioZ)
{
LivingKnockBackEvent event = new LivingKnockBackEvent(target, attacker, strength, ratioX, ratioZ);
MinecraftForge.EVENT_BUS.post(event);
return event;
}
public static float onLivingHurt(EntityLivingBase entity, DamageSource src, float amount)
public static float onLivingHurt(LivingEntity entity, DamageSource src, float amount)
{
LivingHurtEvent event = new LivingHurtEvent(entity, src, amount);
return (MinecraftForge.EVENT_BUS.post(event) ? 0 : event.getAmount());
}
public static float onLivingDamage(EntityLivingBase entity, DamageSource src, float amount)
public static float onLivingDamage(LivingEntity entity, DamageSource src, float amount)
{
LivingDamageEvent event = new LivingDamageEvent(entity, src, amount);
return (MinecraftForge.EVENT_BUS.post(event) ? 0 : event.getAmount());
}
public static boolean onLivingDeath(EntityLivingBase entity, DamageSource src)
public static boolean onLivingDeath(LivingEntity entity, DamageSource src)
{
return MinecraftForge.EVENT_BUS.post(new LivingDeathEvent(entity, src));
}
public static boolean onLivingDrops(EntityLivingBase entity, DamageSource source, Collection<EntityItem> drops, int lootingLevel, boolean recentlyHit)
public static boolean onLivingDrops(LivingEntity entity, DamageSource source, Collection<ItemEntity> drops, int lootingLevel, boolean recentlyHit)
{
return MinecraftForge.EVENT_BUS.post(new LivingDropsEvent(entity, source, drops, lootingLevel, recentlyHit));
}
@Nullable
public static float[] onLivingFall(EntityLivingBase entity, float distance, float damageMultiplier)
public static float[] onLivingFall(LivingEntity entity, float distance, float damageMultiplier)
{
LivingFallEvent event = new LivingFallEvent(entity, distance, damageMultiplier);
return (MinecraftForge.EVENT_BUS.post(event) ? null : new float[]{event.getDistance(), event.getDamageMultiplier()});
@@ -414,21 +356,21 @@ public class ForgeHooks
public static int getLootingLevel(Entity target, @Nullable Entity killer, DamageSource cause)
{
int looting = 0;
if (killer instanceof EntityLivingBase)
looting = EnchantmentHelper.getLootingModifier((EntityLivingBase)killer);
if (target instanceof EntityLivingBase)
looting = getLootingLevel((EntityLivingBase)target, cause, looting);
if (killer instanceof LivingEntity)
looting = EnchantmentHelper.getLootingModifier((LivingEntity)killer);
if (target instanceof LivingEntity)
looting = getLootingLevel((LivingEntity)target, cause, looting);
return looting;
}
public static int getLootingLevel(EntityLivingBase target, DamageSource cause, int level)
public static int getLootingLevel(LivingEntity target, DamageSource cause, int level)
{
LootingLevelEvent event = new LootingLevelEvent(target, cause, level);
MinecraftForge.EVENT_BUS.post(event);
return event.getLootingLevel();
}
public static double getPlayerVisibilityDistance(EntityPlayer player, double xzDistance, double maxXZDistance)
public static double getPlayerVisibilityDistance(PlayerEntity player, double xzDistance, double maxXZDistance)
{
PlayerEvent.Visibility event = new PlayerEvent.Visibility(player);
MinecraftForge.EVENT_BUS.post(event);
@@ -436,9 +378,9 @@ public class ForgeHooks
return value >= maxXZDistance ? maxXZDistance : value;
}
public static boolean isLivingOnLadder(@Nonnull IBlockState state, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull EntityLivingBase entity)
public static boolean isLivingOnLadder(@Nonnull BlockState state, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull LivingEntity entity)
{
boolean isSpectator = (entity instanceof EntityPlayer && ((EntityPlayer)entity).isSpectator());
boolean isSpectator = (entity instanceof PlayerEntity && ((PlayerEntity)entity).isSpectator());
if (isSpectator) return false;
if (!ForgeConfig.SERVER.fullBoundingBoxLadders.get())
{
@@ -469,16 +411,16 @@ public class ForgeHooks
}
}
public static void onLivingJump(EntityLivingBase entity)
public static void onLivingJump(LivingEntity entity)
{
MinecraftForge.EVENT_BUS.post(new LivingJumpEvent(entity));
}
@Nullable
public static EntityItem onPlayerTossEvent(@Nonnull EntityPlayer player, @Nonnull ItemStack item, boolean includeName)
public static ItemEntity onPlayerTossEvent(@Nonnull PlayerEntity player, @Nonnull ItemStack item, boolean includeName)
{
player.captureDrops(Lists.newArrayList());
EntityItem ret = player.dropItem(item, false, includeName);
ItemEntity ret = player.dropItem(item, false, includeName);
player.captureDrops(null);
if (ret == null)
@@ -489,12 +431,12 @@ public class ForgeHooks
return null;
if (!player.world.isRemote)
player.getEntityWorld().spawnEntity(event.getEntityItem());
player.getEntityWorld().func_217376_c(event.getEntityItem());
return event.getEntityItem();
}
@Nullable
public static ITextComponent onServerChatEvent(NetHandlerPlayServer net, String raw, ITextComponent comp)
public static ITextComponent onServerChatEvent(ServerPlayNetHandler net, String raw, ITextComponent comp)
{
ServerChatEvent event = new ServerChatEvent(net.player, raw, comp);
if (MinecraftForge.EVENT_BUS.post(event))
@@ -532,13 +474,13 @@ public class ForgeHooks
if (part.length() > 0)
{
if (ichat == null)
ichat = new TextComponentString(part);
ichat = new StringTextComponent(part);
else
ichat.appendText(part);
}
lastEnd = end;
String url = string.substring(start, end);
ITextComponent link = new TextComponentString(url);
ITextComponent link = new StringTextComponent(url);
try
{
@@ -548,7 +490,7 @@ public class ForgeHooks
if (!allowMissingHeader)
{
if (ichat == null)
ichat = new TextComponentString(url);
ichat = new StringTextComponent(url);
else
ichat.appendText(url);
continue;
@@ -559,7 +501,7 @@ public class ForgeHooks
catch (URISyntaxException e)
{
// Bad syntax bail out!
if (ichat == null) ichat = new TextComponentString(url);
if (ichat == null) ichat = new StringTextComponent(url);
else ichat.appendText(url);
continue;
}
@@ -578,13 +520,13 @@ public class ForgeHooks
// Append the rest of the message.
String end = string.substring(lastEnd);
if (ichat == null)
ichat = new TextComponentString(end);
ichat = new StringTextComponent(end);
else if (end.length() > 0)
ichat.appendText(string.substring(lastEnd));
return ichat;
}
public static int onBlockBreakEvent(World world, GameType gameType, EntityPlayerMP entityPlayer, BlockPos pos)
public static int onBlockBreakEvent(World world, GameType gameType, ServerPlayerEntity entityPlayer, BlockPos pos)
{
// Logic from tryHarvestBlock for pre-canceling the event
boolean preCancelEvent = false;
@@ -600,7 +542,7 @@ public class ForgeHooks
if (!entityPlayer.isAllowEdit())
{
if (itemstack.isEmpty() || !itemstack.canDestroy(world.getTags(), new BlockWorldState(world, pos, false)))
if (itemstack.isEmpty() || !itemstack.canDestroy(world.getTags(), new CachedBlockInfo(world, pos, false)))
preCancelEvent = true;
}
}
@@ -608,11 +550,11 @@ public class ForgeHooks
// Tell client the block is gone immediately then process events
if (world.getTileEntity(pos) == null)
{
entityPlayer.connection.sendPacket(new SPacketBlockChange(DUMMY_WORLD, pos));
entityPlayer.connection.sendPacket(new SChangeBlockPacket(DUMMY_WORLD, pos));
}
// Post the block break event
IBlockState state = world.getBlockState(pos);
BlockState state = world.getBlockState(pos);
BlockEvent.BreakEvent event = new BlockEvent.BreakEvent(world, pos, state, entityPlayer);
event.setCanceled(preCancelEvent);
MinecraftForge.EVENT_BUS.post(event);
@@ -621,13 +563,13 @@ public class ForgeHooks
if (event.isCanceled())
{
// Let the client know the block still exists
entityPlayer.connection.sendPacket(new SPacketBlockChange(world, pos));
entityPlayer.connection.sendPacket(new SChangeBlockPacket(world, pos));
// Update any tile entity data for this block
TileEntity tileentity = world.getTileEntity(pos);
if (tileentity != null)
{
Packet<?> pkt = tileentity.getUpdatePacket();
IPacket<?> pkt = tileentity.getUpdatePacket();
if (pkt != null)
{
entityPlayer.connection.sendPacket(pkt);
@@ -637,32 +579,32 @@ public class ForgeHooks
return event.isCanceled() ? -1 : event.getExpToDrop();
}
public static EnumActionResult onPlaceItemIntoWorld(@Nonnull ItemUseContext context)
public static ActionResultType onPlaceItemIntoWorld(@Nonnull ItemUseContext context)
{
ItemStack itemstack = context.getItem();
World world = context.getWorld();
// handle all placement events here
int size = itemstack.getCount();
NBTTagCompound nbt = null;
CompoundNBT nbt = null;
if (itemstack.hasTag())
{
nbt = itemstack.getTag().copy();
}
if (!(itemstack.getItem() instanceof ItemBucket)) // if not bucket
if (!(itemstack.getItem() instanceof BucketItem)) // if not bucket
{
world.captureBlockSnapshots = true;
}
EnumActionResult ret = itemstack.getItem().onItemUse(context);
ActionResultType ret = itemstack.getItem().onItemUse(context);
world.captureBlockSnapshots = false;
if (ret == EnumActionResult.SUCCESS)
if (ret == ActionResultType.SUCCESS)
{
// save new item data
int newSize = itemstack.getCount();
NBTTagCompound newNBT = null;
CompoundNBT newNBT = null;
if (itemstack.hasTag())
{
newNBT = itemstack.getTag().copy();
@@ -678,8 +620,8 @@ public class ForgeHooks
itemstack.setTag(nbt);
}
EntityPlayer player = context.getPlayer();
EnumFacing side = context.getFace();
PlayerEntity player = context.getPlayer();
Direction side = context.getFace();
boolean eventResult = false;
if (blockSnapshots.size() > 1)
@@ -693,7 +635,7 @@ public class ForgeHooks
if (eventResult)
{
ret = EnumActionResult.FAIL; // cancel placement
ret = ActionResultType.FAIL; // cancel placement
// revert back all captured blocks
for (BlockSnapshot blocksnapshot : Lists.reverse(blockSnapshots))
{
@@ -714,16 +656,16 @@ public class ForgeHooks
for (BlockSnapshot snap : blockSnapshots)
{
int updateFlag = snap.getFlag();
IBlockState oldBlock = snap.getReplacedBlock();
IBlockState newBlock = world.getBlockState(snap.getPos());
BlockState oldBlock = snap.getReplacedBlock();
BlockState newBlock = world.getBlockState(snap.getPos());
if (!newBlock.getBlock().hasTileEntity(newBlock)) // Containers get placed automatically
{
newBlock.onBlockAdded(world, snap.getPos(), oldBlock);
newBlock.func_215705_a(world, snap.getPos(), oldBlock, false);
}
world.markAndNotifyBlock(snap.getPos(), null, oldBlock, newBlock, updateFlag);
}
player.addStat(StatList.ITEM_USED.get(itemstack.getItem()));
player.addStat(Stats.ITEM_USED.get(itemstack.getItem()));
}
}
world.capturedBlockSnapshots.clear();
@@ -731,31 +673,31 @@ public class ForgeHooks
return ret;
}
public static boolean onAnvilChange(ContainerRepair container, @Nonnull ItemStack left, @Nonnull ItemStack right, IInventory outputSlot, String name, int baseCost)
public static boolean onAnvilChange(RepairContainer container, @Nonnull ItemStack left, @Nonnull ItemStack right, IInventory outputSlot, String name, int baseCost)
{
AnvilUpdateEvent e = new AnvilUpdateEvent(left, right, name, baseCost);
if (MinecraftForge.EVENT_BUS.post(e)) return false;
if (e.getOutput().isEmpty()) return true;
outputSlot.setInventorySlotContents(0, e.getOutput());
container.maximumCost = e.getCost();
container.setMaximumCost(e.getCost());
container.materialCost = e.getMaterialCost();
return false;
}
public static float onAnvilRepair(EntityPlayer player, @Nonnull ItemStack output, @Nonnull ItemStack left, @Nonnull ItemStack right)
public static float onAnvilRepair(PlayerEntity player, @Nonnull ItemStack output, @Nonnull ItemStack left, @Nonnull ItemStack right)
{
AnvilRepairEvent e = new AnvilRepairEvent(player, left, right, output);
MinecraftForge.EVENT_BUS.post(e);
return e.getBreakChance();
}
private static ThreadLocal<EntityPlayer> craftingPlayer = new ThreadLocal<EntityPlayer>();
public static void setCraftingPlayer(EntityPlayer player)
private static ThreadLocal<PlayerEntity> craftingPlayer = new ThreadLocal<PlayerEntity>();
public static void setCraftingPlayer(PlayerEntity player)
{
craftingPlayer.set(player);
}
public static EntityPlayer getCraftingPlayer()
public static PlayerEntity getCraftingPlayer()
{
return craftingPlayer.get();
}
@@ -775,7 +717,7 @@ public class ForgeHooks
return ItemStack.EMPTY;
}
public static boolean onPlayerAttackTarget(EntityPlayer player, Entity target)
public static boolean onPlayerAttackTarget(PlayerEntity player, Entity target)
{
if (MinecraftForge.EVENT_BUS.post(new AttackEntityEvent(player, target))) return false;
ItemStack stack = player.getHeldItemMainhand();
@@ -789,76 +731,61 @@ public class ForgeHooks
if (event.isCanceled())
{
// Revert variable back to true as it would have been set to false
if (entity instanceof EntityMinecartContainer)
if (entity instanceof ContainerMinecartEntity)
{
((EntityMinecartContainer) entity).dropContentsWhenDead = true;
((ContainerMinecartEntity) entity).dropContentsWhenDead(true);
}
}
return !event.isCanceled();
}
@Nullable
public static RayTraceResult rayTraceEyes(EntityLivingBase entity, double length)
public static ActionResultType onInteractEntityAt(PlayerEntity player, Entity entity, RayTraceResult ray, Hand hand)
{
Vec3d startPos = new Vec3d(entity.posX, entity.posY + entity.getEyeHeight(), entity.posZ);
Vec3d endPos = startPos.add(new Vec3d(entity.getLookVec().x * length, entity.getLookVec().y * length, entity.getLookVec().z * length));
return entity.world.rayTraceBlocks(startPos, endPos);
}
@Nullable
public static Vec3d rayTraceEyeHitVec(EntityLivingBase entity, double length)
{
RayTraceResult git = rayTraceEyes(entity, length);
return git == null ? null : git.hitVec;
}
public static EnumActionResult onInteractEntityAt(EntityPlayer player, Entity entity, RayTraceResult ray, EnumHand hand)
{
Vec3d vec3d = new Vec3d(ray.hitVec.x - entity.posX, ray.hitVec.y - entity.posY, ray.hitVec.z - entity.posZ);
Vec3d vec3d = new Vec3d(ray.func_216347_e().x - entity.posX, ray.func_216347_e().y - entity.posY, ray.func_216347_e().z - entity.posZ);
return onInteractEntityAt(player, entity, vec3d, hand);
}
public static EnumActionResult onInteractEntityAt(EntityPlayer player, Entity entity, Vec3d vec3d, EnumHand hand)
public static ActionResultType onInteractEntityAt(PlayerEntity player, Entity entity, Vec3d vec3d, Hand hand)
{
PlayerInteractEvent.EntityInteractSpecific evt = new PlayerInteractEvent.EntityInteractSpecific(player, hand, entity, vec3d);
MinecraftForge.EVENT_BUS.post(evt);
return evt.isCanceled() ? evt.getCancellationResult() : null;
}
public static EnumActionResult onInteractEntity(EntityPlayer player, Entity entity, EnumHand hand)
public static ActionResultType onInteractEntity(PlayerEntity player, Entity entity, Hand hand)
{
PlayerInteractEvent.EntityInteract evt = new PlayerInteractEvent.EntityInteract(player, hand, entity);
MinecraftForge.EVENT_BUS.post(evt);
return evt.isCanceled() ? evt.getCancellationResult() : null;
}
public static EnumActionResult onItemRightClick(EntityPlayer player, EnumHand hand)
public static ActionResultType onItemRightClick(PlayerEntity player, Hand hand)
{
PlayerInteractEvent.RightClickItem evt = new PlayerInteractEvent.RightClickItem(player, hand);
MinecraftForge.EVENT_BUS.post(evt);
return evt.isCanceled() ? evt.getCancellationResult() : null;
}
public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(EntityPlayer player, BlockPos pos, EnumFacing face, Vec3d hitVec)
public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(PlayerEntity player, BlockPos pos, Direction face)
{
PlayerInteractEvent.LeftClickBlock evt = new PlayerInteractEvent.LeftClickBlock(player, pos, face, hitVec);
PlayerInteractEvent.LeftClickBlock evt = new PlayerInteractEvent.LeftClickBlock(player, pos, face);
MinecraftForge.EVENT_BUS.post(evt);
return evt;
}
public static PlayerInteractEvent.RightClickBlock onRightClickBlock(EntityPlayer player, EnumHand hand, BlockPos pos, EnumFacing face, Vec3d hitVec)
public static PlayerInteractEvent.RightClickBlock onRightClickBlock(PlayerEntity player, Hand hand, BlockPos pos, Direction face)
{
PlayerInteractEvent.RightClickBlock evt = new PlayerInteractEvent.RightClickBlock(player, hand, pos, face, hitVec);
PlayerInteractEvent.RightClickBlock evt = new PlayerInteractEvent.RightClickBlock(player, hand, pos, face);
MinecraftForge.EVENT_BUS.post(evt);
return evt;
}
public static void onEmptyClick(EntityPlayer player, EnumHand hand)
public static void onEmptyClick(PlayerEntity player, Hand hand)
{
MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.RightClickEmpty(player, hand));
}
public static void onEmptyLeftClick(EntityPlayer player)
public static void onEmptyLeftClick(PlayerEntity player)
{
MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.LeftClickEmpty(player));
}
@@ -956,7 +883,7 @@ public class ForgeHooks
ctx.resetPoolCtx();
if (json.has("name"))
return JsonUtils.getString(json, "name");
return JSONUtils.getString(json, "name");
if (ctx.custom)
return "custom#" + json.hashCode(); //We don't care about custom ones modders shouldn't be editing them!
@@ -975,40 +902,36 @@ public class ForgeHooks
ctx.entryCount++;
if (json.has("entryName"))
return ctx.validateEntryName(JsonUtils.getString(json, "entryName"));
return ctx.validateEntryName(JSONUtils.getString(json, "entryName"));
if (ctx.custom)
return "custom#" + json.hashCode(); //We don't care about custom ones modders shouldn't be editing them!
String name = null;
if ("item".equals(type))
name = JsonUtils.getString(json, "name");
name = JSONUtils.getString(json, "name");
else if ("loot_table".equals(type))
name = JsonUtils.getString(json, "name");
name = JSONUtils.getString(json, "name");
else if ("empty".equals(type))
name = "empty";
return ctx.validateEntryName(name);
}
//TODO: Some registry to support custom LootEntry types?
public static LootEntry deserializeJsonLootEntry(String type, JsonObject json, int weight, int quality, LootCondition[] conditions){ return null; }
public static String getLootEntryType(LootEntry entry){ return null; } //Companion to above function
public static boolean onCropsGrowPre(World worldIn, BlockPos pos, IBlockState state, boolean def)
public static boolean onCropsGrowPre(World worldIn, BlockPos pos, BlockState state, boolean def)
{
BlockEvent ev = new BlockEvent.CropGrowEvent.Pre(worldIn,pos,state);
MinecraftForge.EVENT_BUS.post(ev);
return (ev.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || (ev.getResult() == net.minecraftforge.eventbus.api.Event.Result.DEFAULT && def));
}
public static void onCropsGrowPost(World worldIn, BlockPos pos, IBlockState state)
public static void onCropsGrowPost(World worldIn, BlockPos pos, BlockState state)
{
MinecraftForge.EVENT_BUS.post(new BlockEvent.CropGrowEvent.Post(worldIn, pos, state, worldIn.getBlockState(pos)));
}
@Nullable
public static CriticalHitEvent getCriticalHit(EntityPlayer player, Entity target, boolean vanillaCritical, float damageModifier)
public static CriticalHitEvent getCriticalHit(PlayerEntity player, Entity target, boolean vanillaCritical, float damageModifier)
{
CriticalHitEvent hitResult = new CriticalHitEvent(player, target, damageModifier, vanillaCritical);
MinecraftForge.EVENT_BUS.post(hitResult);
@@ -1019,7 +942,7 @@ public class ForgeHooks
return null;
}
public static void onAdvancement(EntityPlayerMP player, Advancement advancement)
public static void onAdvancement(ServerPlayerEntity player, Advancement advancement)
{
MinecraftForge.EVENT_BUS.post(new AdvancementEvent(player, advancement));
}
@@ -1035,31 +958,31 @@ public class ForgeHooks
String modId = registryName == null ? null : registryName.getNamespace();
if ("minecraft".equals(modId))
{
if (item instanceof ItemEnchantedBook)
if (item instanceof EnchantedBookItem)
{
NBTTagList enchantmentsNbt = ItemEnchantedBook.getEnchantments(itemStack);
ListNBT enchantmentsNbt = EnchantedBookItem.getEnchantments(itemStack);
if (enchantmentsNbt.size() == 1)
{
NBTTagCompound nbttagcompound = enchantmentsNbt.getCompound(0);
ResourceLocation resourceLocation = ResourceLocation.makeResourceLocation(nbttagcompound.getString("id"));
CompoundNBT nbttagcompound = enchantmentsNbt.getCompound(0);
ResourceLocation resourceLocation = ResourceLocation.tryCreate(nbttagcompound.getString("id"));
if (resourceLocation != null && ForgeRegistries.ENCHANTMENTS.containsKey(resourceLocation))
{
return resourceLocation.getNamespace();
}
}
}
else if (item instanceof ItemPotion || item instanceof ItemTippedArrow)
else if (item instanceof PotionItem || item instanceof TippedArrowItem)
{
PotionType potionType = PotionUtils.getPotionFromItem(itemStack);
Potion potionType = PotionUtils.getPotionFromItem(itemStack);
ResourceLocation resourceLocation = ForgeRegistries.POTION_TYPES.getKey(potionType);
if (resourceLocation != null)
{
return resourceLocation.getNamespace();
}
}
else if (item instanceof ItemSpawnEgg)
else if (item instanceof SpawnEggItem)
{
ResourceLocation resourceLocation = ((ItemSpawnEgg)item).getType(null).getRegistryName();
ResourceLocation resourceLocation = ((SpawnEggItem)item).getType(null).getRegistryName();
if (resourceLocation != null)
{
return resourceLocation.getNamespace();
@@ -1069,7 +992,7 @@ public class ForgeHooks
return modId;
}
public static boolean onFarmlandTrample(World world, BlockPos pos, IBlockState state, float fallDistance, Entity entity)
public static boolean onFarmlandTrample(World world, BlockPos pos, BlockState state, float fallDistance, Entity entity)
{
if (entity.canTrample(state, pos, fallDistance))
{
@@ -1111,7 +1034,7 @@ public class ForgeHooks
}
@Override
public IBlockState getBlockState(BlockPos pos) {
public BlockState getBlockState(BlockPos pos) {
return Blocks.AIR.getDefaultState();
}
@@ -1122,50 +1045,46 @@ public class ForgeHooks
}
public static int onNoteChange(World world, BlockPos pos, IBlockState state, int old, int _new) {
public static int onNoteChange(World world, BlockPos pos, BlockState state, int old, int _new) {
NoteBlockEvent.Change event = new NoteBlockEvent.Change(world, pos, state, old, _new);
if (MinecraftForge.EVENT_BUS.post(event))
return -1;
return event.getVanillaNoteId();
}
public static int canEntitySpawn(EntityLiving entity, IWorld world, double x, double y, double z, MobSpawnerBaseLogic spawner) {
public static int canEntitySpawn(MobEntity entity, IWorld world, double x, double y, double z, AbstractSpawner spawner) {
Result res = ForgeEventFactory.canEntitySpawn(entity, world, x, y, z, null);
return res == Result.DEFAULT ? 0 : res == Result.DENY ? -1 : 1;
}
public static <T> void deserializeTagAdditions(Tag.Builder<T> builder, Predicate<ResourceLocation> isValueKnown, Function<ResourceLocation, T> valueGetter, JsonObject json)
public static <T> void deserializeTagAdditions(Tag.Builder<T> builder, Function<ResourceLocation, Optional<T>> valueGetter, JsonObject json)
{
if (json.has("optional"))
{
for (JsonElement entry : JsonUtils.getJsonArray(json, "optional"))
for (JsonElement entry : JSONUtils.getJsonArray(json, "optional"))
{
String s = JsonUtils.getString(entry, "value");
String s = JSONUtils.getString(entry, "value");
if (!s.startsWith("#"))
{
ResourceLocation rl = new ResourceLocation(s);
if (isValueKnown.test(rl) && valueGetter.apply(rl) != null)
{
builder.add(valueGetter.apply(rl));
}
T value = valueGetter.apply(new ResourceLocation(s)).orElse(null);
if (value != null)
builder.add(value);
} else
{
builder.add(new OptionalTagEntry<>(new ResourceLocation(s.substring(1))));
}
}
}
if (json.has("remove"))
{
for (JsonElement entry : JsonUtils.getJsonArray(json, "remove"))
for (JsonElement entry : JSONUtils.getJsonArray(json, "remove"))
{
String s = JsonUtils.getString(entry, "value");
String s = JSONUtils.getString(entry, "value");
if (!s.startsWith("#"))
{
ResourceLocation rl = new ResourceLocation(s);
if (isValueKnown.test(rl) && valueGetter.apply(rl) != null)
T value = valueGetter.apply(new ResourceLocation(s)).orElse(null);
if (value != null)
{
Tag.ITagEntry<T> dummyEntry = new Tag.ListEntry<>(Collections.singletonList(valueGetter.apply(rl)));
Tag.ITagEntry<T> dummyEntry = new Tag.ListEntry<>(Collections.singletonList(value));
builder.remove(dummyEntry);
}
} else
@@ -1206,14 +1125,14 @@ public class ForgeHooks
}
}
private static final Map<DataSerializer<?>, DataSerializerEntry> serializerEntries = GameData.getSerializerMap();
private static final Map<IDataSerializer<?>, DataSerializerEntry> serializerEntries = GameData.getSerializerMap();
//private static final ForgeRegistry<DataSerializerEntry> serializerRegistry = (ForgeRegistry<DataSerializerEntry>) ForgeRegistries.DATA_SERIALIZERS;
// Do not reimplement this ^ it introduces a chicken-egg scenario by classloading registries during bootstrap
@Nullable
public static DataSerializer<?> getSerializer(int id, IntIdentityHashBiMap<DataSerializer<?>> vanilla)
public static IDataSerializer<?> getSerializer(int id, IntIdentityHashBiMap<IDataSerializer<?>> vanilla)
{
DataSerializer<?> serializer = vanilla.get(id);
IDataSerializer<?> serializer = vanilla.getByValue(id);
if (serializer == null)
{
DataSerializerEntry entry = ((ForgeRegistry<DataSerializerEntry>)ForgeRegistries.DATA_SERIALIZERS).getValue(id);
@@ -1222,7 +1141,7 @@ public class ForgeHooks
return serializer;
}
public static int getSerializerId(DataSerializer<?> serializer, IntIdentityHashBiMap<DataSerializer<?>> vanilla)
public static int getSerializerId(IDataSerializer<?> serializer, IntIdentityHashBiMap<IDataSerializer<?>> vanilla)
{
int id = vanilla.getId(serializer);
if (id < 0)
@@ -20,10 +20,10 @@
package net.minecraftforge.common;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.WorldServer;
import net.minecraft.world.ServerWorld;
import net.minecraftforge.client.CloudRenderer;
import net.minecraftforge.common.util.FakePlayerFactory;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
@@ -42,9 +42,9 @@ public class ForgeInternalHandler
public void onEntityJoinWorld(EntityJoinWorldEvent event)
{
Entity entity = event.getEntity();
if (entity.getClass().equals(EntityItem.class))
if (entity.getClass().equals(ItemEntity.class))
{
ItemStack stack = ((EntityItem)entity).getItem();
ItemStack stack = ((ItemEntity)entity).getItem();
Item item = stack.getItem();
/*
if (item.hasCustomEntity(stack))
@@ -65,8 +65,8 @@ public class ForgeInternalHandler
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onDimensionUnload(WorldEvent.Unload event)
{
if (event.getWorld() instanceof WorldServer)
FakePlayerFactory.unloadWorld((WorldServer) event.getWorld());
if (event.getWorld() instanceof ServerWorld)
FakePlayerFactory.unloadWorld((ServerWorld) event.getWorld());
}
@SubscribeEvent
@@ -44,7 +44,7 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.resources.SimpleReloadableResourceManager;
import net.minecraft.world.storage.SaveHandler;
import net.minecraft.world.storage.WorldInfo;
@@ -138,9 +138,9 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
{
VersionChecker.startVersionCheck();
}
// Brandings need to recompute when language changes
DistExecutor.runWhenOn(Dist.CLIENT, () -> () -> ((SimpleReloadableResourceManager)Minecraft.getInstance().getResourceManager()).addReloadListener((ISelectiveResourceReloadListener) BrandingControl::clearCaches));
DistExecutor.runWhenOn(Dist.CLIENT, () -> () -> ((SimpleReloadableResourceManager)Minecraft.getInstance().getResourceManager()).func_219534_a((ISelectiveResourceReloadListener) BrandingControl::clearCaches));
}
/*
@@ -195,19 +195,19 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
}
@Override
public NBTTagCompound getDataForWriting(SaveHandler handler, WorldInfo info)
public CompoundNBT getDataForWriting(SaveHandler handler, WorldInfo info)
{
NBTTagCompound forgeData = new NBTTagCompound();
NBTTagCompound dims = new NBTTagCompound();
CompoundNBT forgeData = new CompoundNBT();
CompoundNBT dims = new CompoundNBT();
DimensionManager.writeRegistry(dims);
if (!dims.isEmpty())
forgeData.setTag("dims", dims);
forgeData.func_218657_a("dims", dims);
// TODO fluids FluidRegistry.writeDefaultFluidList(forgeData);
return forgeData;
}
@Override
public void readData(SaveHandler handler, WorldInfo info, NBTTagCompound tag)
public void readData(SaveHandler handler, WorldInfo info, CompoundNBT tag)
{
if (tag.contains("dims", 10))
DimensionManager.readRegistry(tag.getCompound("dims"));
@@ -41,4 +41,4 @@ package net.minecraftforge.common;
*/
public interface IExtensibleEnum
{
}
}
@@ -21,7 +21,7 @@ package net.minecraftforge.common;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityMinecart;
import net.minecraft.entity.item.minecart.AbstractMinecartEntity;
/**
* This class defines a replacement for the default minecart collision code.
@@ -38,7 +38,7 @@ public interface IMinecartCollisionHandler
* @param cart The cart that called the collision.
* @param other The object it collided with.
*/
void onEntityCollision(EntityMinecart cart, Entity other);
void onEntityCollision(AbstractMinecartEntity cart, Entity other);
/**
* This function replaced the function of the same name in EntityMinecart.
@@ -48,7 +48,7 @@ public interface IMinecartCollisionHandler
* @param other The entity requesting the collision box.
* @return The collision box or null.
*/
AxisAlignedBB getCollisionBox(EntityMinecart cart, Entity other);
AxisAlignedBB getCollisionBox(AbstractMinecartEntity cart, Entity other);
/**
* This function is used to define the box used for detecting minecart collisions.
@@ -56,7 +56,7 @@ public interface IMinecartCollisionHandler
* @param cart The cart for which the collision box was requested.
* @return The collision box, cannot be null.
*/
AxisAlignedBB getMinecartCollisionBox(EntityMinecart cart);
AxisAlignedBB getMinecartCollisionBox(AbstractMinecartEntity cart);
/**
* This function replaces the function of the same name in EntityMinecart.
@@ -64,6 +64,6 @@ public interface IMinecartCollisionHandler
* @param cart The cart for which the bounding box was requested.
* @return The bounding box or null.
*/
AxisAlignedBB getBoundingBox(EntityMinecart cart);
AxisAlignedBB getBoundingBox(AbstractMinecartEntity cart);
}
@@ -19,28 +19,28 @@
package net.minecraftforge.common;
import net.minecraft.block.BlockCrops;
import net.minecraft.block.BlockFlower;
import net.minecraft.block.BlockSapling;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.block.CropsBlock;
import net.minecraft.block.FlowerBlock;
import net.minecraft.block.SaplingBlock;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockReader;
public interface IPlantable
{
default EnumPlantType getPlantType(IBlockReader world, BlockPos pos) {
if (this instanceof BlockCrops) return EnumPlantType.Crop;
if (this instanceof BlockSapling) return EnumPlantType.Plains;
if (this instanceof BlockFlower) return EnumPlantType.Plains;
if (this == Blocks.DEAD_BUSH) return EnumPlantType.Desert;
if (this == Blocks.LILY_PAD) return EnumPlantType.Water;
if (this == Blocks.RED_MUSHROOM) return EnumPlantType.Cave;
if (this == Blocks.BROWN_MUSHROOM) return EnumPlantType.Cave;
if (this == Blocks.NETHER_WART) return EnumPlantType.Nether;
if (this == Blocks.TALL_GRASS) return EnumPlantType.Plains;
return net.minecraftforge.common.EnumPlantType.Plains;
default PlantType getPlantType(IBlockReader world, BlockPos pos) {
if (this instanceof CropsBlock) return PlantType.Crop;
if (this instanceof SaplingBlock) return PlantType.Plains;
if (this instanceof FlowerBlock) return PlantType.Plains;
if (this == Blocks.DEAD_BUSH) return PlantType.Desert;
if (this == Blocks.LILY_PAD) return PlantType.Water;
if (this == Blocks.RED_MUSHROOM) return PlantType.Cave;
if (this == Blocks.BROWN_MUSHROOM) return PlantType.Cave;
if (this == Blocks.NETHER_WART) return PlantType.Nether;
if (this == Blocks.TALL_GRASS) return PlantType.Plains;
return net.minecraftforge.common.PlantType.Plains;
}
IBlockState getPlant(IBlockReader world, BlockPos pos);
BlockState getPlant(IBlockReader world, BlockPos pos);
}
@@ -22,6 +22,7 @@ package net.minecraftforge.common;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IWorld;
import net.minecraft.world.IWorldReader;
@@ -38,6 +39,8 @@ import javax.annotation.Nonnull;
*/
//TODO Change to World, not IWorldReader and make Implementor responsible for removing itself from the world.
//Better mimics vanilla behavior and allows more control for the user.
@Deprecated //TODO: Reevaluate the entire thing, loot from blocks is now a loot table. So this is just a marker now.
public interface IShearable
{
/**
@@ -72,5 +75,7 @@ public interface IShearable
* @return A List containing all items from this shearing. May be empty.
*/
@Nonnull
List<ItemStack> onSheared(@Nonnull ItemStack item, IWorld world, BlockPos pos, int fortune);
default List<ItemStack> onSheared(@Nonnull ItemStack item, IWorld world, BlockPos pos, int fortune) {
return NonNullList.create();
}
}
@@ -21,20 +21,13 @@ package net.minecraftforge.common;
import net.minecraftforge.eventbus.api.BusBuilder;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraft.crash.CrashReport;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.ForgeHooks.SeedEntry;
import net.minecraftforge.common.ForgeHooks.FortuneSeedEntry;
import net.minecraftforge.versions.forge.ForgeVersion;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import javax.annotation.Nonnull;
public class MinecraftForge
{
/**
@@ -51,24 +44,6 @@ public class MinecraftForge
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker FORGE = MarkerManager.getMarker("FORGE");
/**
* Register a new seed to be dropped when breaking tall grass.
*
* @param seed The item to drop as a seed.
* @param weight The relative probability of the seeds,
* where wheat seeds are 10.
*
* Note: These functions may be going away soon, we're looking into loot tables....
*/
public static void addGrassSeed(@Nonnull ItemStack seed, int weight)
{
addGrassSeed(new SeedEntry(seed, weight));
}
public static void addGrassSeed(SeedEntry seed)
{
ForgeHooks.seedList.add(seed);
}
/**
* Method invoked by FML before any other mods are loaded.
*/
@@ -83,8 +58,6 @@ public class MinecraftForge
//For all the normal CrashReport classes to be defined. We're in MC's classloader so this should all be fine
new CrashReport("ThisIsFake", new Exception("Not real"));
addGrassSeed(new FortuneSeedEntry(new ItemStack(Items.WHEAT_SEEDS), 100, 1, 2));
}
@@ -19,9 +19,10 @@
package net.minecraftforge.common;
import java.util.function.Function;
import java.util.function.BiFunction;
import net.minecraft.network.PacketBuffer;
import net.minecraft.world.World;
import net.minecraft.world.dimension.Dimension;
import net.minecraft.world.dimension.DimensionType;
import net.minecraftforge.registries.ForgeRegistryEntry;
@@ -34,7 +35,7 @@ import net.minecraftforge.registries.ForgeRegistryEntry;
*/
public abstract class ModDimension extends ForgeRegistryEntry<ModDimension>
{
public abstract Function<DimensionType, ? extends Dimension> getFactory();
public abstract BiFunction<World, DimensionType, ? extends Dimension> getFactory();
/**
* Serialize any necessary data, this is called both when saving the world on the server.
@@ -19,12 +19,10 @@
package net.minecraftforge.common;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IWorldReader;
public enum EnumPlantType
public enum PlantType
{
Plains,
Desert,
@@ -35,17 +33,17 @@ public enum EnumPlantType
Crop;
/**
* Getting a custom {@link EnumPlantType}, or an existing one if it has the same name as that one. Your plant should implement {@link IPlantable}
* Getting a custom {@link PlantType}, or an existing one if it has the same name as that one. Your plant should implement {@link IPlantable}
* and return this custom type in {@link IPlantable#getPlantType(IBlockAccess, BlockPos)}.
*
* <p>If your new plant grows on blocks like any one of them above, never create a new {@link EnumPlantType}.
* <p>If your new plant grows on blocks like any one of them above, never create a new {@link PlantType}.
* This enumeration is only functioning in
* {@link net.minecraft.block.Block#canSustainPlant(IBlockState, IWorldReader, BlockPos, EnumFacing, IPlantable)},
* which you are supposed to override this function in your new block and create a new plant type to grow on that block.
*
* <p>You can create an instance of your plant type in your API and let your/others mods access it. It will be faster than calling this method.
* @param name the name of the type of plant, you had better follow the style above
* @return the acquired {@link EnumPlantType}, a new one if not found.
* @return the acquired {@link PlantType}, a new one if not found.
*/
public static EnumPlantType create(String name){ return null; }
public static PlantType create(String name){ return null; }
}
@@ -19,7 +19,7 @@
package net.minecraftforge.common.brewing;
import net.minecraft.init.Items;
import net.minecraft.item.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionBrewing;
@@ -23,8 +23,8 @@ import java.util.concurrent.Callable;
import com.google.common.base.Throwables;
import net.minecraft.nbt.INBTBase;
import net.minecraft.util.EnumFacing;
import net.minecraft.nbt.INBT;
import net.minecraft.util.Direction;
import net.minecraftforge.common.util.LazyOptional;
import javax.annotation.Nonnull;
@@ -60,7 +60,7 @@ public class Capability<T>
* @return a NBT holding the data. Null if no data needs to be stored.
*/
@Nullable
INBTBase writeNBT(Capability<T> capability, T instance, EnumFacing side);
INBT writeNBT(Capability<T> capability, T instance, Direction side);
/**
* Read the capability instance from a NBT tag.
@@ -81,7 +81,7 @@ public class Capability<T>
* @param side The side of the object the instance is associated with.
* @param nbt A NBT holding the data. Must not be null, as doesn't make sense to call this function with nothing to read...
*/
void readNBT(Capability<T> capability, T instance, EnumFacing side, INBTBase nbt);
void readNBT(Capability<T> capability, T instance, Direction side, INBT nbt);
}
/**
@@ -99,7 +99,7 @@ public class Capability<T>
* Quick access to the IStorage's readNBT.
* See {@link IStorage#readNBT(Capability, Object, EnumFacing, NBTBase)} for documentation.
*/
public void readNBT(T instance, EnumFacing side, INBTBase nbt)
public void readNBT(T instance, Direction side, INBT nbt)
{
storage.readNBT(this, instance, side, nbt);
}
@@ -109,7 +109,7 @@ public class Capability<T>
* See {@link IStorage#writeNBT(Capability, Object, EnumFacing)} for documentation.
*/
@Nullable
public INBTBase writeNBT(T instance, EnumFacing side)
public INBT writeNBT(T instance, Direction side)
{
return storage.writeNBT(this, instance, side);
}
@@ -28,9 +28,9 @@ import java.util.Map;
import com.google.common.collect.Lists;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.nbt.INBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.nbt.INBT;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.Direction;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.common.util.LazyOptional;
@@ -47,10 +47,10 @@ import net.minecraftforge.common.util.LazyOptional;
*/
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public final class CapabilityDispatcher implements INBTSerializable<NBTTagCompound>, ICapabilityProvider
public final class CapabilityDispatcher implements INBTSerializable<CompoundNBT>, ICapabilityProvider
{
private ICapabilityProvider[] caps;
private INBTSerializable<INBTBase>[] writers;
private INBTSerializable<INBT>[] writers;
private String[] names;
private final List<Runnable> listeners;
@@ -63,7 +63,7 @@ public final class CapabilityDispatcher implements INBTSerializable<NBTTagCompou
public CapabilityDispatcher(Map<ResourceLocation, ICapabilityProvider> list, List<Runnable> listeners, @Nullable ICapabilityProvider parent)
{
List<ICapabilityProvider> lstCaps = Lists.newArrayList();
List<INBTSerializable<INBTBase>> lstWriters = Lists.newArrayList();
List<INBTSerializable<INBT>> lstWriters = Lists.newArrayList();
List<String> lstNames = Lists.newArrayList();
this.listeners = listeners;
@@ -72,7 +72,7 @@ public final class CapabilityDispatcher implements INBTSerializable<NBTTagCompou
lstCaps.add(parent);
if (parent instanceof INBTSerializable)
{
lstWriters.add((INBTSerializable<INBTBase>)parent);
lstWriters.add((INBTSerializable<INBT>)parent);
lstNames.add("Parent");
}
}
@@ -83,7 +83,7 @@ public final class CapabilityDispatcher implements INBTSerializable<NBTTagCompou
lstCaps.add(prov);
if (prov instanceof INBTSerializable)
{
lstWriters.add((INBTSerializable<INBTBase>)prov);
lstWriters.add((INBTSerializable<INBT>)prov);
lstNames.add(entry.getKey().toString());
}
}
@@ -95,7 +95,7 @@ public final class CapabilityDispatcher implements INBTSerializable<NBTTagCompou
@Override
public <T> LazyOptional<T> getCapability(Capability<T> cap, @Nullable EnumFacing side)
public <T> LazyOptional<T> getCapability(Capability<T> cap, @Nullable Direction side)
{
for (ICapabilityProvider c : caps)
{
@@ -108,24 +108,24 @@ public final class CapabilityDispatcher implements INBTSerializable<NBTTagCompou
}
@Override
public NBTTagCompound serializeNBT()
public CompoundNBT serializeNBT()
{
NBTTagCompound nbt = new NBTTagCompound();
CompoundNBT nbt = new CompoundNBT();
for (int x = 0; x < writers.length; x++)
{
nbt.setTag(names[x], writers[x].serializeNBT());
nbt.func_218657_a(names[x], writers[x].serializeNBT());
}
return nbt;
}
@Override
public void deserializeNBT(NBTTagCompound nbt)
public void deserializeNBT(CompoundNBT nbt)
{
for (int x = 0; x < writers.length; x++)
{
if (nbt.hasKey(names[x]))
if (nbt.contains(names[x]))
{
writers[x].deserializeNBT(nbt.getTag(names[x]));
writers[x].deserializeNBT(nbt.get(names[x]));
}
}
}
@@ -22,10 +22,9 @@ package net.minecraftforge.common.capabilities;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.Direction;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.event.ForgeEventFactory;
@@ -79,7 +78,7 @@ public abstract class CapabilityProvider<B extends CapabilityProvider<B>> implem
}
}
protected final @Nullable NBTTagCompound serializeCaps()
protected final @Nullable CompoundNBT serializeCaps()
{
final CapabilityDispatcher disp = getCapabilities();
if (disp != null)
@@ -89,7 +88,7 @@ public abstract class CapabilityProvider<B extends CapabilityProvider<B>> implem
return null;
}
protected final void deserializeCaps(NBTTagCompound tag)
protected final void deserializeCaps(CompoundNBT tag)
{
final CapabilityDispatcher disp = getCapabilities();
if (disp != null)
@@ -113,7 +112,7 @@ public abstract class CapabilityProvider<B extends CapabilityProvider<B>> implem
@Override
@Nonnull
public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable EnumFacing side)
public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side)
{
final CapabilityDispatcher disp = getCapabilities();
return !valid || disp == null ? LazyOptional.empty() : disp.getCapability(cap, side);
@@ -22,7 +22,7 @@ package net.minecraftforge.common.capabilities;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.Direction;
import net.minecraftforge.common.util.LazyOptional;
public interface ICapabilityProvider
@@ -38,7 +38,7 @@ public interface ICapabilityProvider
* <strong>CAN BE NULL</strong>. Null is defined to represent 'internal' or 'self'
* @return The requested an optional holding the requested capability.
*/
@Nonnull <T> LazyOptional<T> getCapability(@Nonnull final Capability<T> cap, final @Nullable EnumFacing side);
@Nonnull <T> LazyOptional<T> getCapability(@Nonnull final Capability<T> cap, final @Nullable Direction side);
/*
* Purely added as a bouncer to sided version, to make modders stop complaining about calling with a null value.
@@ -19,8 +19,8 @@
package net.minecraftforge.common.capabilities;
import net.minecraft.nbt.INBTBase;
import net.minecraft.nbt.INBT;
import net.minecraftforge.common.util.INBTSerializable;
//Just a mix of the two, useful in patches to lower the size.
public interface ICapabilitySerializable<T extends INBTBase> extends ICapabilityProvider, INBTSerializable<T>{}
public interface ICapabilitySerializable<T extends INBT> extends ICapabilityProvider, INBTSerializable<T>{}
@@ -1,161 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2019.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.chunkio;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.common.collect.Maps;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.AnvilChunkLoader;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.gen.ChunkProviderServer;
public class ChunkIOExecutor
{
private static final Logger LOGGER = LogManager.getLogger();
private static final int BASE_THREADS = 1;
private static final int PLAYERS_PER_THREAD = 50;
private static final Map<QueuedChunk, ChunkIOProvider> tasks = Maps.newConcurrentMap();
private static final ThreadPoolExecutor pool = new ChunkIOThreadPoolExecutor(BASE_THREADS, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(),
new ThreadFactory()
{
private AtomicInteger count = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r)
{
Thread thread = new Thread(r, "Chunk I/O Executor Thread-" + count.getAndIncrement());
thread.setDaemon(true);
return thread;
}
}
);
//Load the chunk completely in this thread. Dequeue as needed...
public static Chunk syncChunkLoad(World world, AnvilChunkLoader loader, ChunkProviderServer provider, int x, int z)
{
QueuedChunk key = new QueuedChunk(x, z, world);
ChunkIOProvider task = tasks.remove(key); // Remove task because we will call the sync callbacks directly
if (task != null)
{
if (!pool.remove(task)) // If it wasn't in the pool, and run hasn't finished, then wait for the async thread.
{
synchronized(task)
{
while (!task.runFinished())
{
try
{
task.wait();
}
catch (InterruptedException e)
{
e.printStackTrace(); // Something happened? Log it?
}
}
}
}
else
{
// If the task was not run yet we still need to load the chunk
task.run();
}
}
else
{
task = new ChunkIOProvider(key, loader, provider);
task.run();
}
task.syncCallback();
return task.getChunk();
}
//Queue the chunk to be loaded, and call the runnable when finished
public static void queueChunkLoad(World world, AnvilChunkLoader loader, ChunkProviderServer provider, int x, int z, Runnable runnable)
{
QueuedChunk key = new QueuedChunk(x, z, world);
ChunkIOProvider task = tasks.get(key);
if (task == null)
{
task = new ChunkIOProvider(key, loader, provider);
task.addCallback(runnable); // Add before calling execute for thread safety
tasks.put(key, task);
pool.execute(task);
}
else
{
task.addCallback(runnable);
}
}
// Remove the chunk from the queue if it's in the list.
public static void dropQueuedChunkLoad(World world, int x, int z, Runnable runnable)
{
QueuedChunk key = new QueuedChunk(x, z, world);
ChunkIOProvider task = tasks.get(key);
if (task == null)
{
LOGGER.warn("Attempted to dequeue chunk that wasn't queued? {} @ ({}, {})", DimensionType.func_212678_a(world.dimension.getType()).toString(), x, z);
return;
}
task.removeCallback(runnable);
if (!task.hasCallback())
{
tasks.remove(key);
pool.remove(task);
}
}
public static void adjustPoolSize(int players)
{
pool.setCorePoolSize(Math.max(BASE_THREADS, players / PLAYERS_PER_THREAD));
}
public static void tick()
{
Iterator<ChunkIOProvider> itr = tasks.values().iterator();
while (itr.hasNext())
{
ChunkIOProvider task = itr.next();
if (task.runFinished())
{
if (task.hasCallback())
task.syncCallback();
itr.remove();
}
}
}
}
@@ -1,144 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2019.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.chunkio;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.AnvilChunkLoader;
import net.minecraft.world.gen.ChunkProviderServer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.ChunkPos;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.ChunkDataEvent;
import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;
class ChunkIOProvider implements Runnable
{
private final QueuedChunk chunkInfo;
private final AnvilChunkLoader loader;
private final ChunkProviderServer provider;
private Chunk chunk;
private NBTTagCompound nbt;
private final ConcurrentLinkedQueue<Runnable> callbacks = new ConcurrentLinkedQueue<Runnable>();
private boolean ran = false;
ChunkIOProvider(QueuedChunk chunk, AnvilChunkLoader loader, ChunkProviderServer provider)
{
this.chunkInfo = chunk;
this.loader = loader;
this.provider = provider;
}
public void addCallback(Runnable callback)
{
this.callbacks.add(callback);
}
public void removeCallback(Runnable callback)
{
this.callbacks.remove(callback);
}
@Override
public void run() // async stuff
{
synchronized(this)
{
try
{
Object[] data = null;
/*try
{ TODO Chunk loading
data = this.loader.loadChunk__Async(chunkInfo.world, chunkInfo.x, chunkInfo.z);
}
catch (IOException e)
{
throw new RuntimeException(e); // Allow exception to bubble up to afterExecute
}*/
if (data != null)
{
this.nbt = (NBTTagCompound)data[1];
this.chunk = (Chunk)data[0];
}
}
finally
{
this.ran = true;
this.notifyAll();
}
}
}
// sync stuff
public void syncCallback()
{
if (chunk == null)
{
this.runCallbacks();
return;
}
/*/ Load Entities TODO Chunk loading
this.loader.loadEntities(this.chunkInfo.world, this.nbt.getCompoundTag("Level"), this.chunk);
MinecraftForge.EVENT_BUS.post(new ChunkDataEvent.Load(this.chunk, this.nbt)); // Don't call ChunkDataEvent.Load async
this.chunk.setLastSaveTime(provider.world.getTotalWorldTime());
this.provider.chunkGenerator.recreateStructures(this.chunk, this.chunkInfo.x, this.chunkInfo.z);
provider.id2ChunkMap.put(ChunkPos.asLong(this.chunkInfo.x, this.chunkInfo.z), this.chunk);
this.chunk.onLoad();
this.chunk.populate(provider, provider.chunkGenerator);
*/
this.runCallbacks();
}
public Chunk getChunk()
{
return this.chunk;
}
public boolean runFinished()
{
return this.ran;
}
public boolean hasCallback()
{
return this.callbacks.size() > 0;
}
public void runCallbacks()
{
for (Runnable r : this.callbacks)
{
r.run();
}
this.callbacks.clear();
}
public QueuedChunk getChunkInfo()
{
return chunkInfo;
}
}
@@ -1,63 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2019.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.chunkio;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.crash.CrashReportCategory;
class ChunkIOThreadPoolExecutor extends ThreadPoolExecutor {
private static final Logger LOGGER = LogManager.getLogger();
public ChunkIOThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory)
{
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
}
@Override
protected void afterExecute(Runnable r, Throwable t)
{
if (t != null)
{
try
{
LOGGER.error("Unhandled exception loading chunk:", t);
QueuedChunk queuedChunk = ((ChunkIOProvider) r).getChunkInfo();
LOGGER.error(queuedChunk);
LOGGER.error(CrashReportCategory.getCoordinateInfo(queuedChunk.x << 4, 64, queuedChunk.z << 4));
}
catch (Throwable t2)
{
LOGGER.error(t2);
}
finally
{
// Make absolutely sure that we do not leave any deadlock case
r.notifyAll();
}
}
}
}
@@ -1,67 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2019.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.chunkio;
import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
class QueuedChunk {
final int x;
final int z;
final World world;
public QueuedChunk(int x, int z, World world) {
this.x = x;
this.z = z;
this.world = world;
}
@Override
public int hashCode() {
return (x * 31 + z * 29) ^ world.hashCode();
}
@Override
public boolean equals(Object object) {
if (object instanceof QueuedChunk) {
QueuedChunk other = (QueuedChunk) object;
return x == other.x && z == other.z && world == other.world;
}
return false;
}
@Override
public String toString()
{
StringBuilder result = new StringBuilder();
String NEW_LINE = System.getProperty("line.separator");
result.append(this.getClass().getName() + " {" + NEW_LINE);
result.append(" x: " + x + NEW_LINE);
result.append(" z: " + z + NEW_LINE);
result.append(" world: " + world.getWorldInfo().getWorldName() + NEW_LINE);
result.append(" dimension: " + DimensionType.func_212678_a(world.dimension.getType()).toString() + NEW_LINE);
result.append(" provider: " + world.dimension.getClass().getName() + NEW_LINE);
result.append("}");
return result.toString();
}
}
@@ -118,7 +118,7 @@ public class CompoundIngredient extends Ingredient
@Override
public CompoundIngredient parse(PacketBuffer buffer)
{
return new CompoundIngredient(Stream.generate(() -> Ingredient.fromBuffer(buffer)).limit(buffer.readVarInt()).collect(Collectors.toList()));
return new CompoundIngredient(Stream.generate(() -> Ingredient.read(buffer)).limit(buffer.readVarInt()).collect(Collectors.toList()));
}
@Override
@@ -131,7 +131,7 @@ public class CompoundIngredient extends Ingredient
public void write(PacketBuffer buffer, CompoundIngredient ingredient)
{
buffer.writeVarInt(ingredient.children.size());
ingredient.children.forEach(c -> c.writeToBuffer(buffer));
ingredient.children.forEach(c -> c.write(buffer));
}
}
@@ -49,11 +49,11 @@ import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.item.crafting.Ingredient.IItemList;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.PacketBuffer;
import net.minecraft.resources.IResource;
import net.minecraft.resources.IResourceManager;
import net.minecraft.util.JsonUtils;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistries;
@@ -73,19 +73,19 @@ public class CraftingHelper
private static Map<ResourceLocation, IItemList> constants = new HashMap<>();
public static final IConditionSerializer CONDITION_MOD_LOADED = condition("mod_loaded", json -> {
String modid = JsonUtils.getString(json, "modid");
String modid = JSONUtils.getString(json, "modid");
return () -> ModList.get().isLoaded(modid);
});
public static final IConditionSerializer CONDITION_ITEM_EXISTS = condition("item_exists", json -> {
String itemName = JsonUtils.getString(json, "item");
String itemName = JSONUtils.getString(json, "item");
return () -> ForgeRegistries.ITEMS.containsKey(new ResourceLocation(itemName));
});
public static final IConditionSerializer CONDITION_NOT = condition("not", json -> {
BooleanSupplier child = CraftingHelper.getCondition(JsonUtils.getJsonObject(json, "value"));
BooleanSupplier child = CraftingHelper.getCondition(JSONUtils.getJsonObject(json, "value"));
return () -> !child.getAsBoolean();
});
public static final IConditionSerializer CONDITION_OR = condition("or", json -> {
JsonArray values = JsonUtils.getJsonArray(json, "values");
JsonArray values = JSONUtils.getJsonArray(json, "values");
List<BooleanSupplier> children = Lists.newArrayList();
for (JsonElement j : values)
{
@@ -96,7 +96,7 @@ public class CraftingHelper
return () -> children.stream().anyMatch(BooleanSupplier::getAsBoolean);
});
public static final IConditionSerializer CONDITION_AND = condition("and", json -> {
JsonArray values = JsonUtils.getJsonArray(json, "values");
JsonArray values = JSONUtils.getJsonArray(json, "values");
List<BooleanSupplier> children = Lists.newArrayList();
for (JsonElement j : values)
{
@@ -208,7 +208,7 @@ public class CraftingHelper
JsonObject obj = (JsonObject)json;
String type = JsonUtils.getString(obj, "type", "minecraft:item");
String type = JSONUtils.getString(obj, "type", "minecraft:item");
if (type.isEmpty())
throw new JsonSyntaxException("Ingredient type can not be an empty string");
@@ -221,7 +221,7 @@ public class CraftingHelper
public static ItemStack getItemStack(JsonObject json, boolean readNBT)
{
String itemName = JsonUtils.getString(json, "item");
String itemName = JSONUtils.getString(json, "item");
Item item = ForgeRegistries.ITEMS.getValue(new ResourceLocation(itemName));
@@ -234,22 +234,22 @@ public class CraftingHelper
try
{
JsonElement element = json.get("nbt");
NBTTagCompound nbt;
CompoundNBT nbt;
if(element.isJsonObject())
nbt = JsonToNBT.getTagFromJson(GSON.toJson(element));
else
nbt = JsonToNBT.getTagFromJson(JsonUtils.getString(element, "nbt"));
nbt = JsonToNBT.getTagFromJson(JSONUtils.getString(element, "nbt"));
NBTTagCompound tmp = new NBTTagCompound();
if (nbt.hasKey("ForgeCaps"))
CompoundNBT tmp = new CompoundNBT();
if (nbt.contains("ForgeCaps"))
{
tmp.setTag("ForgeCaps", nbt.getTag("ForgeCaps"));
nbt.removeTag("ForgeCaps");
tmp.func_218657_a("ForgeCaps", nbt.get("ForgeCaps"));
nbt.remove("ForgeCaps");
}
tmp.setTag("tag", nbt);
tmp.setString("id", itemName);
tmp.setInt("Count", JsonUtils.getInt(json, "count", 1));
tmp.func_218657_a("tag", nbt);
tmp.putString("id", itemName);
tmp.putInt("Count", JSONUtils.getInt(json, "count", 1));
return ItemStack.read(tmp);
}
@@ -259,12 +259,12 @@ public class CraftingHelper
}
}
return new ItemStack(item, JsonUtils.getInt(json, "count", 1));
return new ItemStack(item, JSONUtils.getInt(json, "count", 1));
}
public static boolean processConditions(JsonObject json, String memberName)
{
return !json.has(memberName) || processConditions(JsonUtils.getJsonArray(json, memberName));
return !json.has(memberName) || processConditions(JSONUtils.getJsonArray(json, memberName));
}
public static boolean processConditions(JsonArray conditions)
@@ -284,7 +284,7 @@ public class CraftingHelper
public static BooleanSupplier getCondition(JsonObject json)
{
ResourceLocation type = new ResourceLocation(JsonUtils.getString(json, "type"));
ResourceLocation type = new ResourceLocation(JSONUtils.getString(json, "type"));
IConditionSerializer serrializer = conditions.get(type);
if (serrializer == null)
throw new JsonSyntaxException("Unknown condition type: " + type.toString());
@@ -303,23 +303,23 @@ public class CraftingHelper
String path = key.getPath();
if (!path.equals("recipes/_constants.json")) //Top level only
continue;
tmp.putAll(loadConstants(manager, key));
}
constants = tmp;
}
public static Map<ResourceLocation, IItemList> loadConstants(IResourceManager manager, ResourceLocation key) {
Map<ResourceLocation, IItemList> tmp = new HashMap<>();
try (IResource iresource = manager.getResource(key))
{
JsonObject[] elements = JsonUtils.fromJson(GSON, IOUtils.toString(iresource.getInputStream(), StandardCharsets.UTF_8), JsonObject[].class);
JsonObject[] elements = JSONUtils.fromJson(GSON, IOUtils.toString(iresource.getInputStream(), StandardCharsets.UTF_8), JsonObject[].class);
for (int x = 0; x < elements.length; x++)
{
JsonObject json = elements[x];
//Force namespace to the directory that this constants file is in, to prevent modders from overriding other's sneakily
//TODO: Move back to a resource pack/mod specific constant list?
ResourceLocation name = json.has("name") ? new ResourceLocation(JsonUtils.getString(json, "name")) : null;
ResourceLocation name = json.has("name") ? new ResourceLocation(JSONUtils.getString(json, "name")) : null;
if (name != null)
name = new ResourceLocation(key.getNamespace(), name.getPath());
@@ -332,7 +332,7 @@ public class CraftingHelper
else if (json.has("items"))
{
List<ItemStack> items = new ArrayList<>();
for (JsonElement item : JsonUtils.getJsonArray(json, "items"))
for (JsonElement item : JSONUtils.getJsonArray(json, "items"))
{
if (item.isJsonObject())
items.add(getItemStack(item.getAsJsonObject(), true));
@@ -349,7 +349,7 @@ public class CraftingHelper
else if (json.has("tag"))
tmp.put(name, Ingredient.deserializeItemList(json));
else if (json.has("item"))
tmp.put(name, new StackList(Lists.newArrayList(getItemStack(JsonUtils.getJsonObject(json, "item"), true))));
tmp.put(name, new StackList(Lists.newArrayList(getItemStack(JSONUtils.getJsonObject(json, "item"), true))));
else
LOGGER.error(CRAFTHELPER, "Couldn't load constant #{} from {} as it's missing `item` or `items` element", x, key);
}
@@ -19,10 +19,8 @@
package net.minecraftforge.common.crafting;
import net.minecraft.inventory.ContainerPlayer;
import net.minecraft.inventory.ContainerWorkbench;
import net.minecraft.inventory.InventoryCraftResult;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.inventory.CraftResultInventory;
import net.minecraft.inventory.CraftingInventory;
/**
* This interface is to be implemented on Container objects.
@@ -36,12 +34,12 @@ public interface IRecipeContainer
* The equivalent for {@link ContainerWorkbench} is {@link ContainerWorkbench#craftResult}.
* The equivalent for {@link ContainerPlayer} is {@link ContainerPlayer#craftResult}.
*/
InventoryCraftResult getCraftResult();
CraftResultInventory getCraftResult();
/**
* The crafting matrix of your container, where ingredients go for crafting.
* The equivalent for {@link ContainerWorkbench} is {@link ContainerWorkbench#craftMatrix}.
* The equivalent for {@link ContainerPlayer} is {@link ContainerPlayer#craftMatrix}.
*/
InventoryCrafting getCraftMatrix();
CraftingInventory getCraftMatrix();
}
@@ -19,6 +19,7 @@
package net.minecraftforge.common.crafting;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.crafting.IRecipe;
/**
@@ -26,7 +27,7 @@ import net.minecraft.item.crafting.IRecipe;
* book and auto crafting picks the correct shape.
* Note: These methods can't be named 'getHeight' or 'getWidth' due to obfusication issues.
*/
public interface IShapedRecipe extends IRecipe
public interface IShapedRecipe<T extends IInventory> extends IRecipe<T>
{
int getRecipeWidth();
int getRecipeHeight();
@@ -43,7 +43,7 @@ public class StackList implements IItemList
}
@Override
public JsonObject toJson()
public JsonObject serialize()
{
if (items.size() == 1)
return toJson(items.iterator().next());
@@ -1,118 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2019.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.extensions;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import com.google.common.collect.Maps;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.resources.IResourceManager;
import net.minecraft.resources.IResourceManagerReloadListener;
import net.minecraft.util.NonNullList;
import net.minecraft.world.World;
import net.minecraftforge.common.crafting.CraftingHelper;
import net.minecraftforge.common.crafting.RecipeType;
import net.minecraftforge.items.wrapper.RecipeWrapper;
@SuppressWarnings("deprecation")
public abstract class ForgeRecipeManager implements IResourceManagerReloadListener
{
/**
* Master list of sorted recipes.
*/
protected final Map<RecipeType<? extends IRecipe>, List<? extends IRecipe>> sortedRecipes = Maps.newHashMap();
@Override
public void onResourceManagerReload(IResourceManager resourceManager)
{
this.sortedRecipes.clear();
CraftingHelper.reloadConstants(resourceManager);
}
/**
* Returns all the recipes that match this type.
* @param type A recipe type.
* @return All recipes that are of the passed type. This list may be empty.
*/
@SuppressWarnings("unchecked")
public <T extends IRecipe> List<T> getRecipes(RecipeType<T> type)
{
return (List<T>) this.sortedRecipes.computeIfAbsent(type, t -> new ArrayList<>());
}
/**
* Automatically returns a result from the first recipe that matches this inv and type.
* Modders should probably not use this, and instead use {@link #getRecipe(IInventory, World, RecipeType)} since you get the recipe object itself.
* @param input An inventory.
* @param world The world.
* @param type The type of recipe to match against.
* @return The output of the first matching recipe, or {@link ItemStack#EMPTY} if no recipes match.
*/
public ItemStack getResult(IInventory input, World world, RecipeType<?> type)
{
for(IRecipe irecipe : getRecipes(type))
if (irecipe.matches(input, world)) return irecipe.getCraftingResult(input);
return ItemStack.EMPTY;
}
/**
* Used to find a matching recipe for the given inv, world, and type.
* Since this requires an IInventory, modders can use {@link RecipeWrapper} to avoid direct implementation.
* For crafting recipes, it is advised to still use {@link InventoryCrafting}. The dynamic vanilla recipes require they be crafted in one.
* @param input An inventory.
* @param world The world.
* @param type The type of recipe to match against.
* @return The first matching recipe.
*/
@Nullable
public <T extends IRecipe> T getRecipe(IInventory input, World world, RecipeType<T> type)
{
for(T irecipe : getRecipes(type))
if (irecipe.matches(input, world)) return irecipe;
return null;
}
/**
* Modders should not use this if possible. In the context that this is used, you should already have the recipe. Do not run extra lookups using this method.
* Use {@link IRecipe#getRemainingItems(IInventory)}.
*/
@Deprecated
public NonNullList<ItemStack> getRemainingItems(IInventory input, World world, RecipeType<?> type)
{
for(IRecipe irecipe : getRecipes(type))
if (irecipe.matches(input, world)) return irecipe.getRemainingItems(input);
NonNullList<ItemStack> nonnulllist = NonNullList.withSize(input.getSizeInventory(), ItemStack.EMPTY);
for(int i = 0; i < nonnulllist.size(); ++i)
nonnulllist.set(i, input.getStackInSlot(i));
return nonnulllist;
}
}
@@ -20,40 +20,41 @@
package net.minecraftforge.common.extensions;
import java.util.Collection;
import java.util.Optional;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.block.BlockBed;
import net.minecraft.block.BlockFarmland;
import net.minecraft.block.BlockFence;
import net.minecraft.block.BlockFire;
import net.minecraft.block.BlockHorizontal;
import net.minecraft.block.BlockStainedGlass;
import net.minecraft.block.BedBlock;
import net.minecraft.block.FarmlandBlock;
import net.minecraft.block.FenceBlock;
import net.minecraft.block.FireBlock;
import net.minecraft.block.HorizontalBlock;
import net.minecraft.block.IBeaconBeamColorProvider;
import net.minecraft.block.StainedGlassBlock;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.BlockFaceShape;
import net.minecraft.block.state.IBlockState;
import net.minecraft.block.BlockState;
import net.minecraft.client.particle.ParticleManager;
import net.minecraft.client.renderer.ActiveRenderInfo;
import net.minecraft.client.renderer.model.IBakedModel;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.MobEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.EntitySpawnPlacementRegistry;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.boss.EntityWither;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityWitherSkull;
import net.minecraft.entity.boss.dragon.EnderDragonEntity;
import net.minecraft.entity.boss.WitherEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.projectile.WitherSkullEntity;
import net.minecraft.fluid.IFluidState;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.init.MobEffects;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.block.Blocks;
import net.minecraft.item.Items;
import net.minecraft.potion.Effects;
import net.minecraft.item.DyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.pathfinding.PathNodeType;
@@ -62,8 +63,8 @@ import net.minecraft.state.properties.BedPart;
import net.minecraft.tags.BlockTags;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Rotation;
@@ -72,12 +73,12 @@ import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.Explosion;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IEnviromentBlockReader;
import net.minecraft.world.IWorld;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.IWorldReaderBase;
import net.minecraft.world.IWorldWriter;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.ServerWorld;
import net.minecraft.world.dimension.EndDimension;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
@@ -107,7 +108,7 @@ public interface IForgeBlock
* @param entity the entity in question
* @return the factor by which the entity's motion should be multiplied
*/
float getSlipperiness(IBlockState state, IWorldReader world, BlockPos pos, @Nullable Entity entity);
float getSlipperiness(BlockState state, IWorldReader world, BlockPos pos, @Nullable Entity entity);
/**
* Get a light value for this block, taking into account the given state and coordinates, normal ranges are between 0 and 15
@@ -117,7 +118,7 @@ public interface IForgeBlock
* @param pos
* @return The light value
*/
default int getLightValue(IBlockState state, IWorldReader world, BlockPos pos)
default int getLightValue(BlockState state, IEnviromentBlockReader world, BlockPos pos)
{
return state.getLightValue();
}
@@ -131,25 +132,11 @@ public interface IForgeBlock
* @param entity The entity trying to use the ladder, CAN be null.
* @return True if the block should act like a ladder
*/
default boolean isLadder(IBlockState state, IWorldReader world, BlockPos pos, EntityLivingBase entity)
default boolean isLadder(BlockState state, IWorldReader world, BlockPos pos, LivingEntity entity)
{
return false;
}
/**
* Return true if the block is a normal, solid cube. This
* determines indirect power state, entity ejection from blocks, and a few
* others.
*
* @param state The current state
* @param world The current world
* @param pos Block position in world
* @return True if the block is a full cube
*/
default boolean isNormalCube(IBlockState state, IBlockReader world, BlockPos pos)
{
return state.isNormalCube();
}
/**
* Check if the face of a block should block rendering.
*
@@ -162,7 +149,7 @@ public interface IForgeBlock
* @param face The side to check
* @return True if the block is opaque on the specified side.
*/
default boolean doesSideBlockRendering(IBlockState state, IWorldReader world, BlockPos pos, EnumFacing face)
default boolean doesSideBlockRendering(BlockState state, IEnviromentBlockReader world, BlockPos pos, Direction face)
{
return state.isOpaqueCube(world, pos);
}
@@ -175,9 +162,9 @@ public interface IForgeBlock
* @param pos Block position in world
* @return True if the block should deal damage
*/
default boolean isBurning(IBlockState state, IBlockReader world, BlockPos pos)
default boolean isBurning(BlockState state, IBlockReader world, BlockPos pos)
{
return false;
return this == Blocks.FIRE || this == Blocks.LAVA;
}
/**
@@ -191,7 +178,7 @@ public interface IForgeBlock
* @return True if block has a tile entity, false otherwise
*/
@SuppressWarnings("deprecation")
default boolean hasTileEntity(IBlockState state)
default boolean hasTileEntity(BlockState state)
{
return this instanceof ITileEntityProvider;
}
@@ -207,24 +194,13 @@ public interface IForgeBlock
*/
@SuppressWarnings("deprecation")
@Nullable
default TileEntity createTileEntity(IBlockState state, IBlockReader world)
default TileEntity createTileEntity(BlockState state, IBlockReader world)
{
if (getBlock() instanceof ITileEntityProvider)
return ((ITileEntityProvider)getBlock()).createNewTileEntity(world);
return null;
}
/**
* Return true from this function if the player with silk touch can harvest this block directly, and not it's normal drops.
*
* @param state current block state
* @param world The world
* @param pos Block position in world
* @param player The player doing the harvesting
* @return True if the block can be directly harvested using silk touch
*/
boolean canSilkHarvest(IBlockState state, IWorldReader world, BlockPos pos, EntityPlayer player);
/**
* Determines if the player can harvest this block, obtaining it's drops when the block is destroyed.
*
@@ -233,7 +209,7 @@ public interface IForgeBlock
* @param player The player damaging the block
* @return True to spawn the drops
*/
default public boolean canHarvestBlock(IBlockState state, IBlockReader world, BlockPos pos, EntityPlayer player)
default public boolean canHarvestBlock(BlockState state, IBlockReader world, BlockPos pos, PlayerEntity player)
{
return ForgeHooks.canHarvestBlock(state, player, world, pos);
}
@@ -258,10 +234,10 @@ public interface IForgeBlock
* @param fluid The current fluid state at current position
* @return True if the block is actually destroyed.
*/
default boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player, boolean willHarvest, IFluidState fluid)
default boolean removedByPlayer(BlockState state, World world, BlockPos pos, PlayerEntity player, boolean willHarvest, IFluidState fluid)
{
getBlock().onBlockHarvested(world, pos, state, player);
return world.setBlockState(pos, fluid.getBlockState(), world.isRemote ? 11 : 3);
return world.func_217377_a(pos, false);
}
/**
@@ -275,9 +251,9 @@ public interface IForgeBlock
* @param player The player or camera entity, null in some cases.
* @return True to treat this as a bed
*/
default boolean isBed(IBlockState state, IBlockReader world, BlockPos pos, @Nullable Entity player)
default boolean isBed(BlockState state, IBlockReader world, BlockPos pos, @Nullable Entity player)
{
return this.getBlock() instanceof BlockBed; //TODO: Forge: Keep isBed function?
return this.getBlock() instanceof BedBlock; //TODO: Forge: Keep isBed function?
}
/**
@@ -290,29 +266,29 @@ public interface IForgeBlock
* @param type The Mob Category Type
* @return True to allow a mob of the specified category to spawn, false to prevent it.
*/
default boolean canCreatureSpawn(IBlockState state, IWorldReaderBase world, BlockPos pos, EntitySpawnPlacementRegistry.SpawnPlacementType type, @Nullable EntityType<? extends EntityLiving> entityType)
default boolean canCreatureSpawn(BlockState state, IBlockReader world, BlockPos pos, EntitySpawnPlacementRegistry.PlacementType type, @Nullable EntityType<?> entityType)
{
return state.isTopSolid() || entityType != null && EntitySpawnPlacementRegistry.func_209345_a(entityType, state);
return state.func_215688_a(world, pos, entityType);
}
/**
* Returns the position that the player is moved to upon
* Returns the position that the sleeper is moved to upon
* waking up, or respawning at the bed.
*
* @param state The current state
* @param world The current world
* @param pos Block position in world
* @param player The player or camera entity, null in some cases.
* @param sleeper The sleeper or camera entity, null in some cases.
* @return The spawn position
*/
@Nullable
default BlockPos getBedSpawnPosition(IBlockState state, IBlockReader world, BlockPos pos, @Nullable EntityPlayer player)
default Optional<Vec3d> getBedSpawnPosition(EntityType<?> entityType, BlockState state, IWorldReader world, BlockPos pos, @Nullable LivingEntity sleeper)
{
if (world instanceof World)
{
return BlockBed.getSafeExitLocation(world,pos,0);
return BedBlock.func_220172_a(entityType, world,pos,0);
}
return null;
return Optional.empty();
}
/**
@@ -321,29 +297,29 @@ public interface IForgeBlock
*
* @param world The current world
* @param pos Block position in world
* @param player The player or camera entity, null in some cases.
* @param sleeper The sleeper or camera entity, null in some cases.
* @param occupied True if we are occupying the bed, or false if they are stopping use of the bed
*/
default void setBedOccupied(IBlockState state, IWorldReader world, BlockPos pos, EntityPlayer player, boolean occupied)
default void setBedOccupied(BlockState state, IWorldReader world, BlockPos pos, LivingEntity sleeper, boolean occupied)
{
if (world instanceof IWorldWriter)
{
((IWorldWriter)world).setBlockState(pos, state.with(BlockBed.OCCUPIED,occupied), 4);
((IWorldWriter)world).setBlockState(pos, state.with(BedBlock.OCCUPIED,occupied), 4);
}
}
/**
* Returns the direction of the block. Same values that
* are returned by BlockDirectional
* are returned by BlockDirectional. Called every frame tick for every living entity. Be VERY fast.
*
* @param state The current state
* @param world The current world
* @param pos Block position in world
* @return Bed direction
*/
default EnumFacing getBedDirection(IBlockState state, IWorldReader world, BlockPos pos)
default Direction getBedDirection(BlockState state, IWorldReader world, BlockPos pos)
{
return state.get(BlockHorizontal.HORIZONTAL_FACING);
return state.get(HorizontalBlock.HORIZONTAL_FACING);
}
/**
@@ -353,9 +329,9 @@ public interface IForgeBlock
* @param pos Block position in world
* @return True if the current block is the foot side of a bed.
*/
default boolean isBedFoot(IBlockState state, IWorldReader world, BlockPos pos)
default boolean isBedFoot(BlockState state, IWorldReader world, BlockPos pos)
{
return state.get(BlockBed.PART) == BedPart.FOOT;
return state.get(BedBlock.PART) == BedPart.FOOT;
}
/**
@@ -365,7 +341,7 @@ public interface IForgeBlock
* @param world The current world
* @param pos Block position in world
*/
default void beginLeaveDecay(IBlockState state, IWorldReader world, BlockPos pos) {}
default void beginLeaveDecay(BlockState state, IWorldReader world, BlockPos pos) {}
/**
* Determines this block should be treated as an air block
@@ -378,7 +354,7 @@ public interface IForgeBlock
* @param pos Block position in world
* @return True if the block considered air
*/
default boolean isAir(IBlockState state, IBlockReader world, BlockPos pos)
default boolean isAir(BlockState state, IBlockReader world, BlockPos pos)
{
return state.getMaterial() == Material.AIR;
}
@@ -391,11 +367,25 @@ public interface IForgeBlock
* @param pos Block position in world
* @return true if this block can be replaced by growing leaves.
*/
default boolean canBeReplacedByLeaves(IBlockState state, IWorldReaderBase world, BlockPos pos)
default boolean canBeReplacedByLeaves(BlockState state, IWorldReader world, BlockPos pos)
{
return (isAir(state, world, pos) || state.isIn(BlockTags.LEAVES)) || !state.isOpaqueCube(world, pos);
}
/**
* Used during tree growth to determine if newly generated logs can replace this block.
*
* @param state The current state
* @param world The current world
* @param pos Block position in world
* @return true if this block can be replaced by growing leaves.
*/
default boolean canBeReplacedByLogs(BlockState state, IWorldReader world, BlockPos pos)
{
return (isAir(state, world, pos) || state.isIn(BlockTags.LEAVES)) || this == Blocks.GRASS_BLOCK || Block.isDirt(getBlock())
|| getBlock().isIn(BlockTags.LOGS) || getBlock().isIn(BlockTags.SAPLINGS) || this == Blocks.VINE;
}
/**
* Determines if the current block is replaceable by Ore veins during world generation.
*
@@ -406,7 +396,7 @@ public interface IForgeBlock
* for overworld generation, and neatherack for the nether.
* @return True to allow this block to be replaced by a ore
*/
default boolean isReplaceableOreGen(IBlockState state, IWorldReader world, BlockPos pos, Predicate<IBlockState> target)
default boolean isReplaceableOreGen(BlockState state, IWorldReader world, BlockPos pos, Predicate<BlockState> target)
{
return target.test(state);
}
@@ -420,25 +410,11 @@ public interface IForgeBlock
* @param explosion The explosion
* @return The amount of the explosion absorbed.
*/
default float getExplosionResistance(IBlockState state, IWorldReader world, BlockPos pos, @Nullable Entity exploder, Explosion explosion)
default float getExplosionResistance(BlockState state, IWorldReader world, BlockPos pos, @Nullable Entity exploder, Explosion explosion)
{
return this.getBlock().getExplosionResistance();
}
/**
* Called when the block is destroyed by an explosion.
* Useful for allowing the block to take into account tile entities,
* state, etc. when exploded, before it is removed.
*
* @param world The current world
* @param pos Block position in world
* @param explosion The explosion instance affecting the block
*/
default void onBlockExploded(IBlockState state, World world, BlockPos pos, Explosion explosion) {
world.removeBlock(pos);
getBlock().onExplosionDestroy(world, pos, explosion);
}
/**
* Determine if this block can make a redstone connection on the side provided,
* Useful to control which sides are inputs and outputs for redstone wires.
@@ -449,33 +425,11 @@ public interface IForgeBlock
* @param side The side that is trying to make the connection, CAN BE NULL
* @return True to make the connection
*/
default boolean canConnectRedstone(IBlockState state, IBlockReader world, BlockPos pos, @Nullable EnumFacing side)
default boolean canConnectRedstone(BlockState state, IBlockReader world, BlockPos pos, @Nullable Direction side)
{
return state.canProvidePower() && side != null;
}
/**
* Determines if a torch can be placed on the top surface of this block.
* Useful for creating your own block that torches can be on, such as fences.
*
* @param state The current state
* @param world The current world
* @param pos Block position in world
* @return True to allow the torch to be placed
*/
default boolean canPlaceTorchOnTop(IBlockState state, IWorldReaderBase world, BlockPos pos)
{
// Keep conditionals in sync with BlockTorch#isValidPosition
if (this == Blocks.END_GATEWAY) {
return false;
} else if (this instanceof BlockFence || this instanceof BlockStainedGlass || this == Blocks.GLASS || this == Blocks.COBBLESTONE_WALL || this == Blocks.MOSSY_COBBLESTONE_WALL || state.isTopSolid()) {
return true;
} else {
BlockFaceShape shape = state.getBlockFaceShape(world, pos, EnumFacing.UP);
return (shape == BlockFaceShape.SOLID || shape == BlockFaceShape.CENTER || shape == BlockFaceShape.CENTER_BIG) && !Block.isExceptionBlockForAttaching(getBlock());
}
}
/**
*
* Called when A user uses the creative pick block button on this block
@@ -483,7 +437,7 @@ public interface IForgeBlock
* @param target The full target the player is looking at
* @return A ItemStack to add to the player's inventory, empty itemstack if nothing should be added.
*/
default ItemStack getPickBlock(IBlockState state, RayTraceResult target, IBlockReader world, BlockPos pos, EntityPlayer player)
default ItemStack getPickBlock(BlockState state, RayTraceResult target, IBlockReader world, BlockPos pos, PlayerEntity player)
{
return this.getBlock().getItem(world, pos, state);
}
@@ -494,7 +448,7 @@ public interface IForgeBlock
*
* @return False to disallow spawning.
*/
default boolean isFoliage(IBlockState state, IWorldReader world, BlockPos pos)
default boolean isFoliage(BlockState state, IWorldReader world, BlockPos pos)
{
return false;
}
@@ -511,7 +465,7 @@ public interface IForgeBlock
* @param numberOfParticles That vanilla world have spawned
* @return True to prevent vanilla landing particles from spawning
*/
default boolean addLandingEffects(IBlockState state1, WorldServer worldserver, BlockPos pos, IBlockState state2, EntityLivingBase entity, int numberOfParticles)
default boolean addLandingEffects(BlockState state1, ServerWorld worldserver, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles)
{
return false;
}
@@ -528,7 +482,7 @@ public interface IForgeBlock
* @param entity The entity running on the block.
* @return True to prevent vanilla running particles from spawning.
*/
default boolean addRunningEffects(IBlockState state, World world, BlockPos pos, Entity entity)
default boolean addRunningEffects(BlockState state, World world, BlockPos pos, Entity entity)
{
return false;
}
@@ -546,7 +500,7 @@ public interface IForgeBlock
* @return True to prevent vanilla digging particles form spawning.
*/
@OnlyIn(Dist.CLIENT)
default boolean addHitEffects(IBlockState state, World worldObj, RayTraceResult target, ParticleManager manager)
default boolean addHitEffects(BlockState state, World worldObj, RayTraceResult target, ParticleManager manager)
{
return false;
}
@@ -563,7 +517,7 @@ public interface IForgeBlock
* @return True to prevent vanilla break particles from spawning.
*/
@OnlyIn(Dist.CLIENT)
default boolean addDestroyEffects(IBlockState state, World world, BlockPos pos, ParticleManager manager)
default boolean addDestroyEffects(BlockState state, World world, BlockPos pos, ParticleManager manager)
{
return false;
}
@@ -586,7 +540,7 @@ public interface IForgeBlock
* @param plantable The plant that wants to check
* @return True to allow the plant to be planted/stay.
*/
boolean canSustainPlant(IBlockState state, IBlockReader world, BlockPos pos, EnumFacing facing, IPlantable plantable);
boolean canSustainPlant(BlockState state, IBlockReader world, BlockPos pos, Direction facing, IPlantable plantable);
/**
* Called when a plant grows on this block, only implemented for saplings using the WorldGen*Trees classes right now.
@@ -602,9 +556,9 @@ public interface IForgeBlock
* @param pos Block position in world
* @param source Source plant's position in world
*/
default void onPlantGrow(IBlockState state, IWorld world, BlockPos pos, BlockPos source)
default void onPlantGrow(BlockState state, IWorld world, BlockPos pos, BlockPos source)
{
if (this.getBlock() == Blocks.GRASS_BLOCK || this.getBlock() == Blocks.MYCELIUM || this.getBlock() == Blocks.FARMLAND || this.getBlock() == Blocks.AIR)
if (Block.isDirt(getBlock()))
world.setBlockState(pos, Blocks.DIRT.getDefaultState(), 2);
}
@@ -617,10 +571,10 @@ public interface IForgeBlock
* @param pos Block position in world
* @return True if the soil should be considered fertile.
*/
default boolean isFertile(IBlockState state, IBlockReader world, BlockPos pos)
default boolean isFertile(BlockState state, IBlockReader world, BlockPos pos)
{
if (this.getBlock() == Blocks.FARMLAND)
return state.get(BlockFarmland.MOISTURE) > 0;
return state.get(FarmlandBlock.MOISTURE) > 0;
return false;
}
@@ -633,7 +587,7 @@ public interface IForgeBlock
* @param beacon Beacon position in world
* @return True, to support the beacon, and make it active with this block.
*/
default boolean isBeaconBase(IBlockState state, IWorldReader world, BlockPos pos, BlockPos beacon)
default boolean isBeaconBase(BlockState state, IWorldReader world, BlockPos pos, BlockPos beacon)
{
return this.getBlock() == Blocks.EMERALD_BLOCK || this.getBlock() == Blocks.GOLD_BLOCK ||
this.getBlock() == Blocks.DIAMOND_BLOCK || this.getBlock() == Blocks.IRON_BLOCK;
@@ -647,13 +601,13 @@ public interface IForgeBlock
* @param fortune
* @return Amount of XP from breaking this block.
*/
default int getExpDrop(IBlockState state, IWorldReader world, BlockPos pos, int fortune)
default int getExpDrop(BlockState state, IWorldReader world, BlockPos pos, int fortune, int silktouch)
{
return 0;
}
@SuppressWarnings("deprecation")
default IBlockState rotate(IBlockState state, IWorld world, BlockPos pos, Rotation direction)
default BlockState rotate(BlockState state, IWorld world, BlockPos pos, Rotation direction)
{
return state.rotate(direction);
}
@@ -667,15 +621,15 @@ public interface IForgeBlock
* @return An array of valid axes to rotate around, or null for none or unknown
*/
@Nullable
default EnumFacing[] getValidRotations(IBlockState state, IBlockReader world, BlockPos pos)
default Direction[] getValidRotations(BlockState state, IBlockReader world, BlockPos pos)
{
for (IProperty<?> prop : state.getProperties())
{
if ((prop.getName().equals("facing") || prop.getName().equals("rotation")) && prop.getValueClass() == EnumFacing.class)
if ((prop.getName().equals("facing") || prop.getName().equals("rotation")) && prop.getValueClass() == Direction.class)
{
@SuppressWarnings("unchecked")
Collection<EnumFacing> values = ((Collection<EnumFacing>)prop.getAllowedValues());
return values.toArray(new EnumFacing[values.size()]);
Collection<Direction> values = ((Collection<Direction>)prop.getAllowedValues());
return values.toArray(new Direction[values.size()]);
}
}
return null;
@@ -687,7 +641,7 @@ public interface IForgeBlock
* @param pos Block position in world
* @return The amount of enchanting power this block produces.
*/
default float getEnchantPowerBonus(IBlockState state, IWorldReader world, BlockPos pos)
default float getEnchantPowerBonus(BlockState state, IWorldReader world, BlockPos pos)
{
return this.getBlock() == Blocks.BOOKSHELF ? 1: 0;
}
@@ -703,16 +657,16 @@ public interface IForgeBlock
* @return Amount of XP from breaking this block.
*/
@SuppressWarnings("unchecked")
default boolean recolorBlock(IBlockState state, IWorld world, BlockPos pos, EnumFacing facing, EnumDyeColor color)
default boolean recolorBlock(BlockState state, IWorld world, BlockPos pos, Direction facing, DyeColor color)
{
for (IProperty<?> prop : state.getProperties())
{
if (prop.getName().equals("color") && prop.getValueClass() == EnumDyeColor.class)
if (prop.getName().equals("color") && prop.getValueClass() == DyeColor.class)
{
EnumDyeColor current = (EnumDyeColor)state.get(prop);
DyeColor current = (DyeColor)state.get(prop);
if (current != color && prop.getAllowedValues().contains(color))
{
world.setBlockState(pos, state.with(((IProperty<EnumDyeColor>)prop), color), 3);
world.setBlockState(pos, state.with(((IProperty<DyeColor>)prop), color), 3);
return true;
}
}
@@ -726,7 +680,7 @@ public interface IForgeBlock
* @param pos Block position in world
* @param neighbor Block position of neighbor
*/
default void onNeighborChange(IBlockState state, IWorldReader world, BlockPos pos, BlockPos neighbor){}
default void onNeighborChange(BlockState state, IWorldReader world, BlockPos pos, BlockPos neighbor){}
/**
* Called on an Observer block whenever an update for an Observer is received.
@@ -737,7 +691,7 @@ public interface IForgeBlock
* @param changedBlock The updated block.
* @param changedBlockPos The updated block's position.
*/
default void observedNeighborChange(IBlockState observerState, World world, BlockPos observerPos, Block changedBlock, BlockPos changedBlockPos){}
default void observedNeighborChange(BlockState observerState, World world, BlockPos observerPos, Block changedBlock, BlockPos changedBlockPos){}
/**
* Called to determine whether to allow the a block to handle its own indirect power rather than using the default rules.
@@ -746,9 +700,9 @@ public interface IForgeBlock
* @param side The INPUT side of the block to be powered - ie the opposite of this block's output side
* @return Whether Block#isProvidingWeakPower should be called when determining indirect power
*/
default boolean shouldCheckWeakPower(IBlockState state, IWorldReader world, BlockPos pos, EnumFacing side)
default boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side)
{
return state.isNormalCube(world, pos);
return state.func_215686_e(world, pos);
}
/**
@@ -760,7 +714,7 @@ public interface IForgeBlock
* @param pos Block position in world
* @return true To be notified of changes
*/
default boolean getWeakChanges(IBlockState state, IWorldReader world, BlockPos pos)
default boolean getWeakChanges(BlockState state, IWorldReader world, BlockPos pos)
{
return false;
}
@@ -769,7 +723,7 @@ public interface IForgeBlock
* Queries the class of tool required to harvest this block, if null is returned
* we assume that anything can harvest this block.
*/
ToolType getHarvestTool(IBlockState state);
ToolType getHarvestTool(BlockState state);
/**
* Queries the harvest level of this item stack for the specified tool class,
@@ -777,13 +731,13 @@ public interface IForgeBlock
*
* @return Harvest level, or -1 if not the specified tool type.
*/
int getHarvestLevel(IBlockState state);
int getHarvestLevel(BlockState state);
/**
* Checks if the specified tool type is efficient on this block,
* meaning that it digs at full speed.
*/
default boolean isToolEffective(IBlockState state, ToolType tool)
default boolean isToolEffective(BlockState state, ToolType tool)
{
if (tool == ToolType.PICKAXE && (this.getBlock() == Blocks.REDSTONE_ORE || this.getBlock() == Blocks.REDSTONE_LAMP || this.getBlock() == Blocks.OBSIDIAN))
return false;
@@ -793,7 +747,7 @@ public interface IForgeBlock
/**
* Can return IExtendedBlockState
*/
default IBlockState getExtendedState(IBlockState state, IBlockReader world, BlockPos pos)
default BlockState getExtendedState(BlockState state, IBlockReader world, BlockPos pos)
{
return state;
}
@@ -802,7 +756,7 @@ public interface IForgeBlock
* Queries if this block should render in a given layer.
* A custom {@link IBakedModel} can use {@link net.minecraftforge.client.MinecraftForgeClient#getRenderLayer()} to alter the model based on layer.
*/
default boolean canRenderInLayer(IBlockState state, BlockRenderLayer layer)
default boolean canRenderInLayer(BlockState state, BlockRenderLayer layer)
{
return this.getBlock().getRenderLayer() == layer;
}
@@ -815,9 +769,9 @@ public interface IForgeBlock
* @param entity The entity that is breaking/stepping on/placing/hitting/falling on this block, or null if no entity is in this context
* @return A SoundType to use
*/
default SoundType getSoundType(IBlockState state, IWorldReader world, BlockPos pos, @Nullable Entity entity)
default SoundType getSoundType(BlockState state, IWorldReader world, BlockPos pos, @Nullable Entity entity)
{
return this.getBlock().getSoundType();
return this.getBlock().func_220072_p(state);
}
/**
@@ -828,8 +782,10 @@ public interface IForgeBlock
* @return A float RGB [0.0, 1.0] array to be averaged with a beacon's existing beam color, or null to do nothing to the beam
*/
@Nullable
default float[] getBeaconColorMultiplier(IBlockState state, IWorldReader world, BlockPos pos, BlockPos beaconPos)
default float[] getBeaconColorMultiplier(BlockState state, IWorldReader world, BlockPos pos, BlockPos beaconPos)
{
if (getBlock() instanceof IBeaconBeamColorProvider)
return ((IBeaconBeamColorProvider)getBlock()).getColor().getColorComponentValues();
return null;
}
@@ -845,18 +801,18 @@ public interface IForgeBlock
* @return The new fog color.
*/
@OnlyIn(Dist.CLIENT)
default Vec3d getFogColor(IBlockState state, IWorldReader world, BlockPos pos, Entity entity, Vec3d originalColor, float partialTicks)
default Vec3d getFogColor(BlockState state, IWorldReader world, BlockPos pos, Entity entity, Vec3d originalColor, float partialTicks)
{
if (state.getMaterial() == Material.WATER)
{
float f12 = 0.0F;
if (entity instanceof EntityLivingBase)
if (entity instanceof LivingEntity)
{
EntityLivingBase ent = (EntityLivingBase)entity;
LivingEntity ent = (LivingEntity)entity;
f12 = (float) EnchantmentHelper.getRespirationModifier(ent) * 0.2F;
if (ent.isPotionActive(MobEffects.WATER_BREATHING))
if (ent.isPotionActive(Effects.WATER_BREATHING))
{
f12 = f12 * 0.3F + 0.6F;
}
@@ -881,7 +837,7 @@ public interface IForgeBlock
* @param viewpoint the viewpoint
* @return the block state that should be 'seen'
*/
default IBlockState getStateAtViewpoint(IBlockState state, IBlockReader world, BlockPos pos, Vec3d viewpoint)
default BlockState getStateAtViewpoint(BlockState state, IBlockReader world, BlockPos pos, Vec3d viewpoint)
{
return state;
}
@@ -900,7 +856,7 @@ public interface IForgeBlock
* @return The state to be placed in the world
*/
@SuppressWarnings("deprecation")
default IBlockState getStateForPlacement(IBlockState state, EnumFacing facing, IBlockState state2, IWorld world, BlockPos pos1, BlockPos pos2, EnumHand hand)
default BlockState getStateForPlacement(BlockState state, Direction facing, BlockState state2, IWorld world, BlockPos pos1, BlockPos pos2, Hand hand)
{
return this.getBlock().updatePostPlacement(state, facing, state2, world, pos1, pos2);
}
@@ -914,7 +870,7 @@ public interface IForgeBlock
* @param facing The side the connecting block is on
* @return True to allow another block to connect to this block
*/
default boolean canBeConnectedTo(IBlockState state, IBlockReader world, BlockPos pos, EnumFacing facing)
default boolean canBeConnectedTo(BlockState state, IBlockReader world, BlockPos pos, Direction facing)
{
return false;
}
@@ -925,58 +881,20 @@ public interface IForgeBlock
* @return the PathNodeType
*/
@Nullable
default PathNodeType getAiPathNodeType(IBlockState state, IBlockReader world, BlockPos pos, @Nullable EntityLiving entity)
default PathNodeType getAiPathNodeType(BlockState state, IBlockReader world, BlockPos pos, @Nullable MobEntity entity)
{
return state.isBurning(world, pos) ? PathNodeType.DAMAGE_FIRE : null;
}
/**
* @param blockState The state for this block
* @param world The world this block is in
* @param pos The position of this block
* @param side The side of this block that the chest lid is trying to open into
* @return true if the chest should be prevented from opening by this block
*/
default boolean doesSideBlockChestOpening(IBlockState blockState, IBlockReader world, BlockPos pos, EnumFacing side)
{
ResourceLocation registryName = this.getBlock().getRegistryName();
if (registryName != null && "minecraft".equals(registryName.getNamespace()))
{
// maintain the vanilla behavior of https://bugs.mojang.com/browse/MC-378
return blockState.isNormalCube(world, pos);
}
return blockState.isTopSolid();
}
/**
* @param state The state
* @return true if the block is sticky block which used for pull or push adjacent blocks (use by piston)
*/
default boolean isStickyBlock(IBlockState state)
default boolean isStickyBlock(BlockState state)
{
return state.getBlock() == Blocks.SLIME_BLOCK;
}
/**
* This gets a complete list of items dropped from this block.
*
* @param state Current state
* @param drops add all items this block drops to this drops list
* @param world The current world, Currently hard 'World' and not 'IBlockReder' because vanilla needs it.
* @param pos Block position in world
* @param fortune Breakers fortune level
*/
default void getDrops(IBlockState state, NonNullList<ItemStack> drops, World world, BlockPos pos, int fortune)
{
int count = getBlock().getItemsToDropCount(state, fortune, world, pos, world.rand);
for (int i = 0; i < count; i++)
{
Item item = getBlock().getItemDropped(state, world, pos, fortune).asItem();
if (item != Items.AIR)
drops.add(new ItemStack(item));
}
}
/**
* Chance that fire will spread and consume this block.
* 300 being a 100% chance, 0, being a 0% chance.
@@ -987,9 +905,10 @@ public interface IForgeBlock
* @param face The face that the fire is coming from
* @return A number ranging from 0 to 300 relating used to determine if the block will be consumed by fire
*/
default int getFlammability(IBlockState state, IBlockReader world, BlockPos pos, EnumFacing face)
@SuppressWarnings("deprecation")
default int getFlammability(BlockState state, IBlockReader world, BlockPos pos, Direction face)
{
return ((BlockFire)Blocks.FIRE).getFlammability(getBlock());
return ((FireBlock)Blocks.FIRE).func_220274_q(state);
}
/**
@@ -1002,7 +921,7 @@ public interface IForgeBlock
* @param face The face that the fire is coming from
* @return True if the face can be on fire, false otherwise.
*/
default boolean isFlammable(IBlockState state, IBlockReader world, BlockPos pos, EnumFacing face)
default boolean isFlammable(BlockState state, IBlockReader world, BlockPos pos, Direction face)
{
return state.getFlammability(world, pos, face) > 0;
}
@@ -1017,9 +936,9 @@ public interface IForgeBlock
* @param face The face that the fire is coming from
* @return A number that is used to determine the speed of fire growth around the block
*/
default int getFireSpreadSpeed(IBlockState state, IBlockReader world, BlockPos pos, EnumFacing face)
default int getFireSpreadSpeed(BlockState state, IBlockReader world, BlockPos pos, Direction face)
{
return ((BlockFire)Blocks.FIRE).getEncouragement(getBlock());
return ((FireBlock)Blocks.FIRE).func_220275_r(state);
}
/**
@@ -1033,13 +952,13 @@ public interface IForgeBlock
* @param side The face that the fire is coming from
* @return True if this block sustains fire, meaning it will never go out.
*/
default boolean isFireSource(IBlockState state, IBlockReader world, BlockPos pos, EnumFacing side)
default boolean isFireSource(BlockState state, IBlockReader world, BlockPos pos, Direction side)
{
if (side != EnumFacing.UP)
if (side != Direction.UP)
return false;
if (getBlock() == Blocks.NETHERRACK || getBlock() == Blocks.MAGMA_BLOCK)
return true;
if (world instanceof World && ((World)world).dimension instanceof EndDimension && getBlock() == Blocks.BEDROCK)
if (world instanceof IWorldReader && ((IWorldReader)world).getDimension() instanceof EndDimension && getBlock() == Blocks.BEDROCK)
return true;
return false;
}
@@ -1052,9 +971,9 @@ public interface IForgeBlock
* @param pos Block position in world
* @return True to allow the ender dragon to destroy this block
*/
default boolean canEntityDestroy(IBlockState state, IBlockReader world, BlockPos pos, Entity entity)
default boolean canEntityDestroy(BlockState state, IBlockReader world, BlockPos pos, Entity entity)
{
if (entity instanceof EntityDragon)
if (entity instanceof EnderDragonEntity)
{
return this != Blocks.BARRIER &&
this != Blocks.OBSIDIAN &&
@@ -1068,28 +987,15 @@ public interface IForgeBlock
this != Blocks.IRON_BARS &&
this != Blocks.END_GATEWAY;
}
else if ((entity instanceof EntityWither) ||
(entity instanceof EntityWitherSkull))
else if ((entity instanceof WitherEntity) ||
(entity instanceof WitherSkullEntity))
{
return EntityWither.canDestroyBlock(getBlock());
return state.isAir(world, pos) || WitherEntity.canDestroyBlock(state);
}
return true;
}
/**
* Determines if the top is consider 'solid'. This is a helper for getBlockFaceShape(UP) == SOLID.
* Sadly some vanilla logic doesn't sync this value, so we have to have this special function.
*
* @param world The world
* @param pos Block position in world
* @return True if the top is considered solid
*/
default boolean isTopSolid(IBlockState state, IWorldReader world, BlockPos pos)
{
return state.isTopSolid();
}
/**
* Ray traces through the blocks collision from start vector to end vector returning a ray trace hit.
*
@@ -1102,8 +1008,17 @@ public interface IForgeBlock
* @return A result that suits your block
*/
@Nullable
default RayTraceResult getRayTraceResult(IBlockState state, World world, BlockPos pos, Vec3d start, Vec3d end, RayTraceResult original)
default RayTraceResult getRayTraceResult(BlockState state, World world, BlockPos pos, Vec3d start, Vec3d end, RayTraceResult original)
{
return original;
}
/**
* Determines if this block should drop loot when exploded.
*/
@SuppressWarnings("deprecation")
default boolean canDropFromExplosion(BlockState state, IBlockReader world, BlockPos pos, Explosion explosion)
{
return state.getBlock().canDropFromExplosion(explosion);
}
}
@@ -19,22 +19,22 @@
package net.minecraftforge.common.extensions;
import java.util.Optional;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.particle.ParticleManager;
import net.minecraft.client.renderer.model.IBakedModel;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.EntitySpawnPlacementRegistry.SpawnPlacementType;
import net.minecraft.entity.MobEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.EntitySpawnPlacementRegistry.PlacementType;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.fluid.IFluidState;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.DyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.pathfinding.PathNodeType;
@@ -45,11 +45,11 @@ import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.Explosion;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IEnviromentBlockReader;
import net.minecraft.world.IWorld;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.IWorldReaderBase;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.ServerWorld;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.common.IPlantable;
@@ -57,9 +57,9 @@ import net.minecraftforge.common.ToolType;
public interface IForgeBlockState
{
default IBlockState getBlockState()
default BlockState getBlockState()
{
return (IBlockState)this;
return (BlockState)this;
}
/**
@@ -84,7 +84,7 @@ public interface IForgeBlockState
/**
* Get a light value for this block, taking into account the given state and coordinates, normal ranges are between 0 and 15
*/
default int getLightValue(IWorldReader world, BlockPos pos)
default int getLightValue(IEnviromentBlockReader world, BlockPos pos)
{
return getBlockState().getBlock().getLightValue(getBlockState(), world, pos);
}
@@ -97,25 +97,11 @@ public interface IForgeBlockState
* @param entity The entity trying to use the ladder, CAN be null.
* @return True if the block should act like a ladder
*/
default boolean isLadder(IWorldReader world, BlockPos pos, EntityLivingBase entity)
default boolean isLadder(IWorldReader world, BlockPos pos, LivingEntity entity)
{
return getBlockState().getBlock().isLadder(getBlockState(), world, pos, entity);
}
/**
* Return true if the block is a normal, solid cube. This
* determines indirect power state, entity ejection from blocks, and a few
* others.
*
* @param world The current world
* @param pos Block position in world
* @return True if the block is a full cube
*/
default boolean isNormalCube(IBlockReader world, BlockPos pos)
{
return getBlockState().getBlock().isNormalCube(getBlockState(), world, pos);
}
/**
* Check if the face of a block should block rendering.
*
@@ -127,7 +113,7 @@ public interface IForgeBlockState
* @param face The side to check
* @return True if the block is opaque on the specified side.
*/
default boolean doesSideBlockRendering(IWorldReader world, BlockPos pos, EnumFacing face)
default boolean doesSideBlockRendering(IEnviromentBlockReader world, BlockPos pos, Direction face)
{
return getBlockState().getBlock().doesSideBlockRendering(getBlockState(), world, pos, face);
}
@@ -160,19 +146,6 @@ public interface IForgeBlockState
return getBlockState().getBlock().createTileEntity(getBlockState(), world);
}
/**
* Return true from this function if the player with silk touch can harvest this block directly, and not it's normal drops.
*
* @param world The world
* @param pos Block position in world
* @param player The player doing the harvesting
* @return True if the block can be directly harvested using silk touch
*/
default boolean canSilkHarvest(IWorldReader world, BlockPos pos, EntityPlayer player)
{
return getBlockState().getBlock().canSilkHarvest(getBlockState(), world, pos, player);
}
/**
* Determines if the player can harvest this block, obtaining it's drops when the block is destroyed.
*
@@ -181,7 +154,7 @@ public interface IForgeBlockState
* @param player The player damaging the block
* @return True to spawn the drops
*/
default boolean canHarvestBlock(IBlockReader world, BlockPos pos, EntityPlayer player)
default boolean canHarvestBlock(IBlockReader world, BlockPos pos, PlayerEntity player)
{
return getBlockState().getBlock().canHarvestBlock(getBlockState(), world, pos, player);
}
@@ -205,7 +178,7 @@ public interface IForgeBlockState
* @param fluid The current fluid and block state for the position in the world.
* @return True if the block is actually destroyed.
*/
default boolean removedByPlayer(World world, BlockPos pos, EntityPlayer player, boolean willHarvest, IFluidState fluid)
default boolean removedByPlayer(World world, BlockPos pos, PlayerEntity player, boolean willHarvest, IFluidState fluid)
{
return getBlockState().getBlock().removedByPlayer(getBlockState(), world, pos, player, willHarvest, fluid);
}
@@ -220,7 +193,7 @@ public interface IForgeBlockState
* @param player The player or camera entity, null in some cases.
* @return True to treat this as a bed
*/
default boolean isBed(IBlockReader world, BlockPos pos, @Nullable EntityPlayer player)
default boolean isBed(IBlockReader world, BlockPos pos, @Nullable LivingEntity player)
{
return getBlockState().getBlock().isBed(getBlockState(), world, pos, player);
}
@@ -234,23 +207,22 @@ public interface IForgeBlockState
* @param type The Mob Category Type
* @return True to allow a mob of the specified category to spawn, false to prevent it.
*/
default boolean canCreatureSpawn(IWorldReaderBase world, BlockPos pos, SpawnPlacementType type, EntityType<? extends EntityLiving> entityType)
default boolean canCreatureSpawn(IWorldReader world, BlockPos pos, PlacementType type, EntityType<?> entityType)
{
return getBlockState().getBlock().canCreatureSpawn(getBlockState(), world, pos, type, entityType);
}
/**
* Returns the position that the player is moved to upon
* Returns the position that the sleeper is moved to upon
* waking up, or respawning at the bed.
*
* @param world The current world
* @param pos Block position in world
* @param player The player or camera entity, null in some cases.
* @param sleeper The sleeper or camera entity, null in some cases.
* @return The spawn position
*/
@Nullable
default BlockPos getBedSpawnPosition(IBlockReader world, BlockPos pos, @Nullable EntityPlayer player)
default Optional<Vec3d> getBedSpawnPosition(EntityType<?> type, IWorldReader world, BlockPos pos, @Nullable LivingEntity sleeper)
{
return getBlockState().getBlock().getBedSpawnPosition(getBlockState(), world, pos, player);
return getBlockState().getBlock().getBedSpawnPosition(type, getBlockState(), world, pos, sleeper);
}
/**
@@ -258,12 +230,12 @@ public interface IForgeBlockState
*
* @param world The current world
* @param pos Block position in world
* @param player The player or camera entity, null in some cases.
* @param sleeper The sleeper or camera entity, null in some cases.
* @param occupied True if we are occupying the bed, or false if they are stopping use of the bed
*/
default void setBedOccupied(IWorldReader world, BlockPos pos, EntityPlayer player, boolean occupied)
default void setBedOccupied(IWorldReader world, BlockPos pos, LivingEntity sleeper, boolean occupied)
{
getBlockState().getBlock().setBedOccupied(getBlockState(), world, pos, player, occupied);
getBlockState().getBlock().setBedOccupied(getBlockState(), world, pos, sleeper, occupied);
}
/**
@@ -274,7 +246,7 @@ public interface IForgeBlockState
* @param pos Block position in world
* @return Bed direction
*/
default EnumFacing getBedDirection(IWorldReader world, BlockPos pos)
default Direction getBedDirection(IWorldReader world, BlockPos pos)
{
return getBlockState().getBlock().getBedDirection(getBlockState(), world, pos);
}
@@ -324,11 +296,24 @@ public interface IForgeBlockState
* @param pos Block position in world
* @return true if this block can be replaced by growing leaves.
*/
default boolean canBeReplacedByLeaves(IWorldReaderBase world, BlockPos pos)
default boolean canBeReplacedByLeaves(IWorldReader world, BlockPos pos)
{
return getBlockState().getBlock().canBeReplacedByLeaves(getBlockState(), world, pos);
}
/**
* Used during tree growth to determine if newly generated logs can replace this block.
*
* @param state The current state
* @param world The current world
* @param pos Block position in world
* @return true if this block can be replaced by growing leaves.
*/
default boolean canBeReplacedByLogs(IWorldReader world, BlockPos pos)
{
return getBlockState().getBlock().canBeReplacedByLogs(getBlockState(), world, pos);
}
/**
* Determines if the current block is replaceable by Ore veins during world generation.
*
@@ -338,7 +323,7 @@ public interface IForgeBlockState
* for overworld generation, and neatherack for the nether.
* @return True to allow this block to be replaced by a ore
*/
default boolean isReplaceableOreGen(IWorldReader world, BlockPos pos, Predicate<IBlockState> target)
default boolean isReplaceableOreGen(IWorldReader world, BlockPos pos, Predicate<BlockState> target)
{
return getBlockState().getBlock().isReplaceableOreGen(getBlockState(), world, pos, target);
}
@@ -357,20 +342,6 @@ public interface IForgeBlockState
return getBlockState().getBlock().getExplosionResistance(getBlockState(), world, pos, exploder, explosion);
}
/**
* Called when the block is destroyed by an explosion.
* Useful for allowing the block to take into account tile entities,
* state, etc. when exploded, before it is removed.
*
* @param world The current world
* @param pos Block position in world
* @param explosion The explosion instance affecting the block
*/
default void onBlockExploded(World world, BlockPos pos, Explosion explosion)
{
getBlockState().getBlock().onBlockExploded(getBlockState(), world, pos, explosion);
}
/**
* Determine if this block can make a redstone connection on the side provided,
* Useful to control which sides are inputs and outputs for redstone wires.
@@ -380,24 +351,11 @@ public interface IForgeBlockState
* @param side The side that is trying to make the connection, CAN BE NULL
* @return True to make the connection
*/
default boolean canConnectRedstone(IBlockReader world, BlockPos pos, @Nullable EnumFacing side)
default boolean canConnectRedstone(IBlockReader world, BlockPos pos, @Nullable Direction side)
{
return getBlockState().getBlock().canConnectRedstone(getBlockState(), world, pos, side);
}
/**
* Determines if a torch can be placed on the top surface of this block.
* Useful for creating your own block that torches can be on, such as fences.
*
* @param world The current world
* @param pos Block position in world
* @return True to allow the torch to be placed
*/
default boolean canPlaceTorchOnTop(IWorldReaderBase world, BlockPos pos)
{
return getBlockState().getBlock().canPlaceTorchOnTop(getBlockState(), world, pos);
}
/**
*
* Called when A user uses the creative pick block button on this block
@@ -405,7 +363,7 @@ public interface IForgeBlockState
* @param target The full target the player is looking at
* @return A ItemStack to add to the player's inventory, empty itemstack if nothing should be added.
*/
default ItemStack getPickBlock(RayTraceResult target, IBlockReader world, BlockPos pos, EntityPlayer player)
default ItemStack getPickBlock(RayTraceResult target, IBlockReader world, BlockPos pos, PlayerEntity player)
{
return getBlockState().getBlock().getPickBlock(getBlockState(), target, world, pos, player);
}
@@ -433,7 +391,7 @@ public interface IForgeBlockState
* @param numberOfParticles That vanilla world have spawned
* @return True to prevent vanilla landing particles from spawning
*/
default boolean addLandingEffects(WorldServer worldserver, BlockPos pos, IBlockState state2, EntityLivingBase entity, int numberOfParticles)
default boolean addLandingEffects(ServerWorld worldserver, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles)
{
return getBlockState().getBlock().addLandingEffects(getBlockState(), worldserver, pos, state2, entity, numberOfParticles);
}
@@ -503,7 +461,7 @@ public interface IForgeBlockState
* @param plantable The plant that wants to check
* @return True to allow the plant to be planted/stay.
*/
default boolean canSustainPlant(IBlockReader world, BlockPos pos, EnumFacing facing, IPlantable plantable)
default boolean canSustainPlant(IBlockReader world, BlockPos pos, Direction facing, IPlantable plantable)
{
return getBlockState().getBlock().canSustainPlant(getBlockState(), world, pos, facing, plantable);
}
@@ -561,12 +519,12 @@ public interface IForgeBlockState
* @param fortune
* @return Amount of XP from breaking this block.
*/
default int getExpDrop(IWorldReader world, BlockPos pos, int fortune)
default int getExpDrop(IWorldReader world, BlockPos pos, int fortune, int silktouch)
{
return getBlockState().getBlock().getExpDrop(getBlockState(), world, pos, fortune);
return getBlockState().getBlock().getExpDrop(getBlockState(), world, pos, fortune, silktouch);
}
default IBlockState rotate(IWorld world, BlockPos pos, Rotation direction)
default BlockState rotate(IWorld world, BlockPos pos, Rotation direction)
{
return getBlockState().getBlock().rotate(getBlockState(), world, pos, direction);
}
@@ -592,7 +550,7 @@ public interface IForgeBlockState
* @param fortune
* @return Amount of XP from breaking this block.
*/
default boolean recolorBlock(IWorld world, BlockPos pos, EnumFacing facing, EnumDyeColor color)
default boolean recolorBlock(IWorld world, BlockPos pos, Direction facing, DyeColor color)
{
return getBlockState().getBlock().recolorBlock(getBlockState(), world, pos, facing, color);
}
@@ -629,7 +587,7 @@ public interface IForgeBlockState
* @param side The INPUT side of the block to be powered - ie the opposite of this block's output side
* @return Whether Block#isProvidingWeakPower should be called when determining indirect power
*/
default boolean shouldCheckWeakPower(IWorldReader world, BlockPos pos, EnumFacing side)
default boolean shouldCheckWeakPower(IWorldReader world, BlockPos pos, Direction side)
{
return getBlockState().getBlock().shouldCheckWeakPower(getBlockState(), world, pos, side);
}
@@ -674,7 +632,7 @@ public interface IForgeBlockState
/**
* Can return IExtendedBlockState
*/
default IBlockState getExtendedState(IBlockReader world, BlockPos pos)
default BlockState getExtendedState(IBlockReader world, BlockPos pos)
{
return getBlockState().getBlock().getExtendedState(getBlockState(), world, pos);
}
@@ -738,7 +696,7 @@ public interface IForgeBlockState
* @param viewpoint the viewpoint
* @return the block state that should be 'seen'
*/
default IBlockState getStateAtViewpoint(IWorldReader world, BlockPos pos, Vec3d viewpoint)
default BlockState getStateAtViewpoint(IBlockReader world, BlockPos pos, Vec3d viewpoint)
{
return getBlockState().getBlock().getStateAtViewpoint(getBlockState(), world, pos, viewpoint);
}
@@ -756,7 +714,7 @@ public interface IForgeBlockState
* @param hand The player hand used to place this block
* @return The state to be placed in the world
*/
default IBlockState getStateForPlacement(EnumFacing facing, IBlockState state2, IWorld world, BlockPos pos1, BlockPos pos2, EnumHand hand)
default BlockState getStateForPlacement(Direction facing, BlockState state2, IWorld world, BlockPos pos1, BlockPos pos2, Hand hand)
{
return getBlockState().getBlock().getStateForPlacement(getBlockState(), facing, state2, world, pos1, pos2, hand);
}
@@ -769,23 +727,11 @@ public interface IForgeBlockState
* @param facing The side the connecting block is on
* @return True to allow another block to connect to this block
*/
default boolean canBeConnectedTo(IBlockReader world, BlockPos pos, EnumFacing facing)
default boolean canBeConnectedTo(IBlockReader world, BlockPos pos, Direction facing)
{
return getBlockState().getBlock().canBeConnectedTo(getBlockState(), world, pos, facing);
}
/**
* @param blockState The state for this block
* @param world The world this block is in
* @param pos The position of this block
* @param side The side of this block that the chest lid is trying to open into
* @return true if the chest should be prevented from opening by this block
*/
default boolean doesSideBlockChestOpening(IBlockReader world, BlockPos pos, EnumFacing side)
{
return getBlockState().getBlock().doesSideBlockChestOpening(getBlockState(), world, pos, side);
}
/**
* @param state The state
* @return true if the block is sticky block which used for pull or push adjacent blocks (use by piston)
@@ -795,19 +741,6 @@ public interface IForgeBlockState
return getBlockState().getBlock().isStickyBlock(getBlockState());
}
/**
* This gets a complete list of items dropped from this block.
*
* @param drops add all items this block drops to this drops list
* @param world The current world
* @param pos Block position in world
* @param fortune Breakers fortune level
*/
default void getDrops(NonNullList<ItemStack> drops, World world, BlockPos pos, int fortune)
{
getBlockState().getBlock().getDrops(getBlockState(), drops, world, pos, fortune);
}
/**
* Chance that fire will spread and consume this block.
* 300 being a 100% chance, 0, being a 0% chance.
@@ -817,7 +750,7 @@ public interface IForgeBlockState
* @param face The face that the fire is coming from
* @return A number ranging from 0 to 300 relating used to determine if the block will be consumed by fire
*/
default int getFlammability(IBlockReader world, BlockPos pos, EnumFacing face)
default int getFlammability(IBlockReader world, BlockPos pos, Direction face)
{
return getBlockState().getBlock().getFlammability(getBlockState(), world, pos, face);
}
@@ -830,7 +763,7 @@ public interface IForgeBlockState
* @param face The face that the fire is coming from
* @return True if the face can be on fire, false otherwise.
*/
default boolean isFlammable(IBlockReader world, BlockPos pos, EnumFacing face)
default boolean isFlammable(IBlockReader world, BlockPos pos, Direction face)
{
return getBlockState().getBlock().isFlammable(getBlockState(), world, pos, face);
}
@@ -844,7 +777,7 @@ public interface IForgeBlockState
* @param face The face that the fire is coming from
* @return A number that is used to determine the speed of fire growth around the block
*/
default int getFireSpreadSpeed(IBlockReader world, BlockPos pos, EnumFacing face)
default int getFireSpreadSpeed(IBlockReader world, BlockPos pos, Direction face)
{
return getBlockState().getBlock().getFireSpreadSpeed(getBlockState(), world, pos, face);
}
@@ -859,7 +792,7 @@ public interface IForgeBlockState
* @param side The face that the fire is coming from
* @return True if this block sustains fire, meaning it will never go out.
*/
default boolean isFireSource(IBlockReader world, BlockPos pos, EnumFacing side)
default boolean isFireSource(IBlockReader world, BlockPos pos, Direction side)
{
return getBlockState().getBlock().isFireSource(getBlockState(), world, pos, side);
}
@@ -884,7 +817,7 @@ public interface IForgeBlockState
* @return An array of valid axes to rotate around, or null for none or unknown
*/
@Nullable
default EnumFacing[] getValidRotations(IBlockReader world, BlockPos pos)
default Direction[] getValidRotations(IBlockReader world, BlockPos pos)
{
return getBlockState().getBlock().getValidRotations(getBlockState(), world, pos);
}
@@ -902,27 +835,22 @@ public interface IForgeBlockState
return getBlockState().getBlock().isBurning(getBlockState(), world, pos);
}
/**
* Determines if the top is consider 'solid'. This is a helper for getBlockFaceShape(UP) == SOLID.
* Sadly some vanilla logic doesn't sync this value, so we have to have this special function.
*
* @param world The world
* @param pos Block position in world
* @return True if the top is considered solid
*/
default boolean isTopSolid(IWorldReader world, BlockPos pos)
{
return getBlockState().getBlock().isTopSolid(getBlockState(), world, pos);
}
/**
* Get the {@code PathNodeType} for this block. Return {@code null} for vanilla behavior.
*
* @return the PathNodeType
*/
@Nullable
default PathNodeType getAiPathNodeType(IBlockReader world, BlockPos pos, @Nullable EntityLiving entity)
default PathNodeType getAiPathNodeType(IBlockReader world, BlockPos pos, @Nullable MobEntity entity)
{
return getBlockState().getBlock().getAiPathNodeType(getBlockState(), world, pos, entity);
}
/**
* Determines if this block should drop loot when exploded.
*/
default boolean canDropFromExplosion(IBlockReader world, BlockPos pos, Explosion explosion)
{
return getBlockState().getBlock().canDropFromExplosion(getBlockState(), world, pos, explosion);
}
}
@@ -23,8 +23,8 @@ import javax.annotation.Nullable;
import net.minecraft.client.audio.MusicTicker;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
@@ -84,22 +84,6 @@ public interface IForgeDimension
return 1.0;
}
/**
* If this method returns true, then chunks received by the client will
* have {@link net.minecraft.world.chunk.Chunk#resetRelightChecks} called
* on them, queuing lighting checks for all air blocks in the chunk (and
* any adjacent light-emitting blocks).
*
* Returning true here is recommended if the chunk generator used also
* does this for newly generated chunks.
*
* @return true if lighting checks should be performed
*/
default boolean shouldClientCheckLighting()
{
return !(this instanceof OverworldDimension);
}
@OnlyIn(Dist.CLIENT)
@Nullable
IRenderHandler getSkyRenderer();
@@ -166,9 +150,9 @@ public interface IForgeDimension
* @param pos The location where the player tries to sleep at (the position of the clicked on bed for example)
* @return the result of a player trying to sleep at the given location
*/
default SleepResult canSleepAt(net.minecraft.entity.player.EntityPlayer player, BlockPos pos)
default SleepResult canSleepAt(net.minecraft.entity.player.PlayerEntity player, BlockPos pos)
{
return (getDimension().canRespawnHere() && getWorld().getBiome(pos) != net.minecraft.init.Biomes.NETHER) ? SleepResult.ALLOW : SleepResult.BED_EXPLODES;
return (getDimension().canRespawnHere() && getWorld().getBiome(pos) != net.minecraft.world.biome.Biomes.NETHER) ? SleepResult.ALLOW : SleepResult.BED_EXPLODES;
}
enum SleepResult
@@ -196,24 +180,15 @@ public interface IForgeDimension
*
* @return The current brightness factor
**/
default float getSunBrightnessFactor(float partialTicks)
{
return getWorld().getSunBrightnessFactor(partialTicks);
}
/**
* Gets the Sun Brightness for rendering sky.
* */
@OnlyIn(Dist.CLIENT)
default float getSunBrightness(float partialTicks)
{
return getWorld().getSunBrightnessBody(partialTicks);
}
@OnlyIn(Dist.CLIENT)
default Vec3d getSkyColor(Entity cameraEntity, float partialTicks)
default Vec3d getSkyColor(BlockPos cameraPos, float partialTicks)
{
return getWorld().getSkyColorBody(cameraEntity, partialTicks);
return getWorld().getSkyColorBody(cameraPos, partialTicks);
}
@OnlyIn(Dist.CLIENT)
@@ -238,10 +213,7 @@ public interface IForgeDimension
@OnlyIn(Dist.CLIENT)
default float getStarBrightness(float partialTicks)
{
float f = getWorld().getCelestialAngle(partialTicks);
float f1 = 1.0F - (MathHelper.cos(f * ((float)Math.PI * 2F)) * 2.0F + 0.25F);
f1 = MathHelper.clamp(f1, 0.0F, 1.0F);
return f1 * f1 * 0.5F;
return getWorld().getStarBrightnessBody(partialTicks);
}
default void setAllowedSpawnTypes(boolean allowHostile, boolean allowPeaceful) { }
@@ -251,9 +223,9 @@ public interface IForgeDimension
getWorld().calculateInitialWeatherBody();
}
default void updateWeather()
default void updateWeather(Runnable defaultLogic)
{
getWorld().updateWeatherBody();
defaultLogic.run();
}
default long getSeed()
@@ -282,7 +254,7 @@ public interface IForgeDimension
getWorld().getWorldInfo().setSpawn(pos);
}
default boolean canMineBlock(EntityPlayer player, BlockPos pos)
default boolean canMineBlock(PlayerEntity player, BlockPos pos)
{
return getWorld().canMineBlockBody(player, pos);
}
@@ -304,7 +276,7 @@ public interface IForgeDimension
default double getHorizon()
{
return getWorld().getWorldInfo().getTerrainType().getHorizon(getWorld());
return getWorld().getWorldInfo().getGenerator().getHorizon(getWorld());
}
/**
@@ -327,7 +299,7 @@ public interface IForgeDimension
* @param player The player that is respawning
* @return The dimension to respawn the player in
*/
default DimensionType getRespawnDimension(EntityPlayerMP player)
default DimensionType getRespawnDimension(ServerPlayerEntity player)
{
return player.getSpawnDimension();
}
@@ -0,0 +1,108 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2019.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.extensions;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.gui.AbstractGui;
import net.minecraft.client.gui.DisplayEffectsScreen;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.potion.Effect;
import net.minecraft.potion.EffectInstance;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
public interface IForgeEffect {
default Effect getEffect() {
return (Effect)this;
}
/**
* If the Potion effect should be displayed in the players inventory
* @param effect the active PotionEffect
* @return true to display it (default), false to hide it.
*/
default boolean shouldRender(EffectInstance effect) { return true; }
/**
* If the standard PotionEffect text (name and duration) should be drawn when this potion is active.
* @param effect the active PotionEffect
* @return true to draw the standard text
*/
default boolean shouldRenderInvText(EffectInstance effect) { return true; }
/**
* If the Potion effect should be displayed in the player's ingame HUD
* @param effect the active PotionEffect
* @return true to display it (default), false to hide it.
*/
default boolean shouldRenderHUD(EffectInstance effect) { return true; }
/**
* Called to draw the this Potion onto the player's inventory when it's active.
* This can be used to e.g. render Potion icons from your own texture.
*
* @param effect the active PotionEffect
* @param gui the gui instance
* @param x the x coordinate
* @param y the y coordinate
* @param z the z level
*/
@OnlyIn(Dist.CLIENT)
default void renderInventoryEffect(EffectInstance effect, DisplayEffectsScreen<?> gui, int x, int y, float z) { }
/**
* Called to draw the this Potion onto the player's ingame HUD when it's active.
* This can be used to e.g. render Potion icons from your own texture.
* @param effect the active PotionEffect
* @param gui the gui instance
* @param x the x coordinate
* @param y the y coordinate
* @param z the z level
* @param alpha the alpha value, blinks when the potion is about to run out
*/
@OnlyIn(Dist.CLIENT)
default void renderHUDEffect(EffectInstance effect, AbstractGui gui, int x, int y, float z, float alpha) { }
/**
* Get a fresh list of items that can cure this Potion.
* All new PotionEffects created from this Potion will call this to initialize the default curative items
* @see PotionEffect#getCurativeItems
* @return A list of items that can cure this Potion
*/
default List<ItemStack> getCurativeItems() {
ArrayList<ItemStack> ret = new ArrayList<ItemStack>();
ret.add(new ItemStack(Items.MILK_BUCKET));
return ret;
}
/**
* Used for determining {@code PotionEffect} sort order in GUIs.
* Defaults to the {@code PotionEffect}'s liquid color.
* @param potionEffect the {@code PotionEffect} instance containing the potion
* @return a value used to sort {@code PotionEffect}s in GUIs
*/
default int getGuiSortColor(EffectInstance potionEffect) {
return getEffect().getLiquidColor();
}
}
@@ -0,0 +1,73 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2019.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.extensions;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.ListNBT;
import net.minecraft.potion.EffectInstance;
import net.minecraft.potion.Potion;
public interface IForgeEffectInstance {
default EffectInstance getEffectInstance() {
return (EffectInstance)this;
}
/***
* Returns a list of curative items for the potion effect
* By default, this list is initialized using {@link Potion#getCurativeItems}
*
* @return The list (ItemStack) of curative items for the potion effect
*/
List<ItemStack> getCurativeItems();
/***
* Checks the given ItemStack to see if it is in the list of curative items for the potion effect
* @param stack The ItemStack being checked against the list of curative items for this PotionEffect
* @return true if the given ItemStack is in the list of curative items for this PotionEffect, false otherwise
*/
default boolean isCurativeItem(ItemStack stack) {
return this.getCurativeItems().stream().anyMatch(e -> e.isItemEqual(stack));
}
/***
* Sets the list of curative items for this potion effect, overwriting any already present
* @param curativeItems The list of ItemStacks being set to the potion effect
*/
void setCurativeItems(List<ItemStack> curativeItems);
/***
* Adds the given stack to the list of curative items for this PotionEffect
* @param stack The ItemStack being added to the curative item list
*/
default void addCurativeItem(ItemStack stack) {
if (!this.isCurativeItem(stack))
this.getCurativeItems().add(stack);
}
default void writeCurativeItems(CompoundNBT nbt) {
ListNBT list = new ListNBT();
getCurativeItems().forEach(s -> list.add(s.write(new CompoundNBT())));
nbt.func_218657_a("CurativeItems", list);
}
}
@@ -20,52 +20,43 @@
package net.minecraftforge.common.extensions;
import java.util.Collection;
import javax.annotation.Nullable;
import net.minecraft.block.state.IBlockState;
import net.minecraft.block.BlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLeashKnot;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.entity.item.EntityArmorStand;
import net.minecraft.entity.item.EntityBoat;
import net.minecraft.entity.item.EntityEnderCrystal;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.EntityItemFrame;
import net.minecraft.entity.item.EntityMinecart;
import net.minecraft.entity.item.EntityPainting;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemSpawnEgg;
import net.minecraft.entity.item.LeashKnotEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.EntityClassification;
import net.minecraft.entity.item.ArmorStandEntity;
import net.minecraft.entity.item.BoatEntity;
import net.minecraft.entity.item.EnderCrystalEntity;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.item.ItemFrameEntity;
import net.minecraft.entity.item.minecart.AbstractMinecartEntity;
import net.minecraft.entity.item.PaintingEntity;
import net.minecraft.item.Items;
import net.minecraft.item.SpawnEggItem;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.dimension.DimensionType;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.common.util.ITeleporter;
public interface IForgeEntity extends ICapabilitySerializable<NBTTagCompound>
public interface IForgeEntity extends ICapabilitySerializable<CompoundNBT>
{
default Entity getEntity() { return (Entity) this; }
default void deserializeNBT(NBTTagCompound nbt)
default void deserializeNBT(CompoundNBT nbt)
{
getEntity().read(nbt);
}
default NBTTagCompound serializeNBT()
default CompoundNBT serializeNBT()
{
NBTTagCompound ret = new NBTTagCompound();
CompoundNBT ret = new CompoundNBT();
String id = getEntity().getEntityString();
if (id != null)
{
ret.setString("id", getEntity().getEntityString());
ret.putString("id", getEntity().getEntityString());
}
return getEntity().writeWithoutTypeId(ret);
}
@@ -74,8 +65,8 @@ public interface IForgeEntity extends ICapabilitySerializable<NBTTagCompound>
void canUpdate(boolean value);
@Nullable
Collection<EntityItem> captureDrops();
Collection<EntityItem> captureDrops(@Nullable Collection<EntityItem> captureDrops);
Collection<ItemEntity> captureDrops();
Collection<ItemEntity> captureDrops(@Nullable Collection<ItemEntity> captureDrops);
/**
@@ -83,7 +74,7 @@ public interface IForgeEntity extends ICapabilitySerializable<NBTTagCompound>
* It will be written, and read from disc, so it persists over world saves.
* @return A NBTTagCompound
*/
NBTTagCompound getEntityData();
CompoundNBT getEntityData();
/**
* Used in model rendering to determine if the entity riding this entity should be in the 'sitting' position.
@@ -102,51 +93,34 @@ public interface IForgeEntity extends ICapabilitySerializable<NBTTagCompound>
*/
default ItemStack getPickedResult(RayTraceResult target)
{
if (this instanceof EntityPainting)
{
if (this instanceof PaintingEntity)
return new ItemStack(Items.PAINTING);
}
else if (this instanceof EntityLeashKnot)
{
else if (this instanceof LeashKnotEntity)
return new ItemStack(Items.LEAD);
}
else if (this instanceof EntityItemFrame)
else if (this instanceof ItemFrameEntity)
{
ItemStack held = ((EntityItemFrame)this).getDisplayedItem();
ItemStack held = ((ItemFrameEntity)this).getDisplayedItem();
if (held.isEmpty())
return new ItemStack(Items.ITEM_FRAME);
else
return held.copy();
}
else if (this instanceof EntityMinecart)
{
return ((EntityMinecart)this).getCartItem();
}
else if (this instanceof EntityBoat)
{
return new ItemStack(((EntityBoat)this).getItemBoat());
}
else if (this instanceof EntityArmorStand)
{
else if (this instanceof AbstractMinecartEntity)
return ((AbstractMinecartEntity)this).getCartItem();
else if (this instanceof BoatEntity)
return new ItemStack(((BoatEntity)this).getItemBoat());
else if (this instanceof ArmorStandEntity)
return new ItemStack(Items.ARMOR_STAND);
}
else if (this instanceof EntityEnderCrystal)
{
else if (this instanceof EnderCrystalEntity)
return new ItemStack(Items.END_CRYSTAL);
}
else
{
ItemSpawnEgg egg = ItemSpawnEgg.getEgg(getEntity().getType());
SpawnEggItem egg = SpawnEggItem.getEgg(getEntity().getType());
if (egg != null) return new ItemStack(egg);
}
return ItemStack.EMPTY;
}
default boolean shouldRenderInPass(int pass)
{
return pass == 0;
}
/**
* If a rider of this entity can interact with this entity. Should return true on the
* ridden entity if so.
@@ -166,21 +140,9 @@ public interface IForgeEntity extends ICapabilitySerializable<NBTTagCompound>
*/
default boolean canBeRiddenInWater(Entity rider)
{
return this instanceof EntityLivingBase;
return this instanceof LivingEntity;
}
/**
* Override instead of
* {@link Entity#changeDimension(DimensionType, ITeleporter)} if your entity
* needs special handling for specific teleporters.
*
* @param type The target dimension
* @param teleporter The teleporter being used to move the entity to the dimension
* @return The entity to be placed in the target dimension. {@code null} if the entity should despawn.
*/
@Nullable
Entity changeDimension(DimensionType type, ITeleporter teleporter);
/**
* Checks if this {@link Entity} can trample a {@link Block}.
*
@@ -188,18 +150,16 @@ public interface IForgeEntity extends ICapabilitySerializable<NBTTagCompound>
* @param fallDistance The fall distance
* @return {@code true} if this entity can trample, {@code false} otherwise
*/
boolean canTrample(IBlockState state, BlockPos pos, float fallDistance);
boolean canTrample(BlockState state, BlockPos pos, float fallDistance);
/**
* Returns true if the entity is of the @link{EnumCreatureType} provided
* @param type The EnumCreatureType type this entity is evaluating
* Returns The classification of this entity
* @param forSpawnCount If this is being invoked to check spawn count caps.
* @return If the creature is of the type provided
*/
default boolean isCreatureType(EnumCreatureType type, boolean forSpawnCount)
default EntityClassification getClassification(boolean forSpawnCount)
{
if (forSpawnCount && (this instanceof EntityLiving) && ((EntityLiving)this).isNoDespawnRequired()) return false;
return type.getBaseClass().isAssignableFrom(this.getClass());
return getEntity().getType().func_220339_d();
}
/**
@@ -19,20 +19,14 @@
package net.minecraftforge.common.extensions;
import net.minecraft.block.BlockRailBase;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.MoverType;
import net.minecraft.entity.item.EntityMinecart;
import net.minecraft.entity.item.EntityMinecartChest;
import net.minecraft.entity.item.EntityMinecartCommandBlock;
import net.minecraft.entity.item.EntityMinecartFurnace;
import net.minecraft.entity.item.EntityMinecartHopper;
import net.minecraft.entity.item.EntityMinecartTNT;
import net.minecraft.init.Items;
import net.minecraft.entity.item.minecart.AbstractMinecartEntity;
import net.minecraft.item.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.tags.BlockTags;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.common.IMinecartCollisionHandler;
public interface IForgeEntityMinecart
@@ -42,8 +36,8 @@ public interface IForgeEntityMinecart
public static double DEFAULT_AIR_DRAG = 0.95f;
public static IMinecartCollisionHandler COLLISIONS = null;
default EntityMinecart getMinecart() {
return (EntityMinecart)this;
default AbstractMinecartEntity getMinecart() {
return (AbstractMinecartEntity)this;
}
/**
@@ -74,23 +68,7 @@ public interface IForgeEntityMinecart
* Moved to allow overrides.
* This code handles minecart movement and speed capping when on a rail.
*/
default void moveMinecartOnRail(BlockPos pos)
{
EntityMinecart mc = getMinecart();
double mX = mc.motionX;
double mZ = mc.motionZ;
if (mc.isBeingRidden())
{
mX *= 0.75D;
mZ *= 0.75D;
}
double max = getMaxSpeed();
mX = MathHelper.clamp(mX, -max, max);
mZ = MathHelper.clamp(mZ, -max, max);
mc.move(MoverType.SELF, mX, 0.0D, mZ);
}
void moveMinecartOnRail(BlockPos pos);
/**
* This function returns an ItemStack that represents this cart.
@@ -138,7 +116,7 @@ public interface IForgeEntityMinecart
* @return True if powered.
*/
default boolean isPoweredCart() {
return getMinecart().getMinecartType() == EntityMinecart.Type.FURNACE;
return getMinecart().getMinecartType() == AbstractMinecartEntity.Type.FURNACE;
}
/**
@@ -146,7 +124,7 @@ public interface IForgeEntityMinecart
* @return True if this cart can be ridden.
*/
default boolean canBeRidden() {
return getMinecart().getMinecartType() == EntityMinecart.Type.RIDEABLE;
return getMinecart().getMinecartType() == AbstractMinecartEntity.Type.RIDEABLE;
}
/**
@@ -53,7 +53,7 @@ public interface IForgeFluid
*/
default boolean isEntityInside(IFluidState state, IWorldReader world, BlockPos pos, Entity entity, double yToTest, Tag<Fluid> tag, boolean testingHead)
{
return state.isTagged(tag) && yToTest < (double)(pos.getY() + state.getHeight() + 0.11111111F);
return state.isTagged(tag) && yToTest < (double)(pos.getY() + state.func_215679_a(world, pos) + 0.11111111F);
}
/**
@@ -51,6 +51,7 @@ public interface IForgeFluidState
*/
default boolean isEntityInside(IWorldReader world, BlockPos pos, Entity entity, double yToTest, Tag<Fluid> tag, boolean testingHead)
{
// return ifluidstate.isTagged(p_213290_1_) && d0 < (double)((float)blockpos.getY() + ifluidstate.func_215679_a(this.world, blockpos) + 0.11111111F);
return getFluidState().getFluid().isEntityInside(getFluidState(), world, pos, entity, yToTest, tag, testingHead);
}
@@ -26,24 +26,23 @@ import javax.annotation.Nullable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;
import net.minecraft.block.state.IBlockState;
import net.minecraft.block.BlockState;
import net.minecraft.client.renderer.entity.model.BipedModel;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.MobEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.passive.EntityHorse;
import net.minecraft.entity.passive.HorseArmorType;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Items;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.Item;
import net.minecraft.item.ItemAxe;
import net.minecraft.item.AxeItem;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUseContext;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumActionResult;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
@@ -65,7 +64,7 @@ public interface IForgeItem
* ItemStack sensitive version of getItemAttributeModifiers
*/
@SuppressWarnings("deprecation")
default Multimap<String, AttributeModifier> getAttributeModifiers(EntityEquipmentSlot slot, ItemStack stack)
default Multimap<String, AttributeModifier> getAttributeModifiers(EquipmentSlotType slot, ItemStack stack)
{
return getItem().getAttributeModifiers(slot);
}
@@ -78,7 +77,7 @@ public interface IForgeItem
* @param player The player that dropped the item
* @param item The item stack, before the item is removed.
*/
default boolean onDroppedByPlayer(ItemStack item, EntityPlayer player)
default boolean onDroppedByPlayer(ItemStack item, PlayerEntity player)
{
return true;
}
@@ -102,9 +101,9 @@ public interface IForgeItem
*
* @return Return PASS to allow vanilla handling, any other to skip normal code.
*/
default EnumActionResult onItemUseFirst(ItemStack stack, ItemUseContext context)
default ActionResultType onItemUseFirst(ItemStack stack, ItemUseContext context)
{
return EnumActionResult.PASS;
return ActionResultType.PASS;
}
/**
@@ -113,7 +112,7 @@ public interface IForgeItem
* @return True if reparable
*/
boolean isRepairable();
/**
* Determines the amount of durability the mending enchantment
* will repair, on average, per point of experience.
@@ -140,7 +139,7 @@ public interface IForgeItem
* @return The NBT tag
*/
@Nullable
default NBTTagCompound getShareTag(ItemStack stack)
default CompoundNBT getShareTag(ItemStack stack)
{
return stack.getTag();
}
@@ -152,7 +151,7 @@ public interface IForgeItem
* @param stack The stack that received NBT
* @param nbt Received NBT, can be null
*/
default void readShareTag(ItemStack stack, @Nullable NBTTagCompound nbt)
default void readShareTag(ItemStack stack, @Nullable CompoundNBT nbt)
{
stack.setTag(nbt);
}
@@ -168,7 +167,7 @@ public interface IForgeItem
* @param player The Player that is wielding the item
* @return True to prevent harvesting, false to continue as normal
*/
default boolean onBlockStartBreak(ItemStack itemstack, BlockPos pos, EntityPlayer player)
default boolean onBlockStartBreak(ItemStack itemstack, BlockPos pos, PlayerEntity player)
{
return false;
}
@@ -181,7 +180,7 @@ public interface IForgeItem
* @param count The amount of time in tick the item has been used for
* continuously
*/
default void onUsingTick(ItemStack stack, EntityLivingBase player, int count)
default void onUsingTick(ItemStack stack, LivingEntity player, int count)
{
}
@@ -195,7 +194,7 @@ public interface IForgeItem
* @param entity The entity being attacked
* @return True to cancel the rest of the interaction.
*/
default boolean onLeftClickEntity(ItemStack stack, EntityPlayer player, Entity entity)
default boolean onLeftClickEntity(ItemStack stack, PlayerEntity player, Entity entity)
{
return false;
}
@@ -281,7 +280,7 @@ public interface IForgeItem
* @param entity The entity Item
* @return Return true to skip any further update code.
*/
default boolean onEntityItemUpdate(ItemStack stack, EntityItem entity)
default boolean onEntityItemUpdate(ItemStack stack, ItemEntity entity)
{
return false;
}
@@ -321,7 +320,7 @@ public interface IForgeItem
* @param player The Player that is wielding the item
* @return
*/
default boolean doesSneakBypassUse(ItemStack stack, net.minecraft.world.IWorldReader world, BlockPos pos, EntityPlayer player)
default boolean doesSneakBypassUse(ItemStack stack, net.minecraft.world.IWorldReader world, BlockPos pos, PlayerEntity player)
{
return false;
}
@@ -329,7 +328,7 @@ public interface IForgeItem
/**
* Called to tick armor in the armor slot. Override to do something
*/
default void onArmorTick(ItemStack stack, World world, EntityPlayer player)
default void onArmorTick(ItemStack stack, World world, PlayerEntity player)
{
}
@@ -342,9 +341,9 @@ public interface IForgeItem
* @param entity The entity trying to equip the armor
* @return True if the given ItemStack can be inserted in the slot
*/
default boolean canEquip(ItemStack stack, EntityEquipmentSlot armorType, Entity entity)
default boolean canEquip(ItemStack stack, EquipmentSlotType armorType, Entity entity)
{
return EntityLiving.getSlotForItemStack(stack) == armorType;
return MobEntity.getSlotForItemStack(stack) == armorType;
}
/**
@@ -358,7 +357,7 @@ public interface IForgeItem
* decide
*/
@Nullable
default EntityEquipmentSlot getEquipmentSlot(ItemStack stack)
default EquipmentSlotType getEquipmentSlot(ItemStack stack)
{
return null;
}
@@ -389,7 +388,7 @@ public interface IForgeItem
* @return Path of texture to bind, or null to use default
*/
@Nullable
default String getArmorTexture(ItemStack stack, Entity entity, EntityEquipmentSlot slot, String type)
default String getArmorTexture(ItemStack stack, Entity entity, EquipmentSlotType slot, String type)
{
return null;
}
@@ -419,8 +418,7 @@ public interface IForgeItem
*/
@OnlyIn(Dist.CLIENT)
@Nullable
default net.minecraft.client.renderer.entity.model.ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack,
EntityEquipmentSlot armorSlot, net.minecraft.client.renderer.entity.model.ModelBiped _default)
default <A extends BipedModel<?>> A getArmorModel(LivingEntity entityLiving, ItemStack itemStack, EquipmentSlotType armorSlot, A _default)
{
return null;
}
@@ -431,7 +429,7 @@ public interface IForgeItem
* @param entity The entity swinging the item.
* @return True to cancel any further processing by EntityLiving
*/
default boolean onEntitySwing(ItemStack stack, EntityLivingBase entity)
default boolean onEntitySwing(ItemStack stack, LivingEntity entity)
{
return false;
}
@@ -447,7 +445,7 @@ public interface IForgeItem
* @param partialTicks Partial ticks for the renderer, useful for interpolation
*/
@OnlyIn(Dist.CLIENT)
default void renderHelmetOverlay(ItemStack stack, EntityPlayer player, int width, int height, float partialTicks)
default void renderHelmetOverlay(ItemStack stack, PlayerEntity player, int width, int height, float partialTicks)
{
}
@@ -535,7 +533,7 @@ public interface IForgeItem
*/
default void setDamage(ItemStack stack, int damage)
{
stack.getOrCreateTag().setInt("Damage", Math.max(0, damage));
stack.getOrCreateTag().putInt("Damage", Math.max(0, damage));
}
/**
@@ -545,7 +543,7 @@ public interface IForgeItem
* @param state The block trying to harvest
* @return true if can harvest the block
*/
default boolean canHarvestBlock(ItemStack stack, IBlockState state)
default boolean canHarvestBlock(ItemStack stack, BlockState state)
{
return getItem().canHarvestBlock(state);
}
@@ -575,7 +573,7 @@ public interface IForgeItem
* @param blockState The block to harvest
* @return Harvest level, or -1 if not the specified tool type.
*/
int getHarvestLevel(ItemStack stack, ToolType tool, @Nullable EntityPlayer player, @Nullable IBlockState blockState);
int getHarvestLevel(ItemStack stack, ToolType tool, @Nullable PlayerEntity player, @Nullable BlockState blockState);
/**
* ItemStack sensitive version of getItemEnchantability
@@ -696,12 +694,12 @@ public interface IForgeItem
* capabilities for the life of this item.
*/
@Nullable
default net.minecraftforge.common.capabilities.ICapabilityProvider initCapabilities(ItemStack stack, @Nullable NBTTagCompound nbt)
default net.minecraftforge.common.capabilities.ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundNBT nbt)
{
return null;
}
default ImmutableMap<String, ITimeValue> getAnimationParameters(final ItemStack stack, final World world, final EntityLivingBase entity)
default ImmutableMap<String, ITimeValue> getAnimationParameters(final ItemStack stack, final World world, final LivingEntity entity)
{
com.google.common.collect.ImmutableMap.Builder<String, ITimeValue> builder = ImmutableMap.builder();
getItem().properties.forEach((k,v) -> builder.put(k.toString(), input -> v.call(stack, world, entity)));
@@ -717,9 +715,9 @@ public interface IForgeItem
* @param attacker The EntityLivingBase holding the ItemStack
* @retrun True if this ItemStack can disable the shield in question.
*/
default boolean canDisableShield(ItemStack stack, ItemStack shield, EntityLivingBase entity, EntityLivingBase attacker)
default boolean canDisableShield(ItemStack stack, ItemStack shield, LivingEntity entity, LivingEntity attacker)
{
return this instanceof ItemAxe;
return this instanceof AxeItem;
}
/**
@@ -729,7 +727,7 @@ public interface IForgeItem
* @param entity The Entity holding the ItemStack
* @return True if the ItemStack is considered a shield
*/
default boolean isShield(ItemStack stack, @Nullable EntityLivingBase entity)
default boolean isShield(ItemStack stack, @Nullable LivingEntity entity)
{
return stack.getItem() == Items.SHIELD;
}
@@ -744,21 +742,6 @@ public interface IForgeItem
return -1;
}
/**
* Returns an enum constant of type {@code HorseArmorType}. The returned enum
* constant will be used to determine the armor value and texture of this item
* when equipped.
*
* @param stack the armor stack
* @return an enum constant of type {@code HorseArmorType}. Return
* HorseArmorType.NONE if this is not horse armor
*/
@SuppressWarnings("deprecation")
default HorseArmorType getHorseArmorType(ItemStack stack)
{
return HorseArmorType.getByItem(stack.getItem());
}
/**
* Called every tick from {@link EntityHorse#onUpdate()} on the item in the
* armor slot.
@@ -767,7 +750,7 @@ public interface IForgeItem
* @param world the world the horse is in
* @param horse the horse wearing this armor
*/
default void onHorseArmorTick(ItemStack stack, World world, EntityLiving horse)
default void onHorseArmorTick(ItemStack stack, World world, MobEntity horse)
{
}
@@ -776,5 +759,5 @@ public interface IForgeItem
* one.
*/
@OnlyIn(Dist.CLIENT)
net.minecraft.client.renderer.tileentity.TileEntityItemStackRenderer getTileEntityItemStackRenderer();
net.minecraft.client.renderer.tileentity.ItemStackTileEntityRenderer getTileEntityItemStackRenderer();
}
@@ -23,23 +23,21 @@ import java.util.Set;
import javax.annotation.Nullable;
import net.minecraft.block.state.BlockWorldState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.CachedBlockInfo;
import net.minecraft.block.BlockState;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.passive.EntityHorse;
import net.minecraft.entity.passive.HorseArmorType;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.entity.MobEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUseContext;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.stats.StatList;
import net.minecraft.util.EnumActionResult;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.stats.Stats;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.ToolType;
@@ -48,7 +46,7 @@ import net.minecraftforge.common.capabilities.ICapabilitySerializable;
/*
* Extension added to ItemStack that bounces to ItemSack sensitive Item methods. Typically this is just for convince.
*/
public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
{
// Helpers for accessing Item data
default ItemStack getStack()
@@ -99,7 +97,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
* @param state The block to harvest
* @return Harvest level, or -1 if not the specified tool type.
*/
default int getHarvestLevel(ToolType tool, @Nullable EntityPlayer player, @Nullable IBlockState state)
default int getHarvestLevel(ToolType tool, @Nullable PlayerEntity player, @Nullable BlockState state)
{
return getStack().getItem().getHarvestLevel(getStack(), tool, player, state);
}
@@ -108,27 +106,27 @@ public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
return getStack().getItem().getToolTypes(getStack());
}
default EnumActionResult onItemUseFirst(ItemUseContext context)
default ActionResultType onItemUseFirst(ItemUseContext context)
{
EntityPlayer entityplayer = context.getPlayer();
PlayerEntity entityplayer = context.getPlayer();
BlockPos blockpos = context.getPos();
BlockWorldState blockworldstate = new BlockWorldState(context.getWorld(), blockpos, false);
CachedBlockInfo blockworldstate = new CachedBlockInfo(context.getWorld(), blockpos, false);
if (entityplayer != null && !entityplayer.abilities.allowEdit && !getStack().canPlaceOn(context.getWorld().getTags(), blockworldstate)) {
return EnumActionResult.PASS;
return ActionResultType.PASS;
} else {
Item item = getStack().getItem();
EnumActionResult enumactionresult = item.onItemUseFirst(getStack(), context);
if (entityplayer != null && enumactionresult == EnumActionResult.SUCCESS) {
entityplayer.addStat(StatList.ITEM_USED.get(item));
ActionResultType enumactionresult = item.onItemUseFirst(getStack(), context);
if (entityplayer != null && enumactionresult == ActionResultType.SUCCESS) {
entityplayer.addStat(Stats.ITEM_USED.get(item));
}
return enumactionresult;
}
}
default NBTTagCompound serializeNBT()
default CompoundNBT serializeNBT()
{
NBTTagCompound ret = new NBTTagCompound();
CompoundNBT ret = new CompoundNBT();
getStack().write(ret);
return ret;
}
@@ -142,7 +140,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
* @param player The Player that is wielding the item
* @return True to prevent harvesting, false to continue as normal
*/
default boolean onBlockStartBreak(BlockPos pos, EntityPlayer player)
default boolean onBlockStartBreak(BlockPos pos, PlayerEntity player)
{
return !getStack().isEmpty() && getStack().getItem().onBlockStartBreak(getStack(), pos, player);
}
@@ -197,7 +195,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
* decide
*/
@Nullable
default EntityEquipmentSlot getEquipmentSlot()
default EquipmentSlotType getEquipmentSlot()
{
return getStack().getItem().getEquipmentSlot(getStack());
}
@@ -210,7 +208,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
* @param attacker The EntityLivingBase holding the ItemStack
* @retrun True if this ItemStack can disable the shield in question.
*/
default boolean canDisableShield(ItemStack shield, EntityLivingBase entity, EntityLivingBase attacker)
default boolean canDisableShield(ItemStack shield, LivingEntity entity, LivingEntity attacker)
{
return getStack().getItem().canDisableShield(getStack(), shield, entity, attacker);
}
@@ -221,7 +219,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
* @param entity The Entity holding the ItemStack
* @return True if the ItemStack is considered a shield
*/
default boolean isShield(@Nullable EntityLivingBase entity)
default boolean isShield(@Nullable LivingEntity entity)
{
return getStack().getItem().isShield(getStack(), entity);
}
@@ -232,7 +230,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
* @param entity The entity swinging the item.
* @return True to cancel any further processing by EntityLiving
*/
default boolean onEntitySwing(EntityLivingBase entity)
default boolean onEntitySwing(LivingEntity entity)
{
return getStack().getItem().onEntitySwing(getStack(), entity);
}
@@ -244,7 +242,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
* @param count The amount of time in tick the item has been used for
* continuously
*/
default void onUsingTick(EntityLivingBase player, int count)
default void onUsingTick(LivingEntity player, int count)
{
getStack().getItem().onUsingTick(getStack(), player, count);
}
@@ -269,28 +267,24 @@ public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
* @param entity The entity Item
* @return Return true to skip any further update code.
*/
default boolean onEntityItemUpdate(EntityItem entity)
default boolean onEntityItemUpdate(ItemEntity entity)
{
return getStack().getItem().onEntityItemUpdate(getStack(), entity);
}
/**
* Returns an enum constant of type {@code HorseArmorType}. The returned enum
* constant will be used to determine the armor value and texture of this item
* when equipped.
*
* @return an enum constant of type {@code HorseArmorType}. Return
* HorseArmorType.NONE if this is not horse armor
*/
default HorseArmorType getHorseArmorType()
* Determines the amount of durability the mending enchantment
* will repair, on average, per point of experience.
*/
default float getXpRepairRatio()
{
return getStack().getItem().getHorseArmorType(getStack());
return getStack().getItem().getXpRepairRatio(getStack());
}
/**
* Called to tick armor in the armor slot. Override to do something
*/
default void onArmorTick(World world, EntityPlayer player)
default void onArmorTick(World world, PlayerEntity player)
{
getStack().getItem().onArmorTick(getStack(), world, player);
}
@@ -302,7 +296,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
* @param world the world the horse is in
* @param horse the horse wearing this armor
*/
default void onHorseArmorTick(World world, EntityLiving horse)
default void onHorseArmorTick(World world, MobEntity horse)
{
getStack().getItem().onHorseArmorTick(getStack(), world, horse);
}
@@ -325,7 +319,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
* @param entity The entity trying to equip the armor
* @return True if the given ItemStack can be inserted in the slot
*/
default boolean canEquip(EntityEquipmentSlot armorType, Entity entity)
default boolean canEquip(EquipmentSlotType armorType, Entity entity)
{
return getStack().getItem().canEquip(getStack(), armorType, entity);
}
@@ -351,7 +345,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
* @param player The player that dropped the item
* @param item The item stack, before the item is removed.
*/
default boolean onDroppedByPlayer(EntityPlayer player)
default boolean onDroppedByPlayer(PlayerEntity player)
{
return getStack().getItem().onDroppedByPlayer(getStack(), player);
}
@@ -370,7 +364,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
* @return The NBT tag
*/
@Nullable
default NBTTagCompound getShareTag()
default CompoundNBT getShareTag()
{
return getStack().getItem().getShareTag(getStack());
}
@@ -382,7 +376,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
* @param stack The stack that received NBT
* @param nbt Received NBT, can be null
*/
default void readShareTag(@Nullable NBTTagCompound nbt)
default void readShareTag(@Nullable CompoundNBT nbt)
{
getStack().getItem().readShareTag(getStack(), nbt);
}
@@ -396,7 +390,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
* @param player The Player that is wielding the item
* @return
*/
default boolean doesSneakBypassUse(net.minecraft.world.IWorldReader world, BlockPos pos, EntityPlayer player)
default boolean doesSneakBypassUse(net.minecraft.world.IWorldReader world, BlockPos pos, PlayerEntity player)
{
return getStack().isEmpty() || getStack().getItem().doesSneakBypassUse(getStack(), world, pos, player);
}
@@ -408,8 +402,8 @@ public interface IForgeItemStack extends ICapabilitySerializable<NBTTagCompound>
*/
default boolean areShareTagsEqual(ItemStack other)
{
NBTTagCompound shareTagA = getStack().getShareTag();
NBTTagCompound shareTagB = other.getShareTag();
CompoundNBT shareTagA = getStack().getShareTag();
CompoundNBT shareTagB = other.getShareTag();
if (shareTagA == null)
return shareTagB == null;
else
@@ -1,37 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2019.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.extensions;
import net.minecraft.item.crafting.IRecipe;
import net.minecraftforge.common.crafting.RecipeType;
import net.minecraftforge.common.crafting.VanillaRecipeTypes;
public interface IForgeRecipe {
/**
* Used when sorting this recipe into it's category during load. This type determines what class the recipe must subclass.
* @return The type of this recipe.
*/
default RecipeType<? extends IRecipe> getType()
{
return VanillaRecipeTypes.CRAFTING;
}
}
@@ -22,9 +22,9 @@ package net.minecraftforge.common.extensions;
import javax.annotation.Nonnull;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
@@ -36,20 +36,20 @@ import net.minecraftforge.client.model.data.EmptyModelData;
import net.minecraftforge.client.model.data.IModelData;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
public interface IForgeTileEntity extends ICapabilitySerializable<NBTTagCompound>
public interface IForgeTileEntity extends ICapabilitySerializable<CompoundNBT>
{
default TileEntity getTileEntity() { return (TileEntity) this; }
@Override
default void deserializeNBT(NBTTagCompound nbt)
default void deserializeNBT(CompoundNBT nbt)
{
getTileEntity().read(nbt);
}
@Override
default NBTTagCompound serializeNBT()
default CompoundNBT serializeNBT()
{
NBTTagCompound ret = new NBTTagCompound();
CompoundNBT ret = new CompoundNBT();
getTileEntity().write(ret);
return ret;
}
@@ -63,7 +63,7 @@ public interface IForgeTileEntity extends ICapabilitySerializable<NBTTagCompound
* @param net The NetworkManager the packet originated from
* @param pkt The data packet
*/
default void onDataPacket(net.minecraft.network.NetworkManager net, net.minecraft.network.play.server.SPacketUpdateTileEntity pkt){ }
default void onDataPacket(net.minecraft.network.NetworkManager net, net.minecraft.network.play.server.SUpdateTileEntityPacket pkt){ }
/**
* Called when the chunk's TE update tag, gotten from {@link #getUpdateTag()}, is received on the client.
@@ -72,7 +72,7 @@ public interface IForgeTileEntity extends ICapabilitySerializable<NBTTagCompound
*
* @param tag The {@link NBTTagCompound} sent from {@link #getUpdateTag()}
*/
default void handleUpdateTag(NBTTagCompound tag)
default void handleUpdateTag(CompoundNBT tag)
{
getTileEntity().read(tag);
}
@@ -83,7 +83,7 @@ public interface IForgeTileEntity extends ICapabilitySerializable<NBTTagCompound
*
* @return A compound tag for custom data
*/
NBTTagCompound getTileData();
CompoundNBT getTileData();
default void onChunkUnloaded(){}
@@ -95,17 +95,12 @@ public interface IForgeTileEntity extends ICapabilitySerializable<NBTTagCompound
{
requestModelDataUpdate();
}
default boolean shouldRenderInPass(int pass)
{
return pass == 0;
}
/**
* Sometimes default render bounding box: infinite in scope. Used to control rendering on {@link TileEntitySpecialRenderer}.
*/
public static final AxisAlignedBB INFINITE_EXTENT_AABB = new net.minecraft.util.math.AxisAlignedBB(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
/**
* Return an {@link AxisAlignedBB} that controls the visible scope of a {@link TileEntitySpecialRenderer} associated with this {@link TileEntity}
* Defaults to the collision bounding box {@link Block#getCollisionBoundingBoxFromPool(World, int, int, int)} associated with the block
@@ -117,7 +112,7 @@ public interface IForgeTileEntity extends ICapabilitySerializable<NBTTagCompound
default AxisAlignedBB getRenderBoundingBox()
{
AxisAlignedBB bb = INFINITE_EXTENT_AABB;
IBlockState state = getTileEntity().getBlockState();
BlockState state = getTileEntity().getBlockState();
Block block = state.getBlock();
BlockPos pos = getTileEntity().getPos();
if (block == Blocks.ENCHANTING_TABLE)
@@ -162,12 +157,12 @@ public interface IForgeTileEntity extends ICapabilitySerializable<NBTTagCompound
default boolean canRenderBreaking()
{
Block block = getTileEntity().getBlockState().getBlock();
return (block instanceof net.minecraft.block.BlockChest ||
block instanceof net.minecraft.block.BlockEnderChest ||
block instanceof net.minecraft.block.BlockSign ||
block instanceof net.minecraft.block.BlockSkull);
return (block instanceof net.minecraft.block.ChestBlock ||
block instanceof net.minecraft.block.EnderChestBlock ||
block instanceof net.minecraft.block.AbstractSignBlock ||
block instanceof net.minecraft.block.SkullBlock);
}
/**
* If the TileEntitySpecialRenderer associated with this TileEntity can be batched in with another renderers, and won't access the GL state.
* If TileEntity returns true, then TESR should have the same functionality as (and probably extend) the FastTESR class.
@@ -176,7 +171,7 @@ public interface IForgeTileEntity extends ICapabilitySerializable<NBTTagCompound
{
return false;
}
default void requestModelDataUpdate()
{
TileEntity te = getTileEntity();
@@ -186,7 +181,7 @@ public interface IForgeTileEntity extends ICapabilitySerializable<NBTTagCompound
ModelDataManager.requestModelDataRefresh(te);
}
}
default @Nonnull IModelData getModelData()
{
return EmptyModelData.INSTANCE;
@@ -1,46 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2019.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.extensions;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.village.Village;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
public interface IForgeVillage extends ICapabilitySerializable<NBTTagCompound>
{
default Village getVillage()
{
return (Village) this;
}
@Override
default void deserializeNBT(NBTTagCompound nbt)
{
getVillage().readVillageDataFromNBT(nbt);
}
@Override
default NBTTagCompound serializeNBT()
{
NBTTagCompound ret = new NBTTagCompound();
getVillage().writeVillageDataToNBT(ret);
return ret;
}
}
@@ -19,17 +19,9 @@
package net.minecraftforge.common.extensions;
import java.io.File;
import net.minecraft.world.WorldServer;
import net.minecraft.world.chunk.storage.AnvilChunkLoader;
import net.minecraft.world.ServerWorld;
public interface IForgeWorldServer extends IForgeWorld
{
default WorldServer getWorldServer() { return (WorldServer) this; }
default File getChunkSaveLocation()
{
return ((AnvilChunkLoader) getWorldServer().getChunkProvider().chunkLoader).chunkSaveLocation;
}
default ServerWorld getWorldServer() { return (ServerWorld) this; }
}
@@ -22,19 +22,20 @@ package net.minecraftforge.common.extensions;
import java.util.function.LongFunction;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiCreateBuffetWorld;
import net.minecraft.client.gui.GuiCreateFlatWorld;
import net.minecraft.client.gui.GuiCreateWorld;
import net.minecraft.client.gui.screen.CreateBuffetWorldScreen;
import net.minecraft.client.gui.screen.CreateFlatWorldScreen;
import net.minecraft.client.gui.screen.CreateWorldScreen;
import net.minecraft.world.World;
import net.minecraft.world.WorldType;
import net.minecraft.world.gen.IChunkGenerator;
import net.minecraft.world.gen.IContextExtended;
import net.minecraft.world.gen.ChunkGenerator;
import net.minecraft.world.gen.IExtendedNoiseRandom;
import net.minecraft.world.gen.OverworldGenSettings;
import net.minecraft.world.gen.area.IArea;
import net.minecraft.world.gen.area.IAreaFactory;
import net.minecraft.world.gen.layer.GenLayerBiome;
import net.minecraft.world.gen.layer.GenLayerBiomeEdge;
import net.minecraft.world.gen.layer.GenLayerZoom;
import net.minecraft.world.gen.layer.AddBambooForestLayer;
import net.minecraft.world.gen.layer.BiomeLayer;
import net.minecraft.world.gen.layer.EdgeBiomeLayer;
import net.minecraft.world.gen.layer.ZoomLayer;
import net.minecraft.world.gen.layer.LayerUtil;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
@@ -56,17 +57,17 @@ public interface IForgeWorldType
/**
* Called when the 'Customize' button is pressed on world creation GUI
*
*
* @param mc The Minecraft instance
* @param gui the createworld GUI
*/
@OnlyIn(Dist.CLIENT)
default void onCustomizeButton(Minecraft mc, GuiCreateWorld gui)
default void onCustomizeButton(Minecraft mc, CreateWorldScreen gui)
{
if (this == WorldType.FLAT)
mc.displayGuiScreen(new GuiCreateFlatWorld(gui, gui.chunkProviderSettingsJson));
mc.displayGuiScreen(new CreateFlatWorldScreen(gui, gui.chunkProviderSettingsJson));
else if (this == WorldType.BUFFET)
mc.displayGuiScreen(new GuiCreateBuffetWorld(gui, gui.chunkProviderSettingsJson));
mc.displayGuiScreen(new CreateBuffetWorldScreen(gui, gui.chunkProviderSettingsJson));
}
default boolean handleSlimeSpawnReduction(java.util.Random random, World world)
@@ -86,7 +87,7 @@ public interface IForgeWorldType
/**
* Get the height to render the clouds for this world type
*
*
* @return The height to render clouds at
*/
default float getCloudHeight()
@@ -95,7 +96,7 @@ public interface IForgeWorldType
}
@SuppressWarnings("deprecation")
default IChunkGenerator<?> createChunkGenerator(World world)
default ChunkGenerator<?> createChunkGenerator(World world)
{
return world.dimension.createChunkGenerator();
}
@@ -106,7 +107,7 @@ public interface IForgeWorldType
*
* @param <T> The type of {@link IArea}.
* @param <C> The type of {@link IContextExtended}.
*
*
* @param parentLayer The parent layer to feed into any layer you return
* @param chunkSettings The {@link OverworldGenSettings} used to create the
* {@link GenLayerBiome}.
@@ -115,12 +116,13 @@ public interface IForgeWorldType
* @return An {@link IAreaFactory} that representing the Biomes to be generated.
* @see {@link GenLayerBiome}
*/
default <T extends IArea, C extends IContextExtended<T>> IAreaFactory<T> getBiomeLayer(IAreaFactory<T> parentLayer,
default <T extends IArea, C extends IExtendedNoiseRandom<T>> IAreaFactory<T> getBiomeLayer(IAreaFactory<T> parentLayer,
OverworldGenSettings chunkSettings, LongFunction<C> contextFactory)
{
parentLayer = (new GenLayerBiome(getWorldType(), chunkSettings)).apply((IContextExtended) contextFactory.apply(200L), parentLayer);
parentLayer = LayerUtil.repeat(1000L, GenLayerZoom.NORMAL, parentLayer, 2, contextFactory);
parentLayer = GenLayerBiomeEdge.INSTANCE.apply((IContextExtended) contextFactory.apply(1000L), parentLayer);
parentLayer = (new BiomeLayer(getWorldType(), chunkSettings)).apply(contextFactory.apply(200L), parentLayer);
parentLayer = AddBambooForestLayer.INSTANCE.apply(contextFactory.apply(1001L), parentLayer);
parentLayer = LayerUtil.repeat(1000L, ZoomLayer.NORMAL, parentLayer, 2, contextFactory);
parentLayer = EdgeBiomeLayer.INSTANCE.apply(contextFactory.apply(1000L), parentLayer);
return parentLayer;
}
}
@@ -21,7 +21,7 @@ package net.minecraftforge.common.model;
import javax.vecmath.Matrix4f;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.Direction;
/*
* Replacement interface for ModelRotation to allow custom transformations of vanilla models.
@@ -31,7 +31,7 @@ public interface ITransformation
{
Matrix4f getMatrixVec();
EnumFacing rotate(EnumFacing facing);
Direction rotate(Direction facing);
int rotate(EnumFacing facing, int vertexIndex);
int rotate(Direction facing, int vertexIndex);
}
@@ -37,7 +37,7 @@ import javax.vecmath.Vector4f;
import net.minecraft.client.renderer.model.ItemTransformVec3f;
import net.minecraft.client.renderer.model.ModelRotation;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.Direction;
import net.minecraft.util.math.Vec3i;
import net.minecraftforge.api.distmarker.Dist;
@@ -110,19 +110,19 @@ public final class TRSRTransformation implements IModelState, ITransformation
}
@OnlyIn(Dist.CLIENT)
public static TRSRTransformation from(EnumFacing facing)
public static TRSRTransformation from(Direction facing)
{
return Cache.get(getRotation(facing));
}
@OnlyIn(Dist.CLIENT)
public static Matrix4f getMatrix(EnumFacing facing)
public static Matrix4f getMatrix(Direction facing)
{
return getRotation(facing).getMatrixVec();
}
@OnlyIn(Dist.CLIENT)
public static ModelRotation getRotation(EnumFacing facing)
public static ModelRotation getRotation(Direction facing)
{
switch (facing)
{
@@ -589,17 +589,17 @@ public final class TRSRTransformation implements IModelState, ITransformation
}
@Override
public EnumFacing rotate(EnumFacing facing)
public Direction rotate(Direction facing)
{
return rotate(matrix, facing);
}
public static EnumFacing rotate(Matrix4f matrix, EnumFacing facing)
public static Direction rotate(Matrix4f matrix, Direction facing)
{
Vec3i dir = facing.getDirectionVec();
Vector4f vec = new Vector4f(dir.getX(), dir.getY(), dir.getZ(), 0);
matrix.transform(vec);
return EnumFacing.getFacingFromVector(vec.x, vec.y, vec.z);
return Direction.getFacingFromVector(vec.x, vec.y, vec.z);
}
public static boolean isInteger(Matrix4f matrix)
@@ -621,7 +621,7 @@ public final class TRSRTransformation implements IModelState, ITransformation
}
@Override
public int rotate(EnumFacing facing, int vertexIndex)
public int rotate(Direction facing, int vertexIndex)
{
// FIXME check if this is good enough
return vertexIndex;
@@ -800,43 +800,43 @@ public final class TRSRTransformation implements IModelState, ITransformation
);
}
private static final EnumMap<EnumFacing, TRSRTransformation> vanillaUvTransformLocalToGlobal = Maps.newEnumMap(EnumFacing.class);
private static final EnumMap<EnumFacing, TRSRTransformation> vanillaUvTransformGlobalToLocal = Maps.newEnumMap(EnumFacing.class);
private static final EnumMap<Direction, TRSRTransformation> vanillaUvTransformLocalToGlobal = Maps.newEnumMap(Direction.class);
private static final EnumMap<Direction, TRSRTransformation> vanillaUvTransformGlobalToLocal = Maps.newEnumMap(Direction.class);
static
{
vanillaUvTransformLocalToGlobal.put(EnumFacing.SOUTH, identity);
vanillaUvTransformLocalToGlobal.put(Direction.SOUTH, identity);
Quat4f tmp = new Quat4f();
tmp.set(new AxisAngle4f(0, 1, 0, (float)Math.toRadians(90)));
vanillaUvTransformLocalToGlobal.put(EnumFacing.EAST, new TRSRTransformation(null, new Quat4f(tmp), null, null));
vanillaUvTransformLocalToGlobal.put(Direction.EAST, new TRSRTransformation(null, new Quat4f(tmp), null, null));
tmp.set(new AxisAngle4f(0, 1, 0, (float)Math.toRadians(-90)));
vanillaUvTransformLocalToGlobal.put(EnumFacing.WEST, new TRSRTransformation(null, new Quat4f(tmp), null, null));
vanillaUvTransformLocalToGlobal.put(Direction.WEST, new TRSRTransformation(null, new Quat4f(tmp), null, null));
tmp.set(new AxisAngle4f(0, 1, 0, (float)Math.toRadians(180)));
vanillaUvTransformLocalToGlobal.put(EnumFacing.NORTH, new TRSRTransformation(null, new Quat4f(tmp), null, null));
vanillaUvTransformLocalToGlobal.put(Direction.NORTH, new TRSRTransformation(null, new Quat4f(tmp), null, null));
tmp.set(new AxisAngle4f(1, 0, 0, (float)Math.toRadians(-90)));
vanillaUvTransformLocalToGlobal.put(EnumFacing.UP, new TRSRTransformation(null, new Quat4f(tmp), null, null));
vanillaUvTransformLocalToGlobal.put(Direction.UP, new TRSRTransformation(null, new Quat4f(tmp), null, null));
tmp.set(new AxisAngle4f(1, 0, 0, (float)Math.toRadians(90)));
vanillaUvTransformLocalToGlobal.put(EnumFacing.DOWN, new TRSRTransformation(null, new Quat4f(tmp), null, null));
vanillaUvTransformLocalToGlobal.put(Direction.DOWN, new TRSRTransformation(null, new Quat4f(tmp), null, null));
for(EnumFacing side : EnumFacing.values())
for(Direction side : Direction.values())
{
vanillaUvTransformGlobalToLocal.put(side, vanillaUvTransformLocalToGlobal.get(side).inverse());
}
}
public static TRSRTransformation getVanillaUvTransformLocalToGlobal(EnumFacing side)
public static TRSRTransformation getVanillaUvTransformLocalToGlobal(Direction side)
{
return vanillaUvTransformLocalToGlobal.get(side);
}
public static TRSRTransformation getVanillaUvTransformGlobalToLocal(EnumFacing side)
public static TRSRTransformation getVanillaUvTransformGlobalToLocal(Direction side)
{
return vanillaUvTransformGlobalToLocal.get(side);
}
public TRSRTransformation getUVLockTransform(EnumFacing originalSide)
public TRSRTransformation getUVLockTransform(Direction originalSide)
{
EnumFacing newSide = rotate(originalSide);
Direction newSide = rotate(originalSide);
try
{
return blockCenterToCorner(vanillaUvTransformGlobalToLocal.get(originalSide).compose(blockCornerToCenter(this.inverse())).compose(vanillaUvTransformLocalToGlobal.get(newSide)));
@@ -19,8 +19,8 @@
package net.minecraftforge.common.model.animation;
import net.minecraft.nbt.INBTBase;
import net.minecraft.util.EnumFacing;
import net.minecraft.nbt.INBT;
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.CapabilityManager;
@@ -40,13 +40,13 @@ public class CapabilityAnimation
CapabilityManager.INSTANCE.register(IAnimationStateMachine.class, new Capability.IStorage<IAnimationStateMachine>()
{
@Override
public INBTBase writeNBT(Capability<IAnimationStateMachine> capability, IAnimationStateMachine instance, EnumFacing side)
public INBT writeNBT(Capability<IAnimationStateMachine> capability, IAnimationStateMachine instance, Direction side)
{
return null;
}
@Override
public void readNBT(Capability<IAnimationStateMachine> capability, IAnimationStateMachine instance, EnumFacing side, INBTBase nbt) {}
public void readNBT(Capability<IAnimationStateMachine> capability, IAnimationStateMachine instance, Direction side, INBT nbt) {}
}, AnimationStateMachine::getMissing);
}
@@ -62,7 +62,7 @@ public class CapabilityAnimation
@Override
@Nonnull
public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing)
public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> capability, @Nullable Direction facing)
{
return ANIMATION_CAPABILITY.orEmpty(capability, asm);
}
@@ -34,9 +34,9 @@ public class DimensionMessageHandler extends SimpleChannelInboundHandler<ForgeMe
@Override
protected void channelRead0(ChannelHandlerContext ctx, DimensionRegisterMessage msg) throws Exception
{
if (DimensionManager.getRegistry().get(msg.id) == null)
if (DimensionManager.getRegistry().getByValue(msg.id) == null)
{
DimensionManager.registerDimensionInternal(msg.id + 1, msg.name, msg.dim, msg.data);
DimensionManager.registerDimensionInternal(msg.id + 1, msg.name, msg.dim, msg.data, msg.skyLight);
}
}
@Override
@@ -40,15 +40,17 @@ public abstract class ForgeMessage {
int id;
ResourceLocation name;
ModDimension dim;
boolean skyLight;
@Nullable
PacketBuffer data;
public DimensionRegisterMessage(){}
public DimensionRegisterMessage(int id, ResourceLocation name, ModDimension dim, @Nullable PacketBuffer data)
public DimensionRegisterMessage(int id, ResourceLocation name, ModDimension dim, boolean skyLight, @Nullable PacketBuffer data)
{
this.id = id;
this.dim = dim;
this.data = data;
this.skyLight = skyLight;
}
@Override
@@ -58,6 +60,7 @@ public abstract class ForgeMessage {
output.writeInt(id);
output.writeResourceLocation(name);
output.writeResourceLocation(dim.getRegistryName());
output.writeBoolean(skyLight);
if (data == null)
{
@@ -78,6 +81,7 @@ public abstract class ForgeMessage {
id = input.readInt();
name = input.readResourceLocation();
dim = ForgeRegistries.MOD_DIMENSIONS.getValue(input.readResourceLocation());
skyLight = input.readBoolean();
int len = input.readShort();
if (len != 0)
@@ -22,11 +22,12 @@ package net.minecraftforge.common.util;
import java.lang.ref.WeakReference;
import java.util.Objects;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.block.BlockState;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IWorld;
import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
import net.minecraftforge.fml.server.ServerLifecycleHooks;
@@ -48,24 +49,24 @@ public class BlockSnapshot
private final BlockPos pos;
private final int dimId;
@Nullable
private IBlockState replacedBlock;
private BlockState replacedBlock;
private int flag;
@Nullable
private final NBTTagCompound nbt;
private final CompoundNBT nbt;
@Nullable
private WeakReference<World> world;
private WeakReference<IWorld> world;
private final ResourceLocation registryName;
private final int meta = 0; // TODO BlockSnapshot needs a total refactor for the absence of metadata
public BlockSnapshot(World world, BlockPos pos, IBlockState state)
public BlockSnapshot(IWorld world, BlockPos pos, BlockState state)
{
this(world, pos, state, getTileNBT(world.getTileEntity(pos)));
}
public BlockSnapshot(World world, BlockPos pos, IBlockState state, @Nullable NBTTagCompound nbt)
public BlockSnapshot(IWorld world, BlockPos pos, BlockState state, @Nullable CompoundNBT nbt)
{
this.setWorld(world);
this.dimId = world.dimension.getType().getId();
this.dimId = world.getDimension().getType().getId();
this.pos = pos.toImmutable();
this.setReplacedBlock(state);
this.registryName = state.getBlock().getRegistryName();
@@ -77,7 +78,7 @@ public class BlockSnapshot
}
}
public BlockSnapshot(World world, BlockPos pos, IBlockState state, int flag)
public BlockSnapshot(IWorld world, BlockPos pos, BlockState state, int flag)
{
this(world, pos, state);
this.setFlag(flag);
@@ -86,7 +87,7 @@ public class BlockSnapshot
/**
* Raw constructor designed for serialization usages.
*/
public BlockSnapshot(int dimension, BlockPos pos, ResourceLocation registryName, int meta, int flag, @Nullable NBTTagCompound nbt)
public BlockSnapshot(int dimension, BlockPos pos, ResourceLocation registryName, int meta, int flag, @Nullable CompoundNBT nbt)
{
this.dimId = dimension;
this.pos = pos.toImmutable();
@@ -95,17 +96,17 @@ public class BlockSnapshot
this.nbt = nbt;
}
public static BlockSnapshot getBlockSnapshot(World world, BlockPos pos)
public static BlockSnapshot getBlockSnapshot(IWorld world, BlockPos pos)
{
return new BlockSnapshot(world, pos, world.getBlockState(pos));
}
public static BlockSnapshot getBlockSnapshot(World world, BlockPos pos, int flag)
public static BlockSnapshot getBlockSnapshot(IWorld world, BlockPos pos, int flag)
{
return new BlockSnapshot(world, pos, world.getBlockState(pos), flag);
}
public static BlockSnapshot readFromNBT(NBTTagCompound tag)
public static BlockSnapshot readFromNBT(CompoundNBT tag)
{
return new BlockSnapshot(
tag.getInt("dimension"),
@@ -117,31 +118,31 @@ public class BlockSnapshot
}
@Nullable
private static NBTTagCompound getTileNBT(@Nullable TileEntity te)
private static CompoundNBT getTileNBT(@Nullable TileEntity te)
{
if (te == null) return null;
NBTTagCompound nbt = new NBTTagCompound();
CompoundNBT nbt = new CompoundNBT();
te.write(nbt);
return nbt;
}
public IBlockState getCurrentBlock()
public BlockState getCurrentBlock()
{
return getWorld().getBlockState(getPos());
}
public World getWorld()
public IWorld getWorld()
{
World world = this.world != null ? this.world.get() : null;
IWorld world = this.world != null ? this.world.get() : null;
if (world == null)
{
world = ServerLifecycleHooks.getCurrentServer().getWorld(DimensionType.getById(getDimId()));
this.world = new WeakReference<World>(world);
this.world = new WeakReference<IWorld>(world);
}
return world;
}
public IBlockState getReplacedBlock()
public BlockState getReplacedBlock()
{
if (this.replacedBlock == null)
{
@@ -171,10 +172,10 @@ public class BlockSnapshot
return restoreToLocation(getWorld(), getPos(), force, notifyNeighbors);
}
public boolean restoreToLocation(World world, BlockPos pos, boolean force, boolean notifyNeighbors)
public boolean restoreToLocation(IWorld world, BlockPos pos, boolean force, boolean notifyNeighbors)
{
IBlockState current = getCurrentBlock();
IBlockState replaced = getReplacedBlock();
BlockState current = getCurrentBlock();
BlockState replaced = getReplacedBlock();
int flags = notifyNeighbors ? Constants.BlockFlags.DEFAULT : Constants.BlockFlags.NOTIFY_LISTENERS;
@@ -191,7 +192,8 @@ public class BlockSnapshot
}
world.setBlockState(pos, replaced, flags);
world.notifyBlockUpdate(pos, current, replaced, flags);
if (world instanceof World)
((World)world).notifyBlockUpdate(pos, current, replaced, flags);
TileEntity te = null;
if (getNbt() != null)
@@ -211,22 +213,22 @@ public class BlockSnapshot
return true;
}
public void writeToNBT(NBTTagCompound compound)
public void writeToNBT(CompoundNBT compound)
{
compound.setString("blockMod", getRegistryName().getNamespace());
compound.setString("blockName", getRegistryName().getPath());
compound.setInt("posX", getPos().getX());
compound.setInt("posY", getPos().getY());
compound.setInt("posZ", getPos().getZ());
compound.setInt("flag", getFlag());
compound.setInt("dimension", getDimId());
compound.setInt("metadata", getMeta());
compound.putString("blockMod", getRegistryName().getNamespace());
compound.putString("blockName", getRegistryName().getPath());
compound.putInt("posX", getPos().getX());
compound.putInt("posY", getPos().getY());
compound.putInt("posZ", getPos().getZ());
compound.putInt("flag", getFlag());
compound.putInt("dimension", getDimId());
compound.putInt("metadata", getMeta());
compound.setBoolean("hasTE", getNbt() != null);
compound.putBoolean("hasTE", getNbt() != null);
if (getNbt() != null)
{
compound.setTag("tileEntity", getNbt());
compound.func_218657_a("tileEntity", getNbt());
}
}
@@ -234,38 +236,17 @@ public class BlockSnapshot
public boolean equals(Object obj)
{
if (obj == this)
{
return true;
}
if (obj == null)
{
if (obj == null || getClass() != obj.getClass())
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final BlockSnapshot other = (BlockSnapshot) obj;
if (this.getMeta() != other.getMeta())
{
if (this.getMeta() != other.getMeta() ||
this.getDimId() != other.getDimId() ||
!this.getPos().equals(other.getPos()) ||
!this.getRegistryName().equals(other.getRegistryName()) ||
!Objects.equals(this.getNbt(), other.getNbt()))
return false;
}
if (this.getDimId() != other.getDimId())
{
return false;
}
if (!this.getPos().equals(other.getPos()))
{
return false;
}
if (!this.getRegistryName().equals(other.getRegistryName()))
{
return false;
}
if (!Objects.equals(this.getNbt(), other.getNbt()))
{
return false;
}
return true;
}
@@ -285,16 +266,16 @@ public class BlockSnapshot
public int getDimId() { return dimId; }
public void setReplacedBlock(IBlockState replacedBlock) { this.replacedBlock = replacedBlock; }
public void setReplacedBlock(BlockState replacedBlock) { this.replacedBlock = replacedBlock; }
public int getFlag() { return flag; }
public void setFlag(int flag) { this.flag = flag; }
@Nullable
public NBTTagCompound getNbt() { return nbt; }
public CompoundNBT getNbt() { return nbt; }
public void setWorld(World world) { this.world = new WeakReference<World>(world); }
public void setWorld(IWorld world) { this.world = new WeakReference<>(world); }
public ResourceLocation getRegistryName() { return registryName; }
@@ -19,7 +19,7 @@
package net.minecraftforge.common.util;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.util.math.ChunkPos;
// Sorter to load nearby chunks first
@@ -28,7 +28,7 @@ public class ChunkCoordComparator implements java.util.Comparator<ChunkPos>
private int x;
private int z;
public ChunkCoordComparator(EntityPlayerMP entityplayer)
public ChunkCoordComparator(ServerPlayerEntity entityplayer)
{
x = (int) entityplayer.posX >> 4;
z = (int) entityplayer.posZ >> 4;
@@ -20,13 +20,11 @@
package net.minecraftforge.common.util;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.WorldRenderer;
import net.minecraft.entity.ai.attributes.ModifiableAttributeInstance;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IWorld;
import net.minecraft.world.IWorldEventListener;
import net.minecraft.world.World;
/**
@@ -19,7 +19,7 @@
package net.minecraftforge.common.util;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.world.storage.WorldSavedData;
public class DummyWorldSaveData extends WorldSavedData {
@@ -29,12 +29,12 @@ public class DummyWorldSaveData extends WorldSavedData {
}
@Override
public void read(final NBTTagCompound nbt) {
public void read(final CompoundNBT nbt) {
// NOOP
}
@Override
public NBTTagCompound write(final NBTTagCompound compound) {
public CompoundNBT write(final CompoundNBT compound) {
// NOOP
return null;
}
@@ -24,23 +24,23 @@ import javax.annotation.Nullable;
import com.mojang.authlib.GameProfile;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.play.client.CPacketClientSettings;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.network.play.client.CClientSettingsPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.management.PlayerInteractionManager;
import net.minecraft.stats.Stat;
import net.minecraft.util.DamageSource;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.WorldServer;
import net.minecraft.world.ServerWorld;
import net.minecraft.world.dimension.DimensionType;
import net.minecraftforge.fml.server.ServerLifecycleHooks;
//Preliminary, simple Fake Player class
public class FakePlayer extends EntityPlayerMP
public class FakePlayer extends ServerPlayerEntity
{
public FakePlayer(WorldServer world, GameProfile name)
public FakePlayer(ServerWorld world, GameProfile name)
{
super(world.getServer(), world, name, new PlayerInteractionManager(world));
}
@@ -51,10 +51,9 @@ public class FakePlayer extends EntityPlayerMP
@Override public void addStat(Stat par1StatBase, int par2){}
//@Override public void openGui(Object mod, int modGuiId, World world, int x, int y, int z){}
@Override public boolean isInvulnerableTo(DamageSource source){ return true; }
@Override public boolean canAttackPlayer(EntityPlayer player){ return false; }
@Override public boolean canAttackPlayer(PlayerEntity player){ return false; }
@Override public void onDeath(DamageSource source){ return; }
@Override public void tick(){ return; }
@Override public Entity changeDimension(DimensionType dim, ITeleporter teleporter){ return this; }
@Override public void handleClientSettings(CPacketClientSettings pkt){ return; }
@Override public void handleClientSettings(CClientSettingsPacket pkt){ return; }
@Override @Nullable public MinecraftServer getServer() { return ServerLifecycleHooks.getCurrentServer(); }
}
@@ -28,7 +28,7 @@ import java.util.UUID;
import com.google.common.collect.Maps;
import com.mojang.authlib.GameProfile;
import net.minecraft.world.WorldServer;
import net.minecraft.world.ServerWorld;
//To be expanded for generic Mod fake players?
public class FakePlayerFactory
@@ -38,7 +38,7 @@ public class FakePlayerFactory
private static Map<GameProfile, FakePlayer> fakePlayers = Maps.newHashMap();
private static WeakReference<FakePlayer> MINECRAFT_PLAYER = null;
public static FakePlayer getMinecraft(WorldServer world)
public static FakePlayer getMinecraft(ServerWorld world)
{
FakePlayer ret = MINECRAFT_PLAYER != null ? MINECRAFT_PLAYER.get() : null;
if (ret == null)
@@ -54,7 +54,7 @@ public class FakePlayerFactory
* Mods should either hold weak references to the return value, or listen for a
* WorldEvent.Unload and kill all references to prevent worlds staying in memory.
*/
public static FakePlayer get(WorldServer world, GameProfile username)
public static FakePlayer get(ServerWorld world, GameProfile username)
{
if (!fakePlayers.containsKey(username))
{
@@ -65,7 +65,7 @@ public class FakePlayerFactory
return fakePlayers.get(username);
}
public static void unloadWorld(WorldServer world)
public static void unloadWorld(ServerWorld world)
{
fakePlayers.entrySet().removeIf(entry -> entry.getValue().world == world);
if (MINECRAFT_PLAYER != null && MINECRAFT_PLAYER.get() != null && MINECRAFT_PLAYER.get().world == world) // This shouldn't be strictly necessary, but lets be aggressive.
@@ -19,13 +19,13 @@
package net.minecraftforge.common.util;
import net.minecraft.nbt.INBTBase;
import net.minecraft.nbt.INBT;
/**
* An interface designed to unify various things in the Minecraft
* code base that can be serialized to and from a NBT tag.
*/
public interface INBTSerializable<T extends INBTBase>
public interface INBTSerializable<T extends INBT>
{
T serializeNBT();
void deserializeNBT(T nbt);
@@ -1,59 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2019.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.util;
import net.minecraft.entity.Entity;
import net.minecraft.world.Teleporter;
import net.minecraft.world.World;
/**
* Interface for handling the placement of entities during dimension change.
*
* An implementation of this interface can be used to place the entity
* in a safe location, or generate a return portal, for instance.
*
* See the {@link net.minecraft.world.Teleporter} class, which has
* been patched to implement this interface, for a vanilla example.
*/
public interface ITeleporter
{
/**
* Called to handle placing the entity in the new world.
*
* The initial position of the entity will be its
* position in the origin world, multiplied horizontally
* by the computed cross-dimensional movement factor
* (see {@link WorldProvider#getMovementFactor()}).
*
* Note that the supplied entity has not yet been spawned
* in the destination world at the time.
*
* @param world the entity's destination
* @param entity the entity to be placed
* @param yaw the suggested yaw value to apply
*/
void placeEntity(World world, Entity entity, float yaw);
// used internally to handle vanilla hardcoding
default boolean isVanilla()
{
return getClass() == Teleporter.class;
}
}
@@ -39,7 +39,7 @@ import com.google.gson.JsonSyntaxException;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.CompoundNBT;
import javax.annotation.Nullable;
@@ -97,13 +97,13 @@ public class JsonUtils
}
@Nullable
public static NBTTagCompound readNBT(JsonObject json, String key)
public static CompoundNBT readNBT(JsonObject json, String key)
{
if (net.minecraft.util.JsonUtils.hasField(json, key))
if (net.minecraft.util.JSONUtils.hasField(json, key))
{
try
{
return JsonToNBT.getTagFromJson(net.minecraft.util.JsonUtils.getString(json, key));
return JsonToNBT.getTagFromJson(net.minecraft.util.JSONUtils.getString(json, key));
} catch (CommandSyntaxException e)
{
throw new JsonSyntaxException("Malformed NBT tag", e);
@@ -21,7 +21,7 @@ package net.minecraftforge.common.util;
import javax.annotation.Nullable;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.world.dimension.Dimension;
import net.minecraft.world.storage.WorldSavedData;
@@ -29,22 +29,22 @@ public class WorldCapabilityData extends WorldSavedData
{
public static final String ID = "capabilities";
private INBTSerializable<NBTTagCompound> serializable;
private NBTTagCompound capNBT = null;
private INBTSerializable<CompoundNBT> serializable;
private CompoundNBT capNBT = null;
public WorldCapabilityData(String name)
{
super(name);
}
public WorldCapabilityData(@Nullable INBTSerializable<NBTTagCompound> serializable)
public WorldCapabilityData(@Nullable INBTSerializable<CompoundNBT> serializable)
{
super(ID);
this.serializable = serializable;
}
@Override
public void read(NBTTagCompound nbt)
public void read(CompoundNBT nbt)
{
this.capNBT = nbt;
if (serializable != null)
@@ -55,7 +55,7 @@ public class WorldCapabilityData extends WorldSavedData
}
@Override
public NBTTagCompound write(NBTTagCompound nbt)
public CompoundNBT write(CompoundNBT nbt)
{
if (serializable != null)
nbt = serializable.serializeNBT();
@@ -68,7 +68,7 @@ public class WorldCapabilityData extends WorldSavedData
return true;
}
public void setCapabilities(Dimension provider, INBTSerializable<NBTTagCompound> capabilities)
public void setCapabilities(Dimension provider, INBTSerializable<CompoundNBT> capabilities)
{
this.serializable = capabilities;
if (this.capNBT != null && serializable != null)