Initial 1.13.2 update. Major thing to note is that Dimensions have been completely revamped.

DimensionType is not unique per Dimension. See DimensionManager for more details.
Vanilla now has a chunk loading system, so Forge's will need to be deprecated/adapted.
This commit is contained in:
LexManos committed 2019-02-14 15:08:53 -08:00
1 parent 9a1688599a
commit ca72710937
361 files changed
+3166 -3547

No files matched your search

@@ -16,46 +16,46 @@
* 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;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.IdentityHashMap;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import it.unimi.dsi.fastutil.ints.Int2ObjectLinkedOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMaps;
import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntRBTreeSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import it.unimi.dsi.fastutil.ints.IntSets;
import it.unimi.dsi.fastutil.ints.IntSortedSet;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Multiset;
import io.netty.buffer.Unpooled;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.PacketBuffer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import net.minecraft.world.World;
import net.minecraft.world.ServerWorldEventHandler;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldServerMulti;
import net.minecraft.world.dimension.Dimension;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.storage.ISaveHandler;
import net.minecraftforge.event.world.RegisterDimensionsEvent;
import net.minecraftforge.event.world.WorldEvent;
import net.minecraftforge.registries.ClearableRegistry;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.commons.lang3.Validate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
@@ -67,340 +67,193 @@ public class DimensionManager
{
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker DIMMGR = MarkerManager.getMarker("DIMS");
private static class DimensionData
{
private final DimensionType type;
private int ticksWaited;
private DimensionData(DimensionType type)
{
this.type = type;
this.ticksWaited = 0;
}
}
private static boolean hasInit = false;
private static final ClearableRegistry<DimensionType> REGISTRY = new ClearableRegistry<>(new ResourceLocation("dimension_type"));
private static final Int2ObjectMap<WorldServer> worlds = Int2ObjectMaps.synchronize(new Int2ObjectLinkedOpenHashMap<>());
private static final Int2ObjectMap<DimensionData> dimensions = Int2ObjectMaps.synchronize(new Int2ObjectLinkedOpenHashMap<>());
private static final IntSet keepLoaded = IntSets.synchronize(new IntOpenHashSet());
private static final Int2ObjectMap<Data> dimensions = Int2ObjectMaps.synchronize(new Int2ObjectLinkedOpenHashMap<>());
private static final IntSet unloadQueue = IntSets.synchronize(new IntLinkedOpenHashSet());
private static final BitSet dimensionMap = new BitSet(Long.SIZE << 4);
private static final ConcurrentMap<World, World> weakWorldMap = new MapMaker().weakKeys().weakValues().makeMap();
private static final Multiset<Integer> leakedWorlds = HashMultiset.create();
private static final Map<ResourceLocation, SavedEntry> savedEntries = new HashMap<>();
/**
* Returns a list of dimensions associated with this DimensionType.
* Registers a real unique dimension, Should be called on server init, or when the dimension is created.
* On the client, the list will be reset/reloaded every time a InternalServer is refreshed.
*
* Forge will save this data and keep track of registered values, syncing automatically from the remote server.
*
* @param name Registry name for this new dimension.
* @param type Dimension Type.
* @param data Configuration data for this dimension, passed into
*/
public static int[] getDimensions(DimensionType type)
public static void registerDimension(ResourceLocation name, ModDimension type, PacketBuffer data)
{
int[] ret = new int[dimensions.size()];
int x = 0;
for (Int2ObjectMap.Entry<DimensionData> ent : dimensions.int2ObjectEntrySet())
Validate.notNull(name, "Can not register a dimesnion with null name");
Validate.isTrue(!REGISTRY.func_212607_c(name), "Dimension: " + name + " Already registered");
Validate.notNull(type, "Can not register a null dimension type");
int id = REGISTRY.getNextId();
SavedEntry old = savedEntries.get(name);
if (old != null)
{
if (ent.getValue().type == type)
{
ret[x++] = ent.getIntKey();
}
}
return Arrays.copyOf(ret, x);
}
public static Map<DimensionType, IntSortedSet> getRegisteredDimensions()
{
Map<DimensionType, IntSortedSet> map = new IdentityHashMap<>();
for (Int2ObjectMap.Entry<DimensionData> entry : dimensions.int2ObjectEntrySet())
{
map.computeIfAbsent(entry.getValue().type, k -> new IntRBTreeSet()).add(entry.getIntKey());
}
return map;
}
public static void init()
{
if (hasInit)
{
return;
}
hasInit = true;
registerDimension( 0, DimensionType.OVERWORLD);
registerDimension(-1, DimensionType.NETHER);
registerDimension( 1, DimensionType.THE_END);
}
public static void registerDimension(int id, DimensionType type)
{
DimensionType.getById(type.getId()); //Check if type is invalid {will throw an error} No clue how it would be invalid tho...
if (dimensions.containsKey(id))
{
throw new IllegalArgumentException(String.format("Failed to register dimension for id %d, One is already registered", id));
}
dimensions.put(id, new DimensionData(type));
if (id >= 0)
{
dimensionMap.set(id);
id = old.getId();
if (!type.getRegistryName().equals(old.getType()))
LOGGER.info(DIMMGR, "Changing ModDimension for '{}' from '{}' to '{}'", name.toString(), old.getType() == null ? null : old.getType().toString(), type.getRegistryName().toString());
savedEntries.remove(name);
}
DimensionType instance = new DimensionType(id, "", name.getNamespace() + "/" + name.getPath(), type.getFactory(), type, data);
REGISTRY.register(id, name, instance);
LOGGER.info(DIMMGR, "Registered dimension {} of type {} and id {}", name.toString(), type.getRegistryName().toString(), id);
}
/**
* For unregistering a dimension when the save is changed (disconnected from a server or loaded a new save
* Configures if the dimension will stay loaded in memory even if all chunks are unloaded.
*
* @param dim The dimension
* @param value True to keep loaded, false to allow unloading
* @return The old value for this dimension.
*/
public static void unregisterDimension(int id)
public static boolean keepLoaded(DimensionType dim, boolean value)
{
if (!dimensions.containsKey(id))
{
throw new IllegalArgumentException(String.format("Failed to unregister dimension for id %d; No provider registered", id));
}
dimensions.remove(id);
}
public static boolean isDimensionRegistered(int dim)
{
return dimensions.containsKey(dim);
}
public static DimensionType getProviderType(int dim)
{
if (!dimensions.containsKey(dim))
{
throw new IllegalArgumentException(String.format("Could not get provider type for dimension %d, does not exist", dim));
}
return dimensions.get(dim).type;
}
public static Dimension getProvider(int dim)
{
return getWorld(dim).dimension;
}
public static Integer[] getIDs(boolean check)
{
if (check)
{
List<World> allWorlds = Lists.newArrayList(weakWorldMap.keySet());
allWorlds.removeAll(worlds.values());
for (ListIterator<World> li = allWorlds.listIterator(); li.hasNext(); )
{
World w = li.next();
leakedWorlds.add(System.identityHashCode(w));
}
for (World w : allWorlds)
{
int leakCount = leakedWorlds.count(System.identityHashCode(w));
if (leakCount == 5)
{
LOGGER.debug(DIMMGR,"The world {} ({}) may have leaked: first encounter (5 occurrences).\n", Integer.toHexString(System.identityHashCode(w)), w.getWorldInfo().getWorldName());
}
else if (leakCount % 5 == 0)
{
LOGGER.debug(DIMMGR,"The world {} ({}) may have leaked: seen {} times.\n", Integer.toHexString(System.identityHashCode(w)), w.getWorldInfo().getWorldName(), leakCount);
}
}
}
return getIDs();
}
public static Integer[] getIDs()
{
return worlds.keySet().toArray(new Integer[0]); // Only loaded dims, since usually used to cycle through loaded worlds
}
public static Stream<Integer> getIDStream()
{
return worlds.keySet().stream();
}
public static void setWorld(int id, @Nullable WorldServer world, MinecraftServer server)
{
if (world != null)
{
worlds.put(id, world);
weakWorldMap.put(world, world);
LOGGER.info(DIMMGR,"Loading dimension {} ({}) ({})", id, world.getWorldInfo().getWorldName(), world.getServer());
}
else
{
worlds.remove(id);
LOGGER.info(DIMMGR,"Unloading dimension {}", id);
}
ArrayList<WorldServer> tmp = new ArrayList<WorldServer>();
if (worlds.get( 0) != null)
tmp.add(worlds.get( 0));
if (worlds.get(-1) != null)
tmp.add(worlds.get(-1));
if (worlds.get( 1) != null)
tmp.add(worlds.get( 1));
for (Int2ObjectMap.Entry<WorldServer> entry : worlds.int2ObjectEntrySet())
{
int dim = entry.getIntKey();
if (dim >= -1 && dim <= 1)
{
continue;
}
tmp.add(entry.getValue());
}
server.worlds = tmp.toArray(new WorldServer[0]);
}
public static void initDimension(int dim)
{
WorldServer overworld = getWorld(0);
if (overworld == null)
{
throw new RuntimeException("Cannot Hotload Dim: Overworld is not Loaded!");
}
try
{
DimensionManager.getProviderType(dim);
}
catch (Exception e)
{
LOGGER.error(DIMMGR,"Cannot Hotload Dim: {}", dim, e);
return; // If a provider hasn't been registered then we can't hotload the dim
}
MinecraftServer mcServer = overworld.getServer();
ISaveHandler savehandler = overworld.getSaveHandler();
//WorldSettings worldSettings = new WorldSettings(overworld.getWorldInfo());
WorldServer world = (dim == 0 ? overworld : (WorldServer)(new WorldServerMulti(mcServer, savehandler, dim, overworld, mcServer.profiler).init()));
world.addEventListener(new ServerWorldEventHandler(mcServer, world));
MinecraftForge.EVENT_BUS.post(new WorldEvent.Load(world));
if (!mcServer.isSinglePlayer())
{
world.getWorldInfo().setGameType(mcServer.getGameType());
}
mcServer.setDifficultyForAllWorlds(mcServer.getDifficulty());
}
public static WorldServer getWorld(int id)
{
return getWorld(id, false);
}
public static WorldServer getWorld(int id, boolean resetUnloadDelay)
{
return getWorld(id, resetUnloadDelay, false);
}
public static WorldServer getWorld(int id, boolean resetUnloadDelay, boolean forceLoad)
{
if (resetUnloadDelay && unloadQueue.contains(id))
{
dimensions.get(id).ticksWaited = 0;
}
WorldServer ret = worlds.get(id);
if (ret == null && forceLoad)
{
initDimension(id);
ret = worlds.get(id);
}
Validate.notNull(dim, "Dimension type must not be null");
Data data = getData(dim);
boolean ret = data.keepLoaded;
data.keepLoaded = value;
return ret;
}
public static WorldServer[] getWorlds()
/**
* Determines if the dimension will stay loaded in memory even if all chunks are unloaded.
* @param dim The dimension
* @return True if the dimension will stay loaded with no chunks loaded.
*/
public static boolean keepLoaded(DimensionType dim)
{
return worlds.values().toArray(new WorldServer[0]);
}
static
{
init();
Validate.notNull(dim, "Dimension type must not be null");
Data data = dimensions.get(dim.getId());
return data == null ? false : data.keepLoaded;
}
/**
* Not public API: used internally to get dimensions that should load at
* server startup
* Retrieves the world from the server allowing for null return, and optionally resetting it's unload timer.
*
* @param server The server that controlls this world.
* @param dim Dimension to load.
* @param resetUnloadDelay True to reset the unload timer, which is a delay that is used to prevent constant world loading/unloading cycle.
* @param forceLoad True to attempt to load the dimension if the server has it unloaded.
* @return The world, null if unloaded and not loadable.
*/
public static Integer[] getStaticDimensionIDs()
@Nullable
public static WorldServer getWorld(MinecraftServer server, DimensionType dim, boolean resetUnloadDelay, boolean forceLoad)
{
return dimensions.keySet().toArray(new Integer[0]);
Validate.notNull(server, "Must provide server when creating world");
Validate.notNull(dim, "Dimension type must not be null");
if (resetUnloadDelay && unloadQueue.contains(dim.getId()))
getData(dim).ticksWaited = 0;
@SuppressWarnings("deprecation")
WorldServer ret = server.forgeGetWorldMap().get(dim);
if (ret == null && forceLoad)
ret = initWorld(server, dim);
return ret;
}
public static Dimension createProviderFor(int dim)
//==========================================================================================================
// FORGE INTERNAL
//==========================================================================================================
public static void unregisterDimension(int id)
{
try
{
if (dimensions.containsKey(dim))
{
Dimension ret = getProviderType(dim).create();
ret.setId(dim);
return ret;
}
else
{
throw new RuntimeException(String.format("No WorldProvider bound for dimension %d", dim)); //It's going to crash anyway at this point. Might as well be informative
}
}
catch (Exception e)
{
LOGGER.error(DIMMGR,"An error occurred trying to create an instance of WorldProvider {} ({})",
dim, getProviderType(dim), e);
throw new RuntimeException(e);
}
Validate.isTrue(dimensions.containsKey(id), String.format("Failed to unregister dimension for id %d; No provider registered", id));
dimensions.remove(id);
}
/**
* Sets if a dimension should stay loaded.
* @param dim the dimension ID
* @param keep whether or not the dimension should be kept loaded
* @return true iff the dimension's status changed
*/
public static boolean keepDimensionLoaded(int dim, boolean keep)
public static void registerDimensionInternal(int id, ResourceLocation name, ModDimension type, PacketBuffer data)
{
return keep ? keepLoaded.add(dim) : keepLoaded.remove(dim);
Validate.notNull(name, "Can not register a dimesnion with null name");
Validate.notNull(type, "Can not register a null dimension type");
Validate.isTrue(!REGISTRY.func_212607_c(name), "Dimension: " + name + " Already registered");
Validate.isTrue(REGISTRY.get(id) == null, "Dimension with id " + id + " already registered as name " + REGISTRY.getKey(REGISTRY.get(id)));
DimensionType instance = new DimensionType(id, "", name.getNamespace() + "/" + name.getPath(), type.getFactory(), type, data);
REGISTRY.register(id, name, instance);
LOGGER.info(DIMMGR, "Registered dimension {} of type {} and id {}", name.toString(), type.getRegistryName().toString(), id);
}
@SuppressWarnings("deprecation")
public static WorldServer initWorld(MinecraftServer server, DimensionType dim)
{
Validate.isTrue(dim != DimensionType.OVERWORLD, "Can not hotload overworld. This must be loaded at all times by main Server.");
Validate.notNull(server, "Must provide server when creating world");
Validate.notNull(dim, "Must provide dimension when creating world");
WorldServer overworld = getWorld(server, DimensionType.OVERWORLD, false, false);
Validate.notNull(overworld, "Cannot Hotload Dim: Overworld is not Loaded!");
@SuppressWarnings("resource")
WorldServer world = new WorldServerMulti(server, overworld.getSaveHandler(), dim, overworld, server.profiler).func_212251_i__();
world.addEventListener(new ServerWorldEventHandler(server, world));
if (!server.isSinglePlayer())
world.getWorldInfo().setGameType(server.getGameType());
server.forgeGetWorldMap().put(dim, world);
MinecraftForge.EVENT_BUS.post(new WorldEvent.Load(world));
server.setDifficultyForAllWorlds(server.getDifficulty());
return world;
}
private static boolean canUnloadWorld(WorldServer world)
{
return ForgeChunkManager.getPersistentChunksFor(world).isEmpty()
return world.func_212412_ag().isEmpty()
&& world.playerEntities.isEmpty()
&& !world.dimension.getType().shouldLoadSpawn()
&& !keepLoaded.contains(world.dimension.getId());
//&& !world.dimension.getType().shouldLoadSpawn()
&& !getData(world.getDimension().getType()).keepLoaded;
}
/**
* Queues a dimension to unload, if it can be unloaded.
* @param id The id of the dimension
*/
public static void unloadWorld(int id)
public static void unloadWorld(WorldServer world)
{
WorldServer world = worlds.get(id);
if (world == null || !canUnloadWorld(world)) return;
if (world == null || !canUnloadWorld(world))
return;
int id = world.getDimension().getType().getId();
if (unloadQueue.add(id))
{
LOGGER.debug(DIMMGR,"Queueing dimension {} to unload", id);
}
}
public static boolean isWorldQueuedToUnload(int id)
{
return unloadQueue.contains(id);
}
/*
* To be called by the server at the appropriate time, do not call from mod code.
*/
public static void unloadWorlds()
@SuppressWarnings("deprecation")
public static void unloadWorlds(MinecraftServer server, boolean checkLeaks)
{
IntIterator queueIterator = unloadQueue.iterator();
while (queueIterator.hasNext())
{
int id = queueIterator.nextInt();
DimensionData dimension = dimensions.get(id);
DimensionType dim = DimensionType.getById(id);
if (dim == null)
{
LOGGER.warn(DIMMGR, "Dimension with unknown type '{}' added to unload queue, removing", id);
queueIterator.remove();
continue;
}
Data dimension = dimensions.computeIfAbsent(id, k -> new Data());
if (dimension.ticksWaited < ForgeConfig.SERVER.dimensionUnloadQueueDelay.get())
{
dimension.ticksWaited++;
continue;
}
WorldServer w = worlds.get(id);
queueIterator.remove();
WorldServer w = server.forgeGetWorldMap().get(dim);
dimension.ticksWaited = 0;
// Don't unload the world if the status changed
if (w == null || !canUnloadWorld(w))
@@ -420,97 +273,179 @@ public class DimensionManager
{
MinecraftForge.EVENT_BUS.post(new WorldEvent.Unload(w));
w.close();
setWorld(id, null, w.getServer());
server.forgeGetWorldMap().remove(dim);
}
}
if (checkLeaks)
{
List<World> allWorlds = Lists.newArrayList(weakWorldMap.keySet());
allWorlds.removeAll(server.forgeGetWorldMap().values());
allWorlds.stream().map(System::identityHashCode).forEach(leakedWorlds::add);
for (World w : allWorlds)
{
int hash = System.identityHashCode(w);
int leakCount = leakedWorlds.count(hash);
if (leakCount == 5)
LOGGER.debug(DIMMGR,"The world {} ({}) may have leaked: first encounter (5 occurrences).\n", Integer.toHexString(hash), w.getWorldInfo().getWorldName());
else if (leakCount % 5 == 0)
LOGGER.debug(DIMMGR,"The world {} ({}) may have leaked: seen {} times.\n", Integer.toHexString(hash), w.getWorldInfo().getWorldName(), leakCount);
}
}
}
/**
* Return the next free dimension ID. Note: you are not guaranteed a contiguous
* block of free ids. Always call for each individual ID you wish to get.
* @return the next free dimension ID
*/
public static int getNextFreeDimId() {
int next = 0;
while (true)
public static void writeRegistry(NBTTagCompound data)
{
data.setInt("version", 1);
List<SavedEntry> list = new ArrayList<>();
for (DimensionType type : REGISTRY)
list.add(new SavedEntry(type));
savedEntries.values().forEach(list::add);
Collections.sort(list, (a, b) -> a.id - b.id);
NBTTagList lst = new NBTTagList();
list.forEach(e -> lst.add(e.write()));
data.setTag("entries", lst);
}
public static void readRegistry(NBTTagCompound data)
{
int version = data.getInt("version");
if (version != 1)
throw new IllegalStateException("Attempted to load world with unknown Dimension data format: " + version);
LOGGER.debug(DIMMGR, "Reading Dimension Entries.");
Map<ResourceLocation, DimensionType> vanilla = REGISTRY.stream().filter(DimensionType::isVanilla).collect(Collectors.toMap(REGISTRY::getKey, v -> v));
REGISTRY.clear();
vanilla.forEach((key, value) -> {
LOGGER.debug(DIMMGR, "Registering vanilla entry ID: {} Name: {} Value: {}", value.getId() + 1, key.toString(), value.toString());
REGISTRY.register(value.getId() + 1, key, value);
});
savedEntries.clear();
boolean error = false;
NBTTagList list = data.getList("entries", 10);
for (int x = 0; x < list.size(); x++)
{
next = dimensionMap.nextClearBit(next);
if (dimensions.containsKey(next))
SavedEntry entry = new SavedEntry(list.getCompound(x));
if (entry.type == null)
{
dimensionMap.set(next);
DimensionType type = REGISTRY.func_212608_b(entry.name);
if (type == null)
{
LOGGER.error(DIMMGR, "Vanilla entry '{}' id {} in save file not found in registry.", entry.name.toString(), entry.id);
error = true;
continue;
}
int id = REGISTRY.getId(type);
if (id != entry.id)
{
LOGGER.error(DIMMGR, "Vanilla entry '{}' id {} in save file has incorrect in {} in registry.", entry.name.toString(), entry.id, id);
error = true;
continue;
}
}
else
{
return next;
}
}
}
public static NBTTagCompound saveDimensionDataMap()
{
int[] data = new int[(dimensionMap.length() + Integer.SIZE - 1 )/ Integer.SIZE];
NBTTagCompound dimMap = new NBTTagCompound();
for (int i = 0; i < data.length; i++)
{
int val = 0;
for (int j = 0; j < Integer.SIZE; j++)
{
val |= dimensionMap.get(i * Integer.SIZE + j) ? (1 << j) : 0;
}
data[i] = val;
}
dimMap.setIntArray("DimensionArray", data);
return dimMap;
}
public static void loadDimensionDataMap(@Nullable NBTTagCompound compoundTag)
{
dimensionMap.clear();
if (compoundTag == null)
{
IntIterator iterator = dimensions.keySet().iterator();
while (iterator.hasNext())
{
int id = iterator.nextInt();
if (id >= 0)
ModDimension mod = ForgeRegistries.MOD_DIMENSIONS.getValue(entry.type);
if (mod == null)
{
dimensionMap.set(id);
LOGGER.error(DIMMGR, "Modded dimension entry '{}' id {} in save file missing ModDimension.", entry.name.toString(), entry.id, entry.type.toString());
savedEntries.put(entry.name, entry);
continue;
}
registerDimensionInternal(entry.id, entry.name, mod, entry.data == null ? null : new PacketBuffer(Unpooled.wrappedBuffer(entry.data)));
}
}
else
//Allow modders to register dimensions/claim the missing.
MinecraftForge.EVENT_BUS.post(new RegisterDimensionsEvent(savedEntries));
if (!savedEntries.isEmpty())
{
int[] intArray = compoundTag.getIntArray("DimensionArray");
for (int i = 0; i < intArray.length; i++)
{
for (int j = 0; j < Integer.SIZE; j++)
{
dimensionMap.set(i * Integer.SIZE + j, (intArray[i] & (1 << j)) != 0);
}
}
savedEntries.values().forEach(entry -> {
LOGGER.warn(DIMMGR, "Missing Dimension Name: '{}' Id: {} Type: '{}", entry.name.toString(), entry.id, entry.type.toString());
});
}
}
/**
* Return the current root directory for the world save. Accesses getSaveHandler from the overworld
* @return the root directory of the save
*/
@Nullable
public static File getCurrentSaveRootDirectory()
@Deprecated //Forge: Internal use only.
public static IRegistry<DimensionType> getRegistry()
{
if (DimensionManager.getWorld(0) != null)
return REGISTRY;
}
private static Data getData(DimensionType dim)
{
return dimensions.computeIfAbsent(dim.getId(), k -> new Data());
}
private static class Data
{
int ticksWaited = 0;
boolean keepLoaded = false;
}
public static class SavedEntry
{
int id;
ResourceLocation name;
ResourceLocation type;
byte[] data;
public int getId()
{
return DimensionManager.getWorld(0).getSaveHandler().getWorldDirectory();
}/*
else if (MinecraftServer.getServer() != null)
return id;
}
public ResourceLocation getName()
{
MinecraftServer srv = MinecraftServer.getServer();
SaveHandler saveHandler = (SaveHandler) srv.getActiveAnvilConverter().getSaveLoader(srv.getFolderName(), false);
return saveHandler.getWorldDirectory();
}*/
else
return name;
}
@Nullable
public ResourceLocation getType()
{
return null;
return type;
}
@Nullable
public byte[] getData()
{
return data;
}
private SavedEntry(NBTTagCompound data)
{
this.id = data.getInt("id");
this.name = new ResourceLocation(data.getString("name"));
this.type = data.contains("type", 8) ? new ResourceLocation(data.getString("type")) : null;
this.data = data.contains("data", 7) ? data.getByteArray("data") : null;
}
private SavedEntry(DimensionType data)
{
this.id = REGISTRY.getId(data);
this.name = REGISTRY.getKey(data);
if (data.getModType() != null)
this.type = data.getModType().getRegistryName();
if (data.getData() != null)
this.data = data.getData().array();
}
private NBTTagCompound write()
{
NBTTagCompound ret = new NBTTagCompound();
ret.setInt("id", id);
ret.setString("name", name.toString());
if (type != null)
ret.setString("type", type.toString());
if (data != null)
ret.setByteArray("data", data);
return ret;
}
}
}
@@ -41,74 +41,74 @@ public class ForgeConfig
public static class Server {
public final BooleanValue removeErroringEntities;
public final BooleanValue removeErroringTileEntities;
public final BooleanValue fullBoundingBoxLadders;
public final DoubleValue zombieBaseSummonChance;
public final DoubleValue zombieBabyChance;
public final BooleanValue logCascadingWorldGeneration;
public final BooleanValue fixVanillaCascading;
public final IntValue dimensionUnloadQueueDelay;
public final IntValue clumpingThreshold;
Server(ForgeConfigSpec.Builder builder) {
builder.comment("Server configuration settings")
.push("server");
removeErroringEntities = builder
.comment("Set this to true to remove any Entity that throws an error in its update method instead of closing the server and reporting a crash log. BE WARNED THIS COULD SCREW UP EVERYTHING USE SPARINGLY WE ARE NOT RESPONSIBLE FOR DAMAGES.")
.translation("forge.configgui.removeErroringEntities")
.worldRestart()
.define("removeErroringEntities", false);
removeErroringTileEntities = builder
.comment("Set this to true to remove any TileEntity that throws an error in its update method instead of closing the server and reporting a crash log. BE WARNED THIS COULD SCREW UP EVERYTHING USE SPARINGLY WE ARE NOT RESPONSIBLE FOR DAMAGES.")
.translation("forge.configgui.removeErroringTileEntities")
.worldRestart()
.define("removeErroringTileEntities", false);
fullBoundingBoxLadders = builder
.comment("Set this to true to check the entire entity's collision bounding box for ladders instead of just the block they are in. Causes noticeable differences in mechanics so default is vanilla behavior. Default: false")
.translation("forge.configgui.fullBoundingBoxLadders")
.worldRestart()
.define("fullBoundingBoxLadders", false);
zombieBaseSummonChance = builder
.comment("Base zombie summoning spawn chance. Allows changing the bonus zombie summoning mechanic.")
.translation("forge.configgui.zombieBaseSummonChance")
.worldRestart()
.defineInRange("zombieBaseSummonChance", 0.1D, 0.0D, 1.0D);
zombieBabyChance = builder
.comment("Chance that a zombie (or subclass) is a baby. Allows changing the zombie spawning mechanic.")
.translation("forge.configgui.zombieBabyChance")
.worldRestart()
.defineInRange("zombieBabyChance", 0.05D, 0.0D, 1.0D);
logCascadingWorldGeneration = builder
.comment("Log cascading chunk generation issues during terrain population.")
.translation("forge.configgui.logCascadingWorldGeneration")
.define("logCascadingWorldGeneration", true);
fixVanillaCascading = builder
.comment("Fix vanilla issues that cause worldgen cascading. This DOES change vanilla worldgen so DO NOT report bugs related to world differences if this flag is on.")
.translation("forge.configgui.fixVanillaCascading")
.define("fixVanillaCascading", false);
dimensionUnloadQueueDelay = builder
.comment("The time in ticks the server will wait when a dimension was queued to unload. This can be useful when rapidly loading and unloading dimensions, like e.g. throwing items through a nether portal a few time per second.")
.translation("forge.configgui.dimensionUnloadQueueDelay")
.defineInRange("dimensionUnloadQueueDelay", 0, 0, Integer.MAX_VALUE);
clumpingThreshold = builder
.comment("Controls the number threshold at which Packet51 is preferred over Packet52, default and minimum 64, maximum 1024")
.translation("forge.configgui.clumpingThreshold")
.worldRestart()
.defineInRange("clumpingThreshold", 64, 64, 1024);
builder.pop();
}
}
@@ -120,55 +120,55 @@ public class ForgeConfig
public final BooleanValue zoomInMissingModelTextInGui;
public final BooleanValue forgeCloudsEnabled;
public final BooleanValue disableStairSlabCulling;
public final BooleanValue alwaysSetupTerrainOffThread;
public final BooleanValue forgeLightPipelineEnabled;
public final BooleanValue selectiveResourceReloadEnabled;
Client(ForgeConfigSpec.Builder builder) {
builder.comment("Client only settings, mostly things related to rendering")
.push("client");
zoomInMissingModelTextInGui = builder
.comment("Toggle off to make missing model text in the gui fit inside the slot.")
.translation("forge.configgui.zoomInMissingModelTextInGui")
.define("zoomInMissingModelTextInGui", false);
forgeCloudsEnabled = builder
.comment("Enable uploading cloud geometry to the GPU for faster rendering.")
.translation("forge.configgui.forgeCloudsEnabled")
.define("forgeCloudsEnabled", true);
disableStairSlabCulling = builder
.comment("Disable culling of hidden faces next to stairs and slabs. Causes extra rendering, but may fix some resource packs that exploit this vanilla mechanic.")
.translation("forge.configgui.disableStairSlabCulling")
.define("disableStairSlabCulling", false);
alwaysSetupTerrainOffThread = builder
alwaysSetupTerrainOffThread = builder
.comment("Enable forge to queue all chunk updates to the Chunk Update thread.",
"May increase FPS significantly, but may also cause weird rendering lag.",
"Not recommended for computers without a significant number of cores available.")
.translation("forge.configgui.alwaysSetupTerrainOffThread")
.define("alwaysSetupTerrainOffThread", false);
forgeLightPipelineEnabled = builder
.comment("Enable the forge block rendering pipeline - fixes the lighting of custom models.")
.translation("forge.configgui.forgeLightPipelineEnabled")
.define("forgeLightPipelineEnabled", true);
selectiveResourceReloadEnabled = builder
.comment("When enabled, makes specific reload tasks such as language changing quicker to run.")
.translation("forge.configgui.selectiveResourceReloadEnabled")
.define("selectiveResourceReloadEnabled", true);
builder.pop();
}
}
static final ForgeConfigSpec clientSpec;
public static final Client CLIENT;
static {
@@ -101,6 +101,7 @@ import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.GameType;
import net.minecraft.world.IBlockReader;
@@ -749,7 +750,7 @@ public class ForgeHooks
return stack.isEmpty() || !stack.getItem().onLeftClickEntity(stack, player, target);
}
public static boolean onTravelToDimension(Entity entity, int dimension)
public static boolean onTravelToDimension(Entity entity, DimensionType dimension)
{
EntityTravelToDimensionEvent event = new EntityTravelToDimensionEvent(entity, dimension);
MinecraftForge.EVENT_BUS.post(event);
@@ -1100,7 +1101,7 @@ public class ForgeHooks
return event.getVanillaNoteId();
}
public static int canEntitySpawn(EntityLiving entity, IWorld world, float x, float y, float z, MobSpawnerBaseLogic spawner) {
public static int canEntitySpawn(EntityLiving entity, IWorld world, double x, double y, double z, MobSpawnerBaseLogic spawner) {
Result res = ForgeEventFactory.canEntitySpawn(entity, world, x, y, z, null);
return res == Result.DEFAULT ? 0 : res == Result.DENY ? -1 : 1;
}
@@ -69,7 +69,7 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
public static boolean forgeLightPipelineEnabled = true;
public static boolean zoomInMissingModelTextInGui = false;
public static boolean disableStairSlabCulling = false; // Also known as the "DontCullStairsBecauseIUseACrappyTexturePackThatBreaksBasicBlockShapesSoICantTrustBasicBlockCulling" flag
public static boolean alwaysSetupTerrainOffThread = false; // In RenderGlobal.setupTerrain, always force the chunk render updates to be queued to the thread
public static boolean alwaysSetupTerrainOffThread = false; // In WorldRenderer.setupTerrain, always force the chunk render updates to be queued to the thread
public static boolean logCascadingWorldGeneration = true; // see Chunk#logCascadingWorldGeneration()
public static boolean fixVanillaCascading = false; // There are various places in vanilla that cause cascading worldgen. Enabling this WILL change where blocks are placed to prevent this.
// DO NOT contact Forge about worldgen not 'matching' vanilla if this flag is set.
@@ -130,7 +130,7 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
public void playerLogin(PlayerEvent.PlayerLoggedInEvent event)
{
UsernameCache.setUsername(event.player.getUniqueID(), event.player.getGameProfile().getName());
UsernameCache.setUsername(event.getPlayer().getUniqueID(), event.getPlayer().getGameProfile().getName());
}
@@ -204,8 +204,10 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
public NBTTagCompound getDataForWriting(SaveHandler handler, WorldInfo info)
{
NBTTagCompound forgeData = new NBTTagCompound();
NBTTagCompound dimData = DimensionManager.saveDimensionDataMap();
forgeData.setTag("DimensionData", dimData);
NBTTagCompound dims = new NBTTagCompound();
DimensionManager.writeRegistry(dims);
if (!dims.isEmpty())
forgeData.setTag("dims", dims);
// TODO fluids FluidRegistry.writeDefaultFluidList(forgeData);
return forgeData;
}
@@ -213,7 +215,8 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
@Override
public void readData(SaveHandler handler, WorldInfo info, NBTTagCompound tag)
{
DimensionManager.loadDimensionDataMap(tag.hasKey("DimensionData") ? tag.getCompound("DimensionData") : null);
if (tag.contains("dims", 10))
DimensionManager.readRegistry(tag.getCompound("dims"));
// TODO fluids FluidRegistry.loadFluidDefaults(tag);
}
@@ -0,0 +1,55 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2019.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common;
import java.util.function.Function;
import net.minecraft.network.PacketBuffer;
import net.minecraft.world.dimension.Dimension;
import net.minecraft.world.dimension.DimensionType;
import net.minecraftforge.registries.ForgeRegistryEntry;
/**
* In 1.13.2, Mojang made DimensionType as the unique holder/identifier for each Dimension.
* We used to be able to create custom Dimensions separate from DimensionType.
* But now that they are hard linked to a single instance, this is the new class that
* defines the 'template' for new dimensions.
*/
public abstract class ModDimension extends ForgeRegistryEntry<ModDimension>
{
public abstract Function<DimensionType, ? extends Dimension> getFactory();
/**
* Serialize any necessary data, this is called both when saving the world on the server.
* And when sent over the network to the client.
*
* @param buffer The data buffer to write to.
* @param network true when sent over the network, so you can only data needed by the client.
*/
public void write(PacketBuffer buffer, boolean network){}
/**
* Deserialize any necessary data, this is called both when saving the world on the server.
* And when sent over the network to the client.
*
* @param buffer The data buffer to write to.
* @param network true when sent over the network, so you can only data needed by the client.
*/
public void read(PacketBuffer buffer, boolean network){}
}
@@ -1,113 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2019.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common;
import java.io.File;
import java.io.IOException;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.common.io.Files;
import com.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.storage.SessionLockException;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.storage.WorldInfo;
import net.minecraft.world.WorldServer;
//Class used internally to provide the world specific data directories.
public class WorldSpecificSaveHandler implements ISaveHandler
{
private static final Logger LOGGER = LogManager.getLogger();
private WorldServer world;
private ISaveHandler parent;
private File dataDir;
public WorldSpecificSaveHandler(WorldServer world, ISaveHandler parent)
{
this.world = world;
this.parent = parent;
}
@Override public WorldInfo loadWorldInfo() { return parent.loadWorldInfo(); }
@Override public void checkSessionLock() throws SessionLockException { parent.checkSessionLock(); }
@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 getFixer() { return parent.getFixer(); }
@Override
public File getMapFileFromName(String name)
{
if (dataDir == null) //Delayed down here do that world has time to be initialized first.
{
dataDir = new File(world.getChunkSaveLocation(), "data");
dataDir.mkdirs();
}
File file = new File(dataDir, name + ".dat");
if (!file.exists())
{
switch (world.dimension.getId())
{
case -1:
if (name.equalsIgnoreCase("FORTRESS")) copyFile(name, file);
break;
case 1:
if (name.equalsIgnoreCase("VILLAGES_END")) copyFile(name, file);
break;
}
}
return file;
}
private void copyFile(String name, File to)
{
File parentFile = parent.getMapFileFromName(name);
if (parentFile.exists())
{
try
{
Files.copy(parentFile, to);
}
catch (IOException e)
{
LOGGER.error("A critical error occurred copying {} to world specific dat folder - new file will be created.", parentFile.getName(), e);
}
}
}
@Override
public TemplateManager getStructureTemplateManager()
{
return parent.getStructureTemplateManager();
}
}
@@ -35,6 +35,7 @@ import com.google.common.collect.Maps;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.AnvilChunkLoader;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.gen.ChunkProviderServer;
public class ChunkIOExecutor
@@ -124,7 +125,7 @@ public class ChunkIOExecutor
ChunkIOProvider task = tasks.get(key);
if (task == null)
{
LOGGER.warn("Attempted to dequeue chunk that wasn't queued? {} @ ({}, {})", world.dimension.getId(), x, z);
LOGGER.warn("Attempted to dequeue chunk that wasn't queued? {} @ ({}, {})", DimensionType.func_212678_a(world.dimension.getType()).toString(), x, z);
return;
}
@@ -20,6 +20,7 @@
package net.minecraftforge.common.chunkio;
import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
class QueuedChunk {
final int x;
@@ -57,7 +58,7 @@ class QueuedChunk {
result.append(" x: " + x + NEW_LINE);
result.append(" z: " + z + NEW_LINE);
result.append(" world: " + world.getWorldInfo().getWorldName() + NEW_LINE);
result.append(" dimension: " + world.dimension.getId() + NEW_LINE);
result.append(" dimension: " + DimensionType.func_212678_a(world.dimension.getType()).toString() + NEW_LINE);
result.append(" provider: " + world.dimension.getClass().getName() + NEW_LINE);
result.append("}");
@@ -38,7 +38,7 @@ import net.minecraft.block.state.BlockFaceShape;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.particle.ParticleManager;
import net.minecraft.client.renderer.ActiveRenderInfo;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.model.IBakedModel;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
@@ -26,7 +26,7 @@ import javax.annotation.Nullable;
import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.particle.ParticleManager;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.model.IBakedModel;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
@@ -24,6 +24,7 @@ import javax.annotation.Nullable;
import net.minecraft.client.audio.MusicTicker;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
@@ -31,6 +32,7 @@ import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.dimension.Dimension;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.dimension.NetherDimension;
import net.minecraft.world.dimension.OverworldDimension;
import net.minecraft.world.storage.WorldInfo;
@@ -44,7 +46,7 @@ public interface IForgeDimension
{
return (Dimension) this;
}
World getWorld();
/**
@@ -81,7 +83,7 @@ public interface IForgeDimension
}
return 1.0;
}
/**
* If this method returns true, then chunks received by the client will
* have {@link net.minecraft.world.chunk.Chunk#resetRelightChecks} called
@@ -98,17 +100,6 @@ public interface IForgeDimension
return !(this instanceof OverworldDimension);
}
/**
* Sets the providers current dimension ID, used in default getSaveFolder()
* Added to allow default providers to be registered for multiple dimensions.
* This is to denote the exact dimension ID opposed to the 'type' in WorldType
*
* @param id Dimension ID
*/
void setId(int id);
int getId();
@OnlyIn(Dist.CLIENT)
@Nullable
IRenderHandler getSkyRenderer();
@@ -129,7 +120,7 @@ public interface IForgeDimension
@OnlyIn(Dist.CLIENT)
void setWeatherRenderer(IRenderHandler renderer);
/**
* Allows for manipulating the coloring of the lightmap texture.
* Will be called for each 16*16 combination of sky/block light values.
@@ -140,7 +131,7 @@ public interface IForgeDimension
* @param blockLight Block light brightness factor.
* @param colors The color values that will be used: [r, g, b].
*
* @see net.minecraft.client.renderer.EntityRenderer#updateLightmap(float)
* @see net.minecraft.client.renderer.GameRenderer#updateLightmap(float)
*/
default void getLightmapColors(float partialTicks, float sunBrightness, float skyLight, float blockLight, float[] colors) {}
@@ -167,7 +158,7 @@ public interface IForgeDimension
{
return null;
}
/**
* Determines if the player can sleep in this world (or if the bed should explode for example).
*
@@ -316,11 +307,6 @@ public interface IForgeDimension
return getWorld().getWorldInfo().getTerrainType().getHorizon(getWorld());
}
default String getSaveFolder()
{
return getId() == 0 ? null : "DIM" + getId();
}
/**
* Determine if the cursor on the map should 'spin' when rendered, like it does for the player in the nether.
*
@@ -332,7 +318,7 @@ public interface IForgeDimension
*/
default boolean shouldMapSpin(String entity, double x, double z, double rotation)
{
return getId() < 0;
return getDimension().getType() == DimensionType.NETHER;
}
/**
@@ -341,7 +327,7 @@ public interface IForgeDimension
* @param player The player that is respawning
* @return The dimension to respawn the player in
*/
default int getRespawnDimension(net.minecraft.entity.player.EntityPlayerMP player)
default DimensionType getRespawnDimension(EntityPlayerMP player)
{
return player.getSpawnDimension();
}
@@ -22,7 +22,7 @@ package net.minecraftforge.common.extensions;
import javax.annotation.Nullable;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.model.IBakedModel;
import net.minecraft.entity.Entity;
import net.minecraft.fluid.Fluid;
import net.minecraft.fluid.IFluidState;
@@ -21,7 +21,7 @@ package net.minecraftforge.common.extensions;
import javax.annotation.Nullable;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.model.IBakedModel;
import net.minecraft.entity.Entity;
import net.minecraft.fluid.Fluid;
import net.minecraft.fluid.IFluidState;
@@ -23,6 +23,7 @@ import java.util.Set;
import javax.annotation.Nullable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;
import net.minecraft.block.state.IBlockState;
@@ -36,7 +37,6 @@ import net.minecraft.entity.passive.HorseArmorType;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.IItemPropertyGetter;
import net.minecraft.item.Item;
import net.minecraft.item.ItemAxe;
import net.minecraft.item.ItemGroup;
@@ -44,14 +44,13 @@ import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUseContext;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.registry.RegistrySimple;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.common.ToolType;
import net.minecraftforge.common.animation.ITimeValue;
// TODO review most of the methods in this "patch"
public interface IForgeItem
@@ -679,16 +678,10 @@ public interface IForgeItem
return null;
}
default com.google.common.collect.ImmutableMap<String, net.minecraftforge.common.animation.ITimeValue> getAnimationParameters(final ItemStack stack,
final World world, final EntityLivingBase entity)
default ImmutableMap<String, ITimeValue> getAnimationParameters(final ItemStack stack, final World world, final EntityLivingBase entity)
{
com.google.common.collect.ImmutableMap.Builder<String, net.minecraftforge.common.animation.ITimeValue> builder = com.google.common.collect.ImmutableMap
.builder();
for (ResourceLocation location : ((RegistrySimple<ResourceLocation, IItemPropertyGetter>) getItem().properties).getKeys())
{
final IItemPropertyGetter parameter = getItem().properties.get(location);
builder.put(location.toString(), input -> parameter.call(stack, world, entity));
}
com.google.common.collect.ImmutableMap.Builder<String, ITimeValue> builder = ImmutableMap.builder();
getItem().properties.forEach((k,v) -> builder.put(k.toString(), input -> v.call(stack, world, entity)));
return builder.build();
}
@@ -19,17 +19,6 @@
package net.minecraftforge.common.extensions;
import java.util.Iterator;
import java.util.Objects;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.common.ForgeChunkManager;
import net.minecraftforge.common.ForgeChunkManager.Ticket;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
public interface IForgeWorld extends ICapabilityProvider
@@ -40,23 +29,4 @@ public interface IForgeWorld extends ICapabilityProvider
* of one of there entities.
*/
public static double MAX_ENTITY_RADIUS = 2.0D;
default ImmutableSetMultimap<ChunkPos, ForgeChunkManager.Ticket> getPersistentChunks()
{
return ForgeChunkManager.getPersistentChunksFor((World)this);
}
default Iterator<Chunk> getPersistentChunkIterable(Iterator<Chunk> chunkIterator)
{
@SuppressWarnings("resource")
World world = (World)this;
final ImmutableSetMultimap<ChunkPos, Ticket> persistentChunksFor = getPersistentChunks();
final ImmutableSet.Builder<Chunk> builder = ImmutableSet.builder();
world.profiler.startSection("forcedChunkLoading");
builder.addAll(persistentChunksFor.keys().stream().filter(Objects::nonNull).map(input -> world.getChunk(input.x, input.z)).iterator());
world.profiler.endStartSection("regularChunkLoading");
builder.addAll(chunkIterator);
world.profiler.endSection();
return builder.build().iterator();
}
}
@@ -35,8 +35,8 @@ import javax.vecmath.Tuple4f;
import javax.vecmath.Vector3f;
import javax.vecmath.Vector4f;
import net.minecraft.client.renderer.block.model.ItemTransformVec3f;
import net.minecraft.client.renderer.block.model.ModelRotation;
import net.minecraft.client.renderer.model.ItemTransformVec3f;
import net.minecraft.client.renderer.model.ModelRotation;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.Vec3i;
import net.minecraftforge.api.distmarker.Dist;
@@ -536,7 +536,7 @@ public final class TRSRTransformation implements IModelState, ITransformation
*/
@Deprecated
@OnlyIn(Dist.CLIENT)
public net.minecraft.client.renderer.block.model.ItemTransformVec3f toItemTransform()
public net.minecraft.client.renderer.model.ItemTransformVec3f toItemTransform()
{
return new ItemTransformVec3f(toMojang(toXYZDegrees(getLeftRot())), toMojang(getTranslation()), toMojang(getScale()));
}
@@ -21,8 +21,8 @@ package net.minecraftforge.common.model.animation;
import java.io.IOException;
import net.minecraft.client.renderer.block.model.IUnbakedModel;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.model.IUnbakedModel;
import net.minecraft.client.renderer.model.ModelResourceLocation;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.ResourceLocation;
@@ -21,10 +21,8 @@ package net.minecraftforge.common.network;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import net.minecraft.world.dimension.DimensionType;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.network.ForgeMessage.DimensionRegisterMessage;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -36,9 +34,9 @@ public class DimensionMessageHandler extends SimpleChannelInboundHandler<ForgeMe
@Override
protected void channelRead0(ChannelHandlerContext ctx, DimensionRegisterMessage msg) throws Exception
{
if (!DimensionManager.isDimensionRegistered(msg.dimensionId))
if (DimensionManager.getRegistry().get(msg.id) == null)
{
DimensionManager.registerDimension(msg.dimensionId, DimensionType.valueOf(msg.providerId));
DimensionManager.registerDimensionInternal(msg.id + 1, msg.name, msg.dim, msg.data);
}
}
@Override
@@ -20,54 +20,71 @@
package net.minecraftforge.common.network;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Sets;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.ModDimension;
import net.minecraftforge.registries.ForgeRegistries;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
public abstract class ForgeMessage {
private static final Logger LOGGER = LogManager.getLogger();
public static class DimensionRegisterMessage extends ForgeMessage {
/** The dimension ID to register on client */
int dimensionId;
/** The provider ID to register with dimension on client */
String providerId;
int id;
ResourceLocation name;
ModDimension dim;
@Nullable
PacketBuffer data;
public DimensionRegisterMessage(){}
public DimensionRegisterMessage(int dimensionId, String providerId)
public DimensionRegisterMessage(int id, ResourceLocation name, ModDimension dim, @Nullable PacketBuffer data)
{
this.dimensionId = dimensionId;
this.providerId = providerId;
this.id = id;
this.dim = dim;
this.data = data;
}
@Override
void toBytes(ByteBuf bytes)
void toBytes(ByteBuf buff)
{
bytes.writeInt(this.dimensionId);
byte[] data = this.providerId.getBytes(StandardCharsets.UTF_8);
bytes.writeShort(data.length);
bytes.writeBytes(data);
PacketBuffer output = new PacketBuffer(buff);
output.writeInt(id);
output.writeResourceLocation(name);
output.writeResourceLocation(dim.getRegistryName());
if (data == null)
{
output.writeShort(0);
}
else
{
ByteBuf dup = data.duplicate();
output.writeShort(dup.readableBytes());
output.writeBytes(dup);
}
}
@Override
void fromBytes(ByteBuf bytes)
void fromBytes(ByteBuf buff)
{
dimensionId = bytes.readInt();
byte[] data = new byte[bytes.readShort()];
bytes.readBytes(data);
providerId = new String(data, StandardCharsets.UTF_8);
PacketBuffer input = new PacketBuffer(buff);
id = input.readInt();
name = input.readResourceLocation();
dim = ForgeRegistries.MOD_DIMENSIONS.getValue(input.readResourceLocation());
int len = input.readShort();
if (len != 0)
{
data = new PacketBuffer(Unpooled.buffer());
input.readBytes(data, len);
}
}
}
/* TODO fluids
@@ -63,7 +63,7 @@ public class BlockSnapshot
public BlockSnapshot(World world, BlockPos pos, IBlockState state, @Nullable NBTTagCompound nbt)
{
this.setWorld(world);
this.dimId = world.dimension.getId();
this.dimId = world.dimension.getType().getId();
this.pos = pos.toImmutable();
this.setReplacedBlock(state);
this.registryName = state.getBlock().getRegistryName();
@@ -26,12 +26,12 @@ import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.play.client.CPacketClientSettings;
import net.minecraft.server.management.PlayerInteractionManager;
import net.minecraft.stats.StatBase;
import net.minecraft.stats.Stat;
import net.minecraft.util.DamageSource;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.dimension.DimensionType;
//Preliminary, simple Fake Player class
public class FakePlayer extends EntityPlayerMP
@@ -44,12 +44,12 @@ public class FakePlayer extends EntityPlayerMP
@Override public Vec3d getPositionVector(){ return new Vec3d(0, 0, 0); }
@Override public void sendStatusMessage(ITextComponent chatComponent, boolean actionBar){}
@Override public void sendMessage(ITextComponent component) {}
@Override public void addStat(StatBase par1StatBase, int par2){}
@Override public void addStat(Stat par1StatBase, int par2){}
//@Override public void openGui(Object mod, int modGuiId, World world, int x, int y, int z){}
@Override public boolean isInvulnerableTo(DamageSource source){ return true; }
@Override public boolean canAttackPlayer(EntityPlayer player){ return false; }
@Override public void onDeath(DamageSource source){ return; }
@Override public void tick(){ return; }
@Override public Entity changeDimension(int dim, ITeleporter teleporter){ return this; }
@Override public Entity changeDimension(DimensionType dim, ITeleporter teleporter){ return this; }
@Override public void handleClientSettings(CPacketClientSettings pkt){ return; }
}