Merge branches 'experimental' and 'master' of https://github.com/Minestom/Minestom

This commit is contained in:
Eoghanmc22 2020-06-30 17:15:32 -04:00
commit 68049b3eab
33 changed files with 743 additions and 40 deletions

@ -1 +1 @@
Subproject commit 1e52503a6dbabd326bd0fee5e2aba5cd07b2a4f8
Subproject commit fc2078a404b7b6041a1d60f15b6b2b482890bbfb

View File

@ -2,6 +2,9 @@
// AUTOGENERATED BY EnumGenerator
//==============================
package net.minestom.server.entity;
import net.minestom.server.registry.Registries;
import net.minestom.server.utils.NamespaceID;
@SuppressWarnings({"deprecation"})
public enum EntityType {
AREA_EFFECT_CLOUD("minecraft:area_effect_cloud"),
@ -116,6 +119,7 @@ public enum EntityType {
EntityType(String namespaceID) {
this.namespaceID = namespaceID;
Registries.entityTypes.put(NamespaceID.from(namespaceID), this);
}
public int getId() {

View File

@ -0,0 +1,37 @@
//==============================
// AUTOGENERATED BY EnumGenerator
//==============================
package net.minestom.server.fluids;
import net.minestom.server.registry.Registries;
import net.minestom.server.utils.NamespaceID;
@SuppressWarnings({"deprecation"})
public enum Fluid {
EMPTY("minecraft:empty"),
FLOWING_WATER("minecraft:flowing_water"),
WATER("minecraft:water"),
FLOWING_LAVA("minecraft:flowing_lava"),
LAVA("minecraft:lava"),
;
private String namespaceID;
Fluid(String namespaceID) {
this.namespaceID = namespaceID;
Registries.fluids.put(NamespaceID.from(namespaceID), this);
}
public int getId() {
return ordinal();
}
public String getNamespaceID() {
return namespaceID;
}
public static Fluid fromId(int id) {
if(id >= 0 && id < values().length) {
return values()[id];
}
return EMPTY;
}
}

View File

@ -2,6 +2,9 @@
// AUTOGENERATED BY EnumGenerator
//==============================
package net.minestom.server.instance;
import net.minestom.server.registry.Registries;
import net.minestom.server.utils.NamespaceID;
@SuppressWarnings({"deprecation"})
public enum Biome {
OCEAN("minecraft:ocean"),
@ -88,6 +91,7 @@ public enum Biome {
Biome(String namespaceID) {
this.namespaceID = namespaceID;
Registries.biomes.put(NamespaceID.from(namespaceID), this);
}
public int getId() {

View File

@ -2,6 +2,7 @@
// AUTOGENERATED BY EnumGenerator
//==============================
package net.minestom.server.instance.block;
import net.minestom.server.registry.Registries;
import net.minestom.server.utils.NamespaceID;
import java.util.List;
import java.util.ArrayList;
@ -1268,6 +1269,7 @@ public enum Block {
if(singleState) {
addBlockAlternative(new BlockAlternative(defaultID));
}
Registries.blocks.put(NamespaceID.from(namespaceID), this);
}
public short getBlockId() {
@ -1290,6 +1292,10 @@ public enum Block {
return isSolid;
}
public boolean isLiquid() {
return this == WATER || this == LAVA;
}
public double getHardness() {
return hardness;
}

View File

@ -2,6 +2,9 @@
// AUTOGENERATED BY EnumGenerator
//==============================
package net.minestom.server.item;
import net.minestom.server.registry.Registries;
import net.minestom.server.utils.NamespaceID;
@SuppressWarnings({"deprecation"})
public enum Enchantment {
PROTECTION("minecraft:protection"),
@ -47,6 +50,7 @@ public enum Enchantment {
Enchantment(String namespaceID) {
this.namespaceID = namespaceID;
Registries.enchantments.put(NamespaceID.from(namespaceID), this);
}
public int getId() {

View File

@ -3,6 +3,9 @@
//==============================
package net.minestom.server.item;
import net.minestom.server.instance.block.Block;
import net.minestom.server.registry.Registries;
import net.minestom.server.utils.NamespaceID;
@SuppressWarnings({"deprecation"})
public enum Material {
AIR("minecraft:air", 0, Block.AIR),
@ -989,6 +992,7 @@ public enum Material {
this.namespaceID = namespaceID;
this.maxDefaultStackSize = maxDefaultStackSize;
this.correspondingBlock = correspondingBlock;
Registries.materials.put(NamespaceID.from(namespaceID), this);
}
public short getId() {

View File

@ -2,6 +2,9 @@
// AUTOGENERATED BY EnumGenerator
//==============================
package net.minestom.server.particle;
import net.minestom.server.registry.Registries;
import net.minestom.server.utils.NamespaceID;
@SuppressWarnings({"deprecation"})
public enum Particle {
AMBIENT_ENTITY_EFFECT("minecraft:ambient_entity_effect"),
@ -81,6 +84,7 @@ public enum Particle {
Particle(String namespaceID) {
this.namespaceID = namespaceID;
Registries.particles.put(NamespaceID.from(namespaceID), this);
}
public int getId() {

View File

@ -2,6 +2,9 @@
// AUTOGENERATED BY EnumGenerator
//==============================
package net.minestom.server.potion;
import net.minestom.server.registry.Registries;
import net.minestom.server.utils.NamespaceID;
@SuppressWarnings({"deprecation"})
public enum PotionType {
EMPTY("minecraft:empty"),
@ -52,6 +55,7 @@ public enum PotionType {
PotionType(String namespaceID) {
this.namespaceID = namespaceID;
Registries.potionTypes.put(NamespaceID.from(namespaceID), this);
}
public int getId() {

View File

@ -0,0 +1,160 @@
package net.minestom.server.registry;
import java.util.HashMap;
import net.minestom.server.utils.NamespaceID;
import net.minestom.server.instance.block.Block;
import net.minestom.server.item.Material;
import net.minestom.server.instance.Biome;
import net.minestom.server.item.Enchantment;
import net.minestom.server.entity.EntityType;
import net.minestom.server.particle.Particle;
import net.minestom.server.potion.PotionType;
import net.minestom.server.sound.Sound;
import net.minestom.server.stat.StatisticType;
import net.minestom.server.fluids.Fluid;
// AUTOGENERATED
public class Registries {
/** Should only be used for internal code, please use the get* methods. */
@Deprecated
public static final HashMap<NamespaceID, Block> blocks = new HashMap<>();
/** Should only be used for internal code, please use the get* methods. */
@Deprecated
public static final HashMap<NamespaceID, Material> materials = new HashMap<>();
/** Should only be used for internal code, please use the get* methods. */
@Deprecated
public static final HashMap<NamespaceID, Biome> biomes = new HashMap<>();
/** Should only be used for internal code, please use the get* methods. */
@Deprecated
public static final HashMap<NamespaceID, Enchantment> enchantments = new HashMap<>();
/** Should only be used for internal code, please use the get* methods. */
@Deprecated
public static final HashMap<NamespaceID, EntityType> entityTypes = new HashMap<>();
/** Should only be used for internal code, please use the get* methods. */
@Deprecated
public static final HashMap<NamespaceID, Particle> particles = new HashMap<>();
/** Should only be used for internal code, please use the get* methods. */
@Deprecated
public static final HashMap<NamespaceID, PotionType> potionTypes = new HashMap<>();
/** Should only be used for internal code, please use the get* methods. */
@Deprecated
public static final HashMap<NamespaceID, Sound> sounds = new HashMap<>();
/** Should only be used for internal code, please use the get* methods. */
@Deprecated
public static final HashMap<NamespaceID, StatisticType> statisticTypes = new HashMap<>();
/** Should only be used for internal code, please use the get* methods. */
@Deprecated
public static final HashMap<NamespaceID, Fluid> fluids = new HashMap<>();
/** Returns the corresponding Block matching the given id. Returns 'AIR' if none match. */
public static Block getBlock(String id) {
return getBlock(NamespaceID.from(id));
}
/** Returns the corresponding Block matching the given id. Returns 'AIR' if none match. */
public static Block getBlock(NamespaceID id) {
return blocks.getOrDefault(id, Block.AIR);
}
/** Returns the corresponding Material matching the given id. Returns 'AIR' if none match. */
public static Material getMaterial(String id) {
return getMaterial(NamespaceID.from(id));
}
/** Returns the corresponding Material matching the given id. Returns 'AIR' if none match. */
public static Material getMaterial(NamespaceID id) {
return materials.getOrDefault(id, Material.AIR);
}
/** Returns the corresponding Biome matching the given id. Returns null if none match. */
public static Biome getBiome(String id) {
return getBiome(NamespaceID.from(id));
}
/** Returns the corresponding Biome matching the given id. Returns null if none match. */
public static Biome getBiome(NamespaceID id) {
return biomes.get(id);
}
/** Returns the corresponding Enchantment matching the given id. Returns null if none match. */
public static Enchantment getEnchantment(String id) {
return getEnchantment(NamespaceID.from(id));
}
/** Returns the corresponding Enchantment matching the given id. Returns null if none match. */
public static Enchantment getEnchantment(NamespaceID id) {
return enchantments.get(id);
}
/** Returns the corresponding EntityType matching the given id. Returns 'PIG' if none match. */
public static EntityType getEntityType(String id) {
return getEntityType(NamespaceID.from(id));
}
/** Returns the corresponding EntityType matching the given id. Returns 'PIG' if none match. */
public static EntityType getEntityType(NamespaceID id) {
return entityTypes.getOrDefault(id, EntityType.PIG);
}
/** Returns the corresponding Particle matching the given id. Returns null if none match. */
public static Particle getParticle(String id) {
return getParticle(NamespaceID.from(id));
}
/** Returns the corresponding Particle matching the given id. Returns null if none match. */
public static Particle getParticle(NamespaceID id) {
return particles.get(id);
}
/** Returns the corresponding PotionType matching the given id. Returns null if none match. */
public static PotionType getPotionType(String id) {
return getPotionType(NamespaceID.from(id));
}
/** Returns the corresponding PotionType matching the given id. Returns null if none match. */
public static PotionType getPotionType(NamespaceID id) {
return potionTypes.get(id);
}
/** Returns the corresponding Sound matching the given id. Returns null if none match. */
public static Sound getSound(String id) {
return getSound(NamespaceID.from(id));
}
/** Returns the corresponding Sound matching the given id. Returns null if none match. */
public static Sound getSound(NamespaceID id) {
return sounds.get(id);
}
/** Returns the corresponding StatisticType matching the given id. Returns null if none match. */
public static StatisticType getStatisticType(String id) {
return getStatisticType(NamespaceID.from(id));
}
/** Returns the corresponding StatisticType matching the given id. Returns null if none match. */
public static StatisticType getStatisticType(NamespaceID id) {
return statisticTypes.get(id);
}
/** Returns the corresponding Fluid matching the given id. Returns 'EMPTY' if none match. */
public static Fluid getFluid(String id) {
return getFluid(NamespaceID.from(id));
}
/** Returns the corresponding Fluid matching the given id. Returns 'EMPTY' if none match. */
public static Fluid getFluid(NamespaceID id) {
return fluids.getOrDefault(id, Fluid.EMPTY);
}
}

View File

@ -2,6 +2,9 @@
// AUTOGENERATED BY EnumGenerator
//==============================
package net.minestom.server.sound;
import net.minestom.server.registry.Registries;
import net.minestom.server.utils.NamespaceID;
@SuppressWarnings({"deprecation"})
public enum Sound {
AMBIENT_CAVE("minecraft:ambient.cave"),
@ -994,6 +997,7 @@ public enum Sound {
Sound(String namespaceID) {
this.namespaceID = namespaceID;
Registries.sounds.put(NamespaceID.from(namespaceID), this);
}
public int getId() {

View File

@ -2,6 +2,9 @@
// AUTOGENERATED BY EnumGenerator
//==============================
package net.minestom.server.stat;
import net.minestom.server.registry.Registries;
import net.minestom.server.utils.NamespaceID;
@SuppressWarnings({"deprecation"})
public enum StatisticType {
LEAVE_GAME("minecraft:leave_game"),
@ -83,6 +86,7 @@ public enum StatisticType {
StatisticType(String namespaceID) {
this.namespaceID = namespaceID;
Registries.statisticTypes.put(NamespaceID.from(namespaceID), this);
}
public int getId() {

View File

@ -3,6 +3,7 @@ package net.minestom.codegen;
import net.minestom.codegen.blocks.BlockEnumGenerator;
import net.minestom.codegen.enchantment.EnchantmentEnumGenerator;
import net.minestom.codegen.entitytypes.EntityTypeEnumGenerator;
import net.minestom.codegen.fluids.FluidEnumGenerator;
import net.minestom.codegen.items.ItemEnumGenerator;
import net.minestom.codegen.particles.ParticleEnumGenerator;
import net.minestom.codegen.potions.PotionEnumGenerator;
@ -24,5 +25,7 @@ public class AllGenerators {
ParticleEnumGenerator.main(args);
StatsEnumGenerator.main(args);
BiomesEnumGenerator.main(args);
FluidEnumGenerator.main(args);
RegistriesGenerator.main(args);
}
}

View File

@ -2,6 +2,7 @@ package net.minestom.codegen;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import net.minestom.server.registry.Registries;
import net.minestom.server.utils.NamespaceID;
import java.io.File;
@ -63,9 +64,14 @@ public abstract class BasicEnumGenerator extends MinestomEnumGenerator<BasicEnum
@Override
protected void prepare(EnumGenerator generator) {
generator.addClassAnnotation("@SuppressWarnings({\"deprecation\"})");
generator.addImport(Registries.class.getCanonicalName());
generator.addImport(NamespaceID.class.getCanonicalName());
generator.setParams("String namespaceID");
generator.addMethod("getId", "()", "int", "return ordinal();");
generator.addMethod("getNamespaceID", "()", "String", "return namespaceID;");
generator.appendToConstructor("Registries."+CodeGenerator.decapitalize(getClassName())+"s.put(NamespaceID.from(namespaceID), this);");
}
@Override

View File

@ -13,4 +13,8 @@ public interface CodeGenerator {
*/
String generate() throws IOException;
static String decapitalize(String text) {
char first = text.charAt(0);
return ""+Character.toLowerCase(first)+text.substring(1);
}
}

View File

@ -0,0 +1,185 @@
package net.minestom.codegen;
import net.minestom.server.entity.EntityType;
import net.minestom.server.fluids.Fluid;
import net.minestom.server.instance.Biome;
import net.minestom.server.instance.block.Block;
import net.minestom.server.item.Enchantment;
import net.minestom.server.item.Material;
import net.minestom.server.particle.Particle;
import net.minestom.server.potion.PotionType;
import net.minestom.server.registry.ResourceGatherer;
import net.minestom.server.sound.Sound;
import net.minestom.server.stat.StatisticType;
import net.minestom.server.utils.NamespaceID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.HashMap;
import static net.minestom.codegen.MinestomEnumGenerator.DEFAULT_TARGET_PATH;
/**
* Generates the Registries class, which contains methods to get items/blocks/biomes/etc. from a NamespaceID
*/
public class RegistriesGenerator implements CodeGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(RegistriesGenerator.class);
// Order is important!
private static final String[] types = {
Block.class.getCanonicalName(),
Material.class.getCanonicalName(),
Biome.class.getCanonicalName(),
Enchantment.class.getCanonicalName(),
EntityType.class.getCanonicalName(),
Particle.class.getCanonicalName(),
PotionType.class.getCanonicalName(),
Sound.class.getCanonicalName(),
StatisticType.class.getCanonicalName(),
Fluid.class.getCanonicalName(),
};
private static final String[] defaults = {
"AIR",
"AIR",
null,
null,
"PIG",
null,
null,
null,
null,
"EMPTY"
};
@Override
public String generate() throws IOException {
StringBuilder contents = new StringBuilder(
"package net.minestom.server.registry;\n\n" +
"import " + HashMap.class.getCanonicalName() + ";\n" +
"import " + NamespaceID.class.getCanonicalName() + ";\n");
for(String type : types) {
contents.append("import ").append(type).append(";\n");
}
contents.append("\n// AUTOGENERATED\npublic class Registries {\n");
if(types.length != defaults.length) {
throw new Error("types.length != defaults.length");
}
// Hashmaps
for (int i = 0; i < types.length; i++) {
String type = types[i];
String simpleType = type.substring(type.lastIndexOf('.') + 1);
contents.append("\t/** Should only be used for internal code, please use the get* methods. */\n");
contents.append("\t@Deprecated\n");
contents.append('\t');
contents.append("public static final HashMap<NamespaceID, ").append(simpleType).append("> ").append(CodeGenerator.decapitalize(simpleType)).append('s');
contents.append(" = new HashMap<>();").append("\n\n");
}
contents.append('\n');
// accessor methods
for (int i = 0; i < types.length; i++) {
String type = types[i];
String simpleType = type.substring(type.lastIndexOf('.') + 1);
String defaultValue = defaults[i];
// Example:
/*
/** Returns 'AIR' if none match
public static Block getBlock(String id) {
return getBlock(NamespaceID.from(id));
}
/** Returns 'AIR' if none match
public static Block getBlock(NamespaceID id) {
return blocks.getOrDefault(id, AIR);
}
*/
StringBuilder comment = new StringBuilder("/** Returns the corresponding ");
comment.append(simpleType).append(" matching the given id. Returns ");
if(defaultValue != null) {
comment.append('\'').append(defaultValue).append('\'');
} else {
comment.append("null");
}
comment.append(" if none match. */");
// String variant
contents.append('\t').append(comment).append("\n");
contents.append('\t');
contents.append("public static ").append(simpleType).append(" get").append(simpleType).append("(String id) {\n");
contents.append("\t\t").append("return get").append(simpleType).append("(NamespaceID.from(id));\n");
contents.append("\t}\n\n");
// NamespaceID variant
contents.append('\t').append(comment).append("\n");
contents.append('\t');
contents.append("public static ").append(simpleType).append(" get").append(simpleType).append("(NamespaceID id) {\n");
contents.append("\t\t").append("return ").append(CodeGenerator.decapitalize(simpleType)).append("s.");
if(defaultValue != null) {
contents.append("getOrDefault(id, ").append(simpleType).append('.').append(defaultValue).append(");");
} else {
contents.append("get(id);");
}
contents.append("\n");
contents.append("\t}\n\n");
}
contents.append("\n}\n");
return contents.toString();
}
public static void main(String[] args) throws IOException {
// copy-pasted from BlockEnumGenerator, to stay consistent in the order of arguments
String targetVersion;
if(args.length < 1) {
System.err.println("Usage: <MC version> [target folder]");
return;
}
targetVersion = args[0];
try {
ResourceGatherer.ensureResourcesArePresent(targetVersion, null); // TODO
} catch (IOException e) {
e.printStackTrace();
}
String targetPart = DEFAULT_TARGET_PATH;
if(args.length >= 2) {
targetPart = args[1];
}
File targetFolder = new File(targetPart);
if(!targetFolder.exists()) {
targetFolder.mkdirs();
}
new RegistriesGenerator().generateTo(targetFolder);
}
private void generateTo(File targetFolder) throws IOException {
String code = generate();
String folder = "net/minestom/server/registry";
File parentFolder = new File(targetFolder, folder);
if(!parentFolder.exists()) {
parentFolder.mkdirs();
}
LOGGER.debug("Writing to file: "+parentFolder+"/Registries.java");
try(Writer writer = new BufferedWriter(new FileWriter(new File(parentFolder, "Registries.java")))) {
writer.write(code);
}
}
}

View File

@ -9,6 +9,7 @@ import net.minestom.codegen.EnumGenerator;
import net.minestom.codegen.MinestomEnumGenerator;
import net.minestom.codegen.PrismarinePaths;
import net.minestom.server.instance.block.BlockAlternative;
import net.minestom.server.registry.Registries;
import net.minestom.server.registry.ResourceGatherer;
import net.minestom.server.utils.NamespaceID;
import org.slf4j.Logger;
@ -240,6 +241,7 @@ public class BlockEnumGenerator extends MinestomEnumGenerator<BlockContainer> {
protected void prepare(EnumGenerator generator) {
String className = getClassName();
generator.addClassAnnotation("@SuppressWarnings({\"deprecation\"})");
generator.addImport(Registries.class.getCanonicalName());
generator.addImport(NamespaceID.class.getCanonicalName());
generator.addImport(List.class.getCanonicalName());
generator.addImport(ArrayList.class.getCanonicalName());
@ -252,6 +254,7 @@ public class BlockEnumGenerator extends MinestomEnumGenerator<BlockContainer> {
generator.addMethod("hasBlockEntity", "()", "boolean", "return blockEntity != null;");
generator.addMethod("getBlockEntityName", "()", "NamespaceID", "return blockEntity;");
generator.addMethod("isSolid", "()", "boolean", "return isSolid;");
generator.addMethod("isLiquid", "()", "boolean", "return this == WATER || this == LAVA;");
generator.addMethod("getHardness", "()", "double", "return hardness;");
generator.addMethod("getResistance", "()", "double", "return resistance;");
generator.addMethod("breaksInstantaneously", "()", "boolean", "return hardness == 0;");
@ -272,6 +275,7 @@ public class BlockEnumGenerator extends MinestomEnumGenerator<BlockContainer> {
generator.appendToConstructor("if(singleState) {");
generator.appendToConstructor("\taddBlockAlternative(new BlockAlternative(defaultID));");
generator.appendToConstructor("}");
generator.appendToConstructor("Registries.blocks.put(NamespaceID.from(namespaceID), this);");
}
@Override

View File

@ -0,0 +1,56 @@
package net.minestom.codegen.fluids;
import net.minestom.codegen.BasicEnumGenerator;
import net.minestom.server.registry.ResourceGatherer;
import java.io.File;
import java.io.IOException;
public class FluidEnumGenerator extends BasicEnumGenerator {
public static void main(String[] args) throws IOException {
String targetVersion;
if(args.length < 1) {
System.err.println("Usage: <MC version> [target folder]");
return;
}
targetVersion = args[0];
try {
ResourceGatherer.ensureResourcesArePresent(targetVersion, null); // TODO
} catch (IOException e) {
e.printStackTrace();
}
String targetPart = DEFAULT_TARGET_PATH;
if(args.length >= 2) {
targetPart = args[1];
}
File targetFolder = new File(targetPart);
if(!targetFolder.exists()) {
targetFolder.mkdirs();
}
new FluidEnumGenerator(targetFolder);
}
private FluidEnumGenerator(File targetFolder) throws IOException {
super(targetFolder);
}
@Override
protected String getCategoryID() {
return "minecraft:fluid";
}
@Override
public String getPackageName() {
return "net.minestom.server.fluids";
}
@Override
public String getClassName() {
return "Fluid";
}
}

View File

@ -10,6 +10,7 @@ import net.minestom.codegen.PrismarinePaths;
import net.minestom.codegen.blocks.*;
import net.minestom.server.instance.block.Block;
import net.minestom.server.instance.block.BlockAlternative;
import net.minestom.server.registry.Registries;
import net.minestom.server.registry.ResourceGatherer;
import net.minestom.server.utils.NamespaceID;
import org.slf4j.Logger;
@ -130,7 +131,12 @@ public class ItemEnumGenerator extends MinestomEnumGenerator<ItemContainer> {
protected void prepare(EnumGenerator generator) {
String className = getClassName();
generator.addImport(Block.class.getCanonicalName());
generator.addImport(Registries.class.getCanonicalName());
generator.addImport(NamespaceID.class.getCanonicalName());
generator.addClassAnnotation("@SuppressWarnings({\"deprecation\"})");
generator.setParams("String namespaceID", "int maxDefaultStackSize", "Block correspondingBlock");
generator.appendToConstructor("Registries.materials.put(NamespaceID.from(namespaceID), this);");
generator.addMethod("getId", "()", "short", "return (short)ordinal();");
generator.addMethod("getName", "()", "String", "return namespaceID;");
generator.addMethod("getMaxDefaultStackSize", "()", "int", "return maxDefaultStackSize;");

View File

@ -15,6 +15,7 @@ import net.minestom.server.event.item.ItemDropEvent;
import net.minestom.server.event.item.ItemUpdateStateEvent;
import net.minestom.server.event.item.PickupItemEvent;
import net.minestom.server.event.player.*;
import net.minestom.server.gamedata.tags.TagManager;
import net.minestom.server.instance.Chunk;
import net.minestom.server.instance.Instance;
import net.minestom.server.instance.InstanceContainer;
@ -27,15 +28,18 @@ import net.minestom.server.item.ItemFlag;
import net.minestom.server.item.ItemStack;
import net.minestom.server.item.Material;
import net.minestom.server.network.ConnectionManager;
import net.minestom.server.network.packet.server.play.TagsPacket;
import net.minestom.server.ping.ResponseDataConsumer;
import net.minestom.server.timer.TaskRunnable;
import net.minestom.server.utils.MathUtils;
import net.minestom.server.utils.NamespaceID;
import net.minestom.server.utils.Position;
import net.minestom.server.utils.Vector;
import net.minestom.server.utils.time.TimeUnit;
import net.minestom.server.utils.time.UpdateOption;
import net.minestom.server.world.Dimension;
import java.io.FileNotFoundException;
import java.util.Map;
import java.util.UUID;
@ -115,7 +119,6 @@ public class PlayerInit {
});
connectionManager.addPlayerInitialization(player -> {
player.addEventCallback(EntityAttackEvent.class, event -> {
Entity entity = event.getTarget();
if (entity instanceof EntityCreature) {

View File

@ -27,7 +27,7 @@ public class NoiseTestGenerator extends ChunkGenerator {
if (random.nextInt(100) > 10) {
batch.setCustomBlock(x, y, z, "custom_block");
} else {
batch.setBlock(x, y, z, Block.DIAMOND_BLOCK);
batch.setBlock(x, y, z, Block.LAVA);
}
}
}

View File

@ -17,6 +17,7 @@ import net.minestom.server.event.item.ItemDropEvent;
import net.minestom.server.event.item.ItemUpdateStateEvent;
import net.minestom.server.event.item.PickupExperienceEvent;
import net.minestom.server.event.player.*;
import net.minestom.server.gamedata.tags.TagManager;
import net.minestom.server.instance.Chunk;
import net.minestom.server.instance.Instance;
import net.minestom.server.instance.block.CustomBlock;
@ -38,15 +39,13 @@ import net.minestom.server.scoreboard.Team;
import net.minestom.server.sound.Sound;
import net.minestom.server.sound.SoundCategory;
import net.minestom.server.stat.PlayerStatistic;
import net.minestom.server.utils.ArrayUtils;
import net.minestom.server.utils.BlockPosition;
import net.minestom.server.utils.MathUtils;
import net.minestom.server.utils.Position;
import net.minestom.server.utils.*;
import net.minestom.server.utils.chunk.ChunkUtils;
import net.minestom.server.utils.validate.Check;
import net.minestom.server.world.Dimension;
import net.minestom.server.world.LevelType;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArraySet;
@ -236,6 +235,16 @@ public class Player extends LivingEntity implements CommandSender {
}
// Recipes end
// Send server tags
TagsPacket tags = new TagsPacket();
TagManager tagManager = MinecraftServer.getTagManager();
tagManager.addRequiredTagsToPacket(tags);
UpdateTagListEvent event = new UpdateTagListEvent(tags);
callEvent(UpdateTagListEvent.class,event);
getPlayerConnection().sendPacket(tags);
// Some client update
playerConnection.sendPacket(getPropertiesPacket()); // Send default properties
refreshHealth(); // Heal and send health packet

View File

@ -0,0 +1,17 @@
package net.minestom.server.event.player;
import net.minestom.server.event.Event;
import net.minestom.server.network.packet.server.play.TagsPacket;
public class UpdateTagListEvent extends Event {
private TagsPacket packet;
public UpdateTagListEvent(TagsPacket packet) {
this.packet = packet;
}
public TagsPacket getTags() {
return packet;
}
}

View File

@ -6,6 +6,7 @@ import net.minestom.server.gamedata.loottables.LootTableEntryType;
import net.minestom.server.gamedata.loottables.LootTableFunction;
import net.minestom.server.gamedata.loottables.LootTableManager;
import net.minestom.server.item.Material;
import net.minestom.server.registry.Registries;
import net.minestom.server.utils.NamespaceID;
import java.util.List;
@ -17,7 +18,6 @@ public class ItemType implements LootTableEntryType {
@Override
public LootTable.Entry create(LootTableManager lootTableManager, String name, List<Condition> conditions, List<LootTable.Entry> children, boolean expand, List<LootTableFunction> functions, int weight, int quality) {
NamespaceID itemID = NamespaceID.from(name);
// TODO: handle non-vanilla IDs ?
return new ItemEntry(this, Material.valueOf(itemID.getPath().toUpperCase()), weight, quality, functions, conditions);
return new ItemEntry(this, Registries.getMaterial(itemID), weight, quality, functions, conditions);
}
}

View File

@ -0,0 +1,21 @@
package net.minestom.server.gamedata.tags;
import net.minestom.server.utils.NamespaceID;
public class RequiredTag {
private final Tag.BasicTypes type;
private final NamespaceID name;
public RequiredTag(Tag.BasicTypes type, NamespaceID name) {
this.type = type;
this.name = name;
}
public NamespaceID getName() {
return name;
}
public Tag.BasicTypes getType() {
return type;
}
}

View File

@ -13,14 +13,16 @@ import java.util.Set;
*/
public class Tag {
public static final Tag EMPTY = new Tag();
public static final Tag EMPTY = new Tag(NamespaceID.from("minestom:empty"));
private final NamespaceID name;
private Set<NamespaceID> values;
/**
* Creates a new empty tag
*/
public Tag() {
public Tag(NamespaceID name) {
this.name = name;
values = new HashSet<>();
lockValues();
}
@ -32,7 +34,8 @@ public class Tag {
* appends the contents of that pack to the one being constructed
* @param container
*/
public Tag(TagManager manager, String type, Tag lowerPriority, TagContainer container) throws FileNotFoundException {
public Tag(TagManager manager, NamespaceID name, String type, Tag lowerPriority, TagContainer container) throws FileNotFoundException {
this.name = name;
values = new HashSet<>();
if(!container.replace) {
values.addAll(lowerPriority.values);
@ -70,4 +73,19 @@ public class Tag {
public Set<NamespaceID> getValues() {
return values;
}
/**
* Returns the name of this tag
* @return
*/
public NamespaceID getName() {
return name;
}
public enum BasicTypes {
BLOCKS,
ITEMS,
FLUIDS,
ENTITY_TYPES
}
}

View File

@ -2,13 +2,17 @@ package net.minestom.server.gamedata.tags;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minestom.server.network.packet.server.play.TagsPacket;
import net.minestom.server.registry.ResourceGatherer;
import net.minestom.server.utils.BlockPosition;
import net.minestom.server.utils.NamespaceID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
@ -19,10 +23,14 @@ public class TagManager {
private static final Logger LOGGER = LoggerFactory.getLogger(TagManager.class);
private final Gson gson;
private Map<NamespaceID, Tag> cache = new HashMap<>();
private List<RequiredTag> requiredTags = new LinkedList<>();
public TagManager() {
gson = new GsonBuilder()
.create();
addRequiredTag(Tag.BasicTypes.FLUIDS, NamespaceID.from("lava"));
addRequiredTag(Tag.BasicTypes.FLUIDS, NamespaceID.from("water"));
}
/**
@ -57,7 +65,7 @@ public class TagManager {
public Tag forceLoad(NamespaceID name, String tagType, ReaderSupplierWithFileNotFound readerSupplier) throws FileNotFoundException {
Tag prev = cache.getOrDefault(name, Tag.EMPTY);
FileNotFoundException[] ex = new FileNotFoundException[1]; // very ugly code but Java does not let its standard interfaces throw exceptions
Tag result = create(prev, tagType, readerSupplier);
Tag result = create(prev, name, tagType, readerSupplier);
cache.put(name, result);
return result;
}
@ -74,7 +82,7 @@ public class TagManager {
FileNotFoundException[] ex = new FileNotFoundException[1]; // very ugly code but Java does not let its standard interfaces throw exceptions
Tag result = cache.computeIfAbsent(name, _name -> {
try {
return create(prev, tagType, readerSupplier);
return create(prev, name, tagType, readerSupplier);
} catch (FileNotFoundException e) {
ex[0] = e;
return Tag.EMPTY;
@ -86,16 +94,61 @@ public class TagManager {
return result;
}
private Tag create(Tag prev, String tagType, ReaderSupplierWithFileNotFound reader) throws FileNotFoundException {
private Tag create(Tag prev, NamespaceID name, String tagType, ReaderSupplierWithFileNotFound reader) throws FileNotFoundException {
TagContainer container = gson.fromJson(reader.get(), TagContainer.class);
try {
return new Tag(this, tagType, prev, container);
return new Tag(this, name, tagType, prev, container);
} catch (FileNotFoundException e) {
LOGGER.error("Failed to load tag due to error", e);
return Tag.EMPTY;
}
}
/**
* Adds the required tags for the game to function correctly
* @param tags the packet to add the tags to
*/
public void addRequiredTagsToPacket(TagsPacket tags) {
for(RequiredTag requiredTag : requiredTags) {
Tag tag = silentLoad(requiredTag.getName(), requiredTag.getType().name().toLowerCase());
switch (requiredTag.getType()) {
case BLOCKS:
tags.blockTags.add(tag);
break;
case ITEMS:
tags.itemTags.add(tag);
break;
case FLUIDS:
tags.fluidTags.add(tag);
break;
case ENTITY_TYPES:
tags.entityTags.add(tag);
break;
}
}
}
/**
* Adds a required tag to send to players when they connect
* @param type type of tag to send. Required so the client knows its use
* @param name the name of the tag to load
*/
public void addRequiredTag(Tag.BasicTypes type, NamespaceID name) {
requiredTags.add(new RequiredTag(type, name));
}
private Tag silentLoad(NamespaceID name, String type) {
try {
return load(name, type);
} catch (FileNotFoundException e) {
e.printStackTrace();
return Tag.EMPTY;
}
}
public interface ReaderSupplierWithFileNotFound {
Reader get() throws FileNotFoundException;
}

View File

@ -0,0 +1,8 @@
package net.minestom.server.instance;
import java.util.function.Consumer;
public interface IChunkLoader {
boolean loadChunk(Instance instance, int chunkX, int chunkZ, Consumer<Chunk> callback);
void saveChunk(Chunk chunk, Runnable callback);
}

View File

@ -35,7 +35,6 @@ import java.util.function.Consumer;
public abstract class Instance implements BlockModifier, EventHandler, DataContainer {
protected static final ChunkLoader CHUNK_LOADER_IO = new ChunkLoader();
protected static final BlockManager BLOCK_MANAGER = MinecraftServer.getBlockManager();
private Dimension dimension;

View File

@ -54,6 +54,7 @@ public class InstanceContainer extends Instance {
private ReadWriteLock changingBlockLock = new ReentrantReadWriteLock();
private Map<BlockPosition, Block> currentlyChangingBlocks = new HashMap<>();
private IChunkLoader chunkLoader;
private boolean autoChunkLoad;
@ -61,9 +62,12 @@ public class InstanceContainer extends Instance {
super(uniqueId, dimension);
this.storageFolder = storageFolder;
chunkLoader = new MinestomBasicChunkLoader(storageFolder);
if (storageFolder == null)
if (storageFolder == null) {
return;
}
// Retrieve instance data
this.uniqueId = storageFolder.getOrDefault(UUID_KEY, UUID.class, uniqueId);
@ -358,7 +362,7 @@ public class InstanceContainer extends Instance {
@Override
public void saveChunkToStorageFolder(Chunk chunk, Runnable callback) {
Check.notNull(getStorageFolder(), "You cannot save the chunk if no StorageFolder has been defined");
CHUNK_LOADER_IO.saveChunk(chunk, getStorageFolder(), callback);
chunkLoader.saveChunk(chunk, callback);
}
@Override
@ -385,15 +389,14 @@ public class InstanceContainer extends Instance {
@Override
protected void retrieveChunk(int chunkX, int chunkZ, Consumer<Chunk> callback) {
if (storageFolder != null) {
// Load from file if possible
CHUNK_LOADER_IO.loadChunk(this, chunkX, chunkZ, getStorageFolder(), chunk -> {
cacheChunk(chunk);
if (callback != null)
callback.accept(chunk);
});
} else {
// Folder isn't defined, create new chunk
boolean loaded = chunkLoader.loadChunk(this, chunkX, chunkZ, chunk -> {
cacheChunk(chunk);
if (callback != null)
callback.accept(chunk);
});
if(!loaded) {
// Not found, create a new chunk
createChunk(chunkX, chunkZ, callback);
}
}
@ -520,6 +523,14 @@ public class InstanceContainer extends Instance {
this.storageFolder = storageFolder;
}
public IChunkLoader getChunkLoader() {
return chunkLoader;
}
public void setChunkLoader(IChunkLoader chunkLoader) {
this.chunkLoader = chunkLoader;
}
private void sendBlockChange(Chunk chunk, BlockPosition blockPosition, short blockId) {
BlockChangePacket blockChangePacket = new BlockChangePacket();
blockChangePacket.blockPosition = blockPosition;

View File

@ -2,17 +2,28 @@ package net.minestom.server.instance;
import net.minestom.server.reader.ChunkReader;
import net.minestom.server.storage.StorageFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.function.Consumer;
public class ChunkLoader {
public class MinestomBasicChunkLoader implements IChunkLoader {
private static String getChunkKey(int chunkX, int chunkZ) {
return chunkX + "." + chunkZ;
private final static Logger LOGGER = LoggerFactory.getLogger(MinestomBasicChunkLoader.class);
private StorageFolder storageFolder;
public MinestomBasicChunkLoader(StorageFolder storageFolder) {
this.storageFolder = storageFolder;
}
protected void saveChunk(Chunk chunk, StorageFolder storageFolder, Runnable callback) {
@Override
public void saveChunk(Chunk chunk, Runnable callback) {
if(storageFolder == null) {
callback.run();
LOGGER.warn("No folder to save chunk!");
return;
}
int chunkX = chunk.getChunkX();
int chunkZ = chunk.getChunkZ();
@ -27,17 +38,22 @@ public class ChunkLoader {
}
}
protected void loadChunk(Instance instance, int chunkX, int chunkZ, StorageFolder storageFolder, Consumer<Chunk> callback) {
byte[] bytes = storageFolder.get(getChunkKey(chunkX, chunkZ));
@Override
public boolean loadChunk(Instance instance, int chunkX, int chunkZ, Consumer<Chunk> callback) {
byte[] bytes = storageFolder == null ? null : storageFolder.get(getChunkKey(chunkX, chunkZ));
if (bytes == null) {
// Not found, create a new chunk
instance.createChunk(chunkX, chunkZ, callback);
return false;
} else {
// Found, load from result bytes
ChunkReader.readChunk(bytes, instance, chunkX, chunkZ, callback);
return true;
}
}
private static String getChunkKey(int chunkX, int chunkZ) {
return chunkX + "." + chunkZ;
}
}

View File

@ -0,0 +1,50 @@
package net.minestom.server.network.packet.server.play;
import net.minestom.server.gamedata.tags.Tag;
import net.minestom.server.network.packet.PacketWriter;
import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.registry.Registries;
import net.minestom.server.utils.NamespaceID;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
public class TagsPacket implements ServerPacket {
public List<Tag> blockTags = new LinkedList<>();
public List<Tag> itemTags = new LinkedList<>();
public List<Tag> fluidTags = new LinkedList<>();
public List<Tag> entityTags = new LinkedList<>();
@Override
public void write(PacketWriter writer) {
writeTags(writer, blockTags, name -> Registries.getBlock(name).ordinal());
writeTags(writer, itemTags, name -> Registries.getMaterial(name).ordinal());
writeTags(writer, fluidTags, name -> Registries.getFluid(name).ordinal());
writeTags(writer, entityTags, name -> Registries.getEntityType(name).ordinal());
}
private void writeTags(PacketWriter writer, List<Tag> tags, Function<NamespaceID, Integer> idSupplier) {
writer.writeVarInt(tags.size());
for (Tag tag : tags) {
// name
writer.writeSizedString(tag.getName().toString());
Set<NamespaceID> values = tag.getValues();
// count
writer.writeVarInt(values.size());
// entries
for (NamespaceID name : values) {
writer.writeVarInt(idSupplier.apply(name));
}
}
}
@Override
public int getId() {
return ServerPacketIdentifier.TAGS;
}
}

View File

@ -11,6 +11,7 @@ import net.minestom.server.item.attribute.AttributeSlot;
import net.minestom.server.item.attribute.ItemAttribute;
import net.minestom.server.network.packet.PacketReader;
import net.minestom.server.potion.PotionType;
import net.minestom.server.registry.Registries;
import java.util.ArrayList;
import java.util.UUID;
@ -81,8 +82,7 @@ public class NbtReaderUtils {
if (stringName.equals("Potion")) {
String potionId = reader.readShortSizedString();
potionId = potionId.replace("minecraft:", "").toUpperCase();
PotionType potionType = PotionType.valueOf(potionId);
PotionType potionType = Registries.getPotionType(potionId);
item.addPotionType(potionType);
@ -109,8 +109,7 @@ public class NbtReaderUtils {
String id = reader.readShortSizedString();
// Convert id
id = id.replace("minecraft:", "").toUpperCase();
Enchantment enchantment = Enchantment.valueOf(id);
Enchantment enchantment = Registries.getEnchantment(id);
if (isEnchantment) {
item.setEnchantment(enchantment, lvl);