More compile cleanups. (#5139)

This commit is contained in:
tterrag 2018-09-14 12:30:56 -04:00 committed by LexManos
parent dbf649225a
commit 3f743887e7
71 changed files with 901 additions and 411 deletions

View file

@ -6,7 +6,7 @@ buildscript {
mavenCentral() mavenCentral()
} }
dependencies { dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:3.+' classpath 'net.minecraftforge.gradle:ForgeGradle:3.0.4'
} }
} }

View file

@ -0,0 +1,22 @@
--- a/net/minecraft/entity/EntityType.java
+++ b/net/minecraft/entity/EntityType.java
@@ -98,6 +98,7 @@
import net.minecraft.entity.projectile.EntityTippedArrow;
import net.minecraft.entity.projectile.EntityTrident;
import net.minecraft.entity.projectile.EntityWitherSkull;
+import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
@@ -121,9 +122,9 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
-public class EntityType<T extends Entity> {
+public class EntityType<T extends Entity> extends net.minecraftforge.registries.ForgeRegistryEntry<EntityType<T>> {
private static final Logger field_200731_aJ = LogManager.getLogger();
- public static final RegistryNamespaced<ResourceLocation, EntityType<?>> field_200787_a = new RegistryNamespaced<ResourceLocation, EntityType<?>>();
+ public static final RegistryNamespaced<ResourceLocation, EntityType<?>> field_200787_a = net.minecraftforge.registries.GameData.getWrapper(EntityType.class);
public static final EntityType<EntityAreaEffectCloud> field_200788_b = func_200712_a("area_effect_cloud", EntityType.Builder.func_201757_a(EntityAreaEffectCloud.class, EntityAreaEffectCloud::new));
public static final EntityType<EntityArmorStand> field_200789_c = func_200712_a("armor_stand", EntityType.Builder.func_201757_a(EntityArmorStand.class, EntityArmorStand::new));
public static final EntityType<EntityTippedArrow> field_200790_d = func_200712_a("arrow", EntityType.Builder.func_201757_a(EntityTippedArrow.class, EntityTippedArrow::new));

View file

@ -0,0 +1,81 @@
--- a/net/minecraft/entity/monster/EntityZombieVillager.java
+++ b/net/minecraft/entity/monster/EntityZombieVillager.java
@@ -49,15 +49,18 @@
public void setProfession(int profession) {
this.dataManager.set(PROFESSION, profession);
+ net.minecraftforge.fml.common.registry.VillagerRegistry.onSetProfession(this, profession);
}
+ @Deprecated // Use Forge Variant below
public int getProfession() {
- return Math.max(this.dataManager.get(PROFESSION) % 6, 0);
+ return Math.max(this.dataManager.get(PROFESSION), 0);
}
public void writeEntityToNBT(NBTTagCompound compound) {
super.writeEntityToNBT(compound);
compound.setInteger("Profession", this.getProfession());
+ compound.setString("ProfessionName", this.getForgeProfession().getRegistryName().toString());
compound.setInteger("ConversionTime", this.isConverting() ? this.conversionTime : -1);
if (this.converstionStarter != null) {
compound.setUniqueId("ConversionPlayer", this.converstionStarter);
@@ -68,6 +71,11 @@
public void readEntityFromNBT(NBTTagCompound compound) {
super.readEntityFromNBT(compound);
this.setProfession(compound.getInteger("Profession"));
+ if (compound.hasKey("ProfessionName")) {
+ net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession p = net.minecraftforge.registries.ForgeRegistries.VILLAGER_PROFESSIONS.getValue(new net.minecraft.util.ResourceLocation(compound.getString("ProfessionName")));
+ if (p == null) p = net.minecraftforge.fml.common.registry.VillagerRegistry.FARMER.orElseThrow(() -> new IllegalStateException("Farmer profession not initialized?"));
+ this.setForgeProfession(p);
+ }
if (compound.hasKey("ConversionTime", 99) && compound.getInteger("ConversionTime") > -1) {
this.startConverting(compound.hasUniqueId("ConversionPlayer") ? compound.getUniqueId("ConversionPlayer") : null, compound.getInteger("ConversionTime"));
}
@@ -145,7 +153,7 @@
protected void finishConversion() {
EntityVillager entityvillager = new EntityVillager(this.world);
entityvillager.copyLocationAndAnglesFrom(this);
- entityvillager.setProfession(this.getProfession());
+ entityvillager.setProfession(this.getForgeProfession());
entityvillager.finalizeMobSpawn(this.world.getDifficultyForLocation(new BlockPos(entityvillager)), (IEntityLivingData)null, (NBTTagCompound)null, false);
entityvillager.setLookingForHome();
if (this.isChild()) {
@@ -224,4 +232,37 @@
protected ItemStack getSkullDrop() {
return ItemStack.EMPTY;
}
+
+ /* ======================================== FORGE START =====================================*/
+
+ @Nullable
+ private net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession prof;
+ public void setForgeProfession(net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession prof)
+ {
+ this.prof = prof;
+ this.setProfession(net.minecraftforge.fml.common.registry.VillagerRegistry.getId(prof));
+ }
+
+ public net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession getForgeProfession()
+ {
+ if (this.prof == null)
+ {
+ this.prof = net.minecraftforge.fml.common.registry.VillagerRegistry.getById(this.getProfession());
+ if (this.prof == null)
+ return net.minecraftforge.fml.common.registry.VillagerRegistry.FARMER.orElseThrow(() -> new IllegalStateException("Farmer profession not initialized?"));
+ }
+ return this.prof;
+ }
+
+ @Override
+ public void notifyDataManagerChange(DataParameter<?> key)
+ {
+ super.notifyDataManagerChange(key);
+ if (key.equals(PROFESSION))
+ {
+ net.minecraftforge.fml.common.registry.VillagerRegistry.onSetProfession(this, this.dataManager.get(PROFESSION));
+ }
+ }
+
+ /* ======================================== FORGE END =====================================*/
}

View file

@ -0,0 +1,169 @@
--- a/net/minecraft/entity/passive/EntityVillager.java
+++ b/net/minecraft/entity/passive/EntityVillager.java
@@ -105,7 +105,7 @@
private boolean needsInitilization;
private boolean isWillingToMate;
private int wealth;
- private String lastBuyingPlayer;
+ private java.util.UUID lastBuyingPlayer;
private int careerId;
private int careerLevel;
private boolean isLookingForHome;
@@ -220,7 +220,7 @@
if (flag) {
itemstack.interactWithEntity(player, this, hand);
return true;
- } else if (itemstack.getItem() != Items.field_196172_da && this.isEntityAlive() && !this.isTrading() && !this.isChild()) {
+ } else if (itemstack.getItem() != Items.field_196172_da && this.isEntityAlive() && !this.isTrading() && !this.isChild() && !player.isSneaking()) {
if (this.buyingList == null) {
this.populateBuyingList();
}
@@ -250,6 +250,7 @@
public void writeEntityToNBT(NBTTagCompound compound) {
super.writeEntityToNBT(compound);
compound.setInteger("Profession", this.getProfession());
+ compound.setString("ProfessionName", this.getProfessionForge().getRegistryName().toString());
compound.setInteger("Riches", this.wealth);
compound.setInteger("Career", this.careerId);
compound.setInteger("CareerLevel", this.careerLevel);
@@ -273,6 +274,14 @@
public void readEntityFromNBT(NBTTagCompound compound) {
super.readEntityFromNBT(compound);
this.setProfession(compound.getInteger("Profession"));
+ if (compound.hasKey("ProfessionName"))
+ {
+ net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession p =
+ net.minecraftforge.registries.ForgeRegistries.VILLAGER_PROFESSIONS.getValue(new net.minecraft.util.ResourceLocation(compound.getString("ProfessionName")));
+ if (p == null)
+ p = net.minecraftforge.registries.ForgeRegistries.VILLAGER_PROFESSIONS.getValue(new net.minecraft.util.ResourceLocation("minecraft:farmer"));
+ this.setProfession(p);
+ }
this.wealth = compound.getInteger("Riches");
this.careerId = compound.getInteger("Career");
this.careerLevel = compound.getInteger("CareerLevel");
@@ -318,12 +327,42 @@
public void setProfession(int professionId) {
this.dataManager.set(PROFESSION, professionId);
+ net.minecraftforge.fml.common.registry.VillagerRegistry.onSetProfession(this, professionId);
}
+ @Deprecated // Use Forge Variant below
public int getProfession() {
- return Math.max(this.dataManager.get(PROFESSION) % 6, 0);
+ return Math.max(this.dataManager.get(PROFESSION), 0);
}
+ private net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession prof;
+ public void setProfession(net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession prof)
+ {
+ this.prof = prof;
+ this.setProfession(net.minecraftforge.fml.common.registry.VillagerRegistry.getId(prof));
+ }
+
+ public net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession getProfessionForge()
+ {
+ if (this.prof == null)
+ {
+ this.prof = net.minecraftforge.fml.common.registry.VillagerRegistry.getById(this.getProfession());
+ if (this.prof == null)
+ return net.minecraftforge.fml.common.registry.VillagerRegistry.getById(0); //Farmer
+ }
+ return this.prof;
+ }
+
+ @Override
+ public void notifyDataManagerChange(DataParameter<?> key)
+ {
+ super.notifyDataManagerChange(key);
+ if (key.equals(PROFESSION))
+ {
+ net.minecraftforge.fml.common.registry.VillagerRegistry.onSetProfession(this, this.dataManager.get(PROFESSION));
+ }
+ }
+
public boolean isMating() {
return this.isMating;
}
@@ -433,7 +472,7 @@
this.needsInitilization = true;
this.isWillingToMate = true;
if (this.buyingPlayer != null) {
- this.lastBuyingPlayer = this.buyingPlayer.getGameProfile().getName();
+ this.lastBuyingPlayer = this.buyingPlayer.getUniqueID();
} else {
this.lastBuyingPlayer = null;
}
@@ -473,11 +512,10 @@
}
private void populateBuyingList() {
- EntityVillager.ITradeList[][][] aentityvillager$itradelist = DEFAULT_TRADE_LIST_MAP[this.getProfession()];
if (this.careerId != 0 && this.careerLevel != 0) {
++this.careerLevel;
} else {
- this.careerId = this.rand.nextInt(aentityvillager$itradelist.length) + 1;
+ this.careerId = this.getProfessionForge().getRandomCareer(this.rand) + 1;
this.careerLevel = 1;
}
@@ -487,16 +525,11 @@
int i = this.careerId - 1;
int j = this.careerLevel - 1;
- if (i >= 0 && i < aentityvillager$itradelist.length) {
- EntityVillager.ITradeList[][] aentityvillager$itradelist1 = aentityvillager$itradelist[i];
- if (j >= 0 && j < aentityvillager$itradelist1.length) {
- EntityVillager.ITradeList[] aentityvillager$itradelist2 = aentityvillager$itradelist1[j];
-
- for(EntityVillager.ITradeList entityvillager$itradelist : aentityvillager$itradelist2) {
- entityvillager$itradelist.addMerchantRecipe(this, this.buyingList, this.rand);
- }
+ java.util.List<EntityVillager.ITradeList> trades = this.getProfessionForge().getCareer(i).getTrades(j);
+ if (i >= 0 && trades != null) {
+ for (EntityVillager.ITradeList entityvillager$itradelist : trades) {
+ entityvillager$itradelist.addMerchantRecipe(this, this.buyingList, this.rand);
}
-
}
}
@@ -567,7 +600,7 @@
s = "nitwit";
}
- if (s != null) {
+ s = this.getProfessionForge().getCareer(this.careerId-1).getName();
ITextComponent itextcomponent1 = (new TextComponentTranslation(this.func_200600_R().func_210760_d() + '.' + s, new Object[0])).func_211710_a((p_211520_1_) -> {
p_211520_1_.setHoverEvent(this.getHoverEvent()).setInsertion(this.getCachedUniqueIdString());
});
@@ -576,9 +609,6 @@
}
return itextcomponent1;
- } else {
- return super.getDisplayName();
- }
}
}
@@ -619,7 +649,7 @@
public IEntityLivingData finalizeMobSpawn(DifficultyInstance p_190672_1_, @Nullable IEntityLivingData p_190672_2_, @Nullable NBTTagCompound p_190672_3_, boolean p_190672_4_) {
p_190672_2_ = super.func_204210_a(p_190672_1_, p_190672_2_, p_190672_3_);
if (p_190672_4_) {
- this.setProfession(this.world.rand.nextInt(6));
+ net.minecraftforge.fml.common.registry.VillagerRegistry.setRandomProfession(this, this.world.rand);
}
this.setAdditionalAItasks();
@@ -817,6 +847,10 @@
recipeList.add(new MerchantRecipe(itemstack, itemstack1));
}
}
+
+ //MODDERS DO NOT USE OR EDIT THIS IN ANY WAY IT WILL HAVE NO EFFECT, THIS IS JUST IN HERE TO ALLOW FORGE TO ACCESS IT
+ @Deprecated
+ public static ITradeList[][][][] GET_TRADES_DONT_USE(){ return DEFAULT_TRADE_LIST_MAP; }
public static class ListItemForEmeralds implements EntityVillager.ITradeList {
public ItemStack itemToBuy;

View file

@ -0,0 +1,19 @@
--- a/net/minecraft/init/Bootstrap.java
+++ b/net/minecraft/init/Bootstrap.java
@@ -75,6 +75,8 @@
import net.minecraft.world.biome.Biome;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
+import net.minecraftforge.registries.ForgeRegistries;
+
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -421,6 +423,7 @@
redirectOutputToLog();
}
+ ForgeRegistries.ITEMS.getClass(); // TODO figure out a better way to ensure this is initialized
}
}

View file

@ -9,7 +9,13 @@
private World world; private World world;
private final List<VillageDoorInfo> villageDoorInfoList = Lists.<VillageDoorInfo>newArrayList(); private final List<VillageDoorInfo> villageDoorInfoList = Lists.<VillageDoorInfo>newArrayList();
private BlockPos centerHelper = BlockPos.ORIGIN; private BlockPos centerHelper = BlockPos.ORIGIN;
@@ -45,10 +45,12 @@ @@ -40,15 +40,17 @@
private int tickCounter;
private int numVillagers;
private int noBreedTicks;
- private final Map<String, Integer> playerReputation = Maps.<String, Integer>newHashMap();
+ private final Map<UUID, Integer> playerReputation = Maps.<UUID, Integer>newHashMap();
private final List<Village.VillageAggressor> villageAgressors = Lists.<Village.VillageAggressor>newArrayList();
private int numIronGolems; private int numIronGolems;
public Village() { public Village() {
@ -22,8 +28,83 @@
} }
public void setWorld(World worldIn) { public void setWorld(World worldIn) {
@@ -364,7 +366,7 @@ @@ -237,9 +239,9 @@
this.playerReputation.put(nbttagcompound1.getString("Name"), nbttagcompound1.getInteger("S")); double d0 = Double.MAX_VALUE;
EntityPlayer entityplayer = null;
- for(String s : this.playerReputation.keySet()) {
+ for(UUID s : this.playerReputation.keySet()) {
if (this.isPlayerReputationTooLow(s)) {
- EntityPlayer entityplayer1 = this.world.getPlayerEntityByName(s);
+ EntityPlayer entityplayer1 = this.world.getPlayerEntityByUUID(s);
if (entityplayer1 != null) {
double d1 = entityplayer1.getDistanceSq(villageDefender);
if (!(d1 > d0)) {
@@ -317,12 +319,32 @@
}
}
+ @Deprecated //Hasn't worked since 1.9, use UUID version below.
public int getPlayerReputation(String playerName) {
+ return this.getPlayerReputation(findUUID(playerName));
+ }
+
+ public int getPlayerReputation(UUID playerName)
+ {
Integer integer = this.playerReputation.get(playerName);
return integer == null ? 0 : integer;
}
+
+ private UUID findUUID(String name)
+ {
+ if (this.world == null || this.world.getMinecraftServer() == null)
+ return EntityPlayer.getOfflineUUID(name);
+ GameProfile profile = this.world.getMinecraftServer().getPlayerProfileCache().getGameProfileForUsername(name);
+ return profile == null ? EntityPlayer.getOfflineUUID(name) : profile.getId();
+ }
+ @Deprecated //Hasn't worked since 1.9, use UUID version below.
public int modifyPlayerReputation(String playerName, int reputation) {
+ return this.modifyPlayerReputation(findUUID(playerName), reputation);
+ }
+
+ public int modifyPlayerReputation(UUID playerName, int reputation)
+ {
int i = this.getPlayerReputation(playerName);
int j = MathHelper.clamp(i + reputation, -30, 10);
this.playerReputation.put(playerName, j);
@@ -330,9 +352,14 @@
}
public boolean isPlayerReputationTooLow(String playerName) {
- return this.getPlayerReputation(playerName) <= -15;
+ return this.isPlayerReputationTooLow(findUUID(playerName));
}
+ public boolean isPlayerReputationTooLow(UUID uuid)
+ {
+ return this.getPlayerReputation(uuid) <= -15;
+ }
+
public void readVillageDataFromNBT(NBTTagCompound compound) {
this.numVillagers = compound.getInteger("PopSize");
this.villageRadius = compound.getInteger("Radius");
@@ -354,17 +381,14 @@
for(int j = 0; j < nbttaglist1.size(); ++j) {
NBTTagCompound nbttagcompound1 = nbttaglist1.getCompoundTagAt(j);
- if (nbttagcompound1.hasKey("UUID") && this.world != null && this.world.getMinecraftServer() != null) {
- PlayerProfileCache playerprofilecache = this.world.getMinecraftServer().getPlayerProfileCache();
- GameProfile gameprofile = playerprofilecache.getProfileByUUID(UUID.fromString(nbttagcompound1.getString("UUID")));
- if (gameprofile != null) {
- this.playerReputation.put(gameprofile.getName(), nbttagcompound1.getInteger("S"));
- }
+ if (nbttagcompound1.hasKey("UUID")) {
+ this.playerReputation.put(UUID.fromString(nbttagcompound1.getString("UUID")), Integer.valueOf(nbttagcompound1.getInteger("S")));
} else {
- this.playerReputation.put(nbttagcompound1.getString("Name"), nbttagcompound1.getInteger("S"));
+ //World is never set here, so this will always be offline UUIDs, sadly there is no way to convert this.
+ this.playerReputation.put(findUUID(nbttagcompound1.getString("Name")), Integer.valueOf(nbttagcompound1.getInteger("S")));
} }
} }
- -
@ -31,7 +112,25 @@
} }
public void writeVillageDataToNBT(NBTTagCompound compound) { public void writeVillageDataToNBT(NBTTagCompound compound) {
@@ -413,6 +415,8 @@ @@ -396,14 +420,12 @@
compound.setTag("Doors", nbttaglist);
NBTTagList nbttaglist1 = new NBTTagList();
- for(String s : this.playerReputation.keySet()) {
+ for(UUID s : this.playerReputation.keySet()) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
- PlayerProfileCache playerprofilecache = this.world.getMinecraftServer().getPlayerProfileCache();
try {
- GameProfile gameprofile = playerprofilecache.getGameProfileForUsername(s);
- if (gameprofile != null) {
- nbttagcompound1.setString("UUID", gameprofile.getId().toString());
+ {
+ nbttagcompound1.setString("UUID", s.toString());
nbttagcompound1.setInteger("S", this.playerReputation.get(s));
nbttaglist1.add((INBTBase)nbttagcompound1);
}
@@ -413,6 +435,8 @@
} }
compound.setTag("Players", nbttaglist1); compound.setTag("Players", nbttaglist1);
@ -40,3 +139,12 @@
} }
public void endMatingSeason() { public void endMatingSeason() {
@@ -424,7 +448,7 @@
}
public void setDefaultPlayerReputation(int defaultReputation) {
- for(String s : this.playerReputation.keySet()) {
+ for(UUID s : this.playerReputation.keySet()) {
this.modifyPlayerReputation(s, defaultReputation);
}

View file

@ -9,7 +9,7 @@
public static final float[] MOON_PHASE_FACTORS = new float[]{1.0F, 0.75F, 0.5F, 0.25F, 0.0F, 0.25F, 0.5F, 0.75F}; public static final float[] MOON_PHASE_FACTORS = new float[]{1.0F, 0.75F, 0.5F, 0.25F, 0.0F, 0.25F, 0.5F, 0.75F};
protected World world; protected World world;
protected boolean doesWaterVaporize; protected boolean doesWaterVaporize;
@@ -141,4 +141,54 @@ @@ -141,4 +141,67 @@
public abstract boolean doesXZShowFog(int x, int z); public abstract boolean doesXZShowFog(int x, int z);
public abstract DimensionType getDimensionType(); public abstract DimensionType getDimensionType();
@ -18,6 +18,19 @@
+ private net.minecraftforge.client.IRenderHandler skyRenderer = null; + private net.minecraftforge.client.IRenderHandler skyRenderer = null;
+ private net.minecraftforge.client.IRenderHandler cloudRenderer = null; + private net.minecraftforge.client.IRenderHandler cloudRenderer = null;
+ private net.minecraftforge.client.IRenderHandler weatherRenderer = null; + private net.minecraftforge.client.IRenderHandler weatherRenderer = null;
+ private int dimensionId;
+
+ @Override
+ public void setId(int id)
+ {
+ this.dimensionId = id;
+ }
+
+ @Override
+ public int getId()
+ {
+ return this.dimensionId;
+ }
+ +
+ @Nullable + @Nullable
+ @OnlyIn(Dist.CLIENT) + @OnlyIn(Dist.CLIENT)

View file

@ -48,13 +48,12 @@ import com.google.common.collect.Multiset;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.world.DimensionType;
import net.minecraft.world.MinecraftException;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.world.ServerWorldEventHandler; import net.minecraft.world.ServerWorldEventHandler;
import net.minecraft.world.WorldProvider;
import net.minecraft.world.WorldServer; import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldServerMulti; import net.minecraft.world.WorldServerMulti;
import net.minecraft.world.dimension.Dimension;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.storage.ISaveHandler; import net.minecraft.world.storage.ISaveHandler;
import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.event.world.WorldEvent;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
@ -68,11 +67,11 @@ public class DimensionManager
{ {
private static final Logger LOGGER = LogManager.getLogger(); private static final Logger LOGGER = LogManager.getLogger();
private static final Marker DIMMGR = MarkerManager.getMarker("DIMS"); private static final Marker DIMMGR = MarkerManager.getMarker("DIMS");
private static class Dimension private static class DimensionData
{ {
private final DimensionType type; private final DimensionType type;
private int ticksWaited; private int ticksWaited;
private Dimension(DimensionType type) private DimensionData(DimensionType type)
{ {
this.type = type; this.type = type;
this.ticksWaited = 0; this.ticksWaited = 0;
@ -82,7 +81,7 @@ public class DimensionManager
private static boolean hasInit = false; private static boolean hasInit = false;
private static final Int2ObjectMap<WorldServer> worlds = Int2ObjectMaps.synchronize(new Int2ObjectLinkedOpenHashMap<>()); private static final Int2ObjectMap<WorldServer> worlds = Int2ObjectMaps.synchronize(new Int2ObjectLinkedOpenHashMap<>());
private static final Int2ObjectMap<Dimension> dimensions = Int2ObjectMaps.synchronize(new Int2ObjectLinkedOpenHashMap<>()); private static final Int2ObjectMap<DimensionData> dimensions = Int2ObjectMaps.synchronize(new Int2ObjectLinkedOpenHashMap<>());
private static final IntSet keepLoaded = IntSets.synchronize(new IntOpenHashSet()); private static final IntSet keepLoaded = IntSets.synchronize(new IntOpenHashSet());
private static final IntSet unloadQueue = IntSets.synchronize(new IntLinkedOpenHashSet()); private static final IntSet unloadQueue = IntSets.synchronize(new IntLinkedOpenHashSet());
private static final BitSet dimensionMap = new BitSet(Long.SIZE << 4); private static final BitSet dimensionMap = new BitSet(Long.SIZE << 4);
@ -96,7 +95,7 @@ public class DimensionManager
{ {
int[] ret = new int[dimensions.size()]; int[] ret = new int[dimensions.size()];
int x = 0; int x = 0;
for (Int2ObjectMap.Entry<Dimension> ent : dimensions.int2ObjectEntrySet()) for (Int2ObjectMap.Entry<DimensionData> ent : dimensions.int2ObjectEntrySet())
{ {
if (ent.getValue().type == type) if (ent.getValue().type == type)
{ {
@ -110,7 +109,7 @@ public class DimensionManager
public static Map<DimensionType, IntSortedSet> getRegisteredDimensions() public static Map<DimensionType, IntSortedSet> getRegisteredDimensions()
{ {
Map<DimensionType, IntSortedSet> map = new IdentityHashMap<>(); Map<DimensionType, IntSortedSet> map = new IdentityHashMap<>();
for (Int2ObjectMap.Entry<Dimension> entry : dimensions.int2ObjectEntrySet()) for (Int2ObjectMap.Entry<DimensionData> entry : dimensions.int2ObjectEntrySet())
{ {
map.computeIfAbsent(entry.getValue().type, k -> new IntRBTreeSet()).add(entry.getIntKey()); map.computeIfAbsent(entry.getValue().type, k -> new IntRBTreeSet()).add(entry.getIntKey());
} }
@ -138,7 +137,7 @@ public class DimensionManager
{ {
throw new IllegalArgumentException(String.format("Failed to register dimension for id %d, One is already registered", id)); throw new IllegalArgumentException(String.format("Failed to register dimension for id %d, One is already registered", id));
} }
dimensions.put(id, new Dimension(type)); dimensions.put(id, new DimensionData(type));
if (id >= 0) if (id >= 0)
{ {
dimensionMap.set(id); dimensionMap.set(id);
@ -171,7 +170,7 @@ public class DimensionManager
return dimensions.get(dim).type; return dimensions.get(dim).type;
} }
public static WorldProvider getProvider(int dim) public static Dimension getProvider(int dim)
{ {
return getWorld(dim).provider; return getWorld(dim).provider;
} }
@ -309,14 +308,14 @@ public class DimensionManager
return dimensions.keySet().toArray(new Integer[0]); return dimensions.keySet().toArray(new Integer[0]);
} }
public static WorldProvider createProviderFor(int dim) public static Dimension createProviderFor(int dim)
{ {
try try
{ {
if (dimensions.containsKey(dim)) if (dimensions.containsKey(dim))
{ {
WorldProvider ret = getProviderType(dim).createDimension(); Dimension ret = getProviderType(dim).createDimension();
ret.setDimension(dim); ret.setId(dim);
return ret; return ret;
} }
else else
@ -348,7 +347,7 @@ public class DimensionManager
return ForgeChunkManager.getPersistentChunksFor(world).isEmpty() return ForgeChunkManager.getPersistentChunksFor(world).isEmpty()
&& world.playerEntities.isEmpty() && world.playerEntities.isEmpty()
&& !world.provider.getDimensionType().shouldLoadSpawn() && !world.provider.getDimensionType().shouldLoadSpawn()
&& !keepLoaded.contains(world.provider.getDimension()); && !keepLoaded.contains(world.provider.getId());
} }
/** /**
@ -380,7 +379,7 @@ public class DimensionManager
while (queueIterator.hasNext()) while (queueIterator.hasNext())
{ {
int id = queueIterator.nextInt(); int id = queueIterator.nextInt();
Dimension dimension = dimensions.get(id); DimensionData dimension = dimensions.get(id);
if (dimension.ticksWaited < ForgeMod.dimensionUnloadQueueDelay) if (dimension.ticksWaited < ForgeMod.dimensionUnloadQueueDelay)
{ {
dimension.ticksWaited++; dimension.ticksWaited++;

View file

@ -110,7 +110,7 @@ import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.ClickEvent;
import net.minecraft.world.IBlockAccess; import net.minecraft.world.IWorldReader;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.world.EnumDifficulty; import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.GameType; import net.minecraft.world.GameType;
@ -209,7 +209,7 @@ public class ForgeHooks
private static boolean toolInit = false; private static boolean toolInit = false;
//static HashSet<List> toolEffectiveness = new HashSet<List>(); //static HashSet<List> toolEffectiveness = new HashSet<List>();
public static boolean canHarvestBlock(@Nonnull Block block, @Nonnull EntityPlayer player, @Nonnull IBlockAccess world, @Nonnull BlockPos pos) public static boolean canHarvestBlock(@Nonnull Block block, @Nonnull EntityPlayer player, @Nonnull IWorldReader world, @Nonnull BlockPos pos)
{ {
IBlockState state = world.getBlockState(pos); IBlockState state = world.getBlockState(pos);
state = state.getBlock().getActualState(state, world, pos); state = state.getBlock().getActualState(state, world, pos);
@ -234,7 +234,7 @@ public class ForgeHooks
return toolLevel >= block.getHarvestLevel(state); return toolLevel >= block.getHarvestLevel(state);
} }
public static boolean canToolHarvestBlock(IBlockAccess world, BlockPos pos, @Nonnull ItemStack stack) public static boolean canToolHarvestBlock(IWorldReader world, BlockPos pos, @Nonnull ItemStack stack)
{ {
IBlockState state = world.getBlockState(pos); IBlockState state = world.getBlockState(pos);
state = state.getBlock().getActualState(state, world, pos); state = state.getBlock().getActualState(state, world, pos);
@ -261,7 +261,7 @@ public class ForgeHooks
} }
} }
public static boolean isToolEffective(IBlockAccess world, BlockPos pos, @Nonnull ItemStack stack) public static boolean isToolEffective(IWorldReader world, BlockPos pos, @Nonnull ItemStack stack)
{ {
IBlockState state = world.getBlockState(pos); IBlockState state = world.getBlockState(pos);
state = state.getBlock().getActualState(state, world, pos); state = state.getBlock().getActualState(state, world, pos);

View file

@ -105,7 +105,7 @@ public class ForgeModContainer extends FMLModContainer
ConfigCategory GENERAL = config.getCategory(CATEGORY_GENERAL); ConfigCategory GENERAL = config.getCategory(CATEGORY_GENERAL);
if (GENERAL.containsKey(key)) if (GENERAL.containsKey(key))
{ {
FMLLog.log.debug("Remapping property {} from category general to client", key); LOGGER.debug("Remapping property {} from category general to client", key);
Property property = GENERAL.get(key); Property property = GENERAL.get(key);
GENERAL.remove(key); GENERAL.remove(key);
config.getCategory(CATEGORY_CLIENT).put(key, property); config.getCategory(CATEGORY_CLIENT).put(key, property);
@ -182,7 +182,7 @@ public class ForgeModContainer extends FMLModContainer
if (removeErroringEntities) if (removeErroringEntities)
{ {
FMLLog.log.warn("Enabling removal of erroring Entities - USE AT YOUR OWN RISK"); LOGGER.warn("Enabling removal of erroring Entities - USE AT YOUR OWN RISK");
} }
prop = config.get(Configuration.CATEGORY_GENERAL, "removeErroringTileEntities", false); prop = config.get(Configuration.CATEGORY_GENERAL, "removeErroringTileEntities", false);
@ -193,7 +193,7 @@ public class ForgeModContainer extends FMLModContainer
if (removeErroringTileEntities) if (removeErroringTileEntities)
{ {
FMLLog.log.warn("Enabling removal of erroring Tile Entities - USE AT YOUR OWN RISK"); LOGGER.warn("Enabling removal of erroring Tile Entities - USE AT YOUR OWN RISK");
} }
prop = config.get(Configuration.CATEGORY_GENERAL, "fullBoundingBoxLadders", false); prop = config.get(Configuration.CATEGORY_GENERAL, "fullBoundingBoxLadders", false);

View file

@ -21,10 +21,10 @@ package net.minecraftforge.common;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess; import net.minecraft.world.IWorldReader;
public interface IPlantable public interface IPlantable
{ {
EnumPlantType getPlantType(IBlockAccess world, BlockPos pos); EnumPlantType getPlantType(IWorldReader world, BlockPos pos);
IBlockState getPlant(IBlockAccess world, BlockPos pos); IBlockState getPlant(IWorldReader world, BlockPos pos);
} }

View file

@ -23,7 +23,7 @@ import java.util.List;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess; import net.minecraft.world.IWorldReader;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
@ -35,7 +35,7 @@ import javax.annotation.Nonnull;
* to support mod-shears as well. * to support mod-shears as well.
* *
*/ */
//TODO Change to World, not IBlockAccess and make Implementor responsible for removing itself from the world. //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. //Better mimics vanilla behavior and allows more control for the user.
public interface IShearable public interface IShearable
{ {
@ -48,7 +48,7 @@ public interface IShearable
* @param pos Block's position in world. * @param pos Block's position in world.
* @return If this is shearable, and onSheared should be called. * @return If this is shearable, and onSheared should be called.
*/ */
boolean isShearable(@Nonnull ItemStack item, IBlockAccess world, BlockPos pos); boolean isShearable(@Nonnull ItemStack item, IWorldReader world, BlockPos pos);
/** /**
* Performs the shear function on this object. * Performs the shear function on this object.
@ -69,5 +69,5 @@ public interface IShearable
* @return A List containing all items from this shearing. May be empty. * @return A List containing all items from this shearing. May be empty.
*/ */
@Nonnull @Nonnull
List<ItemStack> onSheared(@Nonnull ItemStack item, IBlockAccess world, BlockPos pos, int fortune); List<ItemStack> onSheared(@Nonnull ItemStack item, IWorldReader world, BlockPos pos, int fortune);
} }

View file

@ -121,7 +121,7 @@ public class MinecraftForge
} }
catch (Exception e) catch (Exception e)
{ {
FMLLog.log.error("Could not find class for name '{}'.", name, e); LOGGER.error("Could not find class for name '{}'.", name, e);
} }
} }
} }

View file

@ -23,6 +23,8 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.common.io.Files; import com.google.common.io.Files;
import com.mojang.datafixers.DataFixer; import com.mojang.datafixers.DataFixer;
@ -40,6 +42,8 @@ import net.minecraft.world.WorldServer;
public class WorldSpecificSaveHandler implements ISaveHandler public class WorldSpecificSaveHandler implements ISaveHandler
{ {
private static final Logger LOGGER = LogManager.getLogger();
private WorldServer world; private WorldServer world;
private ISaveHandler parent; private ISaveHandler parent;
private File dataDir; private File dataDir;
@ -95,7 +99,7 @@ public class WorldSpecificSaveHandler implements ISaveHandler
} }
catch (IOException e) catch (IOException e)
{ {
FMLLog.log.error("A critical error occurred copying {} to world specific dat folder - new file will be created.", parentFile.getName(), e); LOGGER.error("A critical error occurred copying {} to world specific dat folder - new file will be created.", parentFile.getName(), e);
} }
} }
} }

View file

@ -67,6 +67,11 @@ public class OptionalCapabilityInstance<T>
return instanceSupplier == null ? EMPTY.cast() : new OptionalCapabilityInstance<>(instanceSupplier); return instanceSupplier == null ? EMPTY.cast() : new OptionalCapabilityInstance<>(instanceSupplier);
} }
public static <T, R> OptionalCapabilityInstance<R> orEmpty(Capability<R> cap, Capability<T> toCheck, OptionalCapabilityInstance<T> inst)
{
return cap == toCheck ? inst.cast() : EMPTY.cast();
}
private @Nullable T getValue() private @Nullable T getValue()
{ {
if (!isValid) if (!isValid)

View file

@ -27,16 +27,20 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger; 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 com.google.common.collect.Maps;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.AnvilChunkLoader; import net.minecraft.world.chunk.storage.AnvilChunkLoader;
import net.minecraft.world.gen.ChunkProviderServer; import net.minecraft.world.gen.ChunkProviderServer;
import net.minecraftforge.fml.common.FMLLog;
public class ChunkIOExecutor public class ChunkIOExecutor
{ {
private static final Logger LOGGER = LogManager.getLogger();
private static final int BASE_THREADS = 1; private static final int BASE_THREADS = 1;
private static final int PLAYERS_PER_THREAD = 50; private static final int PLAYERS_PER_THREAD = 50;
@ -120,7 +124,7 @@ public class ChunkIOExecutor
ChunkIOProvider task = tasks.get(key); ChunkIOProvider task = tasks.get(key);
if (task == null) if (task == null)
{ {
FMLLog.log.warn("Attempted to dequeue chunk that wasn't queued? {} @ ({}, {})", world.provider.getDimension(), x, z); LOGGER.warn("Attempted to dequeue chunk that wasn't queued? {} @ ({}, {})", world.provider.getId(), x, z);
return; return;
} }

View file

@ -65,14 +65,14 @@ class ChunkIOProvider implements Runnable
try try
{ {
Object[] data = null; Object[] data = null;
try /*try
{ { TODO Chunk loading
data = this.loader.loadChunk__Async(chunkInfo.world, chunkInfo.x, chunkInfo.z); data = this.loader.loadChunk__Async(chunkInfo.world, chunkInfo.x, chunkInfo.z);
} }
catch (IOException e) catch (IOException e)
{ {
throw new RuntimeException(e); // Allow exception to bubble up to afterExecute throw new RuntimeException(e); // Allow exception to bubble up to afterExecute
} }*/
if (data != null) if (data != null)
{ {
@ -97,7 +97,7 @@ class ChunkIOProvider implements Runnable
return; return;
} }
// Load Entities /*/ Load Entities TODO Chunk loading
this.loader.loadEntities(this.chunkInfo.world, this.nbt.getCompoundTag("Level"), this.chunk); 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 MinecraftForge.EVENT_BUS.post(new ChunkDataEvent.Load(this.chunk, this.nbt)); // Don't call ChunkDataEvent.Load async
@ -108,7 +108,7 @@ class ChunkIOProvider implements Runnable
provider.id2ChunkMap.put(ChunkPos.asLong(this.chunkInfo.x, this.chunkInfo.z), this.chunk); provider.id2ChunkMap.put(ChunkPos.asLong(this.chunkInfo.x, this.chunkInfo.z), this.chunk);
this.chunk.onLoad(); this.chunk.onLoad();
this.chunk.populate(provider, provider.chunkGenerator); this.chunk.populate(provider, provider.chunkGenerator);
*/
this.runCallbacks(); this.runCallbacks();
} }

View file

@ -24,10 +24,13 @@ import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.crash.CrashReportCategory; import net.minecraft.crash.CrashReportCategory;
import net.minecraftforge.fml.common.FMLLog;
class ChunkIOThreadPoolExecutor extends ThreadPoolExecutor { 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) public ChunkIOThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory)
{ {
@ -41,14 +44,14 @@ class ChunkIOThreadPoolExecutor extends ThreadPoolExecutor {
{ {
try try
{ {
FMLLog.log.error("Unhandled exception loading chunk:", t); LOGGER.error("Unhandled exception loading chunk:", t);
QueuedChunk queuedChunk = ((ChunkIOProvider) r).getChunkInfo(); QueuedChunk queuedChunk = ((ChunkIOProvider) r).getChunkInfo();
FMLLog.log.error(queuedChunk); LOGGER.error(queuedChunk);
FMLLog.log.error(CrashReportCategory.getCoordinateInfo(queuedChunk.x << 4, 64, queuedChunk.z << 4)); LOGGER.error(CrashReportCategory.getCoordinateInfo(queuedChunk.x << 4, 64, queuedChunk.z << 4));
} }
catch (Throwable t2) catch (Throwable t2)
{ {
FMLLog.log.error(t2); LOGGER.error(t2);
} }
finally finally
{ {

View file

@ -57,7 +57,7 @@ class QueuedChunk {
result.append(" x: " + x + NEW_LINE); result.append(" x: " + x + NEW_LINE);
result.append(" z: " + z + NEW_LINE); result.append(" z: " + z + NEW_LINE);
result.append(" world: " + world.getWorldInfo().getWorldName() + NEW_LINE); result.append(" world: " + world.getWorldInfo().getWorldName() + NEW_LINE);
result.append(" dimension: " + world.provider.getDimension() + NEW_LINE); result.append(" dimension: " + world.provider.getId() + NEW_LINE);
result.append(" provider: " + world.provider.getClass().getName() + NEW_LINE); result.append(" provider: " + world.provider.getClass().getName() + NEW_LINE);
result.append("}"); result.append("}");

View file

@ -36,16 +36,19 @@ import com.google.common.collect.Sets;
import net.minecraftforge.common.config.Config.Comment; import net.minecraftforge.common.config.Config.Comment;
import net.minecraftforge.common.config.Config.LangKey; import net.minecraftforge.common.config.Config.LangKey;
import net.minecraftforge.common.config.Config.Name; import net.minecraftforge.common.config.Config.Name;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.FMLPaths; import net.minecraftforge.fml.common.FMLPaths;
import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.LoaderException; import net.minecraftforge.fml.common.LoaderException;
import net.minecraftforge.fml.loading.moddiscovery.ModAnnotation.EnumHolder; import net.minecraftforge.fml.loading.moddiscovery.ModAnnotation.EnumHolder;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ConfigManager public class ConfigManager
{ {
private static final Logger LOGGER = LogManager.getLogger();
private static Map<String, Multimap<Config.Type, ASMData>> asm_data = Maps.newHashMap(); private static Map<String, Multimap<Config.Type, ASMData>> asm_data = Maps.newHashMap();
static Map<Class<?>, ITypeAdapter> ADAPTERS = Maps.newHashMap(); static Map<Class<?>, ITypeAdapter> ADAPTERS = Maps.newHashMap();
static Map<Class<?>, Class<?>> ARRAY_REMAP = Maps.newHashMap(); static Map<Class<?>, Class<?>> ARRAY_REMAP = Maps.newHashMap();
@ -102,7 +105,7 @@ public class ConfigManager
public static void loadData(ASMDataTable data) public static void loadData(ASMDataTable data)
{ {
FMLLog.log.debug("Loading @Config anotation data"); LOGGER.debug("Loading @Config anotation data");
for (ASMData target : data.getAll(Config.class.getName())) for (ASMData target : data.getAll(Config.class.getName()))
{ {
String modid = (String)target.getAnnotationInfo().get("modid"); String modid = (String)target.getAnnotationInfo().get("modid");
@ -143,7 +146,7 @@ public class ConfigManager
*/ */
public static void sync(String modid, Config.Type type) public static void sync(String modid, Config.Type type)
{ {
FMLLog.log.debug("Attempting to inject @Config classes into {} for type {}", modid, type); LOGGER.debug("Attempting to inject @Config classes into {} for type {}", modid, type);
ClassLoader mcl = Loader.instance().getModClassLoader(); ClassLoader mcl = Loader.instance().getModClassLoader();
File configDir = FMLPaths.FMLCONFIG.get().toFile(); File configDir = FMLPaths.FMLCONFIG.get().toFile();
Multimap<Config.Type, ASMData> map = asm_data.get(modid); Multimap<Config.Type, ASMData> map = asm_data.get(modid);
@ -186,7 +189,7 @@ public class ConfigManager
} }
catch (Exception e) catch (Exception e)
{ {
FMLLog.log.error("An error occurred trying to load a config for {} into {}", targ.getClassName(), e); LOGGER.error("An error occurred trying to load a config for {} into {}", targ.getClassName(), e);
throw new LoaderException(e); throw new LoaderException(e);
} }
} }

View file

@ -55,10 +55,11 @@ import net.minecraftforge.fml.client.config.GuiConfig;
import net.minecraftforge.fml.client.config.GuiConfigEntries; import net.minecraftforge.fml.client.config.GuiConfigEntries;
import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry; import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry;
import net.minecraftforge.fml.client.config.IConfigElement; import net.minecraftforge.fml.client.config.IConfigElement;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.FMLPaths; import net.minecraftforge.fml.common.FMLPaths;
import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Loader;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/** /**
* This class offers advanced configurations capabilities, allowing to provide * This class offers advanced configurations capabilities, allowing to provide
@ -66,6 +67,8 @@ import org.apache.commons.io.IOUtils;
*/ */
public class Configuration public class Configuration
{ {
private static final Logger LOGGER = LogManager.getLogger();
public static final String CATEGORY_GENERAL = "general"; public static final String CATEGORY_GENERAL = "general";
public static final String CATEGORY_CLIENT = "client"; public static final String CATEGORY_CLIENT = "client";
public static final String ALLOWED_CHARS = "._-"; public static final String ALLOWED_CHARS = "._-";
@ -132,7 +135,7 @@ public class Configuration
{ {
File fileBak = new File(file.getAbsolutePath() + "_" + File fileBak = new File(file.getAbsolutePath() + "_" +
new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".errored"); new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".errored");
FMLLog.log.fatal("An exception occurred while loading config file {}. This file will be renamed to {} " + LOGGER.fatal("An exception occurred while loading config file {}. This file will be renamed to {} " +
"and a new config file will be generated.", file.getName(), fileBak.getName(), e); "and a new config file will be generated.", file.getName(), fileBak.getName(), e);
file.renameTo(fileBak); file.renameTo(fileBak);
@ -1047,7 +1050,7 @@ public class Configuration
} }
catch (IOException e) catch (IOException e)
{ {
FMLLog.log.error("Error while loading config {}.", fileName, e); LOGGER.error("Error while loading config {}.", fileName, e);
} }
finally finally
{ {
@ -1108,7 +1111,7 @@ public class Configuration
} }
catch (IOException e) catch (IOException e)
{ {
FMLLog.log.error("Error while saving config {}.", fileName, e); LOGGER.error("Error while saving config {}.", fileName, e);
} }
} }
@ -1719,7 +1722,7 @@ public class Configuration
} }
catch (Exception e) catch (Exception e)
{ {
FMLLog.log.error("Failed to get float for {}/{}", name, category, e); LOGGER.error("Failed to get float for {}/{}", name, category, e);
} }
return defaultValue; return defaultValue;
} }

View file

@ -26,6 +26,17 @@ public interface IForgeDimension
return null; return null;
} }
/**
* Sets the providers current dimension ID, used in default getSaveFolder()
* Added to allow default providers to be registered for multiple dimensions.
* This is to denote the exact dimension ID opposed to the 'type' in WorldType
*
* @param id Dimension ID
*/
void setId(int id);
int getId();
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
@Nullable @Nullable
IRenderHandler getSkyRenderer(); IRenderHandler getSkyRenderer();

View file

@ -52,9 +52,10 @@ public class CapabilityAnimation
public static class DefaultItemAnimationCapabilityProvider implements ICapabilityProvider public static class DefaultItemAnimationCapabilityProvider implements ICapabilityProvider
{ {
private final IAnimationStateMachine asm; @Nonnull
private final OptionalCapabilityInstance<IAnimationStateMachine> asm;
public DefaultItemAnimationCapabilityProvider(IAnimationStateMachine asm) public DefaultItemAnimationCapabilityProvider(@Nonnull OptionalCapabilityInstance<IAnimationStateMachine> asm)
{ {
this.asm = asm; this.asm = asm;
} }
@ -63,11 +64,7 @@ public class CapabilityAnimation
@Nonnull @Nonnull
public <T> OptionalCapabilityInstance<T> getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) public <T> OptionalCapabilityInstance<T> getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing)
{ {
if(capability == ANIMATION_CAPABILITY) return OptionalCapabilityInstance.orEmpty(capability, ANIMATION_CAPABILITY, asm);
{
return OptionalCapabilityInstance.of(() -> asm).cast();
}
return OptionalCapabilityInstance.empty();
} }
} }
} }

View file

@ -21,13 +21,18 @@ package net.minecraftforge.common.network;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.SimpleChannelInboundHandler;
import net.minecraft.world.DimensionType; import net.minecraft.world.dimension.DimensionType;
import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.network.ForgeMessage.DimensionRegisterMessage; import net.minecraftforge.common.network.ForgeMessage.DimensionRegisterMessage;
import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Level;
import net.minecraftforge.fml.common.FMLLog; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class DimensionMessageHandler extends SimpleChannelInboundHandler<ForgeMessage.DimensionRegisterMessage>{ public class DimensionMessageHandler extends SimpleChannelInboundHandler<ForgeMessage.DimensionRegisterMessage>{
private static final Logger LOGGER = LogManager.getLogger();
@Override @Override
protected void channelRead0(ChannelHandlerContext ctx, DimensionRegisterMessage msg) throws Exception protected void channelRead0(ChannelHandlerContext ctx, DimensionRegisterMessage msg) throws Exception
{ {
@ -39,7 +44,7 @@ public class DimensionMessageHandler extends SimpleChannelInboundHandler<ForgeMe
@Override @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
{ {
FMLLog.log.error("DimensionMessageHandler exception", cause); LOGGER.error("DimensionMessageHandler exception", cause);
super.exceptionCaught(ctx, cause); super.exceptionCaught(ctx, cause);
} }

View file

@ -22,12 +22,15 @@ package net.minecraftforge.common.network;
import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidRegistry;
import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraftforge.fml.common.FMLLog;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.SimpleChannelInboundHandler;
public class FluidIdRegistryMessageHandler extends SimpleChannelInboundHandler<ForgeMessage.FluidIdMapMessage> { public class FluidIdRegistryMessageHandler extends SimpleChannelInboundHandler<ForgeMessage.FluidIdMapMessage> {
private static final Logger LOGGER = LogManager.getLogger();
@Override @Override
protected void channelRead0(ChannelHandlerContext ctx, ForgeMessage.FluidIdMapMessage msg) throws Exception protected void channelRead0(ChannelHandlerContext ctx, ForgeMessage.FluidIdMapMessage msg) throws Exception
{ {
@ -36,7 +39,7 @@ public class FluidIdRegistryMessageHandler extends SimpleChannelInboundHandler<F
@Override @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
{ {
FMLLog.log.error("FluidIdRegistryMessageHandler exception", cause); LOGGER.error("FluidIdRegistryMessageHandler exception", cause);
super.exceptionCaught(ctx, cause); super.exceptionCaught(ctx, cause);
} }

View file

@ -23,6 +23,9 @@ import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidRegistry;
@ -30,11 +33,12 @@ import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap; import com.google.common.collect.HashBiMap;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.network.ByteBufUtils; import net.minecraftforge.fml.common.network.ByteBufUtils;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
public abstract class ForgeMessage { public abstract class ForgeMessage {
private static final Logger LOGGER = LogManager.getLogger();
public static class DimensionRegisterMessage extends ForgeMessage { public static class DimensionRegisterMessage extends ForgeMessage {
/** The dimension ID to register on client */ /** The dimension ID to register on client */
int dimensionId; int dimensionId;
@ -108,7 +112,7 @@ public abstract class ForgeMessage {
} }
else else
{ {
FMLLog.log.info("Legacy server message contains no default fluid list - there may be problems with fluids"); LOGGER.info("Legacy server message contains no default fluid list - there may be problems with fluids");
defaultFluids.clear(); defaultFluids.clear();
} }
} }

View file

@ -21,25 +21,32 @@ package net.minecraftforge.common.property;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableTable; import com.google.common.collect.ImmutableTable;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.state.AbstractStateHolder;
import net.minecraft.state.IProperty;
import net.minecraft.state.StateContainer;
public class ExtendedBlockState extends BlockStateContainer public class ExtendedBlockState extends StateContainer<Block, IBlockState>
{ {
private final ImmutableSet<IUnlistedProperty<?>> unlistedProperties; private final ImmutableSet<IUnlistedProperty<?>> unlistedProperties;
public ExtendedBlockState(Block blockIn, IProperty<?>[] properties, IUnlistedProperty<?>[] unlistedProperties) public <A extends AbstractStateHolder<Block, IBlockState>> ExtendedBlockState(Block blockIn, StateContainer.IFactory<Block, IBlockState, ?> stateFactory, net.minecraft.state.IProperty<?>[] properties, IUnlistedProperty<?>[] unlistedProperties)
{ {
super(blockIn, properties, buildUnlistedMap(unlistedProperties)); super(blockIn, stateFactory, buildListedMap(properties));// TODO Unlisted properties?, buildUnlistedMap(unlistedProperties));
ImmutableSet.Builder<IUnlistedProperty<?>> builder = ImmutableSet.builder(); ImmutableSet.Builder<IUnlistedProperty<?>> builder = ImmutableSet.builder();
for(IUnlistedProperty<?> property : unlistedProperties) for(IUnlistedProperty<?> property : unlistedProperties)
{ {
@ -53,6 +60,11 @@ public class ExtendedBlockState extends BlockStateContainer
return unlistedProperties; return unlistedProperties;
} }
private static Map<String, IProperty<?>> buildListedMap(IProperty<?>[] properties)
{
return Arrays.stream(properties).collect(Collectors.toMap(IProperty::getName, Function.identity()));
}
private static ImmutableMap<IUnlistedProperty<?>, Optional<?>> buildUnlistedMap(IUnlistedProperty<?>[] unlistedProperties) private static ImmutableMap<IUnlistedProperty<?>, Optional<?>> buildUnlistedMap(IUnlistedProperty<?>[] unlistedProperties)
{ {
ImmutableMap.Builder<IUnlistedProperty<?>, Optional<?>> builder = ImmutableMap.builder(); ImmutableMap.Builder<IUnlistedProperty<?>, Optional<?>> builder = ImmutableMap.builder();

View file

@ -21,6 +21,9 @@ package net.minecraftforge.fluids;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.awt.Color; import java.awt.Color;
import java.util.Locale; import java.util.Locale;
import net.minecraft.block.Block; import net.minecraft.block.Block;
@ -34,8 +37,6 @@ import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.translation.I18n; import net.minecraft.util.text.translation.I18n;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.world.WorldProvider;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraft.item.EnumRarity; import net.minecraft.item.EnumRarity;
/** /**
@ -56,6 +57,8 @@ import net.minecraft.item.EnumRarity;
*/ */
public class Fluid public class Fluid
{ {
private static final Logger LOGGER = LogManager.getLogger();
public static final int BUCKET_VOLUME = 1000; public static final int BUCKET_VOLUME = 1000;
/** The unique identification name for this fluid. */ /** The unique identification name for this fluid. */
@ -189,7 +192,7 @@ public class Fluid
} }
else else
{ {
FMLLog.log.warn("A mod has attempted to assign Block {} to the Fluid '{}' but this Fluid has already been linked to the Block {}. " LOGGER.warn("A mod has attempted to assign Block {} to the Fluid '{}' but this Fluid has already been linked to the Block {}. "
+ "You may have duplicate Fluid Blocks as a result. It *may* be possible to configure your mods to avoid this.", block, fluidName, this.block); + "You may have duplicate Fluid Blocks as a result. It *may* be possible to configure your mods to avoid this.", block, fluidName, this.block);
} }
return this; return this;

View file

@ -22,7 +22,6 @@ package net.minecraftforge.fluids;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.util.Constants; import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.registries.IRegistryDelegate; import net.minecraftforge.registries.IRegistryDelegate;
import javax.annotation.Nullable; import javax.annotation.Nullable;

View file

@ -40,8 +40,9 @@ public class ItemFluidContainer extends Item
/** /**
* @param capacity The maximum capacity of this fluid container. * @param capacity The maximum capacity of this fluid container.
*/ */
public ItemFluidContainer(int capacity) public ItemFluidContainer(Item.Builder builder, int capacity)
{ {
super(builder);
this.capacity = capacity; this.capacity = capacity;
} }

View file

@ -21,8 +21,10 @@ package net.minecraftforge.fluids.capability;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityType;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.OptionalCapabilityInstance;
import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidTank; import net.minecraftforge.fluids.FluidTank;
@ -33,6 +35,13 @@ public class TileFluidHandler extends TileEntity
{ {
protected FluidTank tank = new FluidTank(Fluid.BUCKET_VOLUME); protected FluidTank tank = new FluidTank(Fluid.BUCKET_VOLUME);
private final OptionalCapabilityInstance<IFluidHandler> holder = OptionalCapabilityInstance.of(() -> tank);
public TileFluidHandler(@Nonnull TileEntityType<?> p_i48289_1_)
{
super(p_i48289_1_);
}
@Override @Override
public void readFromNBT(NBTTagCompound tag) public void readFromNBT(NBTTagCompound tag)
{ {
@ -49,18 +58,11 @@ public class TileFluidHandler extends TileEntity
} }
@Override @Override
public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) @Nonnull
{ public <T> OptionalCapabilityInstance<T> getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing)
return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || super.hasCapability(capability, facing);
}
@SuppressWarnings("unchecked")
@Override
@Nullable
public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing)
{ {
if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY)
return (T) tank; return holder.cast();
return super.getCapability(capability, facing); return super.getCapability(capability, facing);
} }
} }

View file

@ -27,6 +27,7 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.capabilities.OptionalCapabilityInstance;
import net.minecraftforge.fluids.*; import net.minecraftforge.fluids.*;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.FluidTankProperties; import net.minecraftforge.fluids.capability.FluidTankProperties;
@ -46,6 +47,8 @@ public class FluidHandlerItemStack implements IFluidHandlerItem, ICapabilityProv
{ {
public static final String FLUID_NBT_KEY = "Fluid"; public static final String FLUID_NBT_KEY = "Fluid";
private final OptionalCapabilityInstance<IFluidHandlerItem> holder = OptionalCapabilityInstance.of(() -> this);
@Nonnull @Nonnull
protected ItemStack container; protected ItemStack container;
protected int capacity; protected int capacity;
@ -201,17 +204,10 @@ public class FluidHandlerItemStack implements IFluidHandlerItem, ICapabilityProv
} }
@Override @Override
public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) @Nonnull
public <T> OptionalCapabilityInstance<T> getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing)
{ {
return capability == CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY; return OptionalCapabilityInstance.orEmpty(capability, CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, holder);
}
@SuppressWarnings("unchecked")
@Override
@Nullable
public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing)
{
return capability == CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY ? (T) this : null;
} }
/** /**

View file

@ -27,6 +27,7 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.capabilities.OptionalCapabilityInstance;
import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.FluidTankProperties; import net.minecraftforge.fluids.capability.FluidTankProperties;
import net.minecraftforge.fluids.capability.IFluidHandlerItem; import net.minecraftforge.fluids.capability.IFluidHandlerItem;
@ -43,6 +44,8 @@ public class FluidHandlerItemStackSimple implements IFluidHandlerItem, ICapabili
{ {
public static final String FLUID_NBT_KEY = "Fluid"; public static final String FLUID_NBT_KEY = "Fluid";
private final OptionalCapabilityInstance<IFluidHandlerItem> holder = OptionalCapabilityInstance.of(() -> this);
@Nonnull @Nonnull
protected ItemStack container; protected ItemStack container;
protected int capacity; protected int capacity;
@ -178,17 +181,10 @@ public class FluidHandlerItemStackSimple implements IFluidHandlerItem, ICapabili
} }
@Override @Override
public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) @Nonnull
public <T> OptionalCapabilityInstance<T> getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing)
{ {
return capability == CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY; return OptionalCapabilityInstance.orEmpty(capability, CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, holder);
}
@SuppressWarnings("unchecked")
@Override
@Nullable
public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing)
{
return capability == CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY ? (T) this : null;
} }
/** /**

View file

@ -1,4 +1,4 @@
/* /* TODO Fluids
* Minecraft Forge * Minecraft Forge
* Copyright (c) 2016-2018. * Copyright (c) 2016-2018.
* *
@ -18,7 +18,7 @@
*/ */
package net.minecraftforge.fluids.capability.wrappers; package net.minecraftforge.fluids.capability.wrappers;
/*
import javax.annotation.Nullable; import javax.annotation.Nullable;
import net.minecraft.block.BlockLiquid; import net.minecraft.block.BlockLiquid;
@ -155,3 +155,4 @@ public class BlockLiquidWrapper implements IFluidHandler
} }
} }
} }
*/

View file

@ -30,6 +30,7 @@ import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.ForgeMod; import net.minecraftforge.common.ForgeMod;
import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.capabilities.OptionalCapabilityInstance;
import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidStack;
@ -45,6 +46,8 @@ import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
*/ */
public class FluidBucketWrapper implements IFluidHandlerItem, ICapabilityProvider public class FluidBucketWrapper implements IFluidHandlerItem, ICapabilityProvider
{ {
private final OptionalCapabilityInstance<IFluidHandlerItem> holder = OptionalCapabilityInstance.of(() -> this);
@Nonnull @Nonnull
protected ItemStack container; protected ItemStack container;
@ -178,19 +181,9 @@ public class FluidBucketWrapper implements IFluidHandlerItem, ICapabilityProvide
} }
@Override @Override
public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) @Nonnull
public <T> OptionalCapabilityInstance<T> getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing)
{ {
return capability == CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY; return OptionalCapabilityInstance.orEmpty(capability, CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, holder);
}
@Override
@Nullable
public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing)
{
if (capability == CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY)
{
return CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY.cast(this);
}
return null;
} }
} }

View file

@ -20,11 +20,11 @@
package net.minecraftforge.fml.client; package net.minecraftforge.fml.client;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.api.distmarker.OnlyIn;
public interface IDisplayableError public interface IDisplayableError
{ {
@SideOnly(Side.CLIENT) @OnlyIn(Dist.CLIENT)
GuiScreen createGui(); GuiScreen createGui();
} }

View file

@ -203,7 +203,7 @@ public class SplashProgress
} }
catch(IOException e) catch(IOException e)
{ {
FMLLog.log.error("Could not save the splash.properties file", e); LOGGER.error("Could not save the splash.properties file", e);
} }
miscPack = createResourcePack(miscPackFile); miscPack = createResourcePack(miscPackFile);
@ -240,7 +240,7 @@ public class SplashProgress
} }
catch (LWJGLException e) catch (LWJGLException e)
{ {
FMLLog.log.error("Error starting SplashProgress:", e); LOGGER.error("Error starting SplashProgress:", e);
disableSplash(e); disableSplash(e);
} }
@ -537,7 +537,7 @@ public class SplashProgress
} }
catch (LWJGLException e) catch (LWJGLException e)
{ {
FMLLog.log.error("Error setting GL context:", e); LOGGER.error("Error setting GL context:", e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
glClearColor((float)((backgroundColor >> 16) & 0xFF) / 0xFF, (float)((backgroundColor >> 8) & 0xFF) / 0xFF, (float)(backgroundColor & 0xFF) / 0xFF, 1); glClearColor((float)((backgroundColor >> 16) & 0xFF) / 0xFF, (float)((backgroundColor >> 8) & 0xFF) / 0xFF, (float)(backgroundColor & 0xFF) / 0xFF, 1);
@ -564,7 +564,7 @@ public class SplashProgress
} }
catch (LWJGLException e) catch (LWJGLException e)
{ {
FMLLog.log.error("Error releasing GL context:", e); LOGGER.error("Error releasing GL context:", e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
finally finally
@ -578,7 +578,7 @@ public class SplashProgress
@Override @Override
public void uncaughtException(Thread t, Throwable e) public void uncaughtException(Thread t, Throwable e)
{ {
FMLLog.log.error("Splash thread Exception", e); LOGGER.error("Splash thread Exception", e);
threadError = e; threadError = e;
} }
}); });
@ -629,7 +629,7 @@ public class SplashProgress
} }
catch (LWJGLException e) catch (LWJGLException e)
{ {
FMLLog.log.error("Error setting GL context:", e); LOGGER.error("Error setting GL context:", e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -650,7 +650,7 @@ public class SplashProgress
} }
catch (LWJGLException e) catch (LWJGLException e)
{ {
FMLLog.log.error("Error releasing GL context:", e); LOGGER.error("Error releasing GL context:", e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
lock.unlock(); lock.unlock();
@ -673,7 +673,7 @@ public class SplashProgress
} }
catch (Exception e) catch (Exception e)
{ {
FMLLog.log.error("Error finishing SplashProgress:", e); LOGGER.error("Error finishing SplashProgress:", e);
disableSplash(e); disableSplash(e);
} }
} }
@ -726,7 +726,7 @@ public class SplashProgress
} }
catch(IOException e) catch(IOException e)
{ {
FMLLog.log.error("Could not save the splash.properties file", e); LOGGER.error("Could not save the splash.properties file", e);
return false; return false;
} }
return true; return true;
@ -843,7 +843,7 @@ public class SplashProgress
} }
catch(IOException e) catch(IOException e)
{ {
FMLLog.log.error("Error reading texture from file: {}", location, e); LOGGER.error("Error reading texture from file: {}", location, e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
finally finally

View file

@ -38,10 +38,11 @@ import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry;
import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent;
import net.minecraftforge.fml.client.event.ConfigChangedEvent.PostConfigChangedEvent; import net.minecraftforge.fml.client.event.ConfigChangedEvent.PostConfigChangedEvent;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.eventbus.api.Event.Result; import net.minecraftforge.eventbus.api.Event.Result;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.input.Keyboard; import org.lwjgl.input.Keyboard;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -54,6 +55,8 @@ import javax.annotation.Nullable;
*/ */
public class GuiConfig extends GuiScreen public class GuiConfig extends GuiScreen
{ {
private static final Logger LOGGER = LogManager.getLogger();
/** /**
* A reference to the screen object that created this. Used for navigating between screens. * A reference to the screen object that created this. Used for navigating between screens.
*/ */
@ -289,7 +292,7 @@ public class GuiConfig extends GuiScreen
} }
catch (Throwable e) catch (Throwable e)
{ {
FMLLog.log.error("Error performing GuiConfig action:", e); LOGGER.error("Error performing GuiConfig action:", e);
} }
if (flag) if (flag)

View file

@ -36,9 +36,11 @@ import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.I18n;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo; import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.input.Keyboard; import org.lwjgl.input.Keyboard;
/** /**
@ -49,6 +51,8 @@ import org.lwjgl.input.Keyboard;
*/ */
public class GuiConfigEntries extends GuiListExtended public class GuiConfigEntries extends GuiListExtended
{ {
private static final Logger LOGGER = LogManager.getLogger();
public final GuiConfig owningScreen; public final GuiConfig owningScreen;
public final Minecraft mc; public final Minecraft mc;
public List<IConfigEntry> listEntries; public List<IConfigEntry> listEntries;
@ -129,7 +133,7 @@ public class GuiConfigEntries extends GuiListExtended
} }
catch (Throwable e) catch (Throwable e)
{ {
FMLLog.log.error("There was a critical error instantiating the custom IConfigEntry for config element {}.", configElement.getName(), e); LOGGER.error("There was a critical error instantiating the custom IConfigEntry for config element {}.", configElement.getName(), e);
} }
else if (configElement.isProperty()) else if (configElement.isProperty())
{ {

View file

@ -33,7 +33,8 @@ import net.minecraft.util.text.TextFormatting;
import static net.minecraftforge.fml.client.config.GuiUtils.RESET_CHAR; import static net.minecraftforge.fml.client.config.GuiUtils.RESET_CHAR;
import static net.minecraftforge.fml.client.config.GuiUtils.UNDO_CHAR; import static net.minecraftforge.fml.client.config.GuiUtils.UNDO_CHAR;
import net.minecraftforge.fml.common.FMLLog; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.input.Keyboard; import org.lwjgl.input.Keyboard;
/** /**
@ -44,6 +45,8 @@ import org.lwjgl.input.Keyboard;
*/ */
public class GuiEditArray extends GuiScreen public class GuiEditArray extends GuiScreen
{ {
private static final Logger LOGGER = LogManager.getLogger();
protected GuiScreen parentScreen; protected GuiScreen parentScreen;
protected IConfigElement configElement; protected IConfigElement configElement;
protected GuiEditArrayEntries entryList; protected GuiEditArrayEntries entryList;
@ -129,7 +132,7 @@ public class GuiEditArray extends GuiScreen
} }
catch (Throwable e) catch (Throwable e)
{ {
FMLLog.log.error("Error performing GuiEditArray action:", e); LOGGER.error("Error performing GuiEditArray action:", e);
} }
this.mc.displayGuiScreen(this.parentScreen); this.mc.displayGuiScreen(this.parentScreen);
} }

View file

@ -29,8 +29,9 @@ import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.I18n;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.client.config.GuiConfigEntries.ArrayEntry; import net.minecraftforge.fml.client.config.GuiConfigEntries.ArrayEntry;
import net.minecraftforge.fml.common.FMLLog;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.input.Keyboard; import org.lwjgl.input.Keyboard;
import static net.minecraftforge.fml.client.config.GuiUtils.INVALID; import static net.minecraftforge.fml.client.config.GuiUtils.INVALID;
@ -42,6 +43,8 @@ import static net.minecraftforge.fml.client.config.GuiUtils.VALID;
*/ */
public class GuiEditArrayEntries extends GuiListExtended public class GuiEditArrayEntries extends GuiListExtended
{ {
private static final Logger LOGGER = LogManager.getLogger();
protected GuiEditArray owningGui; protected GuiEditArray owningGui;
public IConfigElement configElement; public IConfigElement configElement;
public List<IArrayEntry> listEntries; public List<IArrayEntry> listEntries;
@ -80,7 +83,7 @@ public class GuiEditArrayEntries extends GuiListExtended
} }
catch (Throwable e) catch (Throwable e)
{ {
FMLLog.log.error("There was a critical error instantiating the custom IGuiEditListEntry for property {}.", configElement.getName(), e); LOGGER.error("There was a critical error instantiating the custom IGuiEditListEntry for property {}.", configElement.getName(), e);
} }
} }
} }
@ -155,7 +158,7 @@ public class GuiEditArrayEntries extends GuiListExtended
} }
catch (Throwable e) catch (Throwable e)
{ {
FMLLog.log.error("There was a critical error instantiating the custom IGuiEditListEntry for property {}.", configElement.getName(), e); LOGGER.error("There was a critical error instantiating the custom IGuiEditListEntry for property {}.", configElement.getName(), e);
} }
} }
else if (configElement.isList() && configElement.getType() == ConfigGuiType.BOOLEAN) else if (configElement.isList() && configElement.getType() == ConfigGuiType.BOOLEAN)
@ -559,7 +562,7 @@ public class GuiEditArrayEntries extends GuiListExtended
} }
} }
public static class BaseEntry implements IArrayEntry public static class BaseEntry extends GuiListExtended.IGuiListEntry implements IArrayEntry
{ {
protected final GuiEditArray owningScreen; protected final GuiEditArray owningScreen;
protected final GuiEditArrayEntries owningEntryList; protected final GuiEditArrayEntries owningEntryList;
@ -592,31 +595,31 @@ public class GuiEditArrayEntries extends GuiListExtended
} }
@Override @Override
public void drawEntry(int slotIndex, int x, int y, int listWidth, int slotHeight, int mouseX, int mouseY, boolean isSelected, float partial) public void func_194999_a(int entryWidth, int entryHeight, int mouseX, int mouseY, boolean isHovered, float partial)
{ {
if (this.getValue() != null && this.isValidated) if (this.getValue() != null && this.isValidated)
owningEntryList.getMC().fontRenderer.drawString( owningEntryList.getMC().fontRenderer.func_211126_b(
isValidValue ? TextFormatting.GREEN + VALID : TextFormatting.RED + INVALID, isValidValue ? TextFormatting.GREEN + VALID : TextFormatting.RED + INVALID,
listWidth / 4 - owningEntryList.getMC().fontRenderer.getStringWidth(VALID) - 2, entryWidth / 4 - owningEntryList.getMC().fontRenderer.getStringWidth(VALID) - 2,
y + slotHeight / 2 - owningEntryList.getMC().fontRenderer.FONT_HEIGHT / 2, entryHeight / 2 - owningEntryList.getMC().fontRenderer.FONT_HEIGHT / 2,
16777215); 16777215);
int half = listWidth / 2; int half = entryWidth / 2;
if (owningEntryList.canAddMoreEntries) if (owningEntryList.canAddMoreEntries)
{ {
this.btnAddNewEntryAbove.visible = true; this.btnAddNewEntryAbove.visible = true;
this.btnAddNewEntryAbove.x = half + ((half / 2) - 44); this.btnAddNewEntryAbove.x = half + ((half / 2) - 44);
this.btnAddNewEntryAbove.y = y; this.btnAddNewEntryAbove.y = this.func_195001_c();
this.btnAddNewEntryAbove.drawButton(owningEntryList.getMC(), mouseX, mouseY, partial); this.btnAddNewEntryAbove.drawButton(owningEntryList.getMC(), mouseX, mouseY, partial);
} }
else else
this.btnAddNewEntryAbove.visible = false; this.btnAddNewEntryAbove.visible = false;
if (!configElement.isListLengthFixed() && slotIndex != owningEntryList.listEntries.size() - 1) if (!configElement.isListLengthFixed() && this.field_195005_b != owningEntryList.listEntries.size() - 1)
{ {
this.btnRemoveEntry.visible = true; this.btnRemoveEntry.visible = true;
this.btnRemoveEntry.x = half + ((half / 2) - 22); this.btnRemoveEntry.x = half + ((half / 2) - 22);
this.btnRemoveEntry.y = y; this.btnRemoveEntry.y = this.func_195001_c();
this.btnRemoveEntry.drawButton(owningEntryList.getMC(), mouseX, mouseY, partial); this.btnRemoveEntry.drawButton(owningEntryList.getMC(), mouseX, mouseY, partial);
} }
else else
@ -689,7 +692,7 @@ public class GuiEditArrayEntries extends GuiListExtended
public void updatePosition(int p_178011_1_, int p_178011_2_, int p_178011_3_, float partial){} public void updatePosition(int p_178011_1_, int p_178011_2_, int p_178011_3_, float partial){}
} }
public static interface IArrayEntry extends GuiListExtended.IGuiListEntry public static interface IArrayEntry
{ {
void keyTyped(char eventChar, int eventKey); void keyTyped(char eventChar, int eventKey);

View file

@ -25,12 +25,14 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.I18n;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.common.FMLLog;
import static net.minecraftforge.fml.client.config.GuiUtils.RESET_CHAR; import static net.minecraftforge.fml.client.config.GuiUtils.RESET_CHAR;
import static net.minecraftforge.fml.client.config.GuiUtils.UNDO_CHAR; import static net.minecraftforge.fml.client.config.GuiUtils.UNDO_CHAR;
@ -42,6 +44,8 @@ import static net.minecraftforge.fml.client.config.GuiUtils.UNDO_CHAR;
*/ */
public class GuiSelectString extends GuiScreen public class GuiSelectString extends GuiScreen
{ {
private static final Logger LOGGER = LogManager.getLogger();
protected GuiScreen parentScreen; protected GuiScreen parentScreen;
protected IConfigElement configElement; protected IConfigElement configElement;
protected GuiSelectStringEntries entryList; protected GuiSelectStringEntries entryList;
@ -129,7 +133,7 @@ public class GuiSelectString extends GuiScreen
} }
catch (Throwable e) catch (Throwable e)
{ {
FMLLog.log.error("Error performing GuiSelectString action:", e); LOGGER.error("Error performing GuiSelectString action:", e);
} }
this.mc.displayGuiScreen(this.parentScreen); this.mc.displayGuiScreen(this.parentScreen);
} }

View file

@ -21,7 +21,9 @@ package net.minecraftforge.fml.client.gui;
import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiErrorScreen; import net.minecraft.client.gui.GuiErrorScreen;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.client.IDisplayableError;
import net.minecraftforge.fml.common.EnhancedRuntimeException; import net.minecraftforge.fml.common.EnhancedRuntimeException;
import net.minecraftforge.fml.common.IFMLHandledException; import net.minecraftforge.fml.common.IFMLHandledException;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;

View file

@ -22,17 +22,21 @@ package net.minecraftforge.fml.client.gui;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiYesNo; import net.minecraft.client.gui.GuiYesNo;
import net.minecraft.client.gui.GuiYesNoCallback; import net.minecraft.client.gui.GuiYesNoCallback;
import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.StartupQuery; import net.minecraftforge.fml.StartupQuery;
import net.minecraftforge.fml.common.ZipperUtil; import net.minecraftforge.fml.common.ZipperUtil;
public class GuiOldSaveLoadConfirm extends GuiYesNo implements GuiYesNoCallback { public class GuiOldSaveLoadConfirm extends GuiYesNo implements GuiYesNoCallback {
private static final Logger LOGGER = LogManager.getLogger();
private String dirName; private String dirName;
private String saveName; private String saveName;
private File zip; private File zip;
@ -75,7 +79,7 @@ public class GuiOldSaveLoadConfirm extends GuiYesNo implements GuiYesNoCallback
} }
else else
{ {
FMLLog.log.info("Capturing current state of world {} into file {}", saveName, zip.getAbsolutePath()); LOGGER.info("Capturing current state of world {} into file {}", saveName, zip.getAbsolutePath());
try try
{ {
String skip = System.getProperty("fml.doNotBackup"); String skip = System.getProperty("fml.doNotBackup");
@ -86,11 +90,11 @@ public class GuiOldSaveLoadConfirm extends GuiYesNo implements GuiYesNoCallback
else else
{ {
for (int x = 0; x < 10; x++) for (int x = 0; x < 10; x++)
FMLLog.log.fatal("!!!!!!!!!! UPDATING WORLD WITHOUT DOING BACKUP !!!!!!!!!!!!!!!!"); LOGGER.fatal("!!!!!!!!!! UPDATING WORLD WITHOUT DOING BACKUP !!!!!!!!!!!!!!!!");
} }
} catch (IOException e) } catch (IOException e)
{ {
FMLLog.log.warn("There was a problem saving the backup {}. Please fix and try again", zip.getName(), e); LOGGER.warn("There was a problem saving the backup {}. Please fix and try again", zip.getName(), e);
FMLClientHandler.instance().showGuiScreen(new GuiBackupFailed(parent, zip)); FMLClientHandler.instance().showGuiScreen(new GuiBackupFailed(parent, zip));
return; return;
} }

View file

@ -52,10 +52,10 @@ public class GuiSortingProblem extends GuiScreen {
this.drawCenteredString(this.fontRenderer, "The remainder of the cycle involves these mods", this.width / 2, offset, 0xFFFFFF); this.drawCenteredString(this.fontRenderer, "The remainder of the cycle involves these mods", this.width / 2, offset, 0xFFFFFF);
offset+=5; offset+=5;
for (ModContainer mc : failedList.getVisitedNodes()) for (ModContainer mc : failedList.getVisitedNodes())
{ {/* TODO Mod dependencies
offset+=10; offset+=10;
this.drawCenteredString(this.fontRenderer, String.format("%s : before: %s, after: %s", mc.toString(), mc.getDependants(), mc.getDependencies()), this.width / 2, offset, 0xEEEEEE); this.drawCenteredString(this.fontRenderer, String.format("%s : before: %s, after: %s", mc.toString(), mc.getDependants(), mc.getDependencies()), this.width / 2, offset, 0xEEEEEE);
} */}
offset+=20; offset+=20;
this.drawCenteredString(this.fontRenderer, "The file 'ForgeModLoader-client-0.log' contains more information", this.width / 2, offset, 0xFFFFFF); this.drawCenteredString(this.fontRenderer, "The file 'ForgeModLoader-client-0.log' contains more information", this.width / 2, offset, 0xFFFFFF);
} }

View file

@ -44,13 +44,13 @@ public class ClientRegistry
* @param tileEntityClass * @param tileEntityClass
* @param id * @param id
* @param specialRenderer * @param specialRenderer
*/ * / TODO GameRegistry
public static <T extends TileEntity> void registerTileEntity(Class<T> tileEntityClass, String id, TileEntityRenderer<? super T> specialRenderer) public static <T extends TileEntity> void registerTileEntity(Class<T> tileEntityClass, String id, TileEntityRenderer<? super T> specialRenderer)
{ {
GameRegistry.registerTileEntity(tileEntityClass, id); GameRegistry.registerTileEntity(tileEntityClass, id);
bindTileEntitySpecialRenderer(tileEntityClass, specialRenderer); bindTileEntitySpecialRenderer(tileEntityClass, specialRenderer);
} }
*/
public static <T extends TileEntity> void bindTileEntitySpecialRenderer(Class<T> tileEntityClass, TileEntityRenderer<? super T> specialRenderer) public static <T extends TileEntity> void bindTileEntitySpecialRenderer(Class<T> tileEntityClass, TileEntityRenderer<? super T> specialRenderer)
{ {
TileEntityRendererDispatcher.instance.renderers.put(tileEntityClass, specialRenderer); TileEntityRendererDispatcher.instance.renderers.put(tileEntityClass, specialRenderer);

View file

@ -18,7 +18,7 @@
*/ */
package net.minecraftforge.fml.common; package net.minecraftforge.fml.common;
/* TODO ReflectionHelper
import java.util.Arrays; import java.util.Arrays;
import net.minecraftforge.fml.common.asm.deobf.FMLDeobfuscatingRemapper; import net.minecraftforge.fml.common.asm.deobf.FMLDeobfuscatingRemapper;
@ -42,7 +42,7 @@ public class ObfuscationReflectionHelper
} }
catch (UnableToAccessFieldException e) catch (UnableToAccessFieldException e)
{ {
FMLLog.log.error("There was a problem getting field index {} from {}", classToAccess.getName(), e); LOGGER.error("There was a problem getting field index {} from {}", classToAccess.getName(), e);
throw e; throw e;
} }
} }
@ -67,12 +67,12 @@ public class ObfuscationReflectionHelper
} }
catch (UnableToFindFieldException e) catch (UnableToFindFieldException e)
{ {
FMLLog.log.error("Unable to locate any field {} on type {}", Arrays.toString(fieldNames), classToAccess.getName(), e); LOGGER.error("Unable to locate any field {} on type {}", Arrays.toString(fieldNames), classToAccess.getName(), e);
throw e; throw e;
} }
catch (UnableToAccessFieldException e) catch (UnableToAccessFieldException e)
{ {
FMLLog.log.error("Unable to access any field {} on type {}", classToAccess.getName(), e); LOGGER.error("Unable to access any field {} on type {}", classToAccess.getName(), e);
throw e; throw e;
} }
} }
@ -85,7 +85,7 @@ public class ObfuscationReflectionHelper
} }
catch (UnableToAccessFieldException e) catch (UnableToAccessFieldException e)
{ {
FMLLog.log.error("There was a problem setting field index {} on type {}", classToAccess.getName(), e); LOGGER.error("There was a problem setting field index {} on type {}", classToAccess.getName(), e);
throw e; throw e;
} }
} }
@ -98,13 +98,14 @@ public class ObfuscationReflectionHelper
} }
catch (UnableToFindFieldException e) catch (UnableToFindFieldException e)
{ {
FMLLog.log.error("Unable to locate any field {} on type {}", classToAccess.getName(), e); LOGGER.error("Unable to locate any field {} on type {}", classToAccess.getName(), e);
throw e; throw e;
} }
catch (UnableToAccessFieldException e) catch (UnableToAccessFieldException e)
{ {
FMLLog.log.error("Unable to set any field {} on type {}", classToAccess.getName(), e); LOGGER.error("Unable to set any field {} on type {}", classToAccess.getName(), e);
throw e; throw e;
} }
} }
} }
*/

View file

@ -18,7 +18,7 @@
*/ */
package net.minecraftforge.fml.common.asm.transformers; package net.minecraftforge.fml.common.asm.transformers;
/* TODO Class transformers
import java.util.Iterator; import java.util.Iterator;
import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassReader;
@ -167,3 +167,4 @@ public class SoundEngineFixTransformer implements IClassTransformer
} }
} }
*/

View file

@ -31,6 +31,7 @@ import net.minecraftforge.registries.ForgeRegistryEntry;
import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.Validate;
import net.minecraft.entity.passive.EntityVillager; import net.minecraft.entity.passive.EntityVillager;
import net.minecraft.entity.passive.EntityVillager.ITradeList;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.RegistryNamespaced; import net.minecraft.util.registry.RegistryNamespaced;
@ -43,18 +44,17 @@ import javax.annotation.Nullable;
*/ */
public class VillagerRegistry public class VillagerRegistry
{ {
/*
public static final RegistryObject<VillagerProfession> FARMER = RegistryObject.of("minecraft:farmer", ()->VillagerProfession.class); public static final RegistryObject<VillagerProfession> FARMER = RegistryObject.of("minecraft:farmer", ()->VillagerProfession.class);
private static final VillagerRegistry INSTANCE = new VillagerRegistry(); private static final VillagerRegistry INSTANCE = new VillagerRegistry();
/* TODO village creation
private Map<Class<?>, IVillageCreationHandler> villageCreationHandlers = Maps.newHashMap(); private Map<Class<?>, IVillageCreationHandler> villageCreationHandlers = Maps.newHashMap();
*/
private VillagerRegistry() private VillagerRegistry()
{ {
init(); init();
} }
*/
/** /**
* Allow access to the {@link net.minecraft.world.gen.structure.StructureVillagePieces} array controlling new village * Allow access to the {@link net.minecraft.world.gen.structure.StructureVillagePieces} array controlling new village
* creation so you can insert your own new village pieces * creation so you can insert your own new village pieces
@ -100,13 +100,12 @@ public class VillagerRegistry
Village buildComponent(StructureVillagePieces.PieceWeight villagePiece, StructureVillagePieces.Start startPiece, List<StructureComponent> pieces, Random random, int p1, Village buildComponent(StructureVillagePieces.PieceWeight villagePiece, StructureVillagePieces.Start startPiece, List<StructureComponent> pieces, Random random, int p1,
int p2, int p3, EnumFacing facing, int p5); int p2, int p3, EnumFacing facing, int p5);
} }
*/
public static VillagerRegistry instance() public static VillagerRegistry instance()
{ {
return INSTANCE; return INSTANCE;
} }
*/
/** /**
* Register a new village creation handler * Register a new village creation handler
* *
@ -132,7 +131,7 @@ public class VillagerRegistry
{ {
return instance().villageCreationHandlers.get(villagePiece.villagePieceClass).buildComponent(villagePiece, startPiece, pieces, random, p1, p2, p3, facing, p5); return instance().villageCreationHandlers.get(villagePiece.villagePieceClass).buildComponent(villagePiece, startPiece, pieces, random, p1, p2, p3, facing, p5);
} }
*/
RegistryNamespaced<ResourceLocation, VillagerProfession> REGISTRY = GameData.getWrapper(VillagerProfession.class); RegistryNamespaced<ResourceLocation, VillagerProfession> REGISTRY = GameData.getWrapper(VillagerProfession.class);
private void register(VillagerProfession prof, int id) private void register(VillagerProfession prof, int id)
@ -178,9 +177,9 @@ public class VillagerRegistry
"minecraft:textures/entity/zombie_villager/zombie_smith.png"); "minecraft:textures/entity/zombie_villager/zombie_smith.png");
{ {
register(prof, 3); register(prof, 3);
(new VillagerCareer(prof, "armor")).init(VanillaTrades.trades[3][0]); (new VillagerCareer(prof, "armorer")).init(VanillaTrades.trades[3][0]);
(new VillagerCareer(prof, "weapon")).init(VanillaTrades.trades[3][1]); (new VillagerCareer(prof, "weapon_smith")).init(VanillaTrades.trades[3][1]);
(new VillagerCareer(prof, "tool")).init(VanillaTrades.trades[3][2]); (new VillagerCareer(prof, "tool_smith")).init(VanillaTrades.trades[3][2]);
} }
prof = new VillagerProfession("minecraft:butcher", prof = new VillagerProfession("minecraft:butcher",
"minecraft:textures/entity/villager/butcher.png", "minecraft:textures/entity/villager/butcher.png",
@ -188,7 +187,7 @@ public class VillagerRegistry
{ {
register(prof, 4); register(prof, 4);
(new VillagerCareer(prof, "butcher")).init(VanillaTrades.trades[4][0]); (new VillagerCareer(prof, "butcher")).init(VanillaTrades.trades[4][0]);
(new VillagerCareer(prof, "leather")).init(VanillaTrades.trades[4][1]); (new VillagerCareer(prof, "leatherworker")).init(VanillaTrades.trades[4][1]);
} }
prof = new VillagerProfession("minecraft:nitwit", prof = new VillagerProfession("minecraft:nitwit",
"minecraft:textures/entity/villager/villager.png", "minecraft:textures/entity/villager/villager.png",
@ -312,13 +311,12 @@ public class VillagerRegistry
} }
} }
*/
/** /**
* Hook called when spawning a Villager, sets it's profession to a random registered profession. * Hook called when spawning a Villager, sets it's profession to a random registered profession.
* *
* @param entity The new entity * @param entity The new entity
* @param rand The world's RNG * @param rand The world's RNG
*//* */
public static void setRandomProfession(EntityVillager entity, Random rand) public static void setRandomProfession(EntityVillager entity, Random rand)
{ {
@ -369,5 +367,5 @@ public class VillagerRegistry
//It is nasty I know but it's vanilla. //It is nasty I know but it's vanilla.
private static final ITradeList[][][][] trades = EntityVillager.GET_TRADES_DONT_USE(); private static final ITradeList[][][][] trades = EntityVillager.GET_TRADES_DONT_USE();
} }
*/
} }

View file

@ -22,12 +22,12 @@ package net.minecraftforge.fml.common.toposort;
import java.util.Set; import java.util.Set;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.fml.client.GuiSortingProblem; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.client.IDisplayableError; import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.common.EnhancedRuntimeException;
import net.minecraftforge.fml.ModContainer; import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.client.IDisplayableError;
import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.fml.client.gui.GuiSortingProblem;
import net.minecraftforge.fml.common.EnhancedRuntimeException;
public class ModSortingException extends EnhancedRuntimeException implements IDisplayableError public class ModSortingException extends EnhancedRuntimeException implements IDisplayableError
{ {
@ -76,14 +76,14 @@ public class ModSortingException extends EnhancedRuntimeException implements IDi
stream.println("The first mod in the cycle is " + exceptionData.getFirstBadNode()); stream.println("The first mod in the cycle is " + exceptionData.getFirstBadNode());
stream.println("The mod cycle involves:"); stream.println("The mod cycle involves:");
for (ModContainer mc : exceptionData.getVisitedNodes()) for (ModContainer mc : exceptionData.getVisitedNodes())
{ {/* TODO Mod dependencies
stream.println(String.format("\t%s : before: %s, after: %s", mc.toString(), mc.getDependants(), mc.getDependencies())); stream.println(String.format("\t%s : before: %s, after: %s", mc.toString(), mc.getDependants(), mc.getDependencies()));
} */}
} }
@Override @Override
@SideOnly(Side.CLIENT) @OnlyIn(Dist.CLIENT)
public GuiScreen createGui() public GuiScreen createGui()
{ {
return new GuiSortingProblem(this); return new GuiSortingProblem(this);

View file

@ -30,6 +30,7 @@ import java.net.URISyntaxException;
import java.security.CodeSource; import java.security.CodeSource;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.Date; import java.util.Date;
import java.util.HashSet; import java.util.HashSet;
@ -46,17 +47,22 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.ArtifactVersion;
import com.google.common.io.ByteStreams; import com.google.common.io.ByteStreams;
import com.google.common.io.Files; import com.google.common.io.Files;
import net.minecraft.launchwrapper.Launch;
import cpw.mods.modlauncher.Launcher;
import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.common.ForgeVersion;
import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.loading.FMLCommonLaunchHandler;
import net.minecraftforge.fml.relauncher.FMLLaunchHandler; import net.minecraftforge.fml.loading.FMLEnvironment;
public class LibraryManager public class LibraryManager
{ {
private static final Logger LOGGER = LogManager.getLogger();
public static final boolean DISABLE_EXTERNAL_MANIFEST = Boolean.parseBoolean(System.getProperty("forge.disable_external_manifest", "false")); public static final boolean DISABLE_EXTERNAL_MANIFEST = Boolean.parseBoolean(System.getProperty("forge.disable_external_manifest", "false"));
public static final boolean ENABLE_AUTO_MOD_MOVEMENT = Boolean.parseBoolean(System.getProperty("forge.enable_auto_mod_movement", "false")); public static final boolean ENABLE_AUTO_MOD_MOVEMENT = Boolean.parseBoolean(System.getProperty("forge.enable_auto_mod_movement", "false"));
private static final String LIBRARY_DIRECTORY_OVERRIDE = System.getProperty("forge.lib_folder", null); private static final String LIBRARY_DIRECTORY_OVERRIDE = System.getProperty("forge.lib_folder", null);
@ -75,10 +81,10 @@ public class LibraryManager
public static void setup(File minecraftHome) public static void setup(File minecraftHome)
{ {
File libDir = findLibraryFolder(minecraftHome); File libDir = findLibraryFolder(minecraftHome);
FMLLog.log.debug("Determined Minecraft Libraries Root: {}", libDir); LOGGER.debug("Determined Minecraft Libraries Root: {}", libDir);
Repository old = Repository.replace(libDir, "libraries"); Repository old = Repository.replace(libDir, "libraries");
if (old != null) if (old != null)
FMLLog.log.debug(" Overwriting Previous: {}", old); LOGGER.debug(" Overwriting Previous: {}", old);
libraries_dir = Repository.get("libraries"); libraries_dir = Repository.get("libraries");
File mods = new File(minecraftHome, "mods"); File mods = new File(minecraftHome, "mods");
@ -119,14 +125,14 @@ public class LibraryManager
{ {
if (LIBRARY_DIRECTORY_OVERRIDE != null) if (LIBRARY_DIRECTORY_OVERRIDE != null)
{ {
FMLLog.log.error("System variable set to override Library Directory: {}", LIBRARY_DIRECTORY_OVERRIDE); LOGGER.error("System variable set to override Library Directory: {}", LIBRARY_DIRECTORY_OVERRIDE);
return new File(LIBRARY_DIRECTORY_OVERRIDE); return new File(LIBRARY_DIRECTORY_OVERRIDE);
} }
CodeSource source = ArtifactVersion.class.getProtectionDomain().getCodeSource(); CodeSource source = ArtifactVersion.class.getProtectionDomain().getCodeSource();
if (source == null) if (source == null)
{ {
FMLLog.log.error("Unable to determine codesource for {}. Using default libraries directory.", ArtifactVersion.class.getName()); LOGGER.error("Unable to determine codesource for {}. Using default libraries directory.", ArtifactVersion.class.getName());
return new File(minecraftHome, "libraries"); return new File(minecraftHome, "libraries");
} }
@ -142,9 +148,9 @@ public class LibraryManager
if (!comp.endsWith("/org/apache/maven/maven-artifact/")) if (!comp.endsWith("/org/apache/maven/maven-artifact/"))
{ {
FMLLog.log.error("Apache Maven library folder was not in the format expected. Using default libraries directory."); LOGGER.error("Apache Maven library folder was not in the format expected. Using default libraries directory.");
FMLLog.log.error("Full: {}", new File(source.getLocation().toURI())); LOGGER.error("Full: {}", new File(source.getLocation().toURI()));
FMLLog.log.error("Trimmed: {}", comp); LOGGER.error("Trimmed: {}", comp);
return new File(minecraftHome, "libraries"); return new File(minecraftHome, "libraries");
} }
// maven-artifact /maven /apache /org /libraries // maven-artifact /maven /apache /org /libraries
@ -152,7 +158,7 @@ public class LibraryManager
} }
catch (URISyntaxException e) catch (URISyntaxException e)
{ {
FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage("Unable to determine file for {}. Using default libraries directory.", ArtifactVersion.class.getName()), e); LOGGER.error(LOGGER.getMessageFactory().newMessage("Unable to determine file for {}. Using default libraries directory.", ArtifactVersion.class.getName()), e);
} }
return new File(minecraftHome, "libraries"); //Everything else failed, return the default. return new File(minecraftHome, "libraries"); //Everything else failed, return the default.
@ -163,7 +169,7 @@ public class LibraryManager
if (!dir.exists()) if (!dir.exists())
return; return;
FMLLog.log.debug("Cleaning up mods folder: {}", dir); LOGGER.debug("Cleaning up mods folder: {}", dir);
for (File file : dir.listFiles(f -> f.isFile() && f.getName().endsWith(".jar"))) for (File file : dir.listFiles(f -> f.isFile() && f.getName().endsWith(".jar")))
{ {
Pair<Artifact, byte[]> ret = extractPacked(file, modlist, modDirs); Pair<Artifact, byte[]> ret = extractPacked(file, modlist, modDirs);
@ -183,7 +189,7 @@ public class LibraryManager
} }
catch (IOException e) catch (IOException e)
{ {
FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage("Error updating modlist file {}", modlist.getName()), e); LOGGER.error(LOGGER.getMessageFactory().newMessage("Error updating modlist file {}", modlist.getName()), e);
} }
} }
@ -191,20 +197,20 @@ public class LibraryManager
{ {
if (processed.contains(file)) if (processed.contains(file))
{ {
FMLLog.log.debug("File already proccessed {}, Skipping", file.getAbsolutePath()); LOGGER.debug("File already proccessed {}, Skipping", file.getAbsolutePath());
return null; return null;
} }
JarFile jar = null; JarFile jar = null;
try try
{ {
jar = new JarFile(file); jar = new JarFile(file);
FMLLog.log.debug("Examining file: {}", file.getName()); LOGGER.debug("Examining file: {}", file.getName());
processed.add(file); processed.add(file);
return extractPacked(jar, modlist, modDirs); return extractPacked(jar, modlist, modDirs);
} }
catch (IOException ioe) catch (IOException ioe)
{ {
FMLLog.log.error("Unable to read the jar file {} - ignoring", file.getName(), ioe); LOGGER.error("Unable to read the jar file {} - ignoring", file.getName(), ioe);
} }
finally finally
{ {
@ -228,7 +234,7 @@ public class LibraryManager
attrs = jar.getManifest().getMainAttributes(); attrs = jar.getManifest().getMainAttributes();
String modSide = attrs.getValue(LibraryManager.MODSIDE); String modSide = attrs.getValue(LibraryManager.MODSIDE);
if (modSide != null && !"BOTH".equals(modSide) && !FMLLaunchHandler.side().name().equals(modSide)) if (modSide != null && !"BOTH".equals(modSide) && !FMLEnvironment.dist.name().equals(modSide))
return null; return null;
if (attrs.containsKey(MODCONTAINSDEPS)) if (attrs.containsKey(MODCONTAINSDEPS))
@ -237,7 +243,7 @@ public class LibraryManager
{ {
if (!dep.endsWith(".jar")) if (!dep.endsWith(".jar"))
{ {
FMLLog.log.error("Contained Dep is not a jar file: {}", dep); LOGGER.error("Contained Dep is not a jar file: {}", dep);
throw new IllegalStateException("Invalid contained dep, Must be jar: " + dep); throw new IllegalStateException("Invalid contained dep, Must be jar: " + dep);
} }
@ -247,14 +253,14 @@ public class LibraryManager
JarEntry depEntry = jar.getJarEntry(dep); JarEntry depEntry = jar.getJarEntry(dep);
if (depEntry == null) if (depEntry == null)
{ {
FMLLog.log.error("Contained Dep is not in the jar: {}", dep); LOGGER.error("Contained Dep is not in the jar: {}", dep);
throw new IllegalStateException("Invalid contained dep, Missing from jar: " + dep); throw new IllegalStateException("Invalid contained dep, Missing from jar: " + dep);
} }
String depEndName = new File(dep).getName(); // extract last part of name String depEndName = new File(dep).getName(); // extract last part of name
if (skipContainedDeps.contains(dep) || skipContainedDeps.contains(depEndName)) if (skipContainedDeps.contains(dep) || skipContainedDeps.contains(depEndName))
{ {
FMLLog.log.error("Skipping dep at request: {}", dep); LOGGER.error("Skipping dep at request: {}", dep);
continue; continue;
} }
@ -294,14 +300,14 @@ public class LibraryManager
File target = new File(dir, depEndName); File target = new File(dir, depEndName);
if (target.exists()) if (target.exists())
{ {
FMLLog.log.debug("Found existing ContainDep extracted to {}, skipping extraction", target.getCanonicalPath()); LOGGER.debug("Found existing ContainDep extracted to {}, skipping extraction", target.getCanonicalPath());
found = true; found = true;
} }
} }
if (!found) if (!found)
{ {
File target = new File(modDirs[0], depEndName); File target = new File(modDirs[0], depEndName);
FMLLog.log.debug("Extracting ContainedDep {} from {} to {}", dep, jar.getName(), target.getCanonicalPath()); LOGGER.debug("Extracting ContainedDep {} from {} to {}", dep, jar.getName(), target.getCanonicalPath());
try try
{ {
Files.createParentDirs(target); Files.createParentDirs(target);
@ -313,12 +319,12 @@ public class LibraryManager
{ {
ByteStreams.copy(in, out); ByteStreams.copy(in, out);
} }
FMLLog.log.debug("Extracted ContainedDep {} from {} to {}", dep, jar.getName(), target.getCanonicalPath()); LOGGER.debug("Extracted ContainedDep {} from {} to {}", dep, jar.getName(), target.getCanonicalPath());
extractPacked(target, modlist, modDirs); extractPacked(target, modlist, modDirs);
} }
catch (IOException e) catch (IOException e)
{ {
FMLLog.log.error("An error occurred extracting dependency", e); LOGGER.error("An error occurred extracting dependency", e);
} }
} }
} }
@ -330,7 +336,7 @@ public class LibraryManager
File target = artifact.getFile(); File target = artifact.getFile();
if (target.exists()) if (target.exists())
{ {
FMLLog.log.debug("Found existing ContainedDep {}({}) from {} extracted to {}, skipping extraction", dep, artifact.toString(), target.getCanonicalPath(), jar.getName()); LOGGER.debug("Found existing ContainedDep {}({}) from {} extracted to {}, skipping extraction", dep, artifact.toString(), target.getCanonicalPath(), jar.getName());
if (!ENABLE_AUTO_MOD_MOVEMENT) if (!ENABLE_AUTO_MOD_MOVEMENT)
{ {
Pair<?, ?> child = extractPacked(target, modlist, modDirs); //If we're not building a real list we have to re-build the dep list every run. So search down. Pair<?, ?> child = extractPacked(target, modlist, modDirs); //If we're not building a real list we have to re-build the dep list every run. So search down.
@ -342,7 +348,7 @@ public class LibraryManager
} }
else else
{ {
FMLLog.log.debug("Extracting ContainedDep {}({}) from {} to {}", dep, artifact.toString(), jar.getName(), target.getCanonicalPath()); LOGGER.debug("Extracting ContainedDep {}({}) from {} to {}", dep, artifact.toString(), jar.getName(), target.getCanonicalPath());
Files.createParentDirs(target); Files.createParentDirs(target);
try try
( (
@ -352,7 +358,7 @@ public class LibraryManager
{ {
ByteStreams.copy(in, out); ByteStreams.copy(in, out);
} }
FMLLog.log.debug("Extracted ContainedDep {}({}) from {} to {}", dep, artifact.toString(), jar.getName(), target.getCanonicalPath()); LOGGER.debug("Extracted ContainedDep {}({}) from {} to {}", dep, artifact.toString(), jar.getName(), target.getCanonicalPath());
if (artifact.isSnapshot()) if (artifact.isSnapshot())
{ {
@ -375,11 +381,11 @@ public class LibraryManager
} }
catch (NumberFormatException nfe) catch (NumberFormatException nfe)
{ {
FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage("An error occurred extracting dependency. Invalid Timestamp: {}", meta.getValue(TIMESTAMP)), nfe); LOGGER.error(LOGGER.getMessageFactory().newMessage("An error occurred extracting dependency. Invalid Timestamp: {}", meta.getValue(TIMESTAMP)), nfe);
} }
catch (IOException e) catch (IOException e)
{ {
FMLLog.log.error("An error occurred extracting dependency", e); LOGGER.error("An error occurred extracting dependency", e);
} }
} }
} }
@ -443,26 +449,26 @@ public class LibraryManager
List<File> list = new ArrayList<>(); List<File> list = new ArrayList<>();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String,String> args = (Map<String, String>)Launch.blackboard.get("launchArgs"); Map<String,String> args = Collections.emptyMap(); // TODO Launch args - do we need this? (Map<String, String>)Launcher.INSTANCE.blackboard().get("launchArgs");
String extraMods = args.get("--mods"); String extraMods = args.get("--mods");
if (extraMods != null) if (extraMods != null)
{ {
FMLLog.log.info("Found mods from the command line:"); LOGGER.info("Found mods from the command line:");
for (String mod : extraMods.split(",")) for (String mod : extraMods.split(","))
{ {
File file = new File(mcDir, mod); File file = new File(mcDir, mod);
if (!file.exists()) if (!file.exists())
{ {
FMLLog.log.info(" Failed to find mod file {} ({})", mod, file.getAbsolutePath()); LOGGER.info(" Failed to find mod file {} ({})", mod, file.getAbsolutePath());
} }
else if (!list.contains(file)) else if (!list.contains(file))
{ {
FMLLog.log.debug(" Adding {} ({}) to the mod list", mod, file.getAbsolutePath()); LOGGER.debug(" Adding {} ({}) to the mod list", mod, file.getAbsolutePath());
list.add(file); list.add(file);
} }
else if (!list.contains(file)) else if (!list.contains(file))
{ {
FMLLog.log.debug(" Duplicte command line mod detected {} ({})", mod, file.getAbsolutePath()); LOGGER.debug(" Duplicte command line mod detected {} ({})", mod, file.getAbsolutePath());
} }
} }
} }
@ -473,12 +479,12 @@ public class LibraryManager
if (!base.isDirectory() || !base.exists()) if (!base.isDirectory() || !base.exists())
continue; continue;
FMLLog.log.info("Searching {} for mods", base.getAbsolutePath()); LOGGER.info("Searching {} for mods", base.getAbsolutePath());
for (File f : base.listFiles(MOD_FILENAME_FILTER)) for (File f : base.listFiles(MOD_FILENAME_FILTER))
{ {
if (!list.contains(f)) if (!list.contains(f))
{ {
FMLLog.log.debug(" Adding {} to the mod list", f.getName()); LOGGER.debug(" Adding {} to the mod list", f.getName());
list.add(f); list.add(f);
} }
} }

View file

@ -26,10 +26,13 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import net.minecraftforge.fml.common.FMLLog; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LinkRepository extends Repository public class LinkRepository extends Repository
{ {
private static final Logger LOGGER = LogManager.getLogger();
private Map<String, File> artifact_to_file = new HashMap<>(); private Map<String, File> artifact_to_file = new HashMap<>();
private Map<String, File> filesystem = new HashMap<>(); private Map<String, File> filesystem = new HashMap<>();
private Map<String, Artifact> snapshots = new HashMap<>(); private Map<String, Artifact> snapshots = new HashMap<>();
@ -46,14 +49,14 @@ public class LinkRepository extends Repository
known.add(file); known.add(file);
if (artifact_to_file.containsKey(key)) if (artifact_to_file.containsKey(key))
{ {
FMLLog.log.debug("Maven file already exists for {}({}) at {}, ignoring duplicate.", file.getName(), artifact.toString(), artifact_to_file.get(key).getAbsolutePath()); LOGGER.debug("Maven file already exists for {}({}) at {}, ignoring duplicate.", file.getName(), artifact.toString(), artifact_to_file.get(key).getAbsolutePath());
if (artifact.isSnapshot()) if (artifact.isSnapshot())
{ {
Artifact old = snapshots.get(key); Artifact old = snapshots.get(key);
if (old == null || old.compareVersion(artifact) < 0) if (old == null || old.compareVersion(artifact) < 0)
{ {
FMLLog.log.debug("Overriding Snapshot {} -> {}", old == null ? "null" : old.getTimestamp(), artifact.getTimestamp()); LOGGER.debug("Overriding Snapshot {} -> {}", old == null ? "null" : old.getTimestamp(), artifact.getTimestamp());
snapshots.put(key, artifact); snapshots.put(key, artifact);
artifact_to_file.put(key, file); artifact_to_file.put(key, file);
filesystem.put(artifact.getPath(), file); filesystem.put(artifact.getPath(), file);
@ -62,7 +65,7 @@ public class LinkRepository extends Repository
} }
else else
{ {
FMLLog.log.debug("Making maven link for {} in memory to {}.", key, file.getAbsolutePath()); LOGGER.debug("Making maven link for {} in memory to {}.", key, file.getAbsolutePath());
artifact_to_file.put(key, file); artifact_to_file.put(key, file);
filesystem.put(artifact.getPath(), file); filesystem.put(artifact.getPath(), file);

View file

@ -30,18 +30,21 @@ import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.io.Files; import com.google.common.io.Files;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException; import com.google.gson.JsonSyntaxException;
import net.minecraft.launchwrapper.Launch;
import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.common.ForgeVersion;
import net.minecraftforge.fml.common.FMLLog;
public class ModList public class ModList
{ {
private static final Logger LOGGER = LogManager.getLogger();
private static final Gson GSON = new GsonBuilder().setLenient().create(); private static final Gson GSON = new GsonBuilder().setLenient().create();
static final Map<String, ModList> cache = new HashMap<>(); static final Map<String, ModList> cache = new HashMap<>();
@ -54,7 +57,7 @@ public class ModList
} }
catch (IOException e) catch (IOException e)
{ {
FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage("Unable to load ModList json at {}.", json.getAbsoluteFile()), e); LOGGER.error(LOGGER.getMessageFactory().newMessage("Unable to load ModList json at {}.", json.getAbsoluteFile()), e);
} }
return new ModList(json, mcdir); return new ModList(json, mcdir);
@ -63,7 +66,7 @@ public class ModList
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static List<ModList> getKnownLists(File mcdir) public static List<ModList> getKnownLists(File mcdir)
{ {
for (String list : new String[] {"mods/mod_list.json", "mods/" + ForgeVersion.mcVersion + "/mod_list.json", ((Map<String, String>)Launch.blackboard.get("launchArgs")).get("--modListFile")}) for (String list : new String[] {"mods/mod_list.json", "mods/" + ForgeVersion.mcVersion + "/mod_list.json"/* , TODO Launch args ((Map<String, String>)Launch.blackboard.get("launchArgs")).get("--modListFile")*/})
{ {
if (list != null) if (list != null)
{ {
@ -84,7 +87,7 @@ public class ModList
if (memory != null) if (memory != null)
lst.add(memory); lst.add(memory);
for (String list : new String[] {"mods/mod_list.json", "mods/" + ForgeVersion.mcVersion + "/mod_list.json", ((Map<String, String>)Launch.blackboard.get("launchArgs")).get("--modListFile")}) for (String list : new String[] {"mods/mod_list.json", "mods/" + ForgeVersion.mcVersion + "/mod_list.json"/* TODO Launch args, ((Map<String, String>)Launch.blackboard.get("launchArgs")).get("--modListFile")*/})
{ {
if (list != null) if (list != null)
{ {
@ -127,11 +130,11 @@ public class ModList
} }
catch (JsonSyntaxException jse) catch (JsonSyntaxException jse)
{ {
FMLLog.log.info(FMLLog.log.getMessageFactory().newMessage("Failed to parse modList json file {}.", path), jse); LOGGER.info(LOGGER.getMessageFactory().newMessage("Failed to parse modList json file {}.", path), jse);
} }
catch (IOException ioe) catch (IOException ioe)
{ {
FMLLog.log.info(FMLLog.log.getMessageFactory().newMessage("Failed to read modList json file {}.", path), ioe); LOGGER.info(LOGGER.getMessageFactory().newMessage("Failed to read modList json file {}.", path), ioe);
} }
} }
this.mod_list = temp_list == null ? new JsonModList() : temp_list; this.mod_list = temp_list == null ? new JsonModList() : temp_list;
@ -148,7 +151,7 @@ public class ModList
} }
catch (IOException e) catch (IOException e)
{ {
FMLLog.log.info(FMLLog.log.getMessageFactory().newMessage("Failed to create repository for modlist at {}.", mod_list.repositoryRoot), e); LOGGER.info(LOGGER.getMessageFactory().newMessage("Failed to create repository for modlist at {}.", mod_list.repositoryRoot), e);
} }
} }
this.repo = temp; this.repo = temp;
@ -209,7 +212,7 @@ public class ModList
} }
catch (IOException ioe) catch (IOException ioe)
{ {
FMLLog.log.info(FMLLog.log.getMessageFactory().newMessage("Unable to canonicalize path {} relative to {}", path, root.getAbsolutePath())); LOGGER.info(LOGGER.getMessageFactory().newMessage("Unable to canonicalize path {} relative to {}", path, root.getAbsolutePath()));
} }
return null; return null;
} }

View file

@ -25,13 +25,16 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.common.hash.Hashing; import com.google.common.hash.Hashing;
import com.google.common.io.Files; import com.google.common.io.Files;
import net.minecraftforge.fml.common.FMLLog;
public class Repository public class Repository
{ {
private static final Logger LOGGER = LogManager.getLogger();
static final Map<String, Repository> cache = new LinkedHashMap<>(); static final Map<String, Repository> cache = new LinkedHashMap<>();
public static Repository create(File root) throws IOException public static Repository create(File root) throws IOException
@ -129,12 +132,12 @@ public class Repository
{ {
if (target.exists()) if (target.exists())
{ {
FMLLog.log.debug("Maven file already exists for {}({}) at {}, deleting duplicate.", file.getName(), artifact.toString(), target.getAbsolutePath()); LOGGER.debug("Maven file already exists for {}({}) at {}, deleting duplicate.", file.getName(), artifact.toString(), target.getAbsolutePath());
file.delete(); file.delete();
} }
else else
{ {
FMLLog.log.debug("Moving file {}({}) to maven repo at {}.", file.getName(), artifact.toString(), target.getAbsolutePath()); LOGGER.debug("Moving file {}({}) to maven repo at {}.", file.getName(), artifact.toString(), target.getAbsolutePath());
Files.move(file, target); Files.move(file, target);
if (artifact.isSnapshot()) if (artifact.isSnapshot())
@ -154,7 +157,7 @@ public class Repository
} }
catch (IOException e) catch (IOException e)
{ {
FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage("Error moving file {} to {}", file, target.getAbsolutePath()), e); LOGGER.error(LOGGER.getMessageFactory().newMessage("Error moving file {} to {}", file, target.getAbsolutePath()), e);
} }
return file; return file;
} }

View file

@ -133,19 +133,19 @@ public class ServerLifecycleHooks
{ {
try try
{ {
FMLLog.log.info("Waiting for the server to terminate/save."); LOGGER.info("Waiting for the server to terminate/save.");
if (!latch.await(10, TimeUnit.SECONDS)) if (!latch.await(10, TimeUnit.SECONDS))
{ {
FMLLog.log.warn("The server didn't stop within 10 seconds, exiting anyway."); LOGGER.warn("The server didn't stop within 10 seconds, exiting anyway.");
} }
else else
{ {
FMLLog.log.info("Server terminated."); LOGGER.info("Server terminated.");
} }
} }
catch (InterruptedException e) catch (InterruptedException e)
{ {
FMLLog.log.warn("Interrupted wait, exiting."); LOGGER.warn("Interrupted wait, exiting.");
} }
} }

View file

@ -74,10 +74,11 @@ public class ItemHandlerHelper
// Metadata value only matters when the item has subtypes // Metadata value only matters when the item has subtypes
// Vanilla stacks non-subtype items with different metadata together // Vanilla stacks non-subtype items with different metadata together
// e.g. a stick with metadata 0 and a stick with metadata 1 stack // TODO Item subtypes, is this still necessary?
/* e.g. a stick with metadata 0 and a stick with metadata 1 stack
if (a.getHasSubtypes() && a.getMetadata() != b.getMetadata()) if (a.getHasSubtypes() && a.getMetadata() != b.getMetadata())
return false; return false;
*/
if (a.hasTagCompound() != b.hasTagCompound()) if (a.hasTagCompound() != b.hasTagCompound())
return false; return false;

View file

@ -24,12 +24,13 @@ import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryBasic; import net.minecraft.inventory.InventoryBasic;
import net.minecraft.inventory.Slot; import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.text.TextComponentString;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
public class SlotItemHandler extends Slot public class SlotItemHandler extends Slot
{ {
private static IInventory emptyInventory = new InventoryBasic("[Null]", true, 0); private static IInventory emptyInventory = new InventoryBasic(new TextComponentString("[Null]"), 0);
private final IItemHandler itemHandler; private final IItemHandler itemHandler;
private final int index; private final int index;
@ -140,10 +141,10 @@ public class SlotItemHandler extends Slot
{ {
return itemHandler; return itemHandler;
} }
/* TODO Slot patches
@Override @Override
public boolean isSameInventory(Slot other) public boolean isSameInventory(Slot other)
{ {
return other instanceof SlotItemHandler && ((SlotItemHandler) other).getItemHandler() == this.itemHandler; return other instanceof SlotItemHandler && ((SlotItemHandler) other).getItemHandler() == this.itemHandler;
} }*/
} }

View file

@ -20,6 +20,7 @@
package net.minecraftforge.items; package net.minecraftforge.items;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest; import net.minecraft.tileentity.TileEntityChest;
@ -58,7 +59,7 @@ public class VanillaDoubleChestItemHandler extends WeakReference<TileEntityChest
if (world == null || pos == null || !world.isBlockLoaded(pos)) if (world == null || pos == null || !world.isBlockLoaded(pos))
return null; // Still loading return null; // Still loading
Block blockType = chest.getBlockType(); IBlockState state = chest.func_195044_w();
EnumFacing[] horizontals = EnumFacing.HORIZONTALS; EnumFacing[] horizontals = EnumFacing.HORIZONTALS;
for (int i = horizontals.length - 1; i >= 0; i--) // Use reverse order so we can return early for (int i = horizontals.length - 1; i >= 0; i--) // Use reverse order so we can return early
@ -67,7 +68,7 @@ public class VanillaDoubleChestItemHandler extends WeakReference<TileEntityChest
BlockPos blockpos = pos.offset(enumfacing); BlockPos blockpos = pos.offset(enumfacing);
Block block = world.getBlockState(blockpos).getBlock(); Block block = world.getBlockState(blockpos).getBlock();
if (block == blockType) if (block == state.getBlock())
{ {
TileEntity otherTE = world.getTileEntity(blockpos); TileEntity otherTE = world.getTileEntity(blockpos);
@ -125,7 +126,7 @@ public class VanillaDoubleChestItemHandler extends WeakReference<TileEntityChest
TileEntityChest chest = getChest(accessingUpperChest); TileEntityChest chest = getChest(accessingUpperChest);
if (chest != null) if (chest != null)
{ {
IItemHandler singleHandler = chest.getSingleChestHandler(); IItemHandler singleHandler = null; // TODO TileEntityChest patches chest.getSingleChestHandler();
if (singleHandler instanceof IItemHandlerModifiable) if (singleHandler instanceof IItemHandlerModifiable)
{ {
((IItemHandlerModifiable) singleHandler).setStackInSlot(targetSlot, stack); ((IItemHandlerModifiable) singleHandler).setStackInSlot(targetSlot, stack);
@ -148,7 +149,7 @@ public class VanillaDoubleChestItemHandler extends WeakReference<TileEntityChest
return stack; return stack;
int starting = stack.getCount(); int starting = stack.getCount();
ItemStack ret = chest.getSingleChestHandler().insertItem(targetSlot, stack, simulate); ItemStack ret = ItemStack.EMPTY; // TODO TileEntityChest patches chest.getSingleChestHandler().insertItem(targetSlot, stack, simulate);
if (ret.getCount() != starting && !simulate) if (ret.getCount() != starting && !simulate)
{ {
chest = getChest(!accessingUpperChest); chest = getChest(!accessingUpperChest);
@ -169,7 +170,7 @@ public class VanillaDoubleChestItemHandler extends WeakReference<TileEntityChest
if (chest == null) if (chest == null)
return ItemStack.EMPTY; return ItemStack.EMPTY;
ItemStack ret = chest.getSingleChestHandler().extractItem(targetSlot, amount, simulate); ItemStack ret = ItemStack.EMPTY; // TODO TileEntityChest patches chest.getSingleChestHandler().extractItem(targetSlot, amount, simulate);
if (!ret.isEmpty() && !simulate) if (!ret.isEmpty() && !simulate)
{ {
chest = getChest(!accessingUpperChest); chest = getChest(!accessingUpperChest);
@ -195,7 +196,7 @@ public class VanillaDoubleChestItemHandler extends WeakReference<TileEntityChest
TileEntityChest chest = getChest(accessingUpperChest); TileEntityChest chest = getChest(accessingUpperChest);
if (chest != null) if (chest != null)
{ {
return chest.getSingleChestHandler().isItemValid(targetSlot, stack); return false; // TODO TileEntityChest patches chest.getSingleChestHandler().isItemValid(targetSlot, stack);
} }
return true; return true;
} }

View file

@ -31,6 +31,8 @@ import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.OptionalCapabilityInstance;
import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
@ -46,10 +48,8 @@ public class VanillaInventoryCodeHooks
@Nullable @Nullable
public static Boolean extractHook(IHopper dest) public static Boolean extractHook(IHopper dest)
{ {
Pair<IItemHandler, Object> itemHandlerResult = getItemHandler(dest, EnumFacing.UP); return getItemHandler(dest, EnumFacing.UP)
if (itemHandlerResult == null) .map(itemHandlerResult -> {
return null;
IItemHandler handler = itemHandlerResult.getKey(); IItemHandler handler = itemHandlerResult.getKey();
for (int i = 0; i < handler.getSlots(); i++) for (int i = 0; i < handler.getSlots(); i++)
@ -78,6 +78,8 @@ public class VanillaInventoryCodeHooks
} }
return false; return false;
})
.orElse(null); // TODO bad null
} }
/** /**
@ -87,13 +89,8 @@ public class VanillaInventoryCodeHooks
{ {
EnumFacing enumfacing = world.getBlockState(pos).getValue(BlockDropper.FACING); EnumFacing enumfacing = world.getBlockState(pos).getValue(BlockDropper.FACING);
BlockPos blockpos = pos.offset(enumfacing); BlockPos blockpos = pos.offset(enumfacing);
Pair<IItemHandler, Object> destinationResult = getItemHandler(world, (double) blockpos.getX(), (double) blockpos.getY(), (double) blockpos.getZ(), enumfacing.getOpposite()); return getItemHandler(world, (double) blockpos.getX(), (double) blockpos.getY(), (double) blockpos.getZ(), enumfacing.getOpposite())
if (destinationResult == null) .map(destinationResult -> {
{
return true;
}
else
{
IItemHandler itemHandler = destinationResult.getKey(); IItemHandler itemHandler = destinationResult.getKey();
Object destination = destinationResult.getValue(); Object destination = destinationResult.getValue();
ItemStack dispensedStack = stack.copy().splitStack(1); ItemStack dispensedStack = stack.copy().splitStack(1);
@ -111,7 +108,8 @@ public class VanillaInventoryCodeHooks
dropper.setInventorySlotContents(slot, remainder); dropper.setInventorySlotContents(slot, remainder);
return false; return false;
} })
.orElse(false);
} }
/** /**
@ -119,14 +117,9 @@ public class VanillaInventoryCodeHooks
*/ */
public static boolean insertHook(TileEntityHopper hopper) public static boolean insertHook(TileEntityHopper hopper)
{ {
EnumFacing hopperFacing = BlockHopper.getFacing(hopper.getBlockMetadata()); EnumFacing hopperFacing = hopper.func_195044_w().getValue(BlockHopper.FACING);
Pair<IItemHandler, Object> destinationResult = getItemHandler(hopper, hopperFacing); return getItemHandler(hopper, hopperFacing)
if (destinationResult == null) .map(destinationResult -> {
{
return false;
}
else
{
IItemHandler itemHandler = destinationResult.getKey(); IItemHandler itemHandler = destinationResult.getKey();
Object destination = destinationResult.getValue(); Object destination = destinationResult.getValue();
if (isFull(itemHandler)) if (isFull(itemHandler))
@ -154,7 +147,8 @@ public class VanillaInventoryCodeHooks
return false; return false;
} }
} })
.orElse(false);
} }
private static ItemStack putStackInInventoryAllSlots(TileEntity source, Object destination, IItemHandler destInventory, ItemStack stack) private static ItemStack putStackInInventoryAllSlots(TileEntity source, Object destination, IItemHandler destInventory, ItemStack stack)
@ -200,7 +194,7 @@ public class VanillaInventoryCodeHooks
if (!destinationHopper.mayTransfer()) if (!destinationHopper.mayTransfer())
{ {
int k = 0; int k = 0;
/* TODO TileEntityHopper patches
if (source instanceof TileEntityHopper) if (source instanceof TileEntityHopper)
{ {
if (destinationHopper.getLastUpdateTime() >= ((TileEntityHopper) source).getLastUpdateTime()) if (destinationHopper.getLastUpdateTime() >= ((TileEntityHopper) source).getLastUpdateTime())
@ -208,7 +202,7 @@ public class VanillaInventoryCodeHooks
k = 1; k = 1;
} }
} }
*/
destinationHopper.setTransferCooldown(8 - k); destinationHopper.setTransferCooldown(8 - k);
} }
} }
@ -218,12 +212,11 @@ public class VanillaInventoryCodeHooks
return stack; return stack;
} }
@Nullable private static OptionalCapabilityInstance<Pair<IItemHandler, Object>> getItemHandler(IHopper hopper, EnumFacing hopperFacing)
private static Pair<IItemHandler, Object> getItemHandler(IHopper hopper, EnumFacing hopperFacing)
{ {
double x = hopper.getXPos() + (double) hopperFacing.getFrontOffsetX(); double x = hopper.getXPos() + (double) hopperFacing.getXOffset();
double y = hopper.getYPos() + (double) hopperFacing.getFrontOffsetY(); double y = hopper.getYPos() + (double) hopperFacing.getYOffset();
double z = hopper.getZPos() + (double) hopperFacing.getFrontOffsetZ(); double z = hopper.getZPos() + (double) hopperFacing.getZOffset();
return getItemHandler(hopper.getWorld(), x, y, z, hopperFacing.getOpposite()); return getItemHandler(hopper.getWorld(), x, y, z, hopperFacing.getOpposite());
} }
@ -253,10 +246,8 @@ public class VanillaInventoryCodeHooks
return true; return true;
} }
@Nullable public static OptionalCapabilityInstance<Pair<IItemHandler, Object>> getItemHandler(World worldIn, double x, double y, double z, final EnumFacing side)
public static Pair<IItemHandler, Object> getItemHandler(World worldIn, double x, double y, double z, final EnumFacing side)
{ {
Pair<IItemHandler, Object> destination = null;
int i = MathHelper.floor(x); int i = MathHelper.floor(x);
int j = MathHelper.floor(y); int j = MathHelper.floor(y);
int k = MathHelper.floor(z); int k = MathHelper.floor(z);
@ -264,19 +255,16 @@ public class VanillaInventoryCodeHooks
net.minecraft.block.state.IBlockState state = worldIn.getBlockState(blockpos); net.minecraft.block.state.IBlockState state = worldIn.getBlockState(blockpos);
Block block = state.getBlock(); Block block = state.getBlock();
if (block.hasTileEntity(state)) if (block.hasTileEntity(/* TODO Block patches // state */))
{ {
TileEntity tileentity = worldIn.getTileEntity(blockpos); TileEntity tileentity = worldIn.getTileEntity(blockpos);
if (tileentity != null) if (tileentity != null)
{ {
if (tileentity.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, side)) return tileentity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, side)
{ .map(capability -> ImmutablePair.<IItemHandler, Object>of(capability, tileentity));
IItemHandler capability = tileentity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, side);
destination = ImmutablePair.<IItemHandler, Object>of(capability, tileentity);
}
} }
} }
return destination; return OptionalCapabilityInstance.empty();
} }
} }

View file

@ -98,17 +98,17 @@ public class ModelLoaderErrorMessage extends SimpleMessage
if(exception instanceof ModelLoader.ItemLoadingException) if(exception instanceof ModelLoader.ItemLoadingException)
{ {
ModelLoader.ItemLoadingException ex = (ModelLoader.ItemLoadingException)exception; ModelLoader.ItemLoadingException ex = (ModelLoader.ItemLoadingException)exception;
// FMLLog.log.error("{}, normal location exception: ", errorMsg, ex.normalException); // LOGGER.error("{}, normal location exception: ", errorMsg, ex.normalException);
// FMLLog.log.error("{}, blockstate location exception: ", errorMsg, ex.blockstateException); // LOGGER.error("{}, blockstate location exception: ", errorMsg, ex.blockstateException);
} }
else else
{ {
// FMLLog.log.error(errorMsg, entry.getValue()); // LOGGER.error(errorMsg, entry.getValue());
} }
// ResourceLocation blockstateLocation = new ResourceLocation(resourceLocation.getResourceDomain(), resourceLocation.getResourcePath()); // ResourceLocation blockstateLocation = new ResourceLocation(resourceLocation.getResourceDomain(), resourceLocation.getResourcePath());
// if(loadingExceptions.containsKey(blockstateLocation) && !printedBlockStateErrors.contains(blockstateLocation)) // if(loadingExceptions.containsKey(blockstateLocation) && !printedBlockStateErrors.contains(blockstateLocation))
// { // {
// FMLLog.log.error("Exception loading blockstate for the variant {}: ", location, loadingExceptions.get(blockstateLocation)); // LOGGER.error("Exception loading blockstate for the variant {}: ", location, loadingExceptions.get(blockstateLocation));
// printedBlockStateErrors.add(blockstateLocation); // printedBlockStateErrors.add(blockstateLocation);
// } // }
} }

View file

@ -18,7 +18,6 @@
*/ */
package net.minecraftforge.oredict; package net.minecraftforge.oredict;
/* /*
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@ -53,7 +52,6 @@ import net.minecraftforge.fml.common.Loader;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
*/ */
public class OreDictionary public class OreDictionary
{ {
/* /*
@ -381,7 +379,7 @@ public class OreDictionary
ItemStack.EMPTY //So the above can have a comma and we don't have to keep editing extra lines. ItemStack.EMPTY //So the above can have a comma and we don't have to keep editing extra lines.
}; };
FMLLog.log.info("Starts to replace vanilla recipe ingredients with ore ingredients."); LOGGER.info("Starts to replace vanilla recipe ingredients with ore ingredients.");
int replaced = 0; int replaced = 0;
// Search vanilla recipes for recipes to replace // Search vanilla recipes for recipes to replace
for(IRecipe obj : CraftingManager.REGISTRY) for(IRecipe obj : CraftingManager.REGISTRY)
@ -413,7 +411,7 @@ public class OreDictionary
matches = true; matches = true;
if (oreName != null && !oreName.equals(ent.getValue())) if (oreName != null && !oreName.equals(ent.getValue()))
{ {
FMLLog.log.info("Invalid recipe found with multiple oredict ingredients in the same ingredient..."); //TODO: Write a dumper? LOGGER.info("Invalid recipe found with multiple oredict ingredients in the same ingredient..."); //TODO: Write a dumper?
skip = true; skip = true;
break; break;
} }
@ -441,14 +439,14 @@ public class OreDictionary
if(DEBUG && replacedIngs.add(ing)) if(DEBUG && replacedIngs.add(ing))
{ {
String recipeName = obj.getRegistryName().getResourcePath(); String recipeName = obj.getRegistryName().getResourcePath();
FMLLog.log.debug("Replaced {} of the recipe \'{}\' with \"{}\".", ing.getMatchingStacks(), recipeName, oreName); LOGGER.debug("Replaced {} of the recipe \'{}\' with \"{}\".", ing.getMatchingStacks(), recipeName, oreName);
} }
} }
} }
} }
} }
FMLLog.log.info("Replaced {} ore ingredients", replaced); LOGGER.info("Replaced {} ore ingredients", replaced);
} }
/** /**
@ -504,7 +502,7 @@ public class OreDictionary
int id; int id;
if (registryName == null) if (registryName == null)
{ {
FMLLog.log.debug("Attempted to find the oreIDs for an unregistered object ({}). This won't work very well.", stack); LOGGER.debug("Attempted to find the oreIDs for an unregistered object ({}). This won't work very well.", stack);
return new int[0]; return new int[0];
} }
else else
@ -736,7 +734,7 @@ public class OreDictionary
int hash; int hash;
if (name == null) if (name == null)
{ {
FMLLog.log.debug("Defaulting unregistered ore dictionary entry for ore dictionary {}: type {} to -1", getOreName(id), ore.getItem().getClass()); LOGGER.debug("Defaulting unregistered ore dictionary entry for ore dictionary {}: type {} to -1", getOreName(id), ore.getItem().getClass());
hash = -1; hash = -1;
} }
else else

View file

@ -18,7 +18,7 @@
*/ */
package net.minecraftforge.oredict; package net.minecraftforge.oredict;
/*
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -30,7 +30,7 @@ import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient; import net.minecraft.item.crafting.Ingredient;
import net.minecraft.util.NonNullList; import net.minecraft.util.NonNullList;
*/
public class OreIngredient //extends Ingredient public class OreIngredient //extends Ingredient
{ {
/* /*

View file

@ -18,7 +18,7 @@
*/ */
package net.minecraftforge.oredict; package net.minecraftforge.oredict;
/*
import java.util.List; import java.util.List;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.client.util.RecipeItemHelper; import net.minecraft.client.util.RecipeItemHelper;
@ -42,7 +42,7 @@ import com.google.common.collect.Lists;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParseException; import com.google.gson.JsonParseException;
*/
public class ShapelessOreRecipe {} /*extends IForgeRegistryEntry.Impl<IRecipe> implements IRecipe public class ShapelessOreRecipe {} /*extends IForgeRegistryEntry.Impl<IRecipe> implements IRecipe
{ {
@Nonnull @Nonnull

View file

@ -22,6 +22,7 @@ package net.minecraftforge.registries;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.init.Bootstrap; import net.minecraft.init.Bootstrap;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.IRecipe;
@ -50,10 +51,9 @@ public class ForgeRegistries
public static final IForgeRegistry<PotionType> POTION_TYPES = RegistryManager.ACTIVE.getRegistry(PotionType.class); public static final IForgeRegistry<PotionType> POTION_TYPES = RegistryManager.ACTIVE.getRegistry(PotionType.class);
public static final IForgeRegistry<Enchantment> ENCHANTMENTS = RegistryManager.ACTIVE.getRegistry(Enchantment.class); public static final IForgeRegistry<Enchantment> ENCHANTMENTS = RegistryManager.ACTIVE.getRegistry(Enchantment.class);
public static final IForgeRegistry<VillagerProfession> VILLAGER_PROFESSIONS = RegistryManager.ACTIVE.getRegistry(VillagerProfession.class); public static final IForgeRegistry<VillagerProfession> VILLAGER_PROFESSIONS = RegistryManager.ACTIVE.getRegistry(VillagerProfession.class);
public static final IForgeRegistry<EntityEntry> ENTITIES = RegistryManager.ACTIVE.getRegistry(EntityEntry.class); public static final IForgeRegistry<EntityType<?>> ENTITIES = RegistryManager.ACTIVE.getRegistry(EntityType.class);
public static final IForgeRegistry<IRecipe> RECIPES = RegistryManager.ACTIVE.getRegistry(IRecipe.class); public static final IForgeRegistry<IRecipe> RECIPES = RegistryManager.ACTIVE.getRegistry(IRecipe.class);
/** /**
* This function is just to make sure static inializers in other classes have run and setup their registries before we query them. * This function is just to make sure static inializers in other classes have run and setup their registries before we query them.
*/ */

View file

@ -28,6 +28,7 @@ import net.minecraft.block.BlockAir;
import net.minecraft.block.material.Material; import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.EntityType;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemBlock;
import net.minecraft.potion.Potion; import net.minecraft.potion.Potion;
@ -42,6 +43,7 @@ import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.event.RegistryEvent.MissingMappings; import net.minecraftforge.event.RegistryEvent.MissingMappings;
import net.minecraftforge.fml.common.EnhancedRuntimeException; import net.minecraftforge.fml.common.EnhancedRuntimeException;
import net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession;
import net.minecraftforge.fml.ModThreadContext; import net.minecraftforge.fml.ModThreadContext;
import net.minecraftforge.fml.StartupQuery; import net.minecraftforge.fml.StartupQuery;
@ -127,8 +129,9 @@ public class GameData
makeRegistry(POTIONTYPES, PotionType.class, MAX_POTIONTYPE_ID, new ResourceLocation("empty")).create(); makeRegistry(POTIONTYPES, PotionType.class, MAX_POTIONTYPE_ID, new ResourceLocation("empty")).create();
makeRegistry(ENCHANTMENTS, Enchantment.class, MAX_ENCHANTMENT_ID).create(); makeRegistry(ENCHANTMENTS, Enchantment.class, MAX_ENCHANTMENT_ID).create();
// makeRegistry(RECIPES, IRecipe.class, MAX_RECIPE_ID).disableSaving().allowModification().addCallback(RecipeCallbacks.INSTANCE).create(); // makeRegistry(RECIPES, IRecipe.class, MAX_RECIPE_ID).disableSaving().allowModification().addCallback(RecipeCallbacks.INSTANCE).create();
// makeRegistry(PROFESSIONS, VillagerProfession.class, MAX_PROFESSION_ID).create(); makeRegistry(PROFESSIONS, VillagerProfession.class, MAX_PROFESSION_ID).create();
// entityRegistry = (ForgeRegistry<EntityEntry>)makeRegistry(ENTITIES, EntityEntry.class, MAX_ENTITY_ID).addCallback(EntityCallbacks.INSTANCE).create(); // TODO do we need the callback and the static field anymore?
makeRegistry(ENTITIES, EntityType.class, MAX_ENTITY_ID).create();
} }
private static <T extends IForgeRegistryEntry<T>> RegistryBuilder<T> makeRegistry(ResourceLocation name, Class<T> type, int min, int max) private static <T extends IForgeRegistryEntry<T>> RegistryBuilder<T> makeRegistry(ResourceLocation name, Class<T> type, int min, int max)

View file

@ -46,7 +46,7 @@ public enum ObjectHolderRegistry
INSTANCE; INSTANCE;
private static final Logger LOGGER = LogManager.getLogger(); private static final Logger LOGGER = LogManager.getLogger();
private List<ObjectHolderRef> objectHolders = Lists.newArrayList(); private List<ObjectHolderRef> objectHolders = Lists.newArrayList();
/* TODO annotation data
public void findObjectHolders(ASMDataTable table) public void findObjectHolders(ASMDataTable table)
{ {
LOGGER.info("Processing ObjectHolder annotations"); LOGGER.info("Processing ObjectHolder annotations");
@ -69,7 +69,7 @@ public enum ObjectHolderRegistry
}); });
LOGGER.info("Found {} ObjectHolder annotations", objectHolders.size()); LOGGER.info("Found {} ObjectHolder annotations", objectHolders.size());
} }
*/
private void scanTarget(Map<String, String> classModIds, Map<String, Class<?>> classCache, String className, @Nullable String annotationTarget, String value, boolean isClass, boolean extractFromValue) private void scanTarget(Map<String, String> classModIds, Map<String, Class<?>> classCache, String className, @Nullable String annotationTarget, String value, boolean isClass, boolean extractFromValue)
{ {
Class<?> clazz; Class<?> clazz;

View file

@ -41,12 +41,12 @@ public class TextComponentHelper
{ {
if (isVanillaClient(source)) if (isVanillaClient(source))
{ {
return new TextComponentString(LanguageMap.getInstance().translateKey(translation, args)); return new TextComponentString(String.format(LanguageMap.getInstance().translateKey(translation), args));
} }
return new TextComponentTranslation(translation, args); return new TextComponentTranslation(translation, args);
} }
private static boolean isVanillaClient(ICommandSender sender) private static boolean isVanillaClient(ICommandSource sender)
{ {
if (sender instanceof EntityPlayerMP) if (sender instanceof EntityPlayerMP)
{ {

View file

@ -22,8 +22,10 @@ package net.minecraftforge.server.console;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import java.util.List; import java.util.List;
import java.util.Collections;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@ -60,7 +62,7 @@ final class ConsoleCommandCompleter implements Completer
} }
final String input = buffer; final String input = buffer;
Future<List<String>> tabComplete = this.server.callFromMainThread(() -> this.server.getTabCompletions(this.server, input, this.server.getPosition(), false)); Future<List<String>> tabComplete = new FutureTask<>(() -> Collections.emptyList());// TODO commands this.server.callFromMainThread(() -> this.server.getTabCompletions(this.server, input, this.server.getPosition(), false));
try try
{ {

View file

@ -71,9 +71,9 @@ public final class TerminalHandler
line = line.trim(); line = line.trim();
if (!line.isEmpty()) if (!line.isEmpty())
{ {/* TODO Commands
server.addPendingCommand(line, server); server.addPendingCommand(line, server);
} */}
} }
} }
catch (UserInterruptException e) catch (UserInterruptException e)

View file

@ -21,7 +21,6 @@ package net.minecraftforge.server.permission;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.server.permission.context.IContext; import net.minecraftforge.server.permission.context.IContext;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -72,7 +71,7 @@ public enum DefaultPermissionHandler implements IPermissionHandler
return true; return true;
} }
MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); MinecraftServer server = null; // TODO FMLCommonHandler FMLCommonHandler.instance().getMinecraftServerInstance();
return server != null && server.getPlayerList().canSendCommands(profile); return server != null && server.getPlayerList().canSendCommands(profile);
} }

View file

@ -22,15 +22,18 @@ package net.minecraftforge.server.permission;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.server.permission.context.IContext; import net.minecraftforge.server.permission.context.IContext;
import net.minecraftforge.server.permission.context.PlayerContext; import net.minecraftforge.server.permission.context.PlayerContext;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class PermissionAPI public class PermissionAPI
{ {
private static final Logger LOGGER = LogManager.getLogger();
private static IPermissionHandler permissionHandler = DefaultPermissionHandler.INSTANCE; private static IPermissionHandler permissionHandler = DefaultPermissionHandler.INSTANCE;
/** /**
@ -39,8 +42,8 @@ public class PermissionAPI
public static void setPermissionHandler(IPermissionHandler handler) public static void setPermissionHandler(IPermissionHandler handler)
{ {
Preconditions.checkNotNull(handler, "Permission handler can't be null!"); Preconditions.checkNotNull(handler, "Permission handler can't be null!");
Preconditions.checkState(Loader.instance().getLoaderState().ordinal() <= LoaderState.PREINITIALIZATION.ordinal(), "Can't register after IPermissionHandler PreInit!"); // TODO Loader states Preconditions.checkState(Loader.instance().getLoaderState().ordinal() <= LoaderState.PREINITIALIZATION.ordinal(), "Can't register after IPermissionHandler PreInit!");
FMLLog.log.warn("Replacing {} with {}", permissionHandler.getClass().getName(), handler.getClass().getName()); LOGGER.warn("Replacing {} with {}", permissionHandler.getClass().getName(), handler.getClass().getName());
permissionHandler = handler; permissionHandler = handler;
} }
@ -62,7 +65,7 @@ public class PermissionAPI
Preconditions.checkNotNull(level, "Permission level can't be null!"); Preconditions.checkNotNull(level, "Permission level can't be null!");
Preconditions.checkNotNull(desc, "Permission description can't be null!"); Preconditions.checkNotNull(desc, "Permission description can't be null!");
Preconditions.checkArgument(!node.isEmpty(), "Permission node can't be empty!"); Preconditions.checkArgument(!node.isEmpty(), "Permission node can't be empty!");
Preconditions.checkState(Loader.instance().getLoaderState().ordinal() > LoaderState.PREINITIALIZATION.ordinal(), "Can't register permission nodes before Init!"); // TODO Loader states Preconditions.checkState(Loader.instance().getLoaderState().ordinal() > LoaderState.PREINITIALIZATION.ordinal(), "Can't register permission nodes before Init!");
permissionHandler.registerNode(node, level, desc); permissionHandler.registerNode(node, level, desc);
return node; return node;
} }