Holy Moly, it's a big fat commit of broken code!

This commit is contained in:
cpw authored and LexManos committed 2018-09-05 11:16:33 -07:00
1 parent 5b05e103f4
commit c1f0e1b68f
63 files changed
+2027 -542

No files matched your search

@@ -27,6 +27,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraftforge.fml.StringUtils;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.common.versioning.DefaultArtifactVersion;
import net.minecraftforge.fml.common.versioning.VersionRange;
@@ -97,6 +98,12 @@ public class DummyModContainer implements ModContainer
return md.modId;
}
@Override
public String getPrefix()
{
return StringUtils.toLowerCase(getModId());
}
@Override
public String getName()
{
@@ -19,27 +19,18 @@
package net.minecraftforge.fml.common;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
@@ -61,6 +52,7 @@ import net.minecraftforge.client.model.animation.Animation;
import net.minecraftforge.common.ForgeVersion;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.CompoundDataFixer;
import net.minecraftforge.fml.client.BrandingControl;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.EventBus;
import net.minecraftforge.fml.common.gameevent.InputEvent;
@@ -70,22 +62,17 @@ import net.minecraftforge.fml.common.gameevent.TickEvent.Phase;
import net.minecraftforge.fml.common.network.FMLNetworkEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.thread.SidedThreadGroup;
import net.minecraftforge.fml.relauncher.CoreModManager;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.server.FMLServerHandler;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.Logger;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import javax.annotation.Nullable;
/**
* The main class for non-obfuscated hook handling code
*
@@ -113,7 +100,6 @@ public class FMLCommonHandler
private boolean noForge;
private List<String> brandings;
private List<String> brandingsNoMC;
private List<ICrashCallable> crashCallables = Lists.newArrayList(Loader.instance().getCallableCrashInformation());
private Set<SaveHandler> handlerSet = Collections.newSetFromMap(new MapMaker().weakKeys().<SaveHandler,Boolean>makeMap());
private WeakReference<SaveHandler> handlerToCheck;
private EventBus eventBus = MinecraftForge.EVENT_BUS;
@@ -121,26 +107,6 @@ public class FMLCommonHandler
private FMLCommonHandler()
{
registerCrashCallable(new ICrashCallable()
{
@Override
public String call() throws Exception
{
StringBuilder builder = new StringBuilder();
Joiner joiner = Joiner.on("\n ");
for(String coreMod : CoreModManager.getTransformers().keySet())
{
builder.append("\n" + coreMod + "\n ").append(joiner.join(CoreModManager.getTransformers().get(coreMod)));
}
return builder.toString();
}
@Override
public String getLabel()
{
return "Loaded coremods (and transformers)";
}
});
}
/**
* The FML event bus. Subscribe here for FML related events
@@ -224,34 +190,11 @@ public class FMLCommonHandler
}
public void computeBranding()
{
if (brandings == null)
{
Builder<String> brd = ImmutableList.builder();
brd.add(Loader.instance().getMCVersionString());
brd.add(Loader.instance().getMCPVersionString());
brd.add("Powered by Forge " + ForgeVersion.getVersion());
if (sidedDelegate!=null)
{
brd.addAll(sidedDelegate.getAdditionalBrandingInformation());
}
if (Loader.instance().getFMLBrandingProperties().containsKey("fmlbranding"))
{
brd.add(Loader.instance().getFMLBrandingProperties().get("fmlbranding"));
}
int tModCount = Loader.instance().getModList().size();
int aModCount = Loader.instance().getActiveModList().size();
brd.add(String.format("%d mod%s loaded, %d mod%s active", tModCount, tModCount!=1 ? "s" :"", aModCount, aModCount!=1 ? "s" :"" ));
brandings = brd.build();
brandingsNoMC = brandings.subList(1, brandings.size());
}
}
public List<String> getBrandings(boolean includeMC)
{
if (brandings == null)
{
computeBranding();
BrandingControl.computeBranding();
}
return includeMC ? ImmutableList.copyOf(brandings) : ImmutableList.copyOf(brandingsNoMC);
}
@@ -370,19 +313,6 @@ public class FMLCommonHandler
bus().post(new TickEvent.PlayerTickEvent(Phase.END, player));
}
public void registerCrashCallable(ICrashCallable callable)
{
crashCallables.add(callable);
}
public void enhanceCrashReport(CrashReport crashReport, CrashReportCategory category)
{
for (ICrashCallable call: crashCallables)
{
category.addDetail(call.getLabel(), call);
}
}
public void handleWorldDataSave(SaveHandler handler, WorldInfo worldInfo, NBTTagCompound tagCompound)
{
for (ModContainer mc : Loader.instance().getModList())
@@ -709,47 +639,6 @@ public class FMLCommonHandler
}
}
/**
* Loads a lang file, first searching for a marker to enable the 'extended' format {escape characters}
* If the marker is not found it simply returns and let the vanilla code load things.
* The Marker is 'PARSE_ESCAPES' by itself on a line starting with '#' as such:
* #PARSE_ESCAPES
*
* @param table The Map to load each key/value pair into.
* @param inputstream Input stream containing the lang file.
* @return A new InputStream that vanilla uses to load normal Lang files, Null if this is a 'enhanced' file and loading is done.
*/
@Nullable
public InputStream loadLanguage(Map<String, String> table, InputStream inputstream) throws IOException
{
byte[] data = IOUtils.toByteArray(inputstream);
boolean isEnhanced = false;
for (String line : IOUtils.readLines(new ByteArrayInputStream(data), StandardCharsets.UTF_8))
{
if (!line.isEmpty() && line.charAt(0) == '#')
{
line = line.substring(1).trim();
if (line.equals("PARSE_ESCAPES"))
{
isEnhanced = true;
break;
}
}
}
if (!isEnhanced)
return new ByteArrayInputStream(data);
Properties props = new Properties();
props.load(new InputStreamReader(new ByteArrayInputStream(data), StandardCharsets.UTF_8));
for (Entry<Object, Object> e : props.entrySet())
{
table.put((String)e.getKey(), (String)e.getValue());
}
props.clear();
return null;
}
public String stripSpecialChars(String message)
{
return sidedDelegate != null ? sidedDelegate.stripSpecialChars(message) : message;
@@ -54,10 +54,13 @@ import net.minecraftforge.fml.common.versioning.DefaultArtifactVersion;
import net.minecraftforge.fml.common.versioning.DependencyParser;
import net.minecraftforge.fml.common.versioning.VersionParser;
import net.minecraftforge.fml.common.versioning.VersionRange;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import net.minecraftforge.fml.relauncher.Side;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
@@ -73,10 +76,11 @@ import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.apache.logging.log4j.message.FormattedMessage;
import javax.annotation.Nullable;
import static net.minecraftforge.fml.Logging.CORE;
public class FMLModContainer implements ModContainer
{
private Object modInstance;
@@ -105,6 +109,8 @@ public class FMLModContainer implements ModContainer
private URL updateJSONUrl;
private int classVersion;
private Logger modLog;
public FMLModContainer(String className, ModCandidate container, Map<String, Object> modDescriptor)
{
this.className = className;
@@ -126,6 +132,22 @@ public class FMLModContainer implements ModContainer
FMLLog.log.trace("Using custom language adapter {} for {} (modid: {})", languageAdapterType, this.className, getModId());
}
sanityCheckModId();
modLog = LogManager.getLogger(getModId());
}
public FMLModContainer(ModInfo info, String className, ClassLoader modClassLoader)
{
try
{
final Class<?> aClass = Class.forName(className, true, modClassLoader);
LogManager.getLogger("FML").error("Loaded {} with {}", aClass, aClass.getClassLoader());
}
catch (ClassNotFoundException e)
{
LogManager.getLogger("FML").error(CORE, "Failed to load class {}", className, e);
throw new RuntimeException(e);
}
}
private void sanityCheckModId()
@@ -212,15 +234,15 @@ public class FMLModContainer implements ModContainer
modMetadata.requiredMods = info.requirements;
modMetadata.dependencies = info.dependencies;
modMetadata.dependants = info.dependants;
FMLLog.log.trace("Parsed dependency info for {}: Requirements: {} After:{} Before:{}", getModId(), info.requirements, info.dependencies, info.dependants);
modLog.trace("Parsed dependency info : Requirements: {} After:{} Before:{}", info.requirements, info.dependencies, info.dependants);
}
else
{
FMLLog.log.trace("Using mcmod dependency info for {}: {} {} {}", getModId(), modMetadata.requiredMods, modMetadata.dependencies, modMetadata.dependants);
modLog.trace("Using mcmod dependency info : {} {} {}", modMetadata.requiredMods, modMetadata.dependencies, modMetadata.dependants);
}
if (Strings.isNullOrEmpty(modMetadata.name))
{
FMLLog.log.info("Mod {} is missing the required element 'name'. Substituting {}", getModId(), getModId());
modLog.info("Mod {} is missing the required element 'name'. Substituting {}", getModId(), getModId());
modMetadata.name = getModId();
}
internalVersion = (String)descriptor.get("version");
@@ -230,18 +252,18 @@ public class FMLModContainer implements ModContainer
if (versionProps != null)
{
internalVersion = versionProps.getProperty(getModId() + ".version");
FMLLog.log.debug("Found version {} for mod {} in version.properties, using", internalVersion, getModId());
modLog.debug("Found version {} for mod {} in version.properties, using", internalVersion, getModId());
}
}
if (Strings.isNullOrEmpty(internalVersion) && !Strings.isNullOrEmpty(modMetadata.version))
{
FMLLog.log.warn("Mod {} is missing the required element 'version' and a version.properties file could not be found. Falling back to metadata version {}", getModId(), modMetadata.version);
modLog.warn("Mod {} is missing the required element 'version' and a version.properties file could not be found. Falling back to metadata version {}", getModId(), modMetadata.version);
internalVersion = modMetadata.version;
}
if (Strings.isNullOrEmpty(internalVersion))
{
FMLLog.log.warn("Mod {} is missing the required element 'version' and no fallback can be found. Substituting '1.0'.", getModId());
modLog.warn("Mod {} is missing the required element 'version' and no fallback can be found. Substituting '1.0'.", getModId());
modMetadata.version = internalVersion = "1.0";
}
@@ -269,7 +291,7 @@ public class FMLModContainer implements ModContainer
}
catch (MalformedURLException e)
{
FMLLog.log.debug("Specified json URL for mod '{}' is invalid: {}", getModId(), jsonURL);
modLog.debug("Specified json URL invalid: {}", jsonURL);
}
}
}
@@ -279,7 +301,7 @@ public class FMLModContainer implements ModContainer
{
try
{
FMLLog.log.debug("Attempting to load the file version.properties from {} to locate a version number for mod {}", getSource().getName(), getModId());
modLog.debug("Attempting to load the file version.properties from {} to locate a version number for {}", getSource().getName(), getModId());
Properties version = null;
if (getSource().isFile())
{
@@ -316,7 +338,7 @@ public class FMLModContainer implements ModContainer
}
catch (IOException e)
{
FMLLog.log.trace("Failed to find a usable version.properties file for mod {}", getModId());
modLog.trace("Failed to find a usable version.properties file");
return null;
}
}
@@ -368,7 +390,7 @@ public class FMLModContainer implements ModContainer
{
if (this.enabled)
{
FMLLog.log.debug("Enabling mod {}", getModId());
modLog.debug("Enabling mod {}", getModId());
this.eventBus = bus;
this.controller = controller;
eventBus.register(this);
@@ -381,7 +403,8 @@ public class FMLModContainer implements ModContainer
}
@Nullable
private Method gatherAnnotations(Class<?> clazz)
@SuppressWarnings("unchecked")
private Method gatherAnnotations(Class<?> clazz) throws Exception
{
Method factoryMethod = null;
for (Method m : clazz.getDeclaredMethods())
@@ -393,13 +416,11 @@ public class FMLModContainer implements ModContainer
if (m.getParameterTypes().length == 1 && FMLEvent.class.isAssignableFrom(m.getParameterTypes()[0]))
{
m.setAccessible(true);
@SuppressWarnings("unchecked")
Class<? extends FMLEvent> parameterType = (Class<? extends FMLEvent>) m.getParameterTypes()[0];
eventMethods.put(parameterType, m);
eventMethods.put((Class<? extends FMLEvent>)m.getParameterTypes()[0], m);
}
else
{
FMLLog.log.error("The mod {} appears to have an invalid event annotation {}. This annotation can only apply to methods with recognized event arguments - it will not be called", getModId(), a.annotationType().getSimpleName());
modLog.error("The mod {} appears to have an invalid event annotation {}. This annotation can only apply to methods with recognized event arguments - it will not be called", getModId(), a.annotationType().getSimpleName());
}
}
else if (a.annotationType().equals(Mod.InstanceFactory.class))
@@ -411,11 +432,11 @@ public class FMLModContainer implements ModContainer
}
else if (!(Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0))
{
FMLLog.log.error("The InstanceFactory annotation can only apply to a static method, taking zero arguments - it will be ignored on {}({}) for mod {}", m.getName(), Arrays.asList(m.getParameterTypes()), getModId());
modLog.error("The InstanceFactory annotation can only apply to a static method, taking zero arguments - it will be ignored on {}({})", m.getName(), Arrays.asList(m.getParameterTypes()));
}
else if (factoryMethod != null)
{
FMLLog.log.error("The InstanceFactory annotation can only be used once, the application to {}({}) will be ignored for mod {}", m.getName(), Arrays.asList(m.getParameterTypes()), getModId());
modLog.error("The InstanceFactory annotation can only be used once, the application to {}({}) will be ignored", m.getName(), Arrays.asList(m.getParameterTypes()));
}
}
}
@@ -423,7 +444,7 @@ public class FMLModContainer implements ModContainer
return factoryMethod;
}
private void processFieldAnnotations(ASMDataTable asmDataTable) throws IllegalAccessException
private void processFieldAnnotations(ASMDataTable asmDataTable) throws Exception
{
SetMultimap<String, ASMData> annotations = asmDataTable.getAnnotationsFor(this);
@@ -482,7 +503,7 @@ public class FMLModContainer implements ModContainer
}
catch (ReflectiveOperationException e)
{
FMLLog.log.warn("Attempting to load @{} in class {} for {} and failing", annotationName, targets.getClassName(), mc.getModId(), e);
modLog.warn("Attempting to load @{} in class {} for {} and failing", annotationName, targets.getClassName(), mc.getModId(), e);
}
}
if (f != null)
@@ -493,7 +514,7 @@ public class FMLModContainer implements ModContainer
target = modInstance;
if (!modInstance.getClass().equals(clz))
{
FMLLog.log.warn("Unable to inject @{} in non-static field {}.{} for {} as it is NOT the primary mod instance", annotationName, targets.getClassName(), targets.getObjectName(), mc.getModId());
modLog.warn("Unable to inject @{} in non-static field {}.{} for {} as it is NOT the primary mod instance", annotationName, targets.getClassName(), targets.getObjectName(), mc.getModId());
continue;
}
}
@@ -505,108 +526,85 @@ public class FMLModContainer implements ModContainer
@Subscribe
public void constructMod(FMLConstructionEvent event)
{
ModClassLoader modClassLoader = event.getModClassLoader();
try
{
ModClassLoader modClassLoader = event.getModClassLoader();
modClassLoader.addFile(source);
}
catch (MalformedURLException e)
{
FormattedMessage message = new FormattedMessage("{} Failed to add file to classloader: {}", getModId(), source);
throw new LoaderException(message.getFormattedMessage(), e);
}
modClassLoader.clearNegativeCacheFor(candidate.getClassList());
modClassLoader.clearNegativeCacheFor(candidate.getClassList());
//Only place I could think to add this...
MinecraftForge.preloadCrashClasses(event.getASMHarvestedData(), getModId(), candidate.getClassList());
//Only place I could think to add this...
MinecraftForge.preloadCrashClasses(event.getASMHarvestedData(), getModId(), candidate.getClassList());
Class<?> clazz;
try
{
clazz = Class.forName(className, true, modClassLoader);
}
catch (ClassNotFoundException e)
{
FormattedMessage message = new FormattedMessage("{} Failed load class: {}", getModId(), className);
throw new LoaderException(message.getFormattedMessage(), e);
}
Class<?> clazz = Class.forName(className, true, modClassLoader);
Certificate[] certificates = clazz.getProtectionDomain().getCodeSource().getCertificates();
ImmutableList<String> certList = CertificateHelper.getFingerprints(certificates);
sourceFingerprints = ImmutableSet.copyOf(certList);
Certificate[] certificates = clazz.getProtectionDomain().getCodeSource().getCertificates();
ImmutableList<String> certList = CertificateHelper.getFingerprints(certificates);
sourceFingerprints = ImmutableSet.copyOf(certList);
String expectedFingerprint = (String)descriptor.get("certificateFingerprint");
String expectedFingerprint = (String)descriptor.get("certificateFingerprint");
fingerprintNotPresent = true;
fingerprintNotPresent = true;
if (expectedFingerprint != null && !expectedFingerprint.isEmpty())
{
if (!sourceFingerprints.contains(expectedFingerprint))
if (expectedFingerprint != null && !expectedFingerprint.isEmpty())
{
Level warnLevel = source.isDirectory() ? Level.TRACE : Level.ERROR;
FMLLog.log.log(warnLevel, "The mod {} is expecting signature {} for source {}, however there is no signature matching that description", getModId(), expectedFingerprint, source.getName());
if (!sourceFingerprints.contains(expectedFingerprint))
{
Level warnLevel = Level.ERROR;
if (source.isDirectory())
{
warnLevel = Level.TRACE;
}
modLog.log(warnLevel, "The mod {} is expecting signature {} for source {}, however there is no signature matching that description", getModId(), expectedFingerprint, source.getName());
}
else
{
certificate = certificates[certList.indexOf(expectedFingerprint)];
fingerprintNotPresent = false;
}
}
@SuppressWarnings("unchecked")
List<Map<String, Object>> props = (List<Map<String, Object>>)descriptor.get("customProperties");
if (props != null)
{
com.google.common.collect.ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
for (Map<String, Object> p : props)
{
builder.put((String)p.get("k"), (String)p.get("v"));
}
customModProperties = builder.build();
}
else
{
certificate = certificates[certList.indexOf(expectedFingerprint)];
fingerprintNotPresent = false;
customModProperties = EMPTY_PROPERTIES;
}
}
@SuppressWarnings("unchecked")
List<Map<String, String>> props = (List<Map<String, String>>)descriptor.get("customProperties");
if (props != null)
{
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
for (Map<String, String> p : props)
Boolean hasDisableableFlag = (Boolean)descriptor.get("canBeDeactivated");
boolean hasReverseDepends = !event.getReverseDependencies().get(getModId()).isEmpty();
if (hasDisableableFlag != null && hasDisableableFlag)
{
builder.put(p.get("k"), p.get("v"));
disableability = hasReverseDepends ? Disableable.DEPENDENCIES : Disableable.YES;
}
customModProperties = builder.build();
}
else
{
customModProperties = EMPTY_PROPERTIES;
}
else
{
disableability = hasReverseDepends ? Disableable.DEPENDENCIES : Disableable.RESTART;
}
Method factoryMethod = gatherAnnotations(clazz);
modInstance = getLanguageAdapter().getNewInstance(this, clazz, modClassLoader, factoryMethod);
NetworkRegistry.INSTANCE.register(this, clazz, (String)(descriptor.containsKey("acceptableRemoteVersions") ? descriptor.get("acceptableRemoteVersions") : null), event.getASMHarvestedData());
if (fingerprintNotPresent)
{
eventBus.post(new FMLFingerprintViolationEvent(source.isDirectory(), source, ImmutableSet.copyOf(this.sourceFingerprints), expectedFingerprint));
}
ProxyInjector.inject(this, event.getASMHarvestedData(), FMLCommonHandler.instance().getSide(), getLanguageAdapter());
AutomaticEventSubscriber.inject(this, event.getASMHarvestedData(), FMLCommonHandler.instance().getSide());
ConfigManager.sync(this.getModId(), Config.Type.INSTANCE);
Boolean hasDisableableFlag = (Boolean)descriptor.get("canBeDeactivated");
boolean hasReverseDepends = !event.getReverseDependencies().get(getModId()).isEmpty();
if (hasDisableableFlag != null && hasDisableableFlag)
{
disableability = hasReverseDepends ? Disableable.DEPENDENCIES : Disableable.YES;
}
else
{
disableability = hasReverseDepends ? Disableable.DEPENDENCIES : Disableable.RESTART;
}
Method factoryMethod = gatherAnnotations(clazz);
ILanguageAdapter languageAdapter = getLanguageAdapter();
try
{
modInstance = languageAdapter.getNewInstance(this, clazz, modClassLoader, factoryMethod);
}
catch (Exception e)
{
FormattedMessage message = new FormattedMessage("{} Failed to load new mod instance.", getModId());
throw new LoaderException(message.getFormattedMessage(), e);
}
NetworkRegistry.INSTANCE.register(this, clazz, (String)(descriptor.getOrDefault("acceptableRemoteVersions", null)), event.getASMHarvestedData());
if (fingerprintNotPresent)
{
eventBus.post(new FMLFingerprintViolationEvent(source.isDirectory(), source, ImmutableSet.copyOf(this.sourceFingerprints), expectedFingerprint));
}
ProxyInjector.inject(this, event.getASMHarvestedData(), FMLCommonHandler.instance().getSide(), languageAdapter);
AutomaticEventSubscriber.inject(this, event.getASMHarvestedData(), FMLCommonHandler.instance().getSide());
ConfigManager.sync(this.getModId(), Config.Type.INSTANCE);
try
{
processFieldAnnotations(event.getASMHarvestedData());
}
catch (IllegalAccessException e)
catch (Throwable e)
{
FormattedMessage message = new FormattedMessage("{} Failed to process field annotations.", getModId());
throw new LoaderException(message.getFormattedMessage(), e);
controller.errorOccurred(this, e);
}
}
@@ -757,19 +757,6 @@ public class Loader
public ICrashCallable getCallableCrashInformation()
{
return new ICrashCallable() {
@Override
public String call() throws Exception
{
return getCrashInformation();
}
@Override
public String getLabel()
{
return "FML";
}
};
}
public List<ModContainer> getActiveModList()
@@ -61,42 +61,6 @@ public @interface Mod
* By default, you will have a resource domain that matches the modid. All these uses require that constraints are imposed on the format of the modid.
*/
String modid();
/**
* An optional GUI factory for this mod. This is the name of a class implementing {@link IModGuiFactory} that will be instantiated
* on the client side, and will have certain configuration/options guis requested from it.
*
* @return The name of a class implementing {@link IModGuiFactory}
*/
String guiFactory() default "";
/**
* A list of custom properties for this mod. Completely up to the mod author if/when they
* want to put anything in here.
* @return an optional list of custom properties
*/
CustomProperty[] customProperties() default {};
/**
* A custom key => value property pair for use with {@link Mod#customProperties()}
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({})
@interface CustomProperty
{
/**
* A key. Should be unique.
* @return A key
*/
String k();
/**
* A value. Can be anything.
* @return A value
*/
String v();
}
/**
* Marks the associated method as handling an FML lifecycle event.
* The method must have a single parameter, one of the following types. This annotation
@@ -51,11 +51,13 @@ public interface ModContainer
{
public static enum Disableable {
YES, RESTART, NEVER, DEPENDENCIES;
}
/**
* The globally unique modid for this mod
*/
String getModId();
String getPrefix();
/**
* A human readable name
@@ -24,6 +24,16 @@ import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import com.google.common.base.Joiner;
import net.minecraftforge.api.Side;
import net.minecraftforge.fml.SidedExecutor;
import net.minecraftforge.fml.client.SplashProgress;
import org.apache.logging.log4j.message.MessageFormatMessage;
import org.apache.logging.log4j.message.StringFormattedMessage;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.opengl.Display;
import static net.minecraftforge.fml.Logging.SPLASH;
import static net.minecraftforge.fml.Logging.fmlLog;
/**
* Not a fully fleshed out API, may change in future MC versions.
@@ -52,7 +62,7 @@ public class ProgressManager
{
bar.timeEachStep();
}
FMLCommonHandler.instance().processWindowMessages();
SidedExecutor.runOn(Side.CLIENT, ()->SplashProgress::processMessages);
return bar;
}
@@ -71,17 +81,13 @@ public class ProgressManager
{
long newTime = System.nanoTime();
if (bar.timeEachStep)
{
String timeString = String.format("%.3f", ((float) (newTime - bar.lastTime) / 1000000 / 1000));
FMLLog.log.debug("Bar Step: {} - {} took {}s", bar.getTitle(), bar.getMessage(), timeString);
}
String timeString = String.format("%.3f", ((float) (newTime - bar.startTime) / 1000000 / 1000));
fmlLog.debug(SPLASH, () -> new MessageFormatMessage("Bar Step: {0} - {1} took {2,number,0.000}ms", bar.getTitle(), bar.getMessage(), (newTime - bar.lastTime) / 1.0e6));
if (bar.getSteps() == 1)
FMLLog.log.debug("Bar Finished: {} - {} took {}s", bar.getTitle(), bar.getMessage(), timeString);
fmlLog.debug(SPLASH, () -> new MessageFormatMessage("Bar Finished: {0} - {1} took {2,number,0.000}ms", bar.getTitle(), bar.getMessage(), (newTime - bar.lastTime) / 1.0e6));
else
FMLLog.log.debug("Bar Finished: {} took {}s", bar.getTitle(), timeString);
fmlLog.debug(SPLASH, () -> new MessageFormatMessage("Bar Finished: {0} took {1,number,0.000}ms", bar.getTitle(), (newTime - bar.lastTime) / 1.0e6));
}
FMLCommonHandler.instance().processWindowMessages();
SidedExecutor.runOn(Side.CLIENT, ()->SplashProgress::processMessages);
}
/*
@@ -124,7 +130,7 @@ public class ProgressManager
if (timeEachStep && step != 0)
{
long newTime = System.nanoTime();
FMLLog.log.debug(String.format("Bar Step: %s - %s took %.3fs", getTitle(), getMessage(), ((float)(newTime - lastTime) / 1000000 / 1000)));
fmlLog.debug(SPLASH,new MessageFormatMessage("Bar Step: {0} - {1} took {2,number,0.000}ms", getTitle(), getMessage(), (newTime - lastTime) / 1.0e6));
lastTime = newTime;
}
step++;
@@ -24,8 +24,11 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Sets;
import net.minecraftforge.fml.common.DummyModContainer;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.ModAPIManager;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.toposort.TopologicalSort.DirectedGraph;
@@ -137,7 +140,23 @@ public class ModSorter
public List<ModContainer> sort()
{
List<ModContainer> sortedList = TopologicalSort.topologicalSort(modGraph);
List<ModContainer> sortedList;
try
{
sortedList = TopologicalSort.topologicalSort(modGraph);
}
catch (TopologicalSort.TopoSortException tse)
{
FMLLog.log.fatal("Mod Sorting failed.");
FMLLog.log.fatal("Visiting node {}", tse.getNode());
FMLLog.log.fatal("Current sorted list : {}", tse.getSortedResult());
FMLLog.log.fatal("Visited set for this node : {}", tse.getVisitedNodes());
FMLLog.log.fatal("Explored node set : {}", tse.getExpandedNodes());
Sets.SetView<?> cycleList = Sets.difference(tse.getVisitedNodes(), tse.getExpandedNodes());
FMLLog.log.fatal("Likely cycle is in : {}", cycleList);
throw new ModSortingException("There was a cycle detected in the input graph, sorting is not possible", tse.getNode(), cycleList);
}
sortedList.removeAll(Arrays.asList(new ModContainer[] {beforeAll, before, after, afterAll}));
return sortedList;
}
@@ -59,7 +59,7 @@ public class ModSortingException extends EnhancedRuntimeException implements IDi
public <T> ModSortingException(String string, T node, Set<T> visitedNodes)
{
super(string);
this.sortingExceptionData = new SortingExceptionData<T>(node, visitedNodes);
this.sortingExceptionData = new SortingExceptionData<>(node, visitedNodes);
}
@SuppressWarnings("unchecked")
@@ -32,11 +32,6 @@ import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import net.minecraftforge.fml.common.FMLLog;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
/**
* Topological sort for mod loading
*
@@ -48,8 +43,8 @@ public class TopologicalSort
{
public static class DirectedGraph<T> implements Iterable<T>
{
private final Map<T, SortedSet<T>> graph = new HashMap<T, SortedSet<T>>();
private List<T> orderedNodes = new ArrayList<T>();
private final Map<T, SortedSet<T>> graph = new HashMap<>();
private List<T> orderedNodes = new ArrayList<>();
public boolean addNode(T node)
{
@@ -60,7 +55,7 @@ public class TopologicalSort
}
orderedNodes.add(node);
graph.put(node, new TreeSet<T>(Comparator.comparingInt(o -> orderedNodes.indexOf(o))));
graph.put(node, new TreeSet<>(Comparator.comparingInt(o -> orderedNodes.indexOf(o))));
return true;
}
@@ -136,10 +131,10 @@ public class TopologicalSort
public static <T> List<T> topologicalSort(DirectedGraph<T> graph)
{
DirectedGraph<T> rGraph = reverse(graph);
List<T> sortedResult = new ArrayList<T>();
Set<T> visitedNodes = new HashSet<T>();
List<T> sortedResult = new ArrayList<>();
Set<T> visitedNodes = new HashSet<>();
// A list of "fully explored" nodes. Leftovers in here indicate cycles in the graph
Set<T> expandedNodes = new HashSet<T>();
Set<T> expandedNodes = new HashSet<>();
for (T node : rGraph)
{
@@ -151,7 +146,7 @@ public class TopologicalSort
public static <T> DirectedGraph<T> reverse(DirectedGraph<T> graph)
{
DirectedGraph<T> result = new DirectedGraph<T>();
DirectedGraph<T> result = new DirectedGraph<>();
for (T node : graph)
{
@@ -169,7 +164,7 @@ public class TopologicalSort
return result;
}
public static <T> void explore(T node, DirectedGraph<T> graph, List<T> sortedResult, Set<T> visitedNodes, Set<T> expandedNodes)
private static <T> void explore(T node, DirectedGraph<T> graph, List<T> sortedResult, Set<T> visitedNodes, Set<T> expandedNodes)
{
// Have we been here before?
if (visitedNodes.contains(node))
@@ -181,14 +176,7 @@ public class TopologicalSort
return;
}
FMLLog.log.fatal("Mod Sorting failed.");
FMLLog.log.fatal("Visiting node {}", node);
FMLLog.log.fatal("Current sorted list : {}", sortedResult);
FMLLog.log.fatal("Visited set for this node : {}", visitedNodes);
FMLLog.log.fatal("Explored node set : {}", expandedNodes);
SetView<T> cycleList = Sets.difference(visitedNodes, expandedNodes);
FMLLog.log.fatal("Likely cycle is in : {}", cycleList);
throw new ModSortingException("There was a cycle detected in the input graph, sorting is not possible", node, cycleList);
throw new TopoSortException(node, sortedResult, visitedNodes, expandedNodes);
}
// Visit this node
@@ -205,4 +193,39 @@ public class TopologicalSort
// And mark ourselves as explored
expandedNodes.add(node);
}
static class TopoSortException extends RuntimeException {
private final Object node;
private final List<?> sortedResult;
private final Set<?> visitedNodes;
private final Set<?> expandedNodes;
public TopoSortException(Object node, List<?> sortedResult, Set<?> visitedNodes, Set<?> expandedNodes)
{
this.node = node;
this.sortedResult = sortedResult;
this.visitedNodes = visitedNodes;
this.expandedNodes = expandedNodes;
}
public Object getNode()
{
return node;
}
public List<?> getSortedResult()
{
return sortedResult;
}
public Set<?> getVisitedNodes()
{
return visitedNodes;
}
public Set<?> getExpandedNodes()
{
return expandedNodes;
}
}
}
@@ -27,7 +27,7 @@ package net.minecraftforge.fml.common.versioning;
*
* @author <a href="mailto:[email protected]">Brett Porter</a>
*/
public class InvalidVersionSpecificationException extends Exception
public class InvalidVersionSpecificationException extends RuntimeException
{
private static final long serialVersionUID = 1L;