Death to the old energy value registry - long live the new one!

This commit is contained in:
Pahimar 2016-05-18 13:53:13 -04:00
parent 209c18da21
commit 2569e1db9a
39 changed files with 871 additions and 1998 deletions

View file

@ -2,9 +2,7 @@ package com.pahimar.ee3;
import com.pahimar.ee3.array.AlchemyArrayRegistry; import com.pahimar.ee3.array.AlchemyArrayRegistry;
import com.pahimar.ee3.command.CommandEE; import com.pahimar.ee3.command.CommandEE;
import com.pahimar.ee3.exchange.CachedOreDictionary;
import com.pahimar.ee3.exchange.EnergyValueRegistry; import com.pahimar.ee3.exchange.EnergyValueRegistry;
import com.pahimar.ee3.exchange.NewEnergyValueRegistry;
import com.pahimar.ee3.handler.*; import com.pahimar.ee3.handler.*;
import com.pahimar.ee3.init.*; import com.pahimar.ee3.init.*;
import com.pahimar.ee3.knowledge.AbilityRegistry; import com.pahimar.ee3.knowledge.AbilityRegistry;
@ -116,17 +114,14 @@ public class EquivalentExchange3
@EventHandler @EventHandler
public void postInit(FMLPostInitializationEvent event) public void postInit(FMLPostInitializationEvent event)
{ {
CachedOreDictionary.getInstance(); Abilities.init();
Abilities.initNotLearnables();
} }
@EventHandler @EventHandler
public void onServerStopping(FMLServerStoppingEvent event) public void onServerStopping(FMLServerStoppingEvent event)
{ {
WorldEventHandler.hasInitilialized = false; WorldEventHandler.hasInitilialized = false;
EnergyValueRegistry.INSTANCE.save();
EnergyValueRegistry.getInstance().save();
NewEnergyValueRegistry.INSTANCE.save();
TransmutationKnowledgeRegistry.getInstance().clear(); TransmutationKnowledgeRegistry.getInstance().clear();
AbilityRegistry.getInstance().save(); AbilityRegistry.getInstance().save();
} }
@ -146,9 +141,9 @@ public class EquivalentExchange3
} }
} }
public NewEnergyValueRegistry getEnergyValueRegistry() public EnergyValueRegistry getEnergyValueRegistry()
{ {
return NewEnergyValueRegistry.INSTANCE; return EnergyValueRegistry.INSTANCE;
} }
public RecipeRegistry getRecipeRegistry() public RecipeRegistry getRecipeRegistry()

View file

@ -73,15 +73,24 @@ public final class EnergyValueRegistryProxy {
} }
public static void setEnergyValue(Object object, Number energyValue) { public static void setEnergyValue(Object object, Number energyValue) {
setEnergyValue(object, new EnergyValue(energyValue), Phase.POST_CALCULATION);
}
public static void setEnergyValue(Object object, EnergyValue energyValue) {
setEnergyValue(object, energyValue, Phase.POST_CALCULATION); setEnergyValue(object, energyValue, Phase.POST_CALCULATION);
} }
public static void setEnergyValue(Object object, Number energyValue, Phase phase) { public static void setEnergyValue(Object object, Number energyValue, Phase phase) {
setEnergyValue(object, new EnergyValue(energyValue), phase);
}
public static void setEnergyValue(Object object, EnergyValue energyValue, Phase phase) {
init(); init();
if (ee3Mod != null) { if (ee3Mod != null) {
EE3Wrapper.ee3mod.getEnergyValueRegistry().setEnergyValue(object, new EnergyValue(energyValue), phase); EE3Wrapper.ee3mod.getEnergyValueRegistry().setEnergyValue(object, energyValue, phase);
} }
} }
@ -97,10 +106,7 @@ public final class EnergyValueRegistryProxy {
} }
public enum Phase { public enum Phase {
@Deprecated PRE_ASSIGNMENT,
PRE_CALCULATION, PRE_CALCULATION,
@Deprecated POST_ASSIGNMENT, POST_CALCULATION
POST_CALCULATION,
ALL
} }
} }

View file

@ -1,14 +1,10 @@
package com.pahimar.ee3.command; package com.pahimar.ee3.command;
import com.pahimar.ee3.api.exchange.EnergyValue; import com.pahimar.ee3.api.exchange.EnergyValue;
import com.pahimar.ee3.exchange.EnergyValueRegistry; import com.pahimar.ee3.api.exchange.EnergyValueRegistryProxy;
import com.pahimar.ee3.exchange.WrappedStack; import com.pahimar.ee3.exchange.WrappedStack;
import com.pahimar.ee3.network.PacketHandler;
import com.pahimar.ee3.network.message.MessageSetEnergyValue;
import com.pahimar.ee3.reference.Files;
import com.pahimar.ee3.reference.Messages; import com.pahimar.ee3.reference.Messages;
import com.pahimar.ee3.reference.Names; import com.pahimar.ee3.reference.Names;
import com.pahimar.ee3.util.SerializationHelper;
import net.minecraft.command.CommandBase; import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender; import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException; import net.minecraft.command.WrongUsageException;
@ -19,7 +15,6 @@ import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import java.util.List; import java.util.List;
import java.util.Map;
public class CommandSetEnergyValue extends CommandBase public class CommandSetEnergyValue extends CommandBase
{ {
@ -93,46 +88,13 @@ public class CommandSetEnergyValue extends CommandBase
if (wrappedStack != null && newEnergyValue != null && Float.compare(newEnergyValue.getValue(), 0) > 0) if (wrappedStack != null && newEnergyValue != null && Float.compare(newEnergyValue.getValue(), 0) > 0)
{ {
if (args[1].equalsIgnoreCase("pre")) if (args[1].equalsIgnoreCase("pre")) {
{ EnergyValueRegistryProxy.setEnergyValue(wrappedStack, newEnergyValue, EnergyValueRegistryProxy.Phase.PRE_CALCULATION);
EnergyValueRegistry.getInstance().setEnergyValue(wrappedStack, newEnergyValue);
Map<WrappedStack, EnergyValue> preAssignedValues = SerializationHelper.readEnergyValueStackMapFromJsonFile(Files.PRE_CALCULATION_ENERGY_VALUES);
preAssignedValues.put(wrappedStack, newEnergyValue);
SerializationHelper.writeEnergyValueStackMapToJsonFile(Files.PRE_CALCULATION_ENERGY_VALUES, preAssignedValues);
EnergyValueRegistry.getInstance().setShouldRegenNextRestart(true);
} }
else if (args[1].equalsIgnoreCase("global-pre")) else if (args[1].equalsIgnoreCase("post")) {
{ EnergyValueRegistryProxy.setEnergyValue(wrappedStack, newEnergyValue);
EnergyValueRegistry.getInstance().setEnergyValue(wrappedStack, newEnergyValue);
Map<WrappedStack, EnergyValue> preAssignedValues = SerializationHelper.readEnergyValueStackMapFromJsonFile(Files.Global.preCalcluationEnergyValueFile);
preAssignedValues.put(wrappedStack, newEnergyValue);
SerializationHelper.writeEnergyValueStackMapToJsonFile(Files.Global.preCalcluationEnergyValueFile, preAssignedValues);
EnergyValueRegistry.getInstance().setShouldRegenNextRestart(true);
} }
else if (args[1].equalsIgnoreCase("post")) else {
{
EnergyValueRegistry.getInstance().setEnergyValue(wrappedStack, newEnergyValue);
Map<WrappedStack, EnergyValue> postAssignedValues = SerializationHelper.readEnergyValueStackMapFromJsonFile(Files.POST_CALCULATION_ENERGY_VALUES);
postAssignedValues.put(wrappedStack, newEnergyValue);
SerializationHelper.writeEnergyValueStackMapToJsonFile(Files.POST_CALCULATION_ENERGY_VALUES, postAssignedValues);
PacketHandler.INSTANCE.sendToAll(new MessageSetEnergyValue(wrappedStack, newEnergyValue));
}
else if (args[1].equalsIgnoreCase("global-post"))
{
EnergyValueRegistry.getInstance().setEnergyValue(wrappedStack, newEnergyValue);
Map<WrappedStack, EnergyValue> postAssignedValues = SerializationHelper.readEnergyValueStackMapFromJsonFile(Files.Global.postCalcluationEnergyValueFile);
postAssignedValues.put(wrappedStack, newEnergyValue);
SerializationHelper.writeEnergyValueStackMapToJsonFile(Files.Global.postCalcluationEnergyValueFile, postAssignedValues);
PacketHandler.INSTANCE.sendToAll(new MessageSetEnergyValue(wrappedStack, newEnergyValue));
}
else
{
throw new WrongUsageException(Messages.Commands.SET_ENERGY_VALUE_USAGE); throw new WrongUsageException(Messages.Commands.SET_ENERGY_VALUE_USAGE);
} }
@ -151,7 +113,7 @@ public class CommandSetEnergyValue extends CommandBase
{ {
if (args.length == 2) if (args.length == 2)
{ {
return getListOfStringsMatchingLastWord(args, "pre", "global-pre", "post", "global-post"); return getListOfStringsMatchingLastWord(args, "pre", "post");
} }
else if (args.length == 3) else if (args.length == 3)
{ {

View file

@ -1,14 +1,10 @@
package com.pahimar.ee3.command; package com.pahimar.ee3.command;
import com.pahimar.ee3.api.exchange.EnergyValue; import com.pahimar.ee3.api.exchange.EnergyValue;
import com.pahimar.ee3.exchange.EnergyValueRegistry; import com.pahimar.ee3.api.exchange.EnergyValueRegistryProxy;
import com.pahimar.ee3.exchange.WrappedStack; import com.pahimar.ee3.exchange.WrappedStack;
import com.pahimar.ee3.network.PacketHandler;
import com.pahimar.ee3.network.message.MessageSetEnergyValue;
import com.pahimar.ee3.reference.Files;
import com.pahimar.ee3.reference.Messages; import com.pahimar.ee3.reference.Messages;
import com.pahimar.ee3.reference.Names; import com.pahimar.ee3.reference.Names;
import com.pahimar.ee3.util.SerializationHelper;
import net.minecraft.command.CommandBase; import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender; import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException; import net.minecraft.command.WrongUsageException;
@ -16,7 +12,6 @@ import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import java.util.List; import java.util.List;
import java.util.Map;
public class CommandSetEnergyValueCurrentItem extends CommandBase public class CommandSetEnergyValueCurrentItem extends CommandBase
{ {
@ -65,41 +60,11 @@ public class CommandSetEnergyValueCurrentItem extends CommandBase
{ {
if (args[1].equalsIgnoreCase("pre")) if (args[1].equalsIgnoreCase("pre"))
{ {
EnergyValueRegistry.getInstance().setEnergyValue(wrappedStack, newEnergyValue); EnergyValueRegistryProxy.setEnergyValue(wrappedStack, newEnergyValue, EnergyValueRegistryProxy.Phase.PRE_CALCULATION);
Map<WrappedStack, EnergyValue> preAssignedValues = SerializationHelper.readEnergyValueStackMapFromJsonFile(Files.PRE_CALCULATION_ENERGY_VALUES);
preAssignedValues.put(wrappedStack, newEnergyValue);
SerializationHelper.writeEnergyValueStackMapToJsonFile(Files.PRE_CALCULATION_ENERGY_VALUES, preAssignedValues);
EnergyValueRegistry.getInstance().setShouldRegenNextRestart(true);
}
else if (args[1].equalsIgnoreCase("global-pre"))
{
EnergyValueRegistry.getInstance().setEnergyValue(wrappedStack, newEnergyValue);
Map<WrappedStack, EnergyValue> preAssignedValues = SerializationHelper.readEnergyValueStackMapFromJsonFile(Files.Global.preCalcluationEnergyValueFile);
preAssignedValues.put(wrappedStack, newEnergyValue);
SerializationHelper.writeEnergyValueStackMapToJsonFile(Files.Global.preCalcluationEnergyValueFile, preAssignedValues);
EnergyValueRegistry.getInstance().setShouldRegenNextRestart(true);
} }
else if (args[1].equalsIgnoreCase("post")) else if (args[1].equalsIgnoreCase("post"))
{ {
EnergyValueRegistry.getInstance().setEnergyValue(wrappedStack, newEnergyValue); EnergyValueRegistryProxy.setEnergyValue(wrappedStack, newEnergyValue);
Map<WrappedStack, EnergyValue> postAssignedValues = SerializationHelper.readEnergyValueStackMapFromJsonFile(Files.POST_CALCULATION_ENERGY_VALUES);
postAssignedValues.put(wrappedStack, newEnergyValue);
SerializationHelper.writeEnergyValueStackMapToJsonFile(Files.POST_CALCULATION_ENERGY_VALUES, postAssignedValues);
PacketHandler.INSTANCE.sendToAll(new MessageSetEnergyValue(wrappedStack, newEnergyValue));
}
else if (args[1].equalsIgnoreCase("global-post"))
{
EnergyValueRegistry.getInstance().setEnergyValue(wrappedStack, newEnergyValue);
Map<WrappedStack, EnergyValue> postAssignedValues = SerializationHelper.readEnergyValueStackMapFromJsonFile(Files.Global.postCalcluationEnergyValueFile);
postAssignedValues.put(wrappedStack, newEnergyValue);
SerializationHelper.writeEnergyValueStackMapToJsonFile(Files.Global.postCalcluationEnergyValueFile, postAssignedValues);
PacketHandler.INSTANCE.sendToAll(new MessageSetEnergyValue(wrappedStack, newEnergyValue));
} }
else else
{ {
@ -126,7 +91,7 @@ public class CommandSetEnergyValueCurrentItem extends CommandBase
{ {
if (args.length == 2) if (args.length == 2)
{ {
return getListOfStringsMatchingLastWord(args, "pre", "global-pre", "post", "global-post"); return getListOfStringsMatchingLastWord(args, "pre", "post");
} }
return null; return null;

View file

@ -68,7 +68,7 @@ public class CommandSyncEnergyValues extends CommandBase
if (shouldSync) if (shouldSync)
{ {
LogHelper.info(EnergyValueRegistry.ENERGY_VALUE_MARKER, "Syncing energy values with player '{}' at their request", commandSender.getCommandSenderName()); LogHelper.info(EnergyValueRegistry.ENERGY_VALUE_MARKER, "Syncing energy values with player '{}' at their request", commandSender.getCommandSenderName());
PacketHandler.INSTANCE.sendTo(new MessageSyncEnergyValues(EnergyValueRegistry.getInstance()), (EntityPlayerMP) commandSender); PacketHandler.INSTANCE.sendTo(new MessageSyncEnergyValues(), (EntityPlayerMP) commandSender);
commandSender.addChatMessage(new ChatComponentTranslation(Messages.Commands.SYNC_ENERGY_VALUES_SUCCESS)); commandSender.addChatMessage(new ChatComponentTranslation(Messages.Commands.SYNC_ENERGY_VALUES_SUCCESS));
} }
else else

View file

@ -1,100 +0,0 @@
package com.pahimar.ee3.exchange;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
import com.pahimar.ee3.reference.Comparators;
import com.pahimar.ee3.util.LogHelper;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import java.util.*;
public class CachedOreDictionary
{
private static CachedOreDictionary cachedOreDictionary = null;
private ImmutableMap<Integer, String> idToNameMap;
private ImmutableMap<String, List<ItemStack>> oreNameToItemStackMap;
private ImmutableMultimap<WrappedStack, String> itemStackToOreNameMap;
private CachedOreDictionary()
{
Map<Integer, String> idToOreNameMap = new TreeMap<Integer, String>();
Map<String, List<ItemStack>> nameToStackMap = new TreeMap<String, List<ItemStack>>(Comparators.stringComparator);
Multimap<WrappedStack, String> stackToNameMultiMap = TreeMultimap.create(WrappedStack.comparator, Comparators.stringComparator);
for (String oreName : OreDictionary.getOreNames())
{
idToOreNameMap.put(OreDictionary.getOreID(oreName), oreName);
List<ItemStack> oreNameItemStacks = OreDictionary.getOres(oreName);
nameToStackMap.put(oreName, oreNameItemStacks);
for (ItemStack itemStack : oreNameItemStacks)
{
stackToNameMultiMap.put(WrappedStack.wrap(itemStack), oreName);
}
}
idToNameMap = ImmutableMap.copyOf(idToOreNameMap);
oreNameToItemStackMap = ImmutableMap.copyOf(nameToStackMap);
itemStackToOreNameMap = ImmutableMultimap.copyOf(stackToNameMultiMap);
}
public static CachedOreDictionary getInstance()
{
if (cachedOreDictionary == null)
{
cachedOreDictionary = new CachedOreDictionary();
}
return cachedOreDictionary;
}
public Set<String> getOreNames()
{
return oreNameToItemStackMap.keySet();
}
public List<ItemStack> getItemStacksForOreName(String oreName)
{
if (oreNameToItemStackMap.containsKey(oreName))
{
return oreNameToItemStackMap.get(oreName);
}
return new ArrayList<ItemStack>();
}
public List<String> getOreNamesForItemStack(ItemStack itemStack)
{
List<String> oreNameList = new ArrayList<String>();
WrappedStack wrappedStack = WrappedStack.wrap(itemStack);
if (itemStackToOreNameMap.containsKey(wrappedStack))
{
for (String oreName : itemStackToOreNameMap.get(wrappedStack))
{
oreNameList.add(oreName);
}
}
else
{
for (WrappedStack wrappedStack1 : itemStackToOreNameMap.keySet())
{
}
}
return oreNameList;
}
public void dumpCachedOreDictionaryToLog()
{
for (String oreName : CachedOreDictionary.getInstance().getOreNames())
{
LogHelper.info("OreName: {}, ItemStacks: {}", oreName, CachedOreDictionary.getInstance().getItemStacksForOreName(oreName));
}
}
}

View file

@ -1,28 +0,0 @@
package com.pahimar.ee3.exchange;
import com.pahimar.ee3.recipe.AludelRecipeManager;
import com.pahimar.ee3.recipe.RecipeRegistry;
import com.pahimar.ee3.util.LogHelper;
public class DynamicEnergyValueInitThread implements Runnable
{
private static DynamicEnergyValueInitThread instance = new DynamicEnergyValueInitThread();
public static void initEnergyValueRegistry()
{
new Thread(instance, "DynamicEMC Thread").start();
}
@Override
public void run()
{
// Add in recipes to the RecipeRegistry *just* before we do calculations
RecipeRegistry.getInstance().registerVanillaRecipes();
AludelRecipeManager.registerRecipes();
long startTime = System.nanoTime();
// EnergyValueRegistry.getInstance().init();
NewEnergyValueRegistry.INSTANCE.compute();
LogHelper.info(EnergyValueRegistry.ENERGY_VALUE_MARKER, "DynamicEMC system initialized after {} ms", System.nanoTime() - startTime);
}
}

File diff suppressed because it is too large Load diff

View file

@ -5,6 +5,7 @@ import com.pahimar.ee3.api.exchange.EnergyValue;
import java.lang.reflect.Type; import java.lang.reflect.Type;
@Deprecated
public class EnergyValueStackMapping implements JsonSerializer<EnergyValueStackMapping>, JsonDeserializer<EnergyValueStackMapping> public class EnergyValueStackMapping implements JsonSerializer<EnergyValueStackMapping>, JsonDeserializer<EnergyValueStackMapping>
{ {
public static final Gson jsonSerializer = (new GsonBuilder()).setPrettyPrinting().registerTypeAdapter(EnergyValueStackMapping.class, new EnergyValueStackMapping()).registerTypeAdapter(EnergyValue.class, new EnergyValue()).registerTypeAdapter(WrappedStack.class, new WrappedStack()).create(); public static final Gson jsonSerializer = (new GsonBuilder()).setPrettyPrinting().registerTypeAdapter(EnergyValueStackMapping.class, new EnergyValueStackMapping()).registerTypeAdapter(EnergyValue.class, new EnergyValue()).registerTypeAdapter(WrappedStack.class, new WrappedStack()).create();

View file

@ -11,6 +11,7 @@ import net.minecraftforge.fluids.FluidStack;
import java.lang.reflect.Type; import java.lang.reflect.Type;
@Deprecated
public class JsonFluidStack implements JsonSerializer<JsonFluidStack>, JsonDeserializer<JsonFluidStack> public class JsonFluidStack implements JsonSerializer<JsonFluidStack>, JsonDeserializer<JsonFluidStack>
{ {
public static final Gson jsonSerializer = (new GsonBuilder()).registerTypeAdapter(JsonFluidStack.class, new JsonFluidStack()).create(); public static final Gson jsonSerializer = (new GsonBuilder()).registerTypeAdapter(JsonFluidStack.class, new JsonFluidStack()).create();

View file

@ -10,6 +10,7 @@ import net.minecraft.nbt.NBTTagCompound;
import java.lang.reflect.Type; import java.lang.reflect.Type;
@Deprecated
public class JsonItemStack implements JsonSerializer<JsonItemStack>, JsonDeserializer<JsonItemStack> public class JsonItemStack implements JsonSerializer<JsonItemStack>, JsonDeserializer<JsonItemStack>
{ {
public static final Gson jsonSerializer = (new GsonBuilder()).registerTypeAdapter(JsonItemStack.class, new JsonItemStack()).create(); public static final Gson jsonSerializer = (new GsonBuilder()).registerTypeAdapter(JsonItemStack.class, new JsonItemStack()).create();

View file

@ -1,726 +0,0 @@
package com.pahimar.ee3.exchange;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.gson.JsonParseException;
import com.pahimar.ee3.api.event.EnergyValueEvent;
import com.pahimar.ee3.api.exchange.EnergyValue;
import com.pahimar.ee3.api.exchange.IEnergyValueProvider;
import com.pahimar.ee3.handler.ConfigurationHandler;
import com.pahimar.ee3.recipe.RecipeRegistry;
import com.pahimar.ee3.util.LogHelper;
import com.pahimar.ee3.util.SerializationHelper;
import cpw.mods.fml.common.FMLCommonHandler;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.oredict.OreDictionary;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import java.io.*;
import java.util.*;
import static com.pahimar.ee3.api.exchange.EnergyValueRegistryProxy.Phase;
public class NewEnergyValueRegistry {
public static final NewEnergyValueRegistry INSTANCE = new NewEnergyValueRegistry();
private ImmutableSortedMap<WrappedStack, EnergyValue> stackValueMap;
private ImmutableSortedMap<EnergyValue, List<WrappedStack>> valueStackMap;
private final Map<WrappedStack, EnergyValue> preCalculationStackValueMap;
private final Map<WrappedStack, EnergyValue> postCalculationStackValueMap;
private transient SortedSet<WrappedStack> uncomputedStacks;
public static File energyValuesDirectory;
public static File energyValuesFile;
public static File preCalculationValuesFile;
public static File postCalculationValuesFile;
public static final Marker ENERGY_VALUE_MARKER = MarkerManager.getMarker("EE3_ENERGY_VALUE", LogHelper.MOD_MARKER);
private NewEnergyValueRegistry() {
ImmutableSortedMap.Builder<WrappedStack, EnergyValue> stackMapBuilder = ImmutableSortedMap.naturalOrder();
stackValueMap = stackMapBuilder.build();
preCalculationStackValueMap = new TreeMap<>();
postCalculationStackValueMap = new TreeMap<>();
uncomputedStacks = new TreeSet<>();
}
/**
* Returns an {@link EnergyValue} for a {@link Object} in the provided {@link Map>} of {@link WrappedStack}s mapped
* to EnergyValues
*
* <p>The order of checking is as follows;</p>
* <ol>
* <li>{@link ItemStack}s whose {@link Item}s implement {@link IEnergyValueProvider}</li>
* <li>Direct EnergyValue mapping of the provided Object in the provided Map</li>
* <li>The following criteria are only checked (in order) in the event that this is a non-strict query;
* <ol>
* <li>
* ItemStacks that are part of an {@link OreDictionary} entry are checked to see if
* <strong>all</strong> Ores they are registered to have the same non-null EnergyValue assigned to
* it
* <ul>
* <li>
* e.g., ItemStack X is associated with OreDictionary entries A, B and C. An EnergyValue
* would be returned for X only if A, B and C all had the same non-null EnergyValue
* </li>
* </ul>
* </li>
* <li>
* ItemStacks are checked to see if there exist {@link OreDictionary#WILDCARD_VALUE} equivalents
* </li>
* <li>
* {@link OreStack}s are checked to see if all members of the OreDictionary entry represented by the
* OreStack have the same non-null EnergyValue (similar to the case for ItemStacks above)
* </li>
* </ol>
* </li>
* </ol>
*
* @param valueMap a {@link Map} of {@link EnergyValue}'s mapped to {@link WrappedStack}'s
* @param object the {@link Object} that is being checked for a corresponding {@link EnergyValue}
* @param strict whether this is a strict (e.g., only looking for direct value assignment vs associative value
* assignments) query or not
* @return an {@link EnergyValue} if there is one to be found for the provided {@link Object} in the provided Map, null otherwise
*/
private static EnergyValue getEnergyValue(Map<WrappedStack, EnergyValue> valueMap, Object object, boolean strict) {
if (WrappedStack.canBeWrapped(object)) {
WrappedStack wrappedStack = WrappedStack.wrap(object, 1);
Object wrappedObject = wrappedStack.getWrappedObject();
if (wrappedObject instanceof ItemStack && ((ItemStack) wrappedObject).getItem() instanceof IEnergyValueProvider && !strict) {
EnergyValue energyValue = ((IEnergyValueProvider) ((ItemStack) wrappedObject).getItem()).getEnergyValue(((ItemStack) wrappedObject));
if (energyValue != null && Float.compare(energyValue.getValue(), 0f) > 0) {
return energyValue;
}
}
if (valueMap != null && !valueMap.isEmpty()) {
// First check for a direct energy value mapping to the wrapped object
if (valueMap.containsKey(wrappedStack)) {
return valueMap.get(wrappedStack);
}
else if (!strict) {
if (wrappedObject instanceof ItemStack) {
ItemStack unValuedItemStack = ItemStack.copyItemStack((ItemStack) wrappedObject);
EnergyValue minEnergyValue = null;
int[] oreIds = OreDictionary.getOreIDs(unValuedItemStack);
if (oreIds.length > 0) {
EnergyValue energyValue = null;
boolean allHaveSameValue = true;
for (int oreId : oreIds) {
String oreName = OreDictionary.getOreName(oreId);
if (!"Unknown".equalsIgnoreCase(oreName)) {
WrappedStack oreStack = WrappedStack.wrap(new OreStack(oreName));
if (oreStack != null && valueMap.containsKey(oreStack)) {
if (energyValue == null) {
energyValue = valueMap.get(oreStack);
}
else if (!energyValue.equals(valueMap.get(oreStack))) {
allHaveSameValue = false;
}
}
else {
allHaveSameValue = false;
}
}
else {
allHaveSameValue = false;
}
}
if (allHaveSameValue) {
return energyValue;
}
}
else {
for (WrappedStack valuedWrappedStack : valueMap.keySet()) {
if (valuedWrappedStack.getWrappedObject() instanceof ItemStack) {
if (Item.getIdFromItem(((ItemStack) valuedWrappedStack.getWrappedObject()).getItem()) == Item.getIdFromItem(unValuedItemStack.getItem())) {
ItemStack valuedItemStack = (ItemStack) valuedWrappedStack.getWrappedObject();
if (valuedItemStack.getItemDamage() == OreDictionary.WILDCARD_VALUE || unValuedItemStack.getItemDamage() == OreDictionary.WILDCARD_VALUE) {
EnergyValue energyValue = valueMap.get(valuedWrappedStack);
if (energyValue.compareTo(minEnergyValue) < 0) {
minEnergyValue = energyValue;
}
}
}
}
}
}
}
else if (wrappedObject instanceof OreStack) {
OreStack oreStack = (OreStack) wrappedObject;
List<ItemStack> itemStacks = OreDictionary.getOres(oreStack.oreName);
if (!itemStacks.isEmpty()) {
EnergyValue energyValue = null;
boolean allHaveSameValue = true;
for (ItemStack itemStack : itemStacks) {
WrappedStack wrappedItemStack = WrappedStack.wrap(itemStack, 1);
if (wrappedItemStack != null && valueMap.containsKey(wrappedItemStack)) {
if (energyValue == null) {
energyValue = valueMap.get(wrappedItemStack);
}
else if (!energyValue.equals(valueMap.get(wrappedItemStack))) {
allHaveSameValue = false;
}
}
else {
allHaveSameValue = false;
}
}
if (allHaveSameValue) {
return energyValue;
}
}
}
}
}
}
return null;
}
/**
* Calculates an {@link EnergyValue} for the provided {@link WrappedStack} output from the provided {@link List} of
* WrappedStack inputs and {@link Map} of energy value mappings to objects. We calculate the energy value for the
* output by, for each input, summing the input's energy value * the input's stack size. That sum is then divided
* by the stack size of the output. If <strong>any</strong> of the inputs do not have an energy value then no
* energy value can be calculated for the output - therefore we return null
*
* @param valueMap a {@link Map} of {@link EnergyValue}'s mapped to {@link WrappedStack}'s
* @param wrappedOutput the {@link WrappedStack} output for that the inputs "create"
* @param wrappedInputs a {@link List} of {@link WrappedStack}s that "create" the output
* @return an {@link EnergyValue} if there is one that can be calculated, null otherwise
*/
// TODO Make this private when EnergyValueRegistry is properly replaced
public static EnergyValue computeFromInputs(Map<WrappedStack, EnergyValue> valueMap, WrappedStack wrappedOutput, List<WrappedStack> wrappedInputs) {
float sumOfValues = 0f;
for (WrappedStack wrappedInput : wrappedInputs) {
EnergyValue inputValue;
int stackSize = Integer.MIN_VALUE;
if (wrappedInput.getWrappedObject() instanceof ItemStack) {
ItemStack inputItemStack = (ItemStack) wrappedInput.getWrappedObject();
// Check if we are dealing with a potential fluid
if (FluidContainerRegistry.getFluidForFilledItem(inputItemStack) != null) {
if (inputItemStack.getItem().getContainerItem(inputItemStack) != null) {
stackSize = FluidContainerRegistry.getFluidForFilledItem(inputItemStack).amount * wrappedInput.getStackSize();
inputValue = getEnergyValue(valueMap, FluidContainerRegistry.getFluidForFilledItem(inputItemStack), false);
}
else {
inputValue = getEnergyValue(valueMap, wrappedInput, false);
}
}
else if (inputItemStack.getItem().getContainerItem(inputItemStack) != null) {
ItemStack inputContainerItemStack = inputItemStack.getItem().getContainerItem(inputItemStack);
if (getEnergyValue(valueMap, inputItemStack, false) != null && getEnergyValue(valueMap, inputContainerItemStack, false) != null) {
float itemStackValue = getEnergyValue(valueMap, inputItemStack, false).getValue();
float containerStackValue = getEnergyValue(valueMap, inputContainerItemStack, false).getValue();
inputValue = new EnergyValue(itemStackValue - containerStackValue);
}
else {
inputValue = new EnergyValue(0);
}
}
else if (!inputItemStack.getItem().doesContainerItemLeaveCraftingGrid(inputItemStack)) {
inputValue = new EnergyValue(0);
}
else if (OreDictionary.getOreIDs(inputItemStack).length > 0) {
inputValue = getEnergyValue(valueMap, wrappedInput, true);
}
else {
inputValue = getEnergyValue(valueMap, wrappedInput, false);
}
}
else if (wrappedInput.getWrappedObject() instanceof OreStack) {
OreStack inputOreStack = (OreStack) wrappedInput.getWrappedObject();
inputValue = getEnergyValue(valueMap, wrappedInput, false);
for (ItemStack itemStack : OreDictionary.getOres(inputOreStack.oreName)) {
if (!itemStack.getItem().doesContainerItemLeaveCraftingGrid(itemStack)) {
inputValue = new EnergyValue(0);
}
}
}
else {
inputValue = getEnergyValue(valueMap, wrappedInput, false);
}
if (inputValue != null) {
if (stackSize == Integer.MIN_VALUE) {
stackSize = wrappedInput.getStackSize();
}
sumOfValues += inputValue.getValue() * stackSize;
}
else {
return null;
}
}
return EnergyValue.factor(new EnergyValue(sumOfValues), wrappedOutput.getStackSize());
}
/**
* Returns an {@link ImmutableMap} containing the current energy value mappings
*
* @return an {@link ImmutableMap} containing the current energy value mappings
*/
public ImmutableMap<WrappedStack, EnergyValue> getEnergyValues() {
return stackValueMap;
}
/**
* Returns a {@link Map} containing the pre-calculation energy value mappings
*
* @return a {link Map} containing the pre-calculation energy value mappings
*/
public Map<WrappedStack, EnergyValue> getPreCalculationStackValueMap() {
return preCalculationStackValueMap;
}
/**
* Returns a {@link Map} containing the post-calculation energy value mappings
*
* @return a {@link Map} containing the post-calculation energy value mappings
*/
public Map<WrappedStack, EnergyValue> getPostCalculationStackValueMap() {
return postCalculationStackValueMap;
}
/**
* Checks if there exists an {@link EnergyValue} associated with the provided {@link Object}.
*
* @param object the {@link Object} that is being checked for a corresponding {@link EnergyValue}
* @return true if the provided object has an energy value, false otherwise
*/
public boolean hasEnergyValue(Object object) {
return hasEnergyValue(object, false);
}
/**
* Checks if there exists an {@link EnergyValue} associated with the provided {@link Object}
*
* @param object the {@link Object} that is being checked for a corresponding {@link EnergyValue}
* @param strict whether this is a strict (e.g., only looking for direct value assignment vs associative value
* assignments) query or not
* @return true if the provided object has an energy value, false otherwise
*/
public boolean hasEnergyValue(Object object, boolean strict) {
return getEnergyValue(object, strict) != null;
}
/**
* Returns an {@link EnergyValue} associated with the provided {@link Object} (if there is one)
*
* @param object the {@link Object} that is being checked for a corresponding {@link EnergyValue}
* @return an {@link EnergyValue} if there is one to be found, null otherwise
*/
public EnergyValue getEnergyValue(Object object) {
return getEnergyValue(object, false);
}
/**
* Returns an {@link EnergyValue} associated with the provided {@link Object} (if there is one)
*
* @param object the {@link Object} that is being checked for a corresponding {@link EnergyValue}
* @param strict whether this is a strict (e.g., only looking for direct value assignment vs associative value
* assignments) query or not
* @return an {@link EnergyValue} if there is one to be found, null otherwise
*/
public EnergyValue getEnergyValue(Object object, boolean strict) {
return getEnergyValue(stackValueMap, object, strict);
}
/**
* Returns an {@link EnergyValue} associated with the provided {@link Object} (if there is one)
*
* @param object the {@link Object} that is being checked for a corresponding {@link EnergyValue}
* @param strict whether this is a strict (e.g., only looking for direct value assignment vs associative value
* assignments) query or not
* @return an {@link EnergyValue} if there is one to be found, null otherwise
*/
public EnergyValue getEnergyValueForStack(Object object, boolean strict) {
WrappedStack wrappedObject = WrappedStack.wrap(object);
if (wrappedObject != null && getEnergyValue(object, strict) != null) {
return new EnergyValue(getEnergyValue(object, strict).getValue() * wrappedObject.getStackSize());
}
return null;
}
/**
* TODO Finish JavaDoc
*
* @param start
* @param finish
* @return
*/
public List getStacksInRange(Number start, Number finish) {
return getStacksInRange(new EnergyValue(start), new EnergyValue(finish));
}
/**
* TODO Finish JavaDoc
*
* @param start
* @param finish
* @return
*/
public List getStacksInRange(EnergyValue start, EnergyValue finish) {
List stacksInRange = new ArrayList<WrappedStack>();
if (valueStackMap != null) {
SortedMap<EnergyValue, List<WrappedStack>> tailMap = valueStackMap.tailMap(start);
SortedMap<EnergyValue, List<WrappedStack>> headMap = valueStackMap.headMap(finish);
SortedMap<EnergyValue, List<WrappedStack>> smallerMap;
SortedMap<EnergyValue, List<WrappedStack>> biggerMap;
if (!tailMap.isEmpty() && !headMap.isEmpty()) {
if (tailMap.size() <= headMap.size()) {
smallerMap = tailMap;
biggerMap = headMap;
}
else {
smallerMap = headMap;
biggerMap = tailMap;
}
for (EnergyValue value : smallerMap.keySet()) {
if (biggerMap.containsKey(value)) {
for (WrappedStack wrappedStack : valueStackMap.get(value)) {
if (wrappedStack.getWrappedObject() instanceof ItemStack || wrappedStack.getWrappedObject() instanceof FluidStack) {
stacksInRange.add(wrappedStack.getWrappedObject());
}
else if (wrappedStack.getWrappedObject() instanceof OreStack) {
stacksInRange.addAll(OreDictionary.getOres(((OreStack) wrappedStack.getWrappedObject()).oreName));
}
}
}
}
}
}
return stacksInRange;
}
/**
* Sets an {@link EnergyValue} for the provided {@link Object} (if it can be wrapped in a {@link WrappedStack}.
* Depending on whether or not this is a pre-calculation value assignment it's also possible for the calculated
* energy value map to be recomputed to take into account the new mapping.
*
* @param object the object the energy value is being assigned for
* @param energyValue the energy value being setEnergyValue on the object
* @param phase the {@link Phase} of energy value assignment to set this value for
*/
public void setEnergyValue(Object object, EnergyValue energyValue, Phase phase) {
setEnergyValue(object, energyValue, phase, false);
}
/**
* Sets an {@link EnergyValue} for the provided {@link Object} (if it can be wrapped in a {@link WrappedStack}.
* Depending on whether or not this is a pre-calculation value assignment it's also possible for the calculated
* energy value map to be recomputed to take into account the new mapping.
*
* @param object the object the energy value is being assigned for
* @param energyValue the energy value being setEnergyValue on the object
* @param phase the {@link Phase} of energy value assignment to set this value for
* @param doRegenValues whether or not the energy value map needs recomputing. Only an option if the energy value
* is being assigned in the <code>PRE_CALCULATION</code> phase
*/
public void setEnergyValue(Object object, EnergyValue energyValue, Phase phase, boolean doRegenValues) {
if (WrappedStack.canBeWrapped(object) && energyValue != null && Float.compare(energyValue.getValue(), 0f) > 0) {
WrappedStack wrappedStack = WrappedStack.wrap(object, 1);
EnergyValue factoredEnergyValue = EnergyValue.factor(energyValue, wrappedStack.getStackSize());
if (phase == Phase.PRE_CALCULATION) {
if (!FMLCommonHandler.instance().bus().post(new EnergyValueEvent.SetEnergyValueEvent(wrappedStack, factoredEnergyValue, Phase.PRE_CALCULATION))) {
preCalculationStackValueMap.put(wrappedStack, factoredEnergyValue);
if (doRegenValues) {
compute();
}
}
}
else if (!FMLCommonHandler.instance().bus().post(new EnergyValueEvent.SetEnergyValueEvent(wrappedStack, factoredEnergyValue, Phase.POST_CALCULATION))) {
TreeMap<WrappedStack, EnergyValue> valueMap = new TreeMap<>(stackValueMap);
valueMap.put(wrappedStack, energyValue);
ImmutableSortedMap.Builder<WrappedStack, EnergyValue> stackMappingsBuilder = ImmutableSortedMap.naturalOrder();
stackValueMap = stackMappingsBuilder.putAll(valueMap).build();
postCalculationStackValueMap.put(wrappedStack, factoredEnergyValue);
}
}
}
/**
* This is where the magic happens
*/
public void compute() {
// Initialize the "working copy" energy value map
TreeMap<WrappedStack, EnergyValue> stackValueMap = new TreeMap<>();
uncomputedStacks = new TreeSet<>();
// Add in all pre-calculation energy value mappings
preCalculationStackValueMap.keySet().stream()
.filter(wrappedStack -> wrappedStack != null && wrappedStack.getWrappedObject() != null && preCalculationStackValueMap.get(wrappedStack) != null)
.forEach(wrappedStack -> stackValueMap.put(wrappedStack, preCalculationStackValueMap.get(wrappedStack)));
// Calculate values from the known methods to create items, and the pre-calculation value mappings
calculateStackValueMap(stackValueMap);
// Add in all post-calculation energy value mappings
postCalculationStackValueMap.keySet().stream()
.filter(wrappedStack -> wrappedStack != null && wrappedStack.getWrappedObject() != null && postCalculationStackValueMap.get(wrappedStack) != null)
.forEach(wrappedStack -> stackValueMap.put(wrappedStack, postCalculationStackValueMap.get(wrappedStack)));
// Bake the final calculated energy value maps
ImmutableSortedMap.Builder<WrappedStack, EnergyValue> stackMappingsBuilder = ImmutableSortedMap.naturalOrder();
stackMappingsBuilder.putAll(stackValueMap);
this.stackValueMap = stackMappingsBuilder.build();
calculateValueStackMap();
// Save the results to disk
save();
}
private Map<WrappedStack, EnergyValue> calculateStackValueMap(Map<WrappedStack, EnergyValue> stackValueMap) {
LogHelper.info(ENERGY_VALUE_MARKER, "Beginning energy value calculation");
long startingTime = System.nanoTime();
Map<WrappedStack, EnergyValue> computedMap = new TreeMap<>(stackValueMap);
Map<WrappedStack, EnergyValue> tempComputedMap = new TreeMap<>();
int passNumber = 0;
while ((passNumber == 0 || tempComputedMap.size() != computedMap.size()) && passNumber < 16) {
long passStartTime = System.nanoTime();
passNumber++;
/**
* @see EnergyValueRegistry#computeStackMappings(Map, int)
*/
tempComputedMap = new TreeMap<>(computedMap);
for (WrappedStack recipeOutput : RecipeRegistry.getInstance().getRecipeMappings().keySet()) {
// We won't attempt to recalculate values that already have a pre-calculation value assignment
if (!stackValueMap.containsKey(WrappedStack.wrap(recipeOutput, 1))) {
for (List<WrappedStack> recipeInputs : RecipeRegistry.getInstance().getRecipeMappings().get(recipeOutput)) {
// FIXME PRIORITY NUMBER 1 - getting of values should use the same algo in getEnergyValue
EnergyValue currentOutputValue = tempComputedMap.get(WrappedStack.wrap(recipeOutput, 1));
EnergyValue computedOutputValue = computeFromInputs(tempComputedMap, recipeOutput, recipeInputs);
if (computedOutputValue != null && computedOutputValue.compareTo(currentOutputValue) < 0) {
uncomputedStacks.removeIf(wrappedStack -> uncomputedStacks.contains(WrappedStack.wrap(recipeOutput, 1)));
if (ConfigurationHandler.Settings.energyValueDebugLoggingEnabled) {
LogHelper.info(ENERGY_VALUE_MARKER, "Pass {}: Calculated value {} for object {}", passNumber, computedOutputValue, recipeOutput);
}
tempComputedMap.put(WrappedStack.wrap(recipeOutput), computedOutputValue);
}
else if (computedOutputValue != null) {
uncomputedStacks.add(WrappedStack.wrap(recipeOutput, 1));
}
}
}
}
computedMap.putAll(tempComputedMap);
long passDuration = System.nanoTime() - passStartTime;
if (ConfigurationHandler.Settings.energyValueDebugLoggingEnabled) {
LogHelper.info(ENERGY_VALUE_MARKER, "Pass {}: Calculated {} values for objects in {} ns", passNumber, tempComputedMap.size(), passDuration);
}
}
long endingTime = System.nanoTime() - startingTime;
LogHelper.info(ENERGY_VALUE_MARKER, "Finished dynamic value calculation (calculated {} values for objects in {} ns)", computedMap.size() - stackValueMap.size(), endingTime);
return computedMap;
}
private void calculateValueStackMap() {
SortedMap<EnergyValue, List<WrappedStack>> tempValueMap = new TreeMap<>();
for (WrappedStack wrappedStack : getEnergyValues().keySet()) {
if (wrappedStack != null) {
EnergyValue energyValue = getEnergyValues().get(wrappedStack);
if (energyValue != null) {
if (tempValueMap.containsKey(energyValue)) {
if (!(tempValueMap.get(energyValue).contains(wrappedStack))) {
tempValueMap.get(energyValue).add(wrappedStack);
}
}
else {
tempValueMap.put(energyValue, new ArrayList<>(Arrays.asList(wrappedStack)));
}
}
}
}
valueStackMap = ImmutableSortedMap.copyOf(tempValueMap);
}
/**
* Saves the pre-calculation, post-calculation, and calculated energy value maps to disk
*/
public void save() {
writeToJsonFile(stackValueMap, energyValuesFile);
writeToJsonFile(preCalculationStackValueMap, preCalculationValuesFile);
writeToJsonFile(postCalculationStackValueMap, postCalculationValuesFile);
}
/**
* Loads the pre-calculation, post-calculation, and calculated energy value maps from disk. In the event that either
* the pre/post calculation maps can not be loaded from disk they will be initialized as empty maps. If the
* calculated energy value map can not be loaded from disk then the values will be computed from the pre/post
* calculation maps
*/
public void load() {
try {
preCalculationStackValueMap.putAll(readFromJsonFile(preCalculationValuesFile));
} catch (FileNotFoundException e) {
// TODO Log that no pre-calculation values were loaded from file because file wasn't found
}
try {
postCalculationStackValueMap.putAll(readFromJsonFile(postCalculationValuesFile));
} catch (FileNotFoundException e) {
// TODO Log that no post-calculation values were loaded from file because file wasn't found
}
try {
ImmutableSortedMap.Builder<WrappedStack, EnergyValue> stackMapBuilder = ImmutableSortedMap.naturalOrder();
stackMapBuilder.putAll(readFromJsonFile(energyValuesFile));
stackValueMap = stackMapBuilder.build();
calculateValueStackMap();
} catch (FileNotFoundException e) {
LogHelper.warn("No calculated energy value file found, regenerating"); // TODO Better log message
compute();
}
}
/**
* @see net.minecraft.nbt.CompressedStreamTools#safeWrite(NBTTagCompound, File)
*/
private static void writeToJsonFile(Map<WrappedStack, EnergyValue> valueMap, File file) {
File tempFile = new File(file.getAbsolutePath() + "_tmp");
if (tempFile.exists()) {
tempFile.delete();
}
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tempFile))) {
bufferedWriter.write(SerializationHelper.GSON.toJson(valueMap, SerializationHelper.ENERGY_VALUE_MAP_TYPE));
bufferedWriter.close();
}
catch (IOException exception) {
exception.printStackTrace(); // TODO Better logging of the exception
}
if (file.exists()) {
file.delete();
}
if (file.exists()) {
LogHelper.warn("Failed to delete " + file);
}
else {
tempFile.renameTo(file);
}
}
private static Map<WrappedStack, EnergyValue> readFromJsonFile(File file) throws FileNotFoundException {
Map<WrappedStack, EnergyValue> valueMap = new TreeMap<>();
StringBuilder jsonStringBuilder = new StringBuilder();
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
jsonStringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
jsonStringBuilder.append(line);
}
}
catch (IOException exception) {
if (exception instanceof FileNotFoundException) {
throw (FileNotFoundException) exception;
}
else {
exception.printStackTrace(); // TODO Better logging of the exception (other)
}
}
try {
valueMap = SerializationHelper.GSON.fromJson(jsonStringBuilder.toString(), SerializationHelper.ENERGY_VALUE_MAP_TYPE);
}
catch (JsonParseException exception) {
// TODO Better logging of the exception (failed parsing so no values loaded)
}
return valueMap;
}
}

View file

@ -1,73 +1,58 @@
package com.pahimar.ee3.exchange; package com.pahimar.ee3.exchange;
import com.pahimar.ee3.reference.Comparators; import com.pahimar.ee3.reference.Comparators;
import com.pahimar.ee3.util.OreDictionaryHelper;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
public class OreStack implements Comparable<OreStack> {
public class OreStack implements Comparable<OreStack>
{
public String oreName; public String oreName;
public int stackSize; public int stackSize;
public static Comparator<OreStack> comparator = new Comparator<OreStack>()
{ public static Comparator<OreStack> comparator = (oreStack1, oreStack2) -> {
@Override if (oreStack1 != null && oreStack1.oreName != null) {
public int compare(OreStack oreStack1, OreStack oreStack2) if (oreStack2 != null && oreStack2.oreName != null) {
{ if (oreStack1.oreName.equalsIgnoreCase(oreStack2.oreName)) {
if (oreStack1 != null && oreStack1.oreName != null)
{
if (oreStack2 != null && oreStack2.oreName != null)
{
if (oreStack1.oreName.equalsIgnoreCase(oreStack2.oreName))
{
return oreStack1.stackSize - oreStack2.stackSize; return oreStack1.stackSize - oreStack2.stackSize;
} }
else else {
{
return oreStack1.oreName.compareToIgnoreCase(oreStack2.oreName); return oreStack1.oreName.compareToIgnoreCase(oreStack2.oreName);
} }
} }
else else {
{
return -1; return -1;
} }
} }
else else {
{ if (oreStack2 != null) {
if (oreStack2 != null)
{
return 1; return 1;
} }
else else {
{
return 0; return 0;
} }
} }
}
}; };
private OreStack() private OreStack() {
{
} }
public OreStack(String oreName) public OreStack(String oreName) {
{
this(oreName, 1); this(oreName, 1);
} }
public OreStack(String oreName, int stackSize) public OreStack(String oreName, int stackSize) {
{
this.oreName = oreName; this.oreName = oreName;
this.stackSize = stackSize; this.stackSize = stackSize;
} }
public static boolean compareOreNames(OreStack oreStack1, OreStack oreStack2) public static boolean compareOreNames(OreStack oreStack1, OreStack oreStack2) {
{
if (oreStack1 != null && oreStack2 != null) if (oreStack1 != null && oreStack2 != null) {
{ if ((oreStack1.oreName != null) && (oreStack2.oreName != null)) {
if ((oreStack1.oreName != null) && (oreStack2.oreName != null))
{
return oreStack1.oreName.equalsIgnoreCase(oreStack2.oreName); return oreStack1.oreName.equalsIgnoreCase(oreStack2.oreName);
} }
} }
@ -75,47 +60,35 @@ public class OreStack implements Comparable<OreStack>
return false; return false;
} }
public static OreStack getOreStackFromList(Object... objects) public static OreStack getOreStackFromList(Object... objects) {
{
return getOreStackFromList(Arrays.asList(objects)); return getOreStackFromList(Arrays.asList(objects));
} }
public static OreStack getOreStackFromList(List<?> objectList) public static OreStack getOreStackFromList(List<?> objectList) {
{
if (objectList.size() > 0) if (objectList.size() > 0) {
{ Map<String, Integer> oreNameCountMap = new TreeMap<>(Comparators.stringComparator);
Map<String, Integer> oreNameCountMap = new TreeMap<String, Integer>(Comparators.stringComparator); for (Object listElement : objectList) {
for (Object listElement : objectList) if (listElement instanceof ItemStack) {
{
if (listElement instanceof ItemStack)
{
ItemStack itemStack = (ItemStack) listElement; ItemStack itemStack = (ItemStack) listElement;
for (String oreName : CachedOreDictionary.getInstance().getOreNamesForItemStack(itemStack)) for (String oreName : OreDictionaryHelper.getOreNames(itemStack)) {
{ if (oreNameCountMap.containsKey(oreName)) {
if (oreNameCountMap.containsKey(oreName))
{
oreNameCountMap.put(oreName, oreNameCountMap.get(oreName) + 1); oreNameCountMap.put(oreName, oreNameCountMap.get(oreName) + 1);
} }
else else {
{
oreNameCountMap.put(oreName, 1); oreNameCountMap.put(oreName, 1);
} }
} }
} }
} }
List<OreStack> candidateOreStacks = new ArrayList<OreStack>(); List<OreStack> candidateOreStacks = oreNameCountMap.keySet().stream()
for (String oreName : oreNameCountMap.keySet()) .filter(oreName -> oreNameCountMap.get(oreName) == objectList.size())
{ .map(OreStack::new)
if (oreNameCountMap.get(oreName) == objectList.size()) .collect(Collectors.toList());
{
candidateOreStacks.add(new OreStack(oreName));
}
}
if (candidateOreStacks.size() == 1) if (candidateOreStacks.size() == 1) {
{
return candidateOreStacks.get(0); return candidateOreStacks.get(0);
} }
@ -125,46 +98,42 @@ public class OreStack implements Comparable<OreStack>
return null; return null;
} }
public static int compare(OreStack oreStack1, OreStack oreStack2) public static int compare(OreStack oreStack1, OreStack oreStack2) {
{
return comparator.compare(oreStack1, oreStack2); return comparator.compare(oreStack1, oreStack2);
} }
@Override @Override
public boolean equals(Object object) public boolean equals(Object object) {
{
return object instanceof OreStack && (comparator.compare(this, (OreStack) object) == 0); return object instanceof OreStack && (comparator.compare(this, (OreStack) object) == 0);
} }
public NBTTagCompound writeToNBT(NBTTagCompound nbtTagCompound) public NBTTagCompound writeToNBT(NBTTagCompound nbtTagCompound) {
{
nbtTagCompound.setString("oreName", oreName); nbtTagCompound.setString("oreName", oreName);
nbtTagCompound.setInteger("stackSize", stackSize); nbtTagCompound.setInteger("stackSize", stackSize);
return nbtTagCompound; return nbtTagCompound;
} }
public void readFromNBT(NBTTagCompound nbtTagCompound) public void readFromNBT(NBTTagCompound nbtTagCompound) {
{
this.oreName = nbtTagCompound.getString("oreName"); this.oreName = nbtTagCompound.getString("oreName");
this.stackSize = nbtTagCompound.getInteger("stackSize"); this.stackSize = nbtTagCompound.getInteger("stackSize");
} }
public static OreStack loadOreStackFromNBT(NBTTagCompound nbtTagCompound) public static OreStack loadOreStackFromNBT(NBTTagCompound nbtTagCompound) {
{
OreStack oreStack = new OreStack(); OreStack oreStack = new OreStack();
oreStack.readFromNBT(nbtTagCompound); oreStack.readFromNBT(nbtTagCompound);
return oreStack.oreName != null ? oreStack : null; return oreStack.oreName != null ? oreStack : null;
} }
@Override @Override
public String toString() public String toString() {
{
return String.format("%sxoreStack.%s", stackSize, oreName); return String.format("%sxoreStack.%s", stackSize, oreName);
} }
@Override @Override
public int compareTo(OreStack oreStack) public int compareTo(OreStack oreStack) {
{
return comparator.compare(this, oreStack); return comparator.compare(this, oreStack);
} }
} }

View file

@ -454,34 +454,28 @@ public class WrappedStack implements Comparable<WrappedStack>, JsonDeserializer<
* *
*/ */
@Override @Override
public int hashCode() public int hashCode() {
{
int hashCode = 1; int hashCode = 1;
hashCode = (37 * hashCode) + stackSize; hashCode = (37 * hashCode) + stackSize;
if (wrappedStack instanceof ItemStack) if (wrappedStack instanceof ItemStack) {
{
hashCode = (37 * hashCode) + Item.getIdFromItem(((ItemStack) wrappedStack).getItem()); hashCode = (37 * hashCode) + Item.getIdFromItem(((ItemStack) wrappedStack).getItem());
hashCode = (37 * hashCode) + ((ItemStack) wrappedStack).getItemDamage(); hashCode = (37 * hashCode) + ((ItemStack) wrappedStack).getItemDamage();
if (((ItemStack) wrappedStack).getTagCompound() != null) if (((ItemStack) wrappedStack).getTagCompound() != null) {
{
hashCode = (37 * hashCode) + ((ItemStack) wrappedStack).getTagCompound().hashCode(); hashCode = (37 * hashCode) + ((ItemStack) wrappedStack).getTagCompound().hashCode();
} }
} }
else if (wrappedStack instanceof OreStack) else if (wrappedStack instanceof OreStack) {
{ if (((OreStack) wrappedStack).oreName != null) {
if (((OreStack) wrappedStack).oreName != null)
{
hashCode = (37 * hashCode) + ((OreStack) wrappedStack).oreName.hashCode(); hashCode = (37 * hashCode) + ((OreStack) wrappedStack).oreName.hashCode();
} }
} }
else if (wrappedStack instanceof FluidStack) else if (wrappedStack instanceof FluidStack) {
{
hashCode = (37 * hashCode) + wrappedStack.hashCode(); hashCode = (37 * hashCode) + wrappedStack.hashCode();
if (((FluidStack) wrappedStack).tag != null) if (((FluidStack) wrappedStack).tag != null) {
{
hashCode = (37 * hashCode) + ((FluidStack) wrappedStack).tag.hashCode(); hashCode = (37 * hashCode) + ((FluidStack) wrappedStack).tag.hashCode();
} }
} }

View file

@ -1,6 +1,5 @@
package com.pahimar.ee3.handler; package com.pahimar.ee3.handler;
import com.pahimar.ee3.exchange.EnergyValueRegistry;
import com.pahimar.ee3.knowledge.TransmutationKnowledgeRegistry; import com.pahimar.ee3.knowledge.TransmutationKnowledgeRegistry;
import com.pahimar.ee3.network.PacketHandler; import com.pahimar.ee3.network.PacketHandler;
import com.pahimar.ee3.network.message.MessageChalkSettings; import com.pahimar.ee3.network.message.MessageChalkSettings;
@ -47,7 +46,7 @@ public class PlayerEventHandler
PacketHandler.INSTANCE.sendTo(new MessageChalkSettings(chalkSettings), (EntityPlayerMP) event.player); PacketHandler.INSTANCE.sendTo(new MessageChalkSettings(chalkSettings), (EntityPlayerMP) event.player);
TransmutationKnowledgeRegistry.getInstance().loadPlayerFromDiskIfNeeded(event.player); TransmutationKnowledgeRegistry.getInstance().loadPlayerFromDiskIfNeeded(event.player);
PacketHandler.INSTANCE.sendTo(new MessageSyncEnergyValues(EnergyValueRegistry.getInstance()), (EntityPlayerMP) event.player); PacketHandler.INSTANCE.sendTo(new MessageSyncEnergyValues(), (EntityPlayerMP) event.player);
} }
} }

View file

@ -1,21 +1,29 @@
package com.pahimar.ee3.handler; package com.pahimar.ee3.handler;
import com.pahimar.ee3.exchange.DynamicEnergyValueInitThread; import com.pahimar.ee3.exchange.EnergyValueRegistry;
import com.pahimar.ee3.recipe.AludelRecipeManager;
import com.pahimar.ee3.recipe.RecipeRegistry;
import com.pahimar.ee3.util.LogHelper;
import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.Side;
import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.event.world.WorldEvent;
public class WorldEventHandler public class WorldEventHandler {
{
public static boolean hasInitilialized = false; public static boolean hasInitilialized = false;
@SubscribeEvent @SubscribeEvent
public void onWorldLoadEvent(WorldEvent.Load event) public void onWorldLoadEvent(WorldEvent.Load event) {
{
if (!hasInitilialized && FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) if (!hasInitilialized && FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) {
{
DynamicEnergyValueInitThread.initEnergyValueRegistry(); RecipeRegistry.getInstance().registerVanillaRecipes();
AludelRecipeManager.registerRecipes();
long startTime = System.nanoTime();
EnergyValueRegistry.INSTANCE.compute();
LogHelper.info(EnergyValueRegistry.ENERGY_VALUE_MARKER, "Energy value system initialized {} values after {} ms", EnergyValueRegistry.INSTANCE.getEnergyValues().size(), (System.nanoTime() - startTime) / 100000);
hasInitilialized = true; hasInitilialized = true;
} }
} }

View file

@ -1,29 +1,23 @@
package com.pahimar.ee3.init; package com.pahimar.ee3.init;
import com.pahimar.ee3.api.knowledge.AbilityRegistryProxy; import com.pahimar.ee3.api.knowledge.AbilityRegistryProxy;
import com.pahimar.ee3.exchange.CachedOreDictionary;
import com.pahimar.ee3.exchange.OreStack; import com.pahimar.ee3.exchange.OreStack;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.OreDictionary;
public class Abilities public class Abilities {
{
public static void initNotLearnables() public static void init() {
{
for (String oreName : OreDictionary.getOreNames()) for (String oreName : OreDictionary.getOreNames()) {
{ if (oreName.startsWith("ore")) {
if (oreName.startsWith("ore")) OreDictionary.getOres(oreName).forEach(AbilityRegistryProxy::setAsNotLearnable);
{
for (ItemStack itemStack : CachedOreDictionary.getInstance().getItemStacksForOreName(oreName))
{
AbilityRegistryProxy.setAsNotLearnable(itemStack);
}
AbilityRegistryProxy.setAsNotLearnable(new OreStack(oreName)); AbilityRegistryProxy.setAsNotLearnable(new OreStack(oreName));
} }
} }
AbilityRegistryProxy.setAsNotLearnable(new ItemStack(Blocks.coal_ore));
AbilityRegistryProxy.setAsNotLearnable(new ItemStack(Blocks.coal_ore));
AbilityRegistryProxy.setAsNotLearnable(ModItems.shardMinium); AbilityRegistryProxy.setAsNotLearnable(ModItems.shardMinium);
AbilityRegistryProxy.setAsNotLearnable(new ItemStack(ModItems.alchemicalDust, 1, 1)); AbilityRegistryProxy.setAsNotLearnable(new ItemStack(ModItems.alchemicalDust, 1, 1));
AbilityRegistryProxy.setAsNotLearnable(new ItemStack(ModItems.alchemicalDust, 1, 2)); AbilityRegistryProxy.setAsNotLearnable(new ItemStack(ModItems.alchemicalDust, 1, 2));

View file

@ -2,30 +2,13 @@ package com.pahimar.ee3.init;
import com.pahimar.ee3.api.array.AlchemyArray; import com.pahimar.ee3.api.array.AlchemyArray;
import com.pahimar.ee3.api.array.AlchemyArrayRegistryProxy; import com.pahimar.ee3.api.array.AlchemyArrayRegistryProxy;
import com.pahimar.ee3.array.*; import com.pahimar.ee3.array.AlchemyArrayTransmutation;
public class AlchemyArrays {
public class AlchemyArrays
{
public static final AlchemyArray accelerantAlchemyArray = new AlchemyArrayAccelerant();
public static final AlchemyArray combustionAlchemyArray = new AlchemyArrayCombustion();
public static final AlchemyArray constructionAlchemyArray = new AlchemyArrayConstruction();
public static final AlchemyArray conveyorAlchemyArray = new AlchemyArrayConveyor();
public static final AlchemyArray destructionAlchemyArray = new AlchemyArrayDestruction();
public static final AlchemyArray gelidAlchemyArray = new AlchemyArrayGelid();
public static final AlchemyArray parthenogenesisAlchemyArray = new AlchemyArrayParthenogenesis();
public static final AlchemyArray transfigurationAlchemyArray = new AlchemyArrayTransfiguration();
public static final AlchemyArray transmutationAlchemyArray = new AlchemyArrayTransmutation(); public static final AlchemyArray transmutationAlchemyArray = new AlchemyArrayTransmutation();
public static void registerAlchemyArrays() public static void registerAlchemyArrays() {
{
AlchemyArrayRegistryProxy.registerAlchemyArray(accelerantAlchemyArray);
AlchemyArrayRegistryProxy.registerAlchemyArray(combustionAlchemyArray);
AlchemyArrayRegistryProxy.registerAlchemyArray(constructionAlchemyArray);
AlchemyArrayRegistryProxy.registerAlchemyArray(conveyorAlchemyArray);
AlchemyArrayRegistryProxy.registerAlchemyArray(destructionAlchemyArray);
AlchemyArrayRegistryProxy.registerAlchemyArray(gelidAlchemyArray);
AlchemyArrayRegistryProxy.registerAlchemyArray(parthenogenesisAlchemyArray);
AlchemyArrayRegistryProxy.registerAlchemyArray(transfigurationAlchemyArray);
AlchemyArrayRegistryProxy.registerAlchemyArray(transmutationAlchemyArray); AlchemyArrayRegistryProxy.registerAlchemyArray(transmutationAlchemyArray);
} }
} }

View file

@ -1,14 +1,13 @@
package com.pahimar.ee3.inventory; package com.pahimar.ee3.inventory;
import com.pahimar.ee3.api.exchange.EnergyValueRegistryProxy; import com.pahimar.ee3.api.exchange.EnergyValueRegistryProxy;
import com.pahimar.ee3.exchange.EnergyValueRegistry; import com.pahimar.ee3.api.knowledge.AbilityRegistryProxy;
import com.pahimar.ee3.inventory.element.IElementButtonHandler; import com.pahimar.ee3.inventory.element.IElementButtonHandler;
import com.pahimar.ee3.inventory.element.IElementSliderHandler; import com.pahimar.ee3.inventory.element.IElementSliderHandler;
import com.pahimar.ee3.inventory.element.IElementTextFieldHandler; import com.pahimar.ee3.inventory.element.IElementTextFieldHandler;
import com.pahimar.ee3.item.ItemAlchenomicon; import com.pahimar.ee3.item.ItemAlchenomicon;
import com.pahimar.ee3.item.ItemMiniumStone; import com.pahimar.ee3.item.ItemMiniumStone;
import com.pahimar.ee3.item.ItemPhilosophersStone; import com.pahimar.ee3.item.ItemPhilosophersStone;
import com.pahimar.ee3.knowledge.AbilityRegistry;
import com.pahimar.ee3.knowledge.TransmutationKnowledge; import com.pahimar.ee3.knowledge.TransmutationKnowledge;
import com.pahimar.ee3.knowledge.TransmutationKnowledgeRegistry; import com.pahimar.ee3.knowledge.TransmutationKnowledgeRegistry;
import com.pahimar.ee3.network.PacketHandler; import com.pahimar.ee3.network.PacketHandler;
@ -589,7 +588,7 @@ public class ContainerTransmutationTablet extends ContainerEE implements IElemen
@Override @Override
public boolean isItemValid(ItemStack itemStack) public boolean isItemValid(ItemStack itemStack)
{ {
return EnergyValueRegistry.getInstance().hasEnergyValue(itemStack) && AbilityRegistry.getInstance().isRecoverable(itemStack); return EnergyValueRegistryProxy.hasEnergyValue(itemStack) && AbilityRegistryProxy.isRecoverable(itemStack);
} }
@Override @Override

View file

@ -4,8 +4,8 @@ import com.google.gson.*;
import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter; import com.google.gson.stream.JsonWriter;
import com.pahimar.ee3.api.event.AbilityEvent; import com.pahimar.ee3.api.event.AbilityEvent;
import com.pahimar.ee3.api.exchange.EnergyValueRegistryProxy;
import com.pahimar.ee3.api.knowledge.AbilityRegistryProxy; import com.pahimar.ee3.api.knowledge.AbilityRegistryProxy;
import com.pahimar.ee3.exchange.EnergyValueRegistry;
import com.pahimar.ee3.exchange.WrappedStack; import com.pahimar.ee3.exchange.WrappedStack;
import com.pahimar.ee3.reference.Files; import com.pahimar.ee3.reference.Files;
import com.pahimar.ee3.util.LoaderHelper; import com.pahimar.ee3.util.LoaderHelper;
@ -80,7 +80,7 @@ public class AbilityRegistry implements JsonSerializer<AbilityRegistry>, JsonDes
} }
else else
{ {
return !notLearnableSet.contains(wrappedObject) && EnergyValueRegistry.getInstance().hasEnergyValue(wrappedObject); return !notLearnableSet.contains(wrappedObject) && EnergyValueRegistryProxy.hasEnergyValue(wrappedObject);
} }
} }
@ -131,7 +131,7 @@ public class AbilityRegistry implements JsonSerializer<AbilityRegistry>, JsonDes
if (WrappedStack.canBeWrapped(object)) if (WrappedStack.canBeWrapped(object))
{ {
WrappedStack wrappedObject = WrappedStack.wrap(object); WrappedStack wrappedObject = WrappedStack.wrap(object);
return !notRecoverableSet.contains(wrappedObject) && EnergyValueRegistry.getInstance().hasEnergyValue(wrappedObject); return !notRecoverableSet.contains(wrappedObject) && EnergyValueRegistryProxy.hasEnergyValue(wrappedObject);
} }
return false; return false;

View file

@ -1,6 +1,7 @@
package com.pahimar.ee3.network.message; package com.pahimar.ee3.network.message;
import com.pahimar.ee3.api.exchange.EnergyValue; import com.pahimar.ee3.api.exchange.EnergyValue;
import com.pahimar.ee3.api.exchange.EnergyValueRegistryProxy;
import com.pahimar.ee3.exchange.EnergyValueRegistry; import com.pahimar.ee3.exchange.EnergyValueRegistry;
import com.pahimar.ee3.exchange.EnergyValueStackMapping; import com.pahimar.ee3.exchange.EnergyValueStackMapping;
import com.pahimar.ee3.exchange.WrappedStack; import com.pahimar.ee3.exchange.WrappedStack;
@ -11,8 +12,6 @@ import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext; import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import java.io.IOException;
public class MessageSetEnergyValue implements IMessage, IMessageHandler<MessageSetEnergyValue, IMessage> public class MessageSetEnergyValue implements IMessage, IMessageHandler<MessageSetEnergyValue, IMessage>
{ {
public EnergyValueStackMapping energyValueStackMapping; public EnergyValueStackMapping energyValueStackMapping;
@ -39,12 +38,7 @@ public class MessageSetEnergyValue implements IMessage, IMessageHandler<MessageS
if (compressedEnergyValueStackMapping != null) if (compressedEnergyValueStackMapping != null)
{ {
String decompressedEnergyValueStackMapping = null; String decompressedEnergyValueStackMapping = decompressedEnergyValueStackMapping = CompressionHelper.decompress(compressedEnergyValueStackMapping);
try {
decompressedEnergyValueStackMapping = CompressionHelper.decompress(compressedEnergyValueStackMapping);
} catch (IOException e) {
e.printStackTrace();
}
this.energyValueStackMapping = EnergyValueStackMapping.createFromJson(decompressedEnergyValueStackMapping); this.energyValueStackMapping = EnergyValueStackMapping.createFromJson(decompressedEnergyValueStackMapping);
} }
} }
@ -58,11 +52,7 @@ public class MessageSetEnergyValue implements IMessage, IMessageHandler<MessageS
if (jsonEnergyValueStackMapping != null) if (jsonEnergyValueStackMapping != null)
{ {
try {
compressedBytes = CompressionHelper.compress(jsonEnergyValueStackMapping); compressedBytes = CompressionHelper.compress(jsonEnergyValueStackMapping);
} catch (IOException e) {
e.printStackTrace();
}
} }
if (compressedBytes != null) if (compressedBytes != null)
@ -81,7 +71,7 @@ public class MessageSetEnergyValue implements IMessage, IMessageHandler<MessageS
{ {
if (message.energyValueStackMapping != null && message.energyValueStackMapping.wrappedStack != null && message.energyValueStackMapping.energyValue != null) if (message.energyValueStackMapping != null && message.energyValueStackMapping.wrappedStack != null && message.energyValueStackMapping.energyValue != null)
{ {
EnergyValueRegistry.getInstance().setEnergyValue(message.energyValueStackMapping.wrappedStack, message.energyValueStackMapping.energyValue); EnergyValueRegistryProxy.setEnergyValue(message.energyValueStackMapping.wrappedStack, message.energyValueStackMapping.energyValue);
LogHelper.info(EnergyValueRegistry.ENERGY_VALUE_MARKER, "Client successfully received new EnergyValue '{}' for object '{}'", message.energyValueStackMapping.wrappedStack, message.energyValueStackMapping.energyValue); LogHelper.info(EnergyValueRegistry.ENERGY_VALUE_MARKER, "Client successfully received new EnergyValue '{}' for object '{}'", message.energyValueStackMapping.wrappedStack, message.energyValueStackMapping.energyValue);
} }
else else

View file

@ -1,33 +1,25 @@
package com.pahimar.ee3.network.message; package com.pahimar.ee3.network.message;
import com.google.gson.stream.JsonReader; import com.google.gson.JsonParseException;
import com.pahimar.ee3.api.exchange.EnergyValue; import com.pahimar.ee3.api.exchange.EnergyValue;
import com.pahimar.ee3.exchange.EnergyValueRegistry; import com.pahimar.ee3.exchange.EnergyValueRegistry;
import com.pahimar.ee3.exchange.EnergyValueStackMapping;
import com.pahimar.ee3.exchange.WrappedStack; import com.pahimar.ee3.exchange.WrappedStack;
import com.pahimar.ee3.util.CompressionHelper; import com.pahimar.ee3.util.CompressionHelper;
import com.pahimar.ee3.util.LogHelper; import com.pahimar.ee3.util.LogHelper;
import com.pahimar.ee3.util.SerializationHelper;
import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext; import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import java.io.IOException;
import java.io.StringReader;
import java.util.Map; import java.util.Map;
import java.util.TreeMap;
public class MessageSyncEnergyValues implements IMessage, IMessageHandler<MessageSyncEnergyValues, IMessage> public class MessageSyncEnergyValues implements IMessage, IMessageHandler<MessageSyncEnergyValues, IMessage> {
{
public String jsonEnergyValueRegistry;
public MessageSyncEnergyValues() public String jsonString;
{
}
public MessageSyncEnergyValues(EnergyValueRegistry energyValueRegistry) public MessageSyncEnergyValues() {
{ this.jsonString = SerializationHelper.GSON.toJson(EnergyValueRegistry.INSTANCE.getEnergyValues(), SerializationHelper.ENERGY_VALUE_MAP_TYPE);
this.jsonEnergyValueRegistry = energyValueRegistry.toJson();
} }
/** /**
@ -36,22 +28,16 @@ public class MessageSyncEnergyValues implements IMessage, IMessageHandler<Messag
* @param buf * @param buf
*/ */
@Override @Override
public void fromBytes(ByteBuf buf) public void fromBytes(ByteBuf buf) {
{
byte[] compressedBytes = null;
int readableBytes = buf.readInt();
if (readableBytes > 0) byte[] compressedString;
{ int compressedStringLength = buf.readInt();
compressedBytes = buf.readBytes(readableBytes).array();
}
if (compressedBytes != null) if (compressedStringLength > 0) {
{ compressedString = buf.readBytes(compressedStringLength).array();
try {
this.jsonEnergyValueRegistry = CompressionHelper.decompress(compressedBytes); if (compressedString != null) {
} catch (IOException e) { this.jsonString = CompressionHelper.decompress(compressedString);
e.printStackTrace();
} }
} }
} }
@ -62,26 +48,23 @@ public class MessageSyncEnergyValues implements IMessage, IMessageHandler<Messag
* @param buf * @param buf
*/ */
@Override @Override
public void toBytes(ByteBuf buf) public void toBytes(ByteBuf buf) {
{
byte[] compressedBytes = null;
if (jsonEnergyValueRegistry != null) byte[] compressedString = null;
{
try {
compressedBytes = CompressionHelper.compress(jsonEnergyValueRegistry);
} catch (IOException e) {
e.printStackTrace();
}
}
if (compressedBytes != null) if (jsonString != null) {
{
buf.writeInt(compressedBytes.length); compressedString = CompressionHelper.compress(jsonString);
buf.writeBytes(compressedBytes);
if (compressedString != null) {
buf.writeInt(compressedString.length);
buf.writeBytes(compressedString);
} }
else else {
{ buf.writeInt(0);
}
}
else {
buf.writeInt(0); buf.writeInt(0);
} }
} }
@ -95,38 +78,29 @@ public class MessageSyncEnergyValues implements IMessage, IMessageHandler<Messag
* @return an optional return message * @return an optional return message
*/ */
@Override @Override
public IMessage onMessage(MessageSyncEnergyValues message, MessageContext ctx) public IMessage onMessage(MessageSyncEnergyValues message, MessageContext ctx) {
{
if (message.jsonEnergyValueRegistry != null)
{
Map<WrappedStack, EnergyValue> energyValueStackMap = new TreeMap<WrappedStack, EnergyValue>();
try if (message.jsonString != null) {
{
JsonReader jsonReader = new JsonReader(new StringReader(message.jsonEnergyValueRegistry)); Map<WrappedStack, EnergyValue> valueMap = null;
jsonReader.beginArray();
while (jsonReader.hasNext()) try {
{ valueMap = SerializationHelper.GSON.fromJson(message.jsonString, SerializationHelper.ENERGY_VALUE_MAP_TYPE);
EnergyValueStackMapping energyValueStackMapping = EnergyValueStackMapping.jsonSerializer.fromJson(jsonReader, EnergyValueStackMapping.class);
if (energyValueStackMapping != null)
{
energyValueStackMap.put(energyValueStackMapping.wrappedStack, energyValueStackMapping.energyValue);
} }
} catch (JsonParseException e) {
jsonReader.endArray(); // TODO Log an error message here
jsonReader.close();
}
catch (IOException e)
{
e.printStackTrace();
} }
EnergyValueRegistry.getInstance().loadFromMap(energyValueStackMap); if (valueMap != null) {
LogHelper.info(EnergyValueRegistry.ENERGY_VALUE_MARKER, "Client successfully received EnergyValues from server"); EnergyValueRegistry.INSTANCE.load(valueMap);
LogHelper.info(EnergyValueRegistry.ENERGY_VALUE_MARKER, "Client successfully received {} energy values from server", valueMap.size());
} }
else else {
{ // TODO Log a message here
LogHelper.info(EnergyValueRegistry.ENERGY_VALUE_MARKER, "Client failed to receive EnergyValues from server - falling back to local EnergyValues"); }
}
else {
LogHelper.info(EnergyValueRegistry.ENERGY_VALUE_MARKER, "Client failed to receive energy values from server - falling back to local values");
} }
return null; return null;

View file

@ -12,7 +12,6 @@ import io.netty.buffer.ByteBuf;
import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import java.io.IOException;
import java.util.Collection; import java.util.Collection;
public class MessageTransmutationKnowledgeUpdate implements IMessage, IMessageHandler<MessageTransmutationKnowledgeUpdate, IMessage> public class MessageTransmutationKnowledgeUpdate implements IMessage, IMessageHandler<MessageTransmutationKnowledgeUpdate, IMessage>
@ -83,12 +82,7 @@ public class MessageTransmutationKnowledgeUpdate implements IMessage, IMessageHa
if (compressedString != null) if (compressedString != null)
{ {
String uncompressedString = null; String uncompressedString = CompressionHelper.decompress(compressedString);
try {
uncompressedString = CompressionHelper.decompress(compressedString);
} catch (IOException e) {
e.printStackTrace();
}
this.transmutationKnowledge = TransmutationKnowledge.createFromJson(uncompressedString); this.transmutationKnowledge = TransmutationKnowledge.createFromJson(uncompressedString);
} }
} }
@ -102,13 +96,8 @@ public class MessageTransmutationKnowledgeUpdate implements IMessage, IMessageHa
byte[] compressedString = null; byte[] compressedString = null;
if (transmutationKnowledge != null) if (transmutationKnowledge != null) {
{
try {
compressedString = CompressionHelper.compress(transmutationKnowledge.toJson()); compressedString = CompressionHelper.compress(transmutationKnowledge.toJson());
} catch (IOException e) {
e.printStackTrace();
}
} }
if (compressedString != null) if (compressedString != null)

View file

@ -1,6 +1,6 @@
package com.pahimar.ee3.reference; package com.pahimar.ee3.reference;
import com.pahimar.ee3.exchange.EnergyValueRegistry; import com.pahimar.ee3.api.exchange.EnergyValueRegistryProxy;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.OreDictionary;
@ -129,9 +129,9 @@ public class Comparators
{ {
if (itemStack1 != null && itemStack2 != null) if (itemStack1 != null && itemStack2 != null)
{ {
if (EnergyValueRegistry.getInstance().hasEnergyValue(itemStack1) && EnergyValueRegistry.getInstance().hasEnergyValue(itemStack2)) if (EnergyValueRegistryProxy.hasEnergyValue(itemStack1) && EnergyValueRegistryProxy.hasEnergyValue(itemStack2))
{ {
return Float.compare(EnergyValueRegistry.getInstance().getEnergyValue(itemStack1).getValue(), EnergyValueRegistry.getInstance().getEnergyValue(itemStack2).getValue()); return Float.compare(EnergyValueRegistryProxy.getEnergyValue(itemStack1).getValue(), EnergyValueRegistryProxy.getEnergyValue(itemStack2).getValue());
} }
else else
{ {

View file

@ -1,6 +1,6 @@
package com.pahimar.ee3.reference; package com.pahimar.ee3.reference;
import com.pahimar.ee3.exchange.NewEnergyValueRegistry; import com.pahimar.ee3.exchange.EnergyValueRegistry;
import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import java.io.File; import java.io.File;
@ -26,11 +26,11 @@ public class Files {
dataDirectory = new File(event.getModConfigurationDirectory().getParentFile(), "data" + File.separator + Reference.LOWERCASE_MOD_ID); dataDirectory = new File(event.getModConfigurationDirectory().getParentFile(), "data" + File.separator + Reference.LOWERCASE_MOD_ID);
NewEnergyValueRegistry.energyValuesDirectory = new File(dataDirectory, "energy-values"); EnergyValueRegistry.energyValuesDirectory = new File(dataDirectory, "energy-values");
NewEnergyValueRegistry.energyValuesDirectory.mkdirs(); EnergyValueRegistry.energyValuesDirectory.mkdirs();
NewEnergyValueRegistry.energyValuesFile = new File(NewEnergyValueRegistry.energyValuesDirectory, ENERGY_VALUES_JSON); EnergyValueRegistry.energyValuesFile = new File(EnergyValueRegistry.energyValuesDirectory, ENERGY_VALUES_JSON);
NewEnergyValueRegistry.preCalculationValuesFile = new File(NewEnergyValueRegistry.energyValuesDirectory, PRE_CALCULATION_ENERGY_VALUES); EnergyValueRegistry.preCalculationValuesFile = new File(EnergyValueRegistry.energyValuesDirectory, PRE_CALCULATION_ENERGY_VALUES);
NewEnergyValueRegistry.postCalculationValuesFile = new File(NewEnergyValueRegistry.energyValuesDirectory, POST_CALCULATION_ENERGY_VALUES); EnergyValueRegistry.postCalculationValuesFile = new File(EnergyValueRegistry.energyValuesDirectory, POST_CALCULATION_ENERGY_VALUES);
abilitiesDataDirectory = new File(dataDirectory, "abilities"); abilitiesDataDirectory = new File(dataDirectory, "abilities");
abilitiesDataDirectory.mkdirs(); abilitiesDataDirectory.mkdirs();

View file

@ -2,12 +2,11 @@ package com.pahimar.ee3.tileentity;
import com.pahimar.ee3.api.exchange.EnergyValue; import com.pahimar.ee3.api.exchange.EnergyValue;
import com.pahimar.ee3.api.exchange.EnergyValueRegistryProxy; import com.pahimar.ee3.api.exchange.EnergyValueRegistryProxy;
import com.pahimar.ee3.api.knowledge.AbilityRegistryProxy;
import com.pahimar.ee3.block.BlockAshInfusedStoneSlab; import com.pahimar.ee3.block.BlockAshInfusedStoneSlab;
import com.pahimar.ee3.exchange.EnergyValueRegistry;
import com.pahimar.ee3.item.ItemAlchenomicon; import com.pahimar.ee3.item.ItemAlchenomicon;
import com.pahimar.ee3.item.ItemMiniumStone; import com.pahimar.ee3.item.ItemMiniumStone;
import com.pahimar.ee3.item.ItemPhilosophersStone; import com.pahimar.ee3.item.ItemPhilosophersStone;
import com.pahimar.ee3.knowledge.AbilityRegistry;
import com.pahimar.ee3.network.PacketHandler; import com.pahimar.ee3.network.PacketHandler;
import com.pahimar.ee3.network.message.MessageTileEntityTransmutationTablet; import com.pahimar.ee3.network.message.MessageTileEntityTransmutationTablet;
import com.pahimar.ee3.reference.Names; import com.pahimar.ee3.reference.Names;
@ -314,7 +313,7 @@ public class TileEntityTransmutationTablet extends TileEntityEE implements ISide
@Override @Override
public boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) public boolean isItemValidForSlot(int slotIndex, ItemStack itemStack)
{ {
if (slotIndex < STONE_INDEX && EnergyValueRegistry.getInstance().hasEnergyValue(itemStack) && AbilityRegistry.getInstance().isRecoverable(itemStack)) if (slotIndex < STONE_INDEX && EnergyValueRegistryProxy.hasEnergyValue(itemStack) && AbilityRegistryProxy.isRecoverable(itemStack))
{ {
return true; return true;
} }

View file

@ -5,28 +5,45 @@ import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPOutputStream;
public class CompressionHelper public class CompressionHelper {
{
public static byte[] compress(String uncompressedString) throws IOException { /**
*
* @param uncompressedString
* @return
*/
public static byte[] compress(String uncompressedString) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream)) {
gzipOutputStream.write(uncompressedString.getBytes(StandardCharsets.UTF_8)); gzipOutputStream.write(uncompressedString.getBytes(StandardCharsets.UTF_8));
gzipOutputStream.close(); gzipOutputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toByteArray(); return byteArrayOutputStream.toByteArray();
} }
public static String decompress(byte[] compressedString) throws IOException { /**
*
GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(compressedString)); * @param compressedString
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gzipInputStream, StandardCharsets.UTF_8)); * @return
*/
public static String decompress(byte[] compressedString) {
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
String line; String line;
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new GZIPInputStream(new ByteArrayInputStream(compressedString)), StandardCharsets.UTF_8))) {
while ((line = bufferedReader.readLine()) != null) { while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line); stringBuilder.append(line);
} }
}
catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString(); return stringBuilder.toString();
} }

View file

@ -0,0 +1,22 @@
package com.pahimar.ee3.util;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;
public class OreDictionaryHelper {
public static Collection<String> getOreNames(ItemStack itemStack) {
Set<String> oreNames = new TreeSet<>();
for (int oreId : OreDictionary.getOreIDs(itemStack)) {
oreNames.add(OreDictionary.getOreName(oreId));
}
return oreNames;
}
}

View file

@ -1,13 +1,11 @@
package com.pahimar.ee3.util; package com.pahimar.ee3.util;
import com.google.common.io.Files;
import com.google.common.reflect.TypeToken; import com.google.common.reflect.TypeToken;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter; import com.google.gson.stream.JsonWriter;
import com.pahimar.ee3.api.exchange.EnergyValue; import com.pahimar.ee3.api.exchange.EnergyValue;
import com.pahimar.ee3.exchange.EnergyValueRegistry;
import com.pahimar.ee3.exchange.EnergyValueStackMapping; import com.pahimar.ee3.exchange.EnergyValueStackMapping;
import com.pahimar.ee3.exchange.OreStack; import com.pahimar.ee3.exchange.OreStack;
import com.pahimar.ee3.exchange.WrappedStack; import com.pahimar.ee3.exchange.WrappedStack;
@ -216,72 +214,4 @@ public class SerializationHelper {
e.printStackTrace(); e.printStackTrace();
} }
} }
public static void compressEnergyValueStackMapToFile(String fileName, Map<WrappedStack, EnergyValue> energyValueMap)
{
File energyValuesDataDirectory = new File(FMLCommonHandler.instance().getMinecraftServerInstance().getEntityWorld().getSaveHandler().getWorldDirectory(), "data" + File.separator + Reference.LOWERCASE_MOD_ID + File.separator + "energyvalues");
compressEnergyValueStackMapToFile(new File(energyValuesDataDirectory, fileName), energyValueMap);
}
public static void compressEnergyValueStackMapToFile(File file, Map<WrappedStack, EnergyValue> energyValueMap)
{
try
{
byte[] energyValueRegistryArray = CompressionHelper.compress(EnergyValueRegistry.getInstance().toJson());
FileOutputStream fos = new FileOutputStream(file);
fos.write(energyValueRegistryArray);
fos.close();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static Map<WrappedStack, EnergyValue> decompressEnergyValueStackMapFromFile(String fileName)
{
File energyValuesDataDirectory = new File(FMLCommonHandler.instance().getMinecraftServerInstance().getEntityWorld().getSaveHandler().getWorldDirectory(), "data" + File.separator + Reference.LOWERCASE_MOD_ID + File.separator + "energyvalues");
return decompressEnergyValueStackMapFromFile(new File(energyValuesDataDirectory, fileName));
}
public static Map<WrappedStack, EnergyValue> decompressEnergyValueStackMapFromFile(File file)
{
Map<WrappedStack, EnergyValue> energyValueStackMap = new TreeMap<WrappedStack, EnergyValue>();
try
{
String jsonEnergyValueStackMap = CompressionHelper.decompress(Files.toByteArray(file));
JsonReader jsonReader = new JsonReader(new StringReader(jsonEnergyValueStackMap));
jsonReader.beginArray();
while (jsonReader.hasNext())
{
EnergyValueStackMapping energyValueStackMapping = EnergyValueStackMapping.jsonSerializer.fromJson(jsonReader, EnergyValueStackMapping.class);
if (energyValueStackMapping != null)
{
energyValueStackMap.put(energyValueStackMapping.wrappedStack, energyValueStackMapping.energyValue);
}
}
jsonReader.endArray();
jsonReader.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return energyValueStackMap;
}
} }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 84 KiB

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 134 KiB