Introduce rework of Capability provider. And reduce errors to <2000

This commit is contained in:
LexManos committed 2018-09-06 06:27:24 -07:00
1 parent 12869710de
commit eac693e785
25 files changed
+485 -176

No files matched your search

@@ -20,9 +20,9 @@
package net.minecraftforge.common;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
@@ -33,7 +33,6 @@ import java.util.UUID;
import javax.annotation.Nullable;
import com.google.common.base.Charsets;
import net.minecraft.world.storage.ThreadedFileIOBase;
import net.minecraftforge.fml.loading.FMLLoader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -162,6 +161,7 @@ public final class UsernameCache {
try (final BufferedReader reader = Files.newBufferedReader(saveFile, Charsets.UTF_8))
{
@SuppressWarnings("serial")
Type type = new TypeToken<Map<UUID, String>>(){}.getType();
map = gson.fromJson(reader, type);
}
@@ -209,13 +209,13 @@ public final class UsernameCache {
// Make sure we don't save when another thread is still saving
synchronized (saveFile)
{
Files.write(data, saveFile, charset);
Files.write(saveFile, data.getBytes(StandardCharsets.UTF_8));
}
}
catch (IOException e)
{
log.error("Failed to save username cache to file!", e);
LOGGER.error(USRCACHE, "Failed to save username cache to file!", e);
}
}
}
}
}
@@ -22,20 +22,19 @@ package net.minecraftforge.common;
import java.io.File;
import java.io.IOException;
import net.minecraft.world.gen.structure.template.TemplateManager;
import org.apache.logging.log4j.Level;
import com.google.common.io.Files;
import com.mojang.datafixers.DataFixer;
import net.minecraft.world.chunk.storage.IChunkLoader;
import net.minecraft.world.dimension.Dimension;
import net.minecraft.world.gen.feature.template.TemplateManager;
import net.minecraft.world.storage.IPlayerFileData;
import net.minecraft.world.storage.ISaveHandler;
import net.minecraft.world.MinecraftException;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.storage.WorldInfo;
import net.minecraft.world.WorldProvider;
import net.minecraft.world.WorldServer;
import net.minecraftforge.fml.common.FMLLog;
//Class used internally to provide the world specific data directories.
@@ -53,12 +52,13 @@ public class WorldSpecificSaveHandler implements ISaveHandler
@Override public WorldInfo loadWorldInfo() { return parent.loadWorldInfo(); }
@Override public void checkSessionLock() throws MinecraftException { parent.checkSessionLock(); }
@Override public IChunkLoader getChunkLoader(WorldProvider var1) { return parent.getChunkLoader(var1); }
@Override public IChunkLoader getChunkLoader(Dimension var1) { return parent.getChunkLoader(var1); }
@Override public void saveWorldInfoWithPlayer(WorldInfo var1, NBTTagCompound var2) { parent.saveWorldInfoWithPlayer(var1, var2); }
@Override public void saveWorldInfo(WorldInfo var1){ parent.saveWorldInfo(var1); }
@Override public IPlayerFileData getPlayerNBTManager() { return parent.getPlayerNBTManager(); }
@Override public void flush() { parent.flush(); }
@Override public File getWorldDirectory() { return parent.getWorldDirectory(); }
@Override public DataFixer func_197718_i() { return parent.func_197718_i(); }
@Override
public File getMapFileFromName(String name)
@@ -105,5 +105,4 @@ public class WorldSpecificSaveHandler implements ISaveHandler
{
return parent.getStructureTemplateManager();
}
}
@@ -0,0 +1,72 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.asm;
import java.nio.file.Path;
import java.util.List;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
/**
* Removes the final modifier from fields with the @CapabilityInject annotation, prevents the JITer from in lining them so our runtime replacements can work.
*/
public class CapabilityInjectDefinalize implements ILaunchPluginService {
private final String CAP = "Lnet/minecraftforge/common/capabilities/Capability;"; //Don't directly reference this to prevent class loading.
private final String CAP_INJECT = "Lnet/minecraftforge/common/capabilities/CapabilityInject;"; //Don't directly reference this to prevent class loading.
@Override
public String name() {
return "capability_inject_definalize";
}
@Override public void addResource(Path resource, String name) { }
@Override public <T> T getExtension() { return null; } // ?
@Override
public boolean handlesClass(Type classType, boolean isEmpty)
{
return !isEmpty; //Check for annotations?
}
private boolean hasHolder(List<AnnotationNode> lst)
{
return lst != null && lst.stream().anyMatch(n -> n.desc.equals(CAP_INJECT));
}
@Override
public ClassNode processClass(ClassNode classNode, Type classType)
{
final int flags = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL;
classNode.fields.stream().filter(f -> ((f.access & flags) == flags) && f.desc.equals(CAP) && hasHolder(f.visibleAnnotations)).forEach(f ->
{
f.access &= ~Opcodes.ACC_FINAL; //Strip final
f.access |= Opcodes.ACC_SYNTHETIC; //Add Synthetic so we can check in runtime.
});
return classNode;
}
}
@@ -19,7 +19,6 @@
package net.minecraftforge.common.capabilities;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
@@ -86,32 +85,18 @@ public final class CapabilityDispatcher implements INBTSerializable<NBTTagCompou
names = lstNames.toArray(new String[lstNames.size()]);
}
@Override
public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing)
{
for (ICapabilityProvider cap : caps)
{
if (cap.hasCapability(capability, facing))
{
return true;
}
}
return false;
}
@Override
@Nullable
public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing)
public <T> OptionalCapabilityInstance<T> getCapability(Capability<T> cap, EnumFacing side)
{
for (ICapabilityProvider cap : caps)
for (ICapabilityProvider c : caps)
{
T ret = cap.getCapability(capability, facing);
if (ret != null)
{
OptionalCapabilityInstance<T> ret = c.getCapability(cap, side);
if (ret.isPresent()) {
return ret;
}
}
return null;
return OptionalCapabilityInstance.empty();
}
@Override
@@ -38,8 +38,6 @@ import org.objectweb.asm.Type;
import java.util.function.Function;
import java.util.stream.Collectors;
import net.minecraftforge.common.util.EnumHelper;
import static net.minecraftforge.fml.Logging.CAPABILITIES;
public enum CapabilityManager
@@ -138,8 +136,8 @@ public enum CapabilityManager
LOGGER.warn(CAPABILITIES,"Unable to inject capability {} at {}.{} (Non-Static)", capabilityName, targetClass, targetName);
return null;
}
// TODO Remove enumhelper here
EnumHelper.setFailsafeFieldValue(field, null, input);
field.setAccessible(true);
field.set(null, input);
}
catch (Exception e)
{
@@ -19,8 +19,6 @@
package net.minecraftforge.common.capabilities;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@@ -29,41 +27,23 @@ import net.minecraft.util.EnumFacing;
public interface ICapabilityProvider
{
/**
* Determines if this object has support for the capability in question on the specific side.
* The return value of this MIGHT change during runtime if this object gains or loses support
* for a capability. It is not required to call this function before calling
* {@link #getCapability(Capability, EnumFacing)}.
* <p>
* Basically, this method functions analogously to {@link Map#containsKey(Object)}.
* <p>
* <em>Example:</em>
* A Pipe getting a cover placed on one side causing it lose the Inventory attachment function for that side.
* </p><p>
* This is a light weight version of getCapability, intended for metadata uses.
* </p>
* @param capability The capability to check
* @param facing The Side to check from:
* CAN BE NULL. Null is defined to represent 'internal' or 'self'
* @return True if this object supports the capability. If true, then {@link #getCapability(Capability, EnumFacing)}
* must not return null.
*/
boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing);
/**
* Retrieves the handler for the capability requested on the specific side.
* <ul>
* <li>The return value <strong>CAN</strong> be null if the object does not support the capability.</il>
* <li>The return value <strong>CAN</strong> be the same for multiple faces.</li>
* </ul>
* <p>
* Basically, this method functions analogously to {@link Map#get(Object)}.
* Retrieves the Optional handler for the capability requested on the specific side.
* The return value <strong>CAN</strong> be the same for multiple faces.
* Modders are encouraged to cache this value, using the listener capabilities of the Optional to
* be notified if the requested capability get lost.
*
* @param capability The capability to check
* @param facing The Side to check from,
* @param facing The Side to check from,
* <strong>CAN BE NULL</strong>. Null is defined to represent 'internal' or 'self'
* @return The requested capability. Must <strong>NOT</strong> be null when {@link #hasCapability(Capability, EnumFacing)}
* would return true.
* @return The requested an optional holding the requested capability.
*/
@Nullable
<T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing);
@Nonnull <T> OptionalCapabilityInstance<T> getCapability(@Nonnull final Capability<T> cap, final @Nullable EnumFacing side);
/*
* Purely added as a bouncer to sided version, to make modders stop complaining about calling with a null value.
* This should never be OVERRIDDEN, modders should only ever implement the sided version.
*/
@Nonnull default <T> OptionalCapabilityInstance<T> getCapability(@Nonnull final Capability<T> cap) {
return getCapability(cap, null);
}
}
@@ -0,0 +1,29 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.capabilities;
import javax.annotation.Nonnull;
//Exactly like Supplier, except there IS a contract that each invocation should return a new unique instance and it must not be null.
@FunctionalInterface
public interface NonNullSupplier<T>
{
@Nonnull T get();
}
@@ -0,0 +1,247 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.capabilities;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class OptionalCapabilityInstance<T>
{
private final NonNullSupplier<T> supplier;
private AtomicReference<T> resolved;
private Set<Consumer<OptionalCapabilityInstance<T>>> listeners = new HashSet<>();
private boolean isValid = true;
private static final OptionalCapabilityInstance<Void> EMPTY = new OptionalCapabilityInstance<>(null);
@SuppressWarnings("unchecked")
public static <T> OptionalCapabilityInstance<T> empty()
{
return (OptionalCapabilityInstance<T>)EMPTY;
}
@SuppressWarnings("unchecked")
public <X> OptionalCapabilityInstance<X> cast()
{
return (OptionalCapabilityInstance<X>)this;
}
private OptionalCapabilityInstance(NonNullSupplier<T> instanceSupplier)
{
this.supplier = instanceSupplier;
}
public static <T> OptionalCapabilityInstance<T> of(final NonNullSupplier<T> instanceSupplier)
{
return new OptionalCapabilityInstance<>(instanceSupplier);
}
private T getValue()
{
if (!isValid)
return null;
if (resolved != null)
return resolved.get();
if (supplier != null)
{
resolved = new AtomicReference<>(null);
try
{
T temp = supplier.get();
if (temp == null)
throw new IllegalStateException("Supplier must not return null value");
resolved.set(temp);
return resolved.get();
}
catch (Throwable e)
{
return null;
}
}
return null;
}
/**
* Return {@code true} if there is a mod object present, otherwise {@code false}.
*
* @return {@code true} if there is a mod object present, otherwise {@code false}
*/
public boolean isPresent()
{
return supplier != null && isValid;
}
/**
* If a mod object is present, invoke the specified consumer with the object,
* otherwise do nothing.
*
* @param consumer block to be executed if a mod object is present
* @throws NullPointerException if mod object is present and {@code consumer} is
* null
*/
public void ifPresent(Consumer<? super T> consumer)
{
if (isValid && getValue() != null)
consumer.accept(getValue());
}
/**
* If a mod object is present, and the mod object matches the given predicate,
* return an {@code OptionalMod} describing the value, otherwise return an
* empty {@code OptionalMod}.
*
* @param predicate a predicate to apply to the mod object, if present
* @return an {@code OptionalMod} describing the value of this {@code OptionalMod}
* if a mod object is present and the mod object matches the given predicate,
* otherwise an empty {@code OptionalMod}
* @throws NullPointerException if the predicate is null
*/
public OptionalCapabilityInstance<T> filter(Predicate<? super T> predicate)
{
Objects.requireNonNull(predicate);
final T value = getValue(); // To keep the non-null contract we have to evaluate right now. Should we allow this function at all?
return predicate.test(value) ? OptionalCapabilityInstance.of(()->value) : empty();
}
/**
* If a mod object is present, apply the provided mapping function to it,
* and if the result is non-null, return an {@code Optional} describing the
* result. Otherwise return an empty {@code Optional}.
*
* @apiNote This method supports post-processing on optional values, without
* the need to explicitly check for a return status.
*
* @param <U> The type of the result of the mapping function
* @param mapper a mapping function to apply to the mod object, if present
* @return an {@code Optional} describing the result of applying a mapping
* function to the mod object of this {@code OptionalMod}, if a mod object is present,
* otherwise an empty {@code Optional}
* @throws NullPointerException if the mapping function is null
*/
public<U> OptionalCapabilityInstance<U> map(Function<? super T, ? extends U> mapper)
{
Objects.requireNonNull(mapper);
return isPresent() ? OptionalCapabilityInstance.of(()->mapper.apply(getValue())) : empty();
}
/**
* If a value is present, apply the provided {@code Optional}-bearing
* mapping function to it, return that result, otherwise return an empty
* {@code Optional}. This method is similar to {@link #map(Function)},
* but the provided mapper is one whose result is already an {@code Optional},
* and if invoked, {@code flatMap} does not wrap it with an additional
* {@code Optional}.
*
* @param <U> The type parameter to the {@code Optional} returned by
* @param mapper a mapping function to apply to the mod object, if present
* the mapping function
* @return the result of applying an {@code Optional}-bearing mapping
* function to the value of this {@code Optional}, if a value is present,
* otherwise an empty {@code Optional}
* @throws NullPointerException if the mapping function is null or returns
* a null result
*/
public<U> OptionalCapabilityInstance<U> flatMap(Function<? super T, Optional<U>> mapper)
{//I am not sure this is valid, or how to handle this, it's just a copy pasta from Optional. I dont think its needed. Returning a null supplier is bad
Objects.requireNonNull(mapper);
final U value = map(mapper).orElse(Optional.empty()).orElse(null); // To keep the non-null contract we have to evaluate right now. Should we allow this function at all?
return value != null ? OptionalCapabilityInstance.of(() -> value) : OptionalCapabilityInstance.empty();
}
/**
* Return the mod object if present, otherwise return {@code other}.
*
* @param other the mod object to be returned if there is no mod object present, may
* be null
* @return the mod object, if present, otherwise {@code other}
*/
public T orElse(T other)
{
return getValue() != null ? getValue() : other;
}
/**
* Return the mod object if present, otherwise invoke {@code other} and return
* the result of that invocation.
*
* @param other a {@code Supplier} whose result is returned if no mod object
* is present
* @return the mod object if present otherwise the result of {@code other.get()}
* @throws NullPointerException if mod object is not present and {@code other} is
* null
*/
public T orElseGet(Supplier<? extends T> other)
{
return getValue() != null ? getValue() : other.get();
}
/**
* Return the contained mod object, if present, otherwise throw an exception
* to be created by the provided supplier.
*
* @apiNote A method reference to the exception constructor with an empty
* argument list can be used as the supplier. For example,
* {@code IllegalStateException::new}
*
* @param <X> Type of the exception to be thrown
* @param exceptionSupplier The supplier which will return the exception to
* be thrown
* @return the present mod object
* @throws X if there is no mod object present
* @throws NullPointerException if no mod object is present and
* {@code exceptionSupplier} is null
*/
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X
{
if (getValue() != null)
return getValue();
throw exceptionSupplier.get();
}
/**
* Registers a listener that will be called when this Optional becomes invalid.
*/
public void addListener(Consumer<OptionalCapabilityInstance<T>> listener)
{
if (!isPresent())
listener.accept(this); // They are stupid so just directly call them.
else
this.listeners.add(listener);
}
/*
* Should only be called by the 'Owner' of this capability, this is to notify any listerners that this has become invalid and they should update.
* For example, a TE would call this, if they are covered with a microblock panel, thus cutting off pipe connectivity to this side.
* Also should be called for all caps when a TE is invalidated, or a world/chunk unloads, or a entity dies, etc...
* This allows modders to keep a cache of Capabilities instead of re-checking them every tick.
*/
public void invalidate()
{
this.isValid = false;
this.listeners.forEach(e -> e.accept(this));
}
}