Compiling fixes - IN GAME!

This commit is contained in:
covers1624 authored and cpw committed 2020-06-25 17:55:52 -04:00
1 parent 631230b298
commit 80eb12e59d
364 files changed
+1170 -9853

No files matched your search

@@ -321,10 +321,10 @@ public class ForgeHooksClient
if (status == BETA || status == BETA_OUTDATED)
{
// render a warning at the top of the screen,
ITextComponent line = new TranslationTextComponent("forge.update.beta.1", TextFormatting.RED, TextFormatting.RESET);
gui.func_238472_a_(mStack, font, line, (width - font.func_238414_a_(line)) / 2, 4 + (0 * (font.FONT_HEIGHT + 1)), -1);
ITextComponent line = new TranslationTextComponent("forge.update.beta.1", TextFormatting.RED, TextFormatting.RESET).func_240699_a_(TextFormatting.RED);
gui.func_238472_a_(mStack, font, line, width / 2, 4 + (0 * (font.FONT_HEIGHT + 1)), -1);
line = new TranslationTextComponent("forge.update.beta.2");
gui.func_238472_a_(mStack, font, line, (width - font.func_238414_a_(line)) / 2, 4 + (1 * (font.FONT_HEIGHT + 1)), -1);
gui.func_238472_a_(mStack, font, line, width / 2, 4 + (1 * (font.FONT_HEIGHT + 1)), -1);
}
String line = null;
@@ -1,617 +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 java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ConcurrentMap;
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.IntSet;
import it.unimi.dsi.fastutil.ints.IntSets;
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.CompoundNBT;
import net.minecraft.nbt.INBT;
import net.minecraft.nbt.ListNBT;
import net.minecraft.nbt.StringNBT;
import net.minecraft.network.PacketBuffer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.management.PlayerList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.registry.MutableRegistry;
import net.minecraft.world.World;
import net.minecraft.world.biome.IBiomeMagnifier;
import net.minecraft.world.chunk.ChunkStatus;
import net.minecraft.world.chunk.listener.IChunkStatusListener;
import net.minecraft.world.server.ServerMultiWorld;
import net.minecraft.world.server.ServerWorld;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.storage.SaveFormat;
import net.minecraft.world.storage.SaveHandler;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.event.world.RegisterDimensionsEvent;
import net.minecraftforge.event.world.WorldEvent;
import net.minecraftforge.fml.StartupQuery;
import net.minecraftforge.fml.server.ServerModLoader;
import net.minecraftforge.registries.ClearableRegistry;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.Validate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import javax.annotation.Nullable;
public class DimensionManager
{
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker DIMMGR = MarkerManager.getMarker("DIMS");
private static final ClearableRegistry<DimensionType> REGISTRY = new ClearableRegistry<>(new ResourceLocation("dimension_type"), DimensionType.class);
private static final Int2ObjectMap<Data> dimensions = Int2ObjectMaps.synchronize(new Int2ObjectLinkedOpenHashMap<>());
private static final IntSet unloadQueue = IntSets.synchronize(new IntLinkedOpenHashSet());
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<>();
private static final List<String> foldersScheduledForDeletion = new ArrayList<>();
private static volatile Set<World> playerWorlds = new HashSet<>();
/**
* Register or get the existing dimension type for the given dimtype name.
*
* Dimensions already known to the save are loaded into the DimensionType map before the {@link RegisterDimensionsEvent} is fired.
* You can use this helper to get your existing dimension, or create it if it is not found.
*
* @param name Registry name
* @param type ModDimension type data
* @param data Extra data for the ModDimension
* @param hasSkyLight does this dimension have a skylight?
* @param magnifier The biome generation processor
* @return the DimensionType for the dimension.
* /
public static DimensionType registerOrGetDimension(ResourceLocation name, ModDimension type, PacketBuffer data, boolean hasSkyLight)
{
return REGISTRY.getValue(name).orElseGet(()->registerDimension(name, type, data, hasSkyLight));
}
/**
* 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
* @param hasSkyLight skylight for this dimension
* @param magnifier The biome generation processor
* @return the DimensionType for the dimension.
* /
public static DimensionType registerDimension(ResourceLocation name, ModDimension type, PacketBuffer data, boolean hasSkyLight)
{
Validate.notNull(name, "Can not register a dimension with null name");
Validate.isTrue(!REGISTRY.containsKey(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)
{
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);
}
@SuppressWarnings("deprecation")
DimensionType instance = new DimensionType(id, "", name.getNamespace() + "/" + name.getPath(), type.getFactory(), hasSkyLight, type.getMagnifier(), type, data);
REGISTRY.register(id, name, instance);
LOGGER.info(DIMMGR, "Registered dimension {} of type {} and id {}", name.toString(), type.getRegistryName().toString(), id);
return instance;
}
/**
* 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 boolean keepLoaded(DimensionType dim, boolean value)
{
Validate.notNull(dim, "Dimension type must not be null");
Data data = getData(dim);
boolean ret = data.keepLoaded;
data.keepLoaded = value;
return ret;
}
/**
* 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)
{
Validate.notNull(dim, "Dimension type must not be null");
Data data = dimensions.get(dim.getId());
return data == null ? false : data.keepLoaded;
}
/**
* Retrieves the world from the server allowing for null return, and optionally resetting it's unload timer.
*
* @param server The server that controls 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.
* /
@Nullable
public static ServerWorld getWorld(MinecraftServer server, DimensionType dim, boolean resetUnloadDelay, boolean forceLoad)
{
Validate.notNull(server, "Must provide server when creating world");
Validate.notNull(dim, "Dimension type must not be null");
if (ServerModLoader.hasErrors()) {
throw new RuntimeException("The server has failed to initialize correctly due to mod loading errors. Examine the crash report for more details.");
}
// If we're in the early stages of loading, we need to return null so CommandSource can work properly for command function
if (StartupQuery.pendingQuery()) {
return null;
}
if (resetUnloadDelay && unloadQueue.contains(dim.getId()))
getData(dim).ticksWaited = 0;
@SuppressWarnings("deprecation")
ServerWorld ret = server.forgeGetWorldMap().get(dim);
if (ret == null && forceLoad)
ret = initWorld(server, dim);
return ret;
}
/**
* Marks the given dimension for deletion upon next reload of the save.
* The corresponding data directory will be deleted as well.
*
* Note that the dimension need not be currently unloaded. The dimension will stay functioning as normal
* until the save is reloaded.
*
* Vanilla dimensions are not supported and will throw an exception.
*
* @param dim the dimension to delete
* /
public static void markForDeletion(DimensionType dim)
{
if (dim.isVanilla())
{
throw new IllegalArgumentException("Cannot delete vanilla dimensions.");
}
getData(dim).markedForDeletion = true;
Path base = Paths.get(".").toAbsolutePath().normalize();
Path directory = dim.getDirectory(base.toFile()).toPath().toAbsolutePath().normalize();
if (!directory.startsWith(base))
{
LOGGER.warn("DimensionType {} returned save directory outside of base directory. This is bad. The directory will not be deleted.", dim);
}
else
{
String relative = base.relativize(directory).toString();
foldersScheduledForDeletion.add(relative);
}
}
//==========================================================================================================
// FORGE INTERNAL
//==========================================================================================================
/**
* Deprecated, unregistering dimensions at runtime is not supported.
* @see DimensionManager#markForDeletion(DimensionType)
* /
@Deprecated
public static void unregisterDimension(int id)
{
}
public static DimensionType registerDimensionInternal(int id, ResourceLocation name, ModDimension type, PacketBuffer data, boolean hasSkyLight)
{
Validate.notNull(name, "Can not register a dimension with null name");
Validate.notNull(type, "Can not register a null dimension type");
Validate.isTrue(!REGISTRY.containsKey(name), "Dimension: " + name + " Already registered");
Validate.isTrue(REGISTRY.getByValue(id) == null, "Dimension with id " + id + " already registered as name " + REGISTRY.getKey(REGISTRY.getByValue(id)));
@SuppressWarnings("deprecation")
DimensionType instance = new DimensionType(id, "", name.getNamespace() + "/" + name.getPath(), type.getFactory(), hasSkyLight, type.getMagnifier(), type, data);
REGISTRY.register(id, name, instance);
LOGGER.info(DIMMGR, "Registered dimension {} of type {} and id {}", name.toString(), type.getRegistryName().toString(), id);
return instance;
}
@SuppressWarnings("deprecation")
public static ServerWorld 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");
ServerWorld overworld = getWorld(server, DimensionType.OVERWORLD, false, false);
Validate.notNull(overworld, "Cannot Hotload Dim: Overworld is not Loaded!");
@SuppressWarnings("resource")
ServerWorld world = new ServerMultiWorld(overworld, server, server.getBackgroundExecutor(), overworld.getSaveHandler(), dim, server.getProfiler(), new NoopChunkStatusListener());
if (!server.isSinglePlayer())
world.getWorldInfo().setGameType(server.getGameType());
server.forgeGetWorldMap().put(dim, world);
server.markWorldsDirty();
MinecraftForge.EVENT_BUS.post(new WorldEvent.Load(world));
return world;
}
private static boolean canUnloadWorld(ServerWorld world)
{
return world.getDimension().getType() != DimensionType.OVERWORLD
&& world.getPlayers().isEmpty()
&& world.getForcedChunks().isEmpty()
&& !getData(world.getDimension().getType()).keepLoaded
&& !playerWorlds.contains(world);
}
/**
* Queues a dimension to unload, if it can be unloaded.
* @param world The world to unload
* /
public static void unloadWorld(ServerWorld world)
{
if (world == null || !canUnloadWorld(world))
return;
int id = world.getDimension().getType().getId();
if (unloadQueue.add(id))
LOGGER.debug(DIMMGR,"Queueing dimension {} to unload", id);
}
@SuppressWarnings("deprecation")
public static void unloadWorlds(MinecraftServer server, boolean checkLeaks)
{
IntIterator queueIterator = unloadQueue.iterator();
while (queueIterator.hasNext())
{
int id = queueIterator.nextInt();
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;
}
queueIterator.remove();
ServerWorld w = server.forgeGetWorldMap().get(dim);
dimension.ticksWaited = 0;
// Don't unload the world if the status changed
if (w == null || !canUnloadWorld(w))
{
LOGGER.debug(DIMMGR,"Aborting unload for dimension {} as status changed", id);
continue;
}
try
{
w.save(null, true, true);
}
catch (Exception e)
{
LOGGER.error(DIMMGR,"Caught an exception while saving all chunks:", e);
}
finally
{
MinecraftForge.EVENT_BUS.post(new WorldEvent.Unload(w));
LOGGER.debug(DIMMGR, "Unloading dimension {}", id);
try {
w.close();
} catch (IOException e) {
LOGGER.error("Exception closing the level", e);
}
server.forgeGetWorldMap().remove(dim);
server.markWorldsDirty();
}
}
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);
}
}
}
public static void writeRegistry(CompoundNBT data)
{
data.putInt("version", 1);
List<SavedEntry> list = new ArrayList<>();
for (DimensionType type : REGISTRY)
list.add(new SavedEntry(type, getData(type).markedForDeletion));
savedEntries.values().forEach(list::add);
Collections.sort(list, (a, b) -> a.id - b.id);
ListNBT lst = new ListNBT();
list.forEach(e -> lst.add(e.write()));
data.put("entries", lst);
ListNBT deleteLst = new ListNBT();
foldersScheduledForDeletion.forEach(folder -> deleteLst.add(StringNBT.valueOf(folder)));
data.put("delete_dirs", deleteLst);
}
public static void readRegistry(CompoundNBT 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();
@SuppressWarnings("unused")
boolean error = false;
ListNBT list = data.getList("entries", 10);
for (int x = 0; x < list.size(); x++)
{
SavedEntry entry = new SavedEntry(list.getCompound(x));
if (entry.type == null)
{
DimensionType type = REGISTRY.getOrDefault(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 if (!entry.markedForDeletion)
{
ModDimension mod = ForgeRegistries.MOD_DIMENSIONS.getValue(entry.type);
if (mod == null)
{
LOGGER.error(DIMMGR, "Modded dimension entry '{}' id {} type {} 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)), entry.skyLight());
}
}
foldersScheduledForDeletion.clear();
ListNBT folderList = data.getList("delete_dirs", Constants.NBT.TAG_STRING);
folderList.stream()
.map(INBT::getString)
.forEach(foldersScheduledForDeletion::add);
}
public static void processScheduledDeletions(SaveFormat.LevelSave levelSave)
{
List<String> toDelete = new ArrayList<>(foldersScheduledForDeletion);
foldersScheduledForDeletion.clear();
if (!toDelete.isEmpty())
{
StringBuilder text = new StringBuilder();
text.append("The following dimensions are marked for deletion by their owning mod. Proceed?\n\n");
for (String folder : toDelete)
{
text.append(folder).append('\n');
}
if (!StartupQuery.confirm(text.toString()))
{
StartupQuery.abort();
return;
}
}
for (String folderName : toDelete)
{
File folder = new File(levelSave.getWorldDir().toFile(), folderName);
try
{
FileUtils.deleteDirectory(folder);
LOGGER.info(DIMMGR, "Modded dimension directory {} scheduled for deletion was deleted.", folderName);
}
catch (Exception e)
{
LOGGER.error(DIMMGR, "Failed to delete modded dimension directory {} that was scheduled for deletion.", folderName, e);
}
}
}
public static void fireRegister()
{
MinecraftForge.EVENT_BUS.post(new RegisterDimensionsEvent(savedEntries));
if (!savedEntries.isEmpty())
{
savedEntries.values().forEach(entry -> {
LOGGER.warn(DIMMGR, "Missing Dimension Name: '{}' Id: {} Type: '{}", entry.name.toString(), entry.id, entry.type.toString());
});
}
}
@Deprecated //Forge: Internal use only.
public static MutableRegistry<DimensionType> getRegistry()
{
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;
boolean markedForDeletion = false;
}
public static class SavedEntry
{
int id;
ResourceLocation name;
ResourceLocation type;
byte[] data;
boolean skyLight;
boolean markedForDeletion;
public int getId()
{
return id;
}
public ResourceLocation getName()
{
return name;
}
@Nullable
public ResourceLocation getType()
{
return type;
}
@Nullable
public byte[] getData()
{
return data;
}
public boolean skyLight()
{
return this.skyLight;
}
private SavedEntry(CompoundNBT 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;
this.skyLight = data.contains("sky_light", 99) ? data.getBoolean("sky_light") : true;
this.markedForDeletion = data.getBoolean("marked_for_deletion");
}
private SavedEntry(DimensionType data, boolean markedForDeletion)
{
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();
this.skyLight = data.hasSkyLight();
this.markedForDeletion = markedForDeletion;
}
private CompoundNBT write()
{
CompoundNBT ret = new CompoundNBT();
ret.putInt("id", id);
ret.putString("name", name.toString());
if (type != null)
ret.putString("type", type.toString());
if (data != null)
ret.putByteArray("data", data);
ret.putBoolean("sky_light", skyLight);
ret.putBoolean("marked_for_deletion", markedForDeletion);
return ret;
}
}
private static class NoopChunkStatusListener implements IChunkStatusListener
{
@Override public void start(ChunkPos center) { }
@Override public void statusChanged(ChunkPos chunkPosition, ChunkStatus newStatus) { }
@Override public void stop() { }
}
public static boolean rebuildPlayerMap(PlayerList players, boolean changed)
{
playerWorlds = players.getPlayers().stream().map(e -> e.world).collect(Collectors.toSet());
return changed;
}
}*/
@@ -94,6 +94,8 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
public static final RegistryObject<Attribute> NAMETAG_DISTANCE = ATTRIBUTES.register("nametag_distance", () -> new RangedAttribute("forge.nameTagDistance", 64.0D, 0.0D, Float.MAX_VALUE).func_233753_a_(true));
public static final RegistryObject<Attribute> ENTITY_GRAVITY = ATTRIBUTES.register("entity_gravity", () -> new RangedAttribute("forge.entity_gravity", 0.08D, -8.0D, 8.0D).func_233753_a_(true));
public static final RegistryObject<Attribute> REACH_DISTANCE = ATTRIBUTES.register("reach_distance", () -> new RangedAttribute( "generic.reachDistance", 5.0D, 0.0D, 1024.0D).func_233753_a_(true));
private static ForgeMod INSTANCE;
public static ForgeMod getInstance()
{
@@ -1,79 +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.util.function.BiFunction;
import net.minecraft.network.PacketBuffer;
import net.minecraft.world.World;
import net.minecraft.world.biome.ColumnFuzzedBiomeMagnifier;
import net.minecraft.world.biome.IBiomeMagnifier;
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 BiFunction<World, 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){}
public IBiomeMagnifier getMagnifier() {
return ColumnFuzzedBiomeMagnifier.INSTANCE;
}
/**
* Convenience method for generating a ModDimension with a specific factory but no extra
* data handling behaviour. Extend ModDimension to override other methods.
*
* @param factory Factory for creating {@link Dimension} instances from DimType and World.
* @return A custom ModDimension with that factory.
* /
public static ModDimension withFactory(BiFunction<World, DimensionType, ? extends Dimension> factory) {
return new ModDimension() {
@Override
public BiFunction<World, DimensionType, ? extends Dimension> getFactory() {
return factory;
}
};
}
}*/
@@ -23,7 +23,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
@@ -31,7 +30,6 @@ import com.google.gson.JsonSyntaxException;
import net.minecraft.advancements.Advancement;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.crafting.conditions.ICondition;
public class ConditionalAdvancement
@@ -41,14 +39,11 @@ public class ConditionalAdvancement
return new Builder();
}
public static Advancement.Builder read(Gson gson, ResourceLocation recipeId, JsonObject json)
{
public static boolean processConditions(JsonObject json) {
JsonArray entries = JSONUtils.getJsonArray(json, "advancements", null);
if (entries == null)
{
if (!CraftingHelper.processConditions(json, "conditions"))
return null;
return gson.fromJson(json, Advancement.Builder.class);
return CraftingHelper.processConditions(json, "conditions");
}
int idx = 0;
@@ -57,10 +52,10 @@ public class ConditionalAdvancement
if (!ele.isJsonObject())
throw new JsonSyntaxException("Invalid advancement entry at index " + idx + " Must be JsonObject");
if (CraftingHelper.processConditions(JSONUtils.getJsonArray(ele.getAsJsonObject(), "conditions")))
return gson.fromJson(JSONUtils.getJsonObject(ele.getAsJsonObject(), "advancement"), Advancement.Builder.class);
return true;
idx++;
}
return null;
return false;
}
public static class Builder
@@ -114,7 +114,7 @@ public interface IForgeBlock
*/
default boolean isLadder(BlockState state, IWorldReader world, BlockPos pos, LivingEntity entity)
{
return false;
return state.getBlock().isIn(BlockTags.field_232878_as_);
}
/**
@@ -533,7 +533,7 @@ public interface IForgeBlock
*/
default boolean isFertile(BlockState state, IBlockReader world, BlockPos pos)
{
if (this.getBlock() == Blocks.FARMLAND)
if (state.isIn(Blocks.FARMLAND))
return state.get(FarmlandBlock.MOISTURE) > 0;
return false;
@@ -581,7 +581,7 @@ public interface IForgeBlock
*/
default boolean isPortalFrame(BlockState state, IWorldReader world, BlockPos pos)
{
return state.getBlock() == Blocks.OBSIDIAN;
return state.isIn(Blocks.OBSIDIAN);
}
/**
@@ -634,7 +634,7 @@ public interface IForgeBlock
*/
default float getEnchantPowerBonus(BlockState state, IWorldReader world, BlockPos pos)
{
return this.getBlock() == Blocks.BOOKSHELF ? 1: 0;
return state.isIn(Blocks.BOOKSHELF) ? 1: 0;
}
/**
@@ -23,6 +23,7 @@ import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.RegistryKey;
import net.minecraft.world.World;
import net.minecraftforge.client.model.animation.Animation;
import net.minecraftforge.common.MinecraftForge;
@@ -32,11 +33,11 @@ import net.minecraftforge.event.TickEvent;
public class BasicEventHooks
{
//TODO Dimensions..
// public static void firePlayerChangedDimensionEvent(PlayerEntity player, DimensionType fromDim, DimensionType toDim)
// {
// MinecraftForge.EVENT_BUS.post(new PlayerEvent.PlayerChangedDimensionEvent(player, fromDim, toDim));
// }
public static void firePlayerChangedDimensionEvent(PlayerEntity player, RegistryKey<World> fromDim, RegistryKey<World> toDim)
{
MinecraftForge.EVENT_BUS.post(new PlayerEvent.PlayerChangedDimensionEvent(player, fromDim, toDim));
}
public static void firePlayerLoggedIn(PlayerEntity player)
{
@@ -308,61 +308,4 @@ public class FMLPlayMessages
return additionalData;
}
}
//TODO Dimensions..
/*public static class DimensionInfoMessage
{
private ResourceLocation dimName;
private boolean skylight;
private int id;
private ResourceLocation modDimensionName;
private PacketBuffer extraData;
DimensionInfoMessage(DimensionType type) {
id = type.getId() + 1;
dimName = type.getRegistryName();
modDimensionName = type.getModType().getRegistryName();
skylight = type.hasSkyLight();
extraData = new PacketBuffer(Unpooled.buffer());
type.getModType().write(extraData, true);
}
DimensionInfoMessage(final int dimId, final ResourceLocation dimname, final ResourceLocation modDimensionName, final boolean skylight, final PacketBuffer extraData) {
id = dimId;
this.dimName = dimname;
this.modDimensionName = modDimensionName;
this.skylight = skylight;
this.extraData = extraData;
}
public static DimensionInfoMessage decode(PacketBuffer buffer) {
int dimId = buffer.readInt();
ResourceLocation dimname = buffer.readResourceLocation();
ResourceLocation moddimname = buffer.readResourceLocation();
boolean skylight = buffer.readBoolean();
PacketBuffer pb = new PacketBuffer(Unpooled.wrappedBuffer(buffer.readByteArray()));
return new DimensionInfoMessage(dimId, dimname, moddimname, skylight, pb);
}
public static void encode(DimensionInfoMessage message, PacketBuffer buffer) {
buffer.writeInt(message.id);
buffer.writeResourceLocation(message.dimName);
buffer.writeResourceLocation(message.modDimensionName);
buffer.writeBoolean(message.skylight);
buffer.writeByteArray(message.extraData.array());
}
private DimensionType makeDummyDimensionType() {
final ModDimension modDim = ForgeRegistries.MOD_DIMENSIONS.getValue(modDimensionName);
// default to overworld if no moddim found
if (modDim == null) return DimensionType.OVERWORLD;
modDim.read(extraData, true);
return new DimensionType(id, "dummy", "dummy", modDim.getFactory(), skylight, FuzzedBiomeMagnifier.INSTANCE, modDim, extraData);
}
public static boolean handle(final DimensionInfoMessage message, final Supplier<NetworkEvent.Context> contextSupplier) {
contextSupplier.get().enqueueWork(()-> NetworkHooks.addCachedDimensionType(message.makeDummyDimensionType(), message.dimName));
return true;
}
}*/
}
@@ -80,7 +80,7 @@ public class ForgeRegistries
public static final IForgeRegistry<IRecipeSerializer<?>> RECIPE_SERIALIZERS = RegistryManager.ACTIVE.getRegistry(IRecipeSerializer.class);
public static final IForgeRegistry<Attribute> ATTRIBUTES = RegistryManager.ACTIVE.getRegistry(Attribute.class);
public static final IForgeRegistry<StatType<?>> STAT_TYPES = RegistryManager.ACTIVE.getRegistry(StatType.class);
// Villages
public static final IForgeRegistry<VillagerProfession> PROFESSIONS = RegistryManager.ACTIVE.getRegistry(VillagerProfession.class);
public static final IForgeRegistry<PointOfInterestType> POI_TYPES = RegistryManager.ACTIVE.getRegistry(PointOfInterestType.class);
@@ -94,7 +94,6 @@ public class ForgeRegistries
public static final IForgeRegistry<SurfaceBuilder<?>> SURFACE_BUILDERS = RegistryManager.ACTIVE.getRegistry(SurfaceBuilder.class);
public static final IForgeRegistry<Feature<?>> FEATURES = RegistryManager.ACTIVE.getRegistry(Feature.class);
public static final IForgeRegistry<Placement<?>> DECORATORS = RegistryManager.ACTIVE.getRegistry(Placement.class);
// public static final IForgeRegistry<BiomeProviderType<?, ?>> BIOME_PROVIDER_TYPES = RegistryManager.ACTIVE.getRegistry(BiomeProviderType.class);
// public static final IForgeRegistry<ChunkGeneratorType<?, ?>> CHUNK_GENERATOR_TYPES = RegistryManager.ACTIVE.getRegistry(ChunkGeneratorType.class);
public static final IForgeRegistry<ChunkStatus> CHUNK_STATUS = RegistryManager.ACTIVE.getRegistry(ChunkStatus.class);
public static final IForgeRegistry<BlockStateProviderType<?>> BLOCK_STATE_PROVIDER_TYPES = RegistryManager.ACTIVE.getRegistry(BlockStateProviderType.class);
@@ -103,7 +102,6 @@ public class ForgeRegistries
public static final IForgeRegistry<TreeDecoratorType<?>> TREE_DECORATOR_TYPES = RegistryManager.ACTIVE.getRegistry(TreeDecoratorType.class);
// Custom forge registries
//public static final IForgeRegistry<ModDimension> MOD_DIMENSIONS = RegistryManager.ACTIVE.getRegistry(ModDimension.class); //TODO Dimensions..
public static final IForgeRegistry<DataSerializerEntry> DATA_SERIALIZERS = RegistryManager.ACTIVE.getRegistry(DataSerializerEntry.class);
public static final IForgeRegistry<GlobalLootModifierSerializer<?>> LOOT_MODIFIER_SERIALIZERS = RegistryManager.ACTIVE.getRegistry(GlobalLootModifierSerializer.class);
@@ -141,7 +141,6 @@ public class GameData
public static final ResourceLocation FEATURES = new ResourceLocation("feature");
public static final ResourceLocation DECORATORS = new ResourceLocation("decorator");
public static final ResourceLocation BIOME_PROVIDER_TYPES = new ResourceLocation("biome_source_type");
public static final ResourceLocation CHUNK_GENERATOR_TYPES = new ResourceLocation("chunk_generator_type");
public static final ResourceLocation CHUNK_STATUS = new ResourceLocation("chunk_status");
public static final ResourceLocation BLOCK_STATE_PROVIDER_TYPES = new ResourceLocation("block_state_provider_type");
public static final ResourceLocation BLOCK_PLACER_TYPES = new ResourceLocation("block_placer_type");
@@ -149,7 +148,6 @@ public class GameData
public static final ResourceLocation TREE_DECORATOR_TYPES = new ResourceLocation("tree_decorator_type");
// Custom forge registries
public static final ResourceLocation MODDIMENSIONS = new ResourceLocation("forge:moddimensions");
public static final ResourceLocation SERIALIZERS = new ResourceLocation("minecraft:dataserializers");
public static final ResourceLocation LOOT_MODIFIER_SERIALIZERS = new ResourceLocation("forge:loot_modifier_serializers");
@@ -212,8 +210,6 @@ public class GameData
makeRegistry(SURFACE_BUILDERS, SurfaceBuilder.class).disableSaving().disableSync().create();
makeRegistry(FEATURES, Feature.class).addCallback(FeatureCallbacks.INSTANCE).disableSaving().create();
makeRegistry(DECORATORS, Placement.class).disableSaving().disableSync().create();
// makeRegistry(BIOME_PROVIDER_TYPES, BiomeProviderType.class).disableSaving().disableSync().create();
// makeRegistry(CHUNK_GENERATOR_TYPES, ChunkGeneratorType.class).disableSaving().disableSync().create();
makeRegistry(CHUNK_STATUS, ChunkStatus.class, new ResourceLocation("empty")).disableSaving().disableSync().create();
makeRegistry(BLOCK_STATE_PROVIDER_TYPES, BlockStateProviderType.class).disableSaving().disableSync().create();
makeRegistry(BLOCK_PLACER_TYPES, BlockPlacerType.class).disableSaving().disableSync().create();
@@ -221,7 +217,6 @@ public class GameData
makeRegistry(TREE_DECORATOR_TYPES, TreeDecoratorType.class).disableSaving().disableSync().create();
// Custom forge registries
//makeRegistry(MODDIMENSIONS, ModDimension.class ).disableSaving().create(); //TODO Dimensions
makeRegistry(SERIALIZERS, DataSerializerEntry.class, 256 /*vanilla space*/, MAX_VARINT).disableSaving().disableOverrides().addCallback(SerializerCallbacks.INSTANCE).create();
makeRegistry(LOOT_MODIFIER_SERIALIZERS, GlobalLootModifierSerializer.class).disableSaving().disableSync().create();
}