Reduce duplicate code (#18)

* Reduce duplicate code

* Fix gradle task name

* Revert name changes

* Revert action name

* Cleanup

* Revert to java 17

* Fix generation

* Cleanup

* Simplify code of DGU

* Remove unnecessary annotations

* Remove unused var

* Halt with error on error

* Remove unused mixins

* Update fabric loader

* Ignore success result

* Update gradle and use merged jar

* Implement new client and server merged environment for running fabric

* Set server run dir as asset dir

* More cleanup

* More cleanup 2

* More improvements

* Remove more duplicate code

* Use newer java methods

* More cleanup

* Remove SoundAccessors

* More cleanup

* Use java 21 for build

* Initial work on 1.20.5

* Cleanup a lot of stuff

* Do not generate mod jars to speed up builds

* Override merger on now open classes directly

* Use recommended approach

* Readd custom merger

* Working materials data generator

* Fix inconsistencies

* Fix collision order to be random

* Use LinkedHashMap for more reproducibility

* Fix imports
This commit is contained in:
Alex
2024-07-14 09:23:34 +02:00
committed by GitHub
parent 44f49b4ab5
commit 71070c32bc
459 changed files with 3421 additions and 9078 deletions
+30 -14
View File
@@ -1,15 +1,33 @@
import xyz.wagyourtail.unimined.api.minecraft.task.RemapJarTask
import xyz.wagyourtail.unimined.internal.minecraft.MinecraftProvider
plugins {
id 'fabric-loom'
id 'xyz.wagyourtail.unimined'
}
unimined.minecraft {
version "1.20"
mappings {
intermediary()
yarn(1)
devFallbackNamespace "intermediary"
}
runs.config("server") {
javaVersion = JavaVersion.VERSION_21
}
customPatcher(new CustomOfficialFabricMinecraftTransformer(project, delegate as MinecraftProvider)) {
it.loader libs.versions.fabric.loader.get()
}
defaultRemapJar = true
}
dependencies {
// To change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
// Fabric API. This is technically optional, but you probably want it anyway.
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
implementation project(":common")
}
processResources {
@@ -20,12 +38,10 @@ processResources {
}
}
tasks.withType(RemapJarTask).configureEach {
onlyIf { false}
}
tasks.withType(JavaCompile).configureEach {
it.options.encoding = "UTF-8"
}
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(17))
}
}
-8
View File
@@ -1,8 +0,0 @@
# Fabric Properties
# check these on https://modmuss50.me/fabric.html
minecraft_version=1.20.2
yarn_mappings=1.20.2+build.4
loader_version=0.14.24
# Dependencies
# check this on https://modmuss50.me/fabric.html
fabric_version=0.90.4+1.20.2
@@ -1,14 +0,0 @@
package dev.u9g.minecraftdatagenerator;
import net.fabricmc.api.ModInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main implements ModInitializer {
public static final Logger LOGGER = LoggerFactory.getLogger("mc-data-gen-serv");
@Override
public void onInitialize() {
}
}
@@ -2,36 +2,24 @@ package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import dev.u9g.minecraftdatagenerator.mixin.TheEndBiomeDataAccessor;
import dev.u9g.minecraftdatagenerator.util.DGU;
import net.fabricmc.fabric.api.biome.v1.NetherBiomes;
import net.minecraft.registry.DynamicRegistryManager;
import net.minecraft.registry.Registry;
import net.minecraft.registry.RegistryKey;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.registry.tag.BiomeTags;
import net.minecraft.util.Identifier;
import net.minecraft.world.biome.Biome;
import java.util.HashSet;
import java.util.Set;
public class BiomesDataGenerator implements IDataGenerator {
private static final Set<RegistryKey<Biome>> END_BIOMES = new HashSet<>();
static {
END_BIOMES.addAll(TheEndBiomeDataAccessor.END_BIOMES_MAP().keySet());
END_BIOMES.addAll(TheEndBiomeDataAccessor.END_BARRENS_MAP().keySet());
END_BIOMES.addAll(TheEndBiomeDataAccessor.END_MIDLANDS_MAP().keySet());
}
private static String guessBiomeDimensionFromCategory(Biome biome, String biomeName) {
var key = DGU.getWorld().getRegistryManager().get(RegistryKeys.BIOME).getKey(biome).orElseThrow();
if (NetherBiomes.canGenerateInNether(key)) {
private static String guessBiomeDimensionFromCategory(Biome biome) {
var biomeRegistry = DGU.getWorld().getRegistryManager().get(RegistryKeys.BIOME);
if (biomeRegistry.getEntry(biome).isIn(BiomeTags.IS_NETHER)) {
return "nether";
} else if (END_BIOMES.contains(key) || biomeName.startsWith("end_")) {
} else if (biomeRegistry.getEntry(biome).isIn(BiomeTags.IS_END)) {
return "end";
} else {
return "overworld";
}
return "overworld";
}
private static String guessCategoryBasedOnName(String name, String dimension) {
@@ -87,196 +75,6 @@ public class BiomesDataGenerator implements IDataGenerator {
}
}
private static int getBiomeColorFor(String biomeName) {
switch (biomeName) {
case "the_void" -> {
return 0;
}
case "plains" -> {
return 9286496;
}
case "sunflower_plains" -> {
return 11918216;
}
case "snowy_plains" -> {
return 16777215;
}
case "ice_spikes" -> {
return 11853020;
}
case "desert" -> {
return 16421912;
}
case "swamp" -> {
return 522674;
}
case "forest" -> {
return 353825;
}
case "flower_forest" -> {
return 2985545;
}
case "birch_forest" -> {
return 3175492;
}
case "dark_forest" -> {
return 4215066;
}
case "old_growth_birch_forest" -> {
return 5807212;
}
case "old_growth_pine_taiga" -> {
return 5858897;
}
case "old_growth_spruce_taiga" -> {
return 8490617;
}
case "taiga" -> {
return 747097;
}
case "snowy_taiga" -> {
return 3233098;
}
case "savanna" -> {
return 12431967;
}
case "savanna_plateau" -> {
return 10984804;
}
case "windswept_hills" -> {
return 6316128;
}
case "windswept_gravelly_hills" -> {
return 8947848;
}
case "windswept_forest" -> {
return 2250012;
}
case "windswept_savanna" -> {
return 15063687;
}
case "jungle" -> {
return 5470985;
}
case "sparse_jungle" -> {
return 6458135;
}
case "bamboo_jungle" -> {
return 7769620;
}
case "badlands" -> {
return 14238997;
}
case "eroded_badlands" -> {
return 16739645;
}
case "wooded_badlands" -> {
return 11573093;
}
case "meadow" -> {
return 9217136;
}
case "grove" -> {
return 14675173;
}
case "snowy_slopes" -> {
return 14348785;
}
case "frozen_peaks" -> {
return 15399931;
}
case "jagged_peaks" -> {
return 14937325;
}
case "stony_peaks" -> {
return 13750737;
}
case "river" -> {
return 255;
}
case "frozen_river" -> {
return 10526975;
}
case "beach" -> {
return 16440917;
}
case "snowy_beach" -> {
return 16445632;
}
case "stony_shore" -> {
return 10658436;
}
case "warm_ocean" -> {
return 172;
}
case "lukewarm_ocean" -> {
return 144;
}
case "deep_lukewarm_ocean" -> {
return 64;
}
case "ocean" -> {
return 112;
}
case "deep_ocean" -> {
return 48;
}
case "cold_ocean" -> {
return 2105456;
}
case "deep_cold_ocean" -> {
return 2105400;
}
case "frozen_ocean" -> {
return 7368918;
}
case "deep_frozen_ocean" -> {
return 4210832;
}
case "mushroom_fields" -> {
return 16711935;
}
case "dripstone_caves" -> {
return 12690831;
}
case "lush_caves" -> {
return 14652980;
}
case "nether_wastes" -> {
return 12532539;
}
case "warped_forest" -> {
return 4821115;
}
case "crimson_forest" -> {
return 14485512;
}
case "soul_sand_valley" -> {
return 6174768;
}
case "basalt_deltas" -> {
return 4208182;
}
case "the_end" -> {
return 8421631;
}
case "end_highlands" -> {
return 12828041;
}
case "end_midlands" -> {
return 15464630;
}
case "small_end_islands" -> {
return 42;
}
case "end_barrens" -> {
return 9474162;
}
}
System.out.println("Don't know the color of biome: '" + biomeName + "'");
return 0;
}
public static JsonObject generateBiomeInfo(Registry<Biome> registry, Biome biome) {
JsonObject biomeDesc = new JsonObject();
Identifier registryKey = registry.getKey(biome).orElseThrow().getValue();
@@ -284,7 +82,7 @@ public class BiomesDataGenerator implements IDataGenerator {
String name = registryKey.getPath();
biomeDesc.addProperty("id", registry.getRawId(biome));
biomeDesc.addProperty("name", name);
String dimension = guessBiomeDimensionFromCategory(biome, name);
String dimension = guessBiomeDimensionFromCategory(biome);
biomeDesc.addProperty("category", guessCategoryBasedOnName(name, dimension));
biomeDesc.addProperty("temperature", biome.getTemperature());
//biomeDesc.addProperty("precipitation", biome.getPrecipitation().getName());// - removed in 1.19.4
@@ -292,7 +90,7 @@ public class BiomesDataGenerator implements IDataGenerator {
//biomeDesc.addProperty("depth", biome.getDepth()); - Doesn't exist anymore in minecraft source
biomeDesc.addProperty("dimension", dimension);
biomeDesc.addProperty("displayName", DGU.translateText(localizationKey));
biomeDesc.addProperty("color", getBiomeColorFor(registryKey.getPath()));
biomeDesc.addProperty("color", biome.getSkyColor());
//biomeDesc.addProperty("rainfall", biome.getDownfall());// - removed in 1.19.4
return biomeDesc;
@@ -14,10 +14,7 @@ import net.minecraft.util.math.BlockPos;
import net.minecraft.util.shape.VoxelShape;
import net.minecraft.world.EmptyBlockView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
public class BlockCollisionShapesDataGenerator implements IDataGenerator {
@@ -42,8 +39,8 @@ public class BlockCollisionShapesDataGenerator implements IDataGenerator {
}
private static class BlockShapesCache {
public final Map<VoxelShape, Integer> uniqueBlockShapes = new HashMap<>();
public final Map<Block, List<Integer>> blockCollisionShapes = new HashMap<>();
public final Map<VoxelShape, Integer> uniqueBlockShapes = new LinkedHashMap<>();
public final Map<Block, List<Integer>> blockCollisionShapes = new LinkedHashMap<>();
private int lastCollisionShapeId = 0;
public void processBlock(Block block) {
@@ -72,7 +69,7 @@ public class BlockCollisionShapesDataGenerator implements IDataGenerator {
long distinctShapesCount = blockCollisions.stream().distinct().count();
JsonElement blockCollision;
if (distinctShapesCount == 1L) {
blockCollision = new JsonPrimitive(blockCollisions.get(0));
blockCollision = new JsonPrimitive(blockCollisions.getFirst());
} else {
blockCollision = new JsonArray();
for (int collisionId : blockCollisions) {
@@ -12,7 +12,7 @@ import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.loot.context.LootContextParameterSet;
import net.minecraft.loot.context.LootContextParameters;
import net.minecraft.registry.Registry;
import net.minecraft.registry.Registries;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.world.ServerWorld;
@@ -105,7 +105,7 @@ public class BlocksDataGenerator implements IDataGenerator {
.collect(Collectors.toList());
if (matchingMaterials.size() > 1) {
var firstMaterial = matchingMaterials.get(0);
var firstMaterial = matchingMaterials.getFirst();
var otherMaterials = matchingMaterials.subList(1, matchingMaterials.size());
if (!otherMaterials.stream().allMatch(firstMaterial::includesMaterial)) {
@@ -115,19 +115,19 @@ public class BlocksDataGenerator implements IDataGenerator {
if (matchingMaterials.isEmpty()) {
return "default";
}
return matchingMaterials.get(0).getMaterialName();
return matchingMaterials.getFirst().getMaterialName();
}
public static JsonObject generateBlock(Registry<Block> blockRegistry, List<MaterialsDataGenerator.MaterialInfo> materials, Block block) {
public static JsonObject generateBlock(List<MaterialsDataGenerator.MaterialInfo> materials, Block block) {
JsonObject blockDesc = new JsonObject();
List<BlockState> blockStates = block.getStateManager().getStates();
BlockState defaultState = block.getDefaultState();
Identifier registryKey = blockRegistry.getKey(block).orElseThrow().getValue();
Identifier registryKey = Registries.BLOCK.getKey(block).orElseThrow().getValue();
String localizationKey = block.getTranslationKey();
List<Item> effectiveTools = getItemsEffectiveForBlock(defaultState);
blockDesc.addProperty("id", blockRegistry.getRawId(block));
blockDesc.addProperty("id", Registries.BLOCK.getRawId(block));
blockDesc.addProperty("name", registryKey.getPath());
blockDesc.addProperty("displayName", DGU.translateText(localizationKey));
@@ -148,8 +148,8 @@ public class BlocksDataGenerator implements IDataGenerator {
blockDesc.addProperty("filterLight", defaultState.getOpacity(EmptyBlockView.INSTANCE, BlockPos.ORIGIN));
blockDesc.addProperty("defaultState", Block.getRawIdFromState(defaultState));
blockDesc.addProperty("minStateId", Block.getRawIdFromState(blockStates.get(0)));
blockDesc.addProperty("maxStateId", Block.getRawIdFromState(blockStates.get(blockStates.size() - 1)));
blockDesc.addProperty("minStateId", Block.getRawIdFromState(blockStates.getFirst()));
blockDesc.addProperty("maxStateId", Block.getRawIdFromState(blockStates.getLast()));
JsonArray stateProperties = new JsonArray();
for (Property<?> property : block.getStateManager().getProperties()) {
@@ -167,7 +167,7 @@ public class BlocksDataGenerator implements IDataGenerator {
}
List<ItemStack> actualBlockDrops = new ArrayList<>();
populateDropsIfPossible(defaultState, effectiveTools.isEmpty() ? Items.AIR : effectiveTools.get(0), actualBlockDrops);
populateDropsIfPossible(defaultState, effectiveTools.isEmpty() ? Items.AIR : effectiveTools.getFirst(), actualBlockDrops);
JsonArray dropsArray = new JsonArray();
for (ItemStack dropStack : actualBlockDrops) {
@@ -189,10 +189,9 @@ public class BlocksDataGenerator implements IDataGenerator {
@Override
public JsonArray generateDataJson() {
JsonArray resultBlocksArray = new JsonArray();
Registry<Block> blockRegistry = DGU.getWorld().getRegistryManager().get(RegistryKeys.BLOCK);
List<MaterialsDataGenerator.MaterialInfo> availableMaterials = MaterialsDataGenerator.getGlobalMaterialInfo();
blockRegistry.forEach(block -> resultBlocksArray.add(generateBlock(blockRegistry, availableMaterials, block)));
Registries.BLOCK.forEach(block -> resultBlocksArray.add(generateBlock(availableMaterials, block)));
return resultBlocksArray;
}
}
@@ -1,78 +0,0 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonElement;
import com.google.gson.internal.Streams;
import com.google.gson.stream.JsonWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
public class DataGenerators {
private static final Logger logger = LoggerFactory.getLogger(DataGenerators.class);
private static final List<IDataGenerator> GENERATORS = new ArrayList<>();
static {
register(new BiomesDataGenerator());
register(new BlockCollisionShapesDataGenerator());
register(new BlocksDataGenerator());
register(new EffectsDataGenerator());
register(new EnchantmentsDataGenerator());
register(new EntitiesDataGenerator());
register(new FoodsDataGenerator());
register(new ItemsDataGenerator());
register(new ParticlesDataGenerator());
register(new TintsDataGenerator());
register(new MaterialsDataGenerator());
// register(new RecipeDataGenerator()); - On hold until mcdata supports multiple materials for a recipe
register(new LanguageDataGenerator());
register(new InstrumentsDataGenerator());
register(new SoundsDataGenerator());
}
public static void register(IDataGenerator generator) {
GENERATORS.add(generator);
}
public static boolean runDataGenerators(Path outputDirectory) {
try {
Files.createDirectories(outputDirectory);
} catch (IOException exception) {
logger.error("Failed to create data generator output directory at {}", outputDirectory, exception);
return false;
}
int generatorsFailed = 0;
logger.info("Running minecraft data generators, output at {}", outputDirectory);
for (IDataGenerator dataGenerator : GENERATORS) {
logger.info("Running generator {}", dataGenerator.getDataName());
try {
String outputFileName = String.format("%s.json", dataGenerator.getDataName());
JsonElement outputElement = dataGenerator.generateDataJson();
Path outputFilePath = outputDirectory.resolve(outputFileName);
try (Writer writer = Files.newBufferedWriter(outputFilePath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
JsonWriter jsonWriter = new JsonWriter(writer);
jsonWriter.setIndent(" ");
Streams.write(outputElement, jsonWriter);
}
logger.info("Generator: {} -> {}", dataGenerator.getDataName(), outputFileName);
} catch (Throwable exception) {
logger.error("Failed to run data generator {}", dataGenerator.getDataName(), exception);
generatorsFailed++;
}
}
logger.info("Finishing running data generators");
return generatorsFailed == 0;
}
}
@@ -14,7 +14,6 @@ import java.util.Arrays;
import java.util.stream.Collectors;
public class EffectsDataGenerator implements IDataGenerator {
public static JsonObject generateEffect(Registry<StatusEffect> registry, StatusEffect statusEffect) {
JsonObject effectDesc = new JsonObject();
Identifier registryKey = registry.getKey(statusEffect).orElseThrow().getValue();
@@ -1,6 +1,5 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import dev.u9g.minecraftdatagenerator.util.DGU;
@@ -12,29 +11,10 @@ import net.minecraft.util.Identifier;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
public class EnchantmentsDataGenerator implements IDataGenerator {
private static final ImmutableMap<EnchantmentTarget, String> ENCHANTMENT_TARGET_NAMES = ImmutableMap.<EnchantmentTarget, String>builder()
.put(EnchantmentTarget.ARMOR, "armor")
.put(EnchantmentTarget.ARMOR_FEET, "armor_feet")
.put(EnchantmentTarget.ARMOR_LEGS, "armor_legs")
.put(EnchantmentTarget.ARMOR_CHEST, "armor_chest")
.put(EnchantmentTarget.ARMOR_HEAD, "armor_head")
.put(EnchantmentTarget.WEAPON, "weapon")
.put(EnchantmentTarget.DIGGER, "digger")
.put(EnchantmentTarget.FISHING_ROD, "fishing_rod")
.put(EnchantmentTarget.TRIDENT, "trident")
.put(EnchantmentTarget.BREAKABLE, "breakable")
.put(EnchantmentTarget.BOW, "bow")
.put(EnchantmentTarget.WEARABLE, "wearable")
.put(EnchantmentTarget.CROSSBOW, "crossbow")
.put(EnchantmentTarget.VANISHABLE, "vanishable")
.build();
public static String getEnchantmentTargetName(EnchantmentTarget target) {
return ENCHANTMENT_TARGET_NAMES.getOrDefault(target, target.name().toLowerCase(Locale.ROOT));
return target.name().toLowerCase(Locale.ROOT);
}
//Equation enchantment costs follow is a * level + b, so we can easily retrieve a and b by passing zero level
@@ -2,7 +2,6 @@ package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import dev.u9g.minecraftdatagenerator.mixin.EntityTypeAccessor;
import dev.u9g.minecraftdatagenerator.util.DGU;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
@@ -20,7 +19,6 @@ import net.minecraft.server.MinecraftServer;
import net.minecraft.util.Identifier;
public class EntitiesDataGenerator implements IDataGenerator {
public static JsonObject generateEntity(Registry<EntityType<?>> entityRegistry, EntityType<?> entityType) {
JsonObject entityDesc = new JsonObject();
Identifier registryKey = entityRegistry.getKey(entityType).orElseThrow().getValue();
@@ -48,11 +46,8 @@ public class EntitiesDataGenerator implements IDataGenerator {
}
private static String getCategoryFrom(EntityType<?> entityType) {
if (entityType == EntityType.PLAYER) return "UNKNOWN"; // fail early for player entities
/*public T create(World world) {
return this.factory.create(this, world);
}*/
Entity entity = ((EntityTypeAccessor) entityType).factory().create(entityType, DGU.getWorld());
if (entityType == EntityType.PLAYER) return "UNKNOWN";
Entity entity = entityType.create(DGU.getWorld());
if (entity == null)
throw new Error("Entity was null after trying to create a: " + DGU.translateText(entityType.getTranslationKey()));
entity.discard();
@@ -12,7 +12,6 @@ import net.minecraft.util.Identifier;
import java.util.Objects;
public class FoodsDataGenerator implements IDataGenerator {
public static JsonObject generateFoodDescriptor(Registry<Item> registry, Item foodItem) {
JsonObject foodDesc = new JsonObject();
Identifier registryKey = registry.getKey(foodItem).orElseThrow().getValue();
@@ -1,10 +0,0 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonElement;
public interface IDataGenerator {
String getDataName();
JsonElement generateDataJson();
}
@@ -1,6 +1,5 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonElement;
@@ -41,7 +40,7 @@ public class MaterialsDataGenerator implements IDataGenerator {
}
private static void createCompositeMaterialInfo(List<MaterialInfo> allMaterials, List<String> combinedMaterials) {
String compositeMaterialName = Joiner.on(';').join(combinedMaterials);
String compositeMaterialName = String.join(";", combinedMaterials);
List<MaterialInfo> mappedMaterials = combinedMaterials.stream()
.map(otherName -> allMaterials.stream()
@@ -53,13 +52,13 @@ public class MaterialsDataGenerator implements IDataGenerator {
mappedMaterials.stream().allMatch(it -> it.getPredicate().test(blockState));
MaterialInfo materialInfo = new MaterialInfo(compositeMaterialName, compositePredicate).includes(mappedMaterials);
allMaterials.add(0, materialInfo);
allMaterials.addFirst(materialInfo);
}
private static void createCompositeMaterial(Map<String, Map<Item, Float>> allMaterials, List<String> combinedMaterials) {
String compositeMaterialName = Joiner.on(';').join(combinedMaterials);
String compositeMaterialName = String.join(";", combinedMaterials);
Map<Item, Float> resultingToolSpeeds = new HashMap<>();
Map<Item, Float> resultingToolSpeeds = new LinkedHashMap<>();
combinedMaterials.stream()
.map(allMaterials::get)
.forEach(resultingToolSpeeds::putAll);
@@ -108,14 +107,14 @@ public class MaterialsDataGenerator implements IDataGenerator {
public JsonElement generateDataJson() {
Registry<Item> itemRegistry = DGU.getWorld().getRegistryManager().get(RegistryKeys.ITEM);
Map<String, Map<Item, Float>> materialMiningSpeeds = new HashMap<>();
Map<String, Map<Item, Float>> materialMiningSpeeds = new LinkedHashMap<>();
materialMiningSpeeds.put("default", ImmutableMap.of());
//Special materials used for shears and swords special mining speed logic
Map<Item, Float> leavesMaterialSpeeds = new HashMap<>();
Map<Item, Float> cowebMaterialSpeeds = new HashMap<>();
Map<Item, Float> plantMaterialSpeeds = new HashMap<>();
Map<Item, Float> gourdMaterialSpeeds = new HashMap<>();
Map<Item, Float> leavesMaterialSpeeds = new LinkedHashMap<>();
Map<Item, Float> cowebMaterialSpeeds = new LinkedHashMap<>();
Map<Item, Float> plantMaterialSpeeds = new LinkedHashMap<>();
Map<Item, Float> gourdMaterialSpeeds = new LinkedHashMap<>();
materialMiningSpeeds.put(makeMaterialNameForTag(BlockTags.LEAVES), leavesMaterialSpeeds);
materialMiningSpeeds.put("coweb", cowebMaterialSpeeds);
@@ -134,7 +133,7 @@ public class MaterialsDataGenerator implements IDataGenerator {
TagKey<Block> effectiveBlocks = ((MiningToolItemAccessor) toolItem).getEffectiveBlocks();
String materialName = makeMaterialNameForTag(effectiveBlocks);
Map<Item, Float> materialSpeeds = materialMiningSpeeds.computeIfAbsent(materialName, k -> new HashMap<>());
Map<Item, Float> materialSpeeds = materialMiningSpeeds.computeIfAbsent(materialName, k -> new LinkedHashMap<>());
float miningSpeed = ((MiningToolItemAccessor) toolItem).getMiningSpeed();
materialSpeeds.put(item, miningSpeed);
}
@@ -9,7 +9,6 @@ import net.minecraft.registry.RegistryKeys;
import net.minecraft.util.Identifier;
public class ParticlesDataGenerator implements IDataGenerator {
public static JsonObject generateParticleType(Registry<ParticleType<?>> registry, ParticleType<?> particleType) {
JsonObject effectDesc = new JsonObject();
Identifier registryKey = registry.getKey(particleType).orElseThrow().getValue();
@@ -7,7 +7,10 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import dev.u9g.minecraftdatagenerator.util.DGU;
import net.minecraft.item.Item;
import net.minecraft.recipe.*;
import net.minecraft.recipe.Ingredient;
import net.minecraft.recipe.Recipe;
import net.minecraft.recipe.ShapedRecipe;
import net.minecraft.recipe.ShapelessRecipe;
import net.minecraft.registry.DynamicRegistryManager;
import net.minecraft.registry.RegistryKeys;
@@ -31,8 +34,7 @@ public class RecipeDataGenerator implements IDataGenerator {
DynamicRegistryManager registryManager = DGU.getWorld().getRegistryManager();
JsonObject finalObj = new JsonObject();
Multimap<Integer, JsonObject> recipes = ArrayListMultimap.create();
for (RecipeEntry<?> recipeE : Objects.requireNonNull(DGU.getWorld()).getRecipeManager().values()) {
Recipe<?> recipe = recipeE.value();
for (Recipe<?> recipe : Objects.requireNonNull(DGU.getWorld()).getRecipeManager().values()) {
if (recipe instanceof ShapedRecipe sr) {
var ingredients = sr.getIngredients();
List<Integer> ingr = new ArrayList<>();
@@ -67,11 +69,11 @@ public class RecipeDataGenerator implements IDataGenerator {
finalRecipe.add("inShape", inShape);
var resultObject = new JsonObject();
resultObject.addProperty("id", getRawIdFor(sr.getResult(registryManager).getItem()));
resultObject.addProperty("count", sr.getResult(registryManager).getCount());
resultObject.addProperty("id", getRawIdFor(sr.getOutput(registryManager).getItem()));
resultObject.addProperty("count", sr.getOutput(registryManager).getCount());
finalRecipe.add("result", resultObject);
String id = ((Integer) getRawIdFor(sr.getResult(registryManager).getItem())).toString();
String id = ((Integer) getRawIdFor(sr.getOutput(registryManager).getItem())).toString();
if (!finalObj.has(id)) {
finalObj.add(id, new JsonArray());
@@ -111,10 +113,10 @@ public class RecipeDataGenerator implements IDataGenerator {
var rootRecipeObject = new JsonObject();
rootRecipeObject.add("ingredients", ingredients);
var resultObject = new JsonObject();
resultObject.addProperty("id", getRawIdFor(sl.getResult(registryManager).getItem()));
resultObject.addProperty("count", sl.getResult(registryManager).getCount());
resultObject.addProperty("id", getRawIdFor(sl.getOutput(registryManager).getItem()));
resultObject.addProperty("count", sl.getOutput(registryManager).getCount());
rootRecipeObject.add("result", resultObject);
recipes.put(getRawIdFor(sl.getResult(registryManager).getItem()), rootRecipeObject);
recipes.put(getRawIdFor(sl.getOutput(registryManager).getItem()), rootRecipeObject);
}
}
recipes.forEach((a, b) -> {
@@ -2,17 +2,14 @@ package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import dev.u9g.minecraftdatagenerator.util.DGU;
import net.minecraft.registry.Registry;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.registry.Registries;
import net.minecraft.sound.SoundEvent;
public class SoundsDataGenerator implements IDataGenerator {
public static JsonObject generateSound(Registry<SoundEvent> registry, SoundEvent soundEvent) {
public static JsonObject generateSound(SoundEvent soundEvent) {
JsonObject soundDesc = new JsonObject();
soundDesc.addProperty("id", registry.getRawId(soundEvent)+1); // the plus 1 is required for 1.19.2+ due to Mojang using 0 in the packet to say that you should read a string id instead.
soundDesc.addProperty("id", Registries.SOUND_EVENT.getRawId(soundEvent) + 1); // the plus 1 is required for 1.19.2+ due to Mojang using 0 in the packet to say that you should read a string id instead.
soundDesc.addProperty("name", soundEvent.getId().getPath());
return soundDesc;
@@ -26,8 +23,7 @@ public class SoundsDataGenerator implements IDataGenerator {
@Override
public JsonArray generateDataJson() {
JsonArray resultsArray = new JsonArray();
Registry<SoundEvent> soundEventRegistry = DGU.getWorld().getRegistryManager().get(RegistryKeys.SOUND_EVENT);
soundEventRegistry.forEach(sound -> resultsArray.add(generateSound(soundEventRegistry, sound)));
Registries.SOUND_EVENT.forEach(sound -> resultsArray.add(generateSound(sound)));
return resultsArray;
}
}
@@ -2,12 +2,12 @@ package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import dev.u9g.minecraftdatagenerator.mojangannoyances.BlockColors;
import dev.u9g.minecraftdatagenerator.util.DGU;
import dev.u9g.minecraftdatagenerator.util.EmptyRenderBlockView;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.block.RedstoneWireBlock;
import net.minecraft.client.color.block.BlockColors;
import net.minecraft.client.color.world.FoliageColors;
import net.minecraft.registry.DynamicRegistryManager;
import net.minecraft.registry.Registry;
@@ -16,13 +16,9 @@ import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.biome.Biome;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
public class TintsDataGenerator implements IDataGenerator {
public static BiomeTintColors generateBiomeTintColors(Registry<Biome> biomeRegistry) {
BiomeTintColors colors = new BiomeTintColors();
@@ -39,7 +35,7 @@ public class TintsDataGenerator implements IDataGenerator {
}
public static Map<Integer, Integer> generateRedstoneTintColors() {
Map<Integer, Integer> resultColors = new HashMap<>();
Map<Integer, Integer> resultColors = new LinkedHashMap<>();
for (int redstoneLevel : RedstoneWireBlock.POWER.getValues()) {
int color = RedstoneWireBlock.getWireColor(redstoneLevel);
@@ -48,24 +44,23 @@ public class TintsDataGenerator implements IDataGenerator {
return resultColors;
}
private static int getBlockColor(Block block, BlockColors blockColors) {
return blockColors.getColor(block.getDefaultState(), EmptyRenderBlockView.INSTANCE, BlockPos.ORIGIN, 0xFFFFFF);
private static int getBlockColor(Block block) {
return BlockColors.create().getColor(block.getDefaultState(), EmptyRenderBlockView.INSTANCE, BlockPos.ORIGIN, 0xFFFFFF);
}
public static Map<Block, Integer> generateConstantTintColors() {
Map<Block, Integer> resultColors = new HashMap<>();
BlockColors blockColors = BlockColors.create();
Map<Block, Integer> resultColors = new LinkedHashMap<>();
resultColors.put(Blocks.BIRCH_LEAVES, FoliageColors.getBirchColor());
resultColors.put(Blocks.SPRUCE_LEAVES, FoliageColors.getSpruceColor());
resultColors.put(Blocks.LILY_PAD, getBlockColor(Blocks.LILY_PAD, blockColors));
resultColors.put(Blocks.ATTACHED_MELON_STEM, getBlockColor(Blocks.ATTACHED_MELON_STEM, blockColors));
resultColors.put(Blocks.ATTACHED_PUMPKIN_STEM, getBlockColor(Blocks.ATTACHED_PUMPKIN_STEM, blockColors));
resultColors.put(Blocks.LILY_PAD, getBlockColor(Blocks.LILY_PAD));
resultColors.put(Blocks.ATTACHED_MELON_STEM, getBlockColor(Blocks.ATTACHED_MELON_STEM));
resultColors.put(Blocks.ATTACHED_PUMPKIN_STEM, getBlockColor(Blocks.ATTACHED_PUMPKIN_STEM));
//not really constant, depend on the block age, but kinda have to be handled since textures are literally white without them
resultColors.put(Blocks.MELON_STEM, getBlockColor(Blocks.MELON_STEM, blockColors));
resultColors.put(Blocks.PUMPKIN_STEM, getBlockColor(Blocks.PUMPKIN_STEM, blockColors));
resultColors.put(Blocks.MELON_STEM, getBlockColor(Blocks.MELON_STEM));
resultColors.put(Blocks.PUMPKIN_STEM, getBlockColor(Blocks.PUMPKIN_STEM));
return resultColors;
}
@@ -156,8 +151,8 @@ public class TintsDataGenerator implements IDataGenerator {
}
public static class BiomeTintColors {
final Map<Integer, List<Biome>> grassColoursMap = new HashMap<>();
final Map<Integer, List<Biome>> foliageColoursMap = new HashMap<>();
final Map<Integer, List<Biome>> waterColourMap = new HashMap<>();
final Map<Integer, List<Biome>> grassColoursMap = new LinkedHashMap<>();
final Map<Integer, List<Biome>> foliageColoursMap = new LinkedHashMap<>();
final Map<Integer, List<Biome>> waterColourMap = new LinkedHashMap<>();
}
}
@@ -1,12 +0,0 @@
package dev.u9g.minecraftdatagenerator.mixin;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(EntityType.class)
public interface EntityTypeAccessor<T extends Entity> {
@Accessor("factory")
EntityType.EntityFactory<T> factory();
}
@@ -1,7 +1,6 @@
package dev.u9g.minecraftdatagenerator.mixin;
import dev.u9g.minecraftdatagenerator.Main;
import dev.u9g.minecraftdatagenerator.generators.DataGenerators;
import dev.u9g.minecraftdatagenerator.MinecraftDataGenerator;
import dev.u9g.minecraftdatagenerator.util.DGU;
import net.minecraft.MinecraftVersion;
import net.minecraft.server.dedicated.MinecraftDedicatedServer;
@@ -10,18 +9,13 @@ import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.nio.file.Path;
@Mixin(MinecraftDedicatedServer.class)
public class ReadyMixin {
@Inject(method = "setupServer()Z", at = @At("TAIL"))
private void init(CallbackInfoReturnable<Boolean> cir) {
Main.LOGGER.info("Starting data generation!");
String versionName = MinecraftVersion.CURRENT.getName();
Path serverRootDirectory = DGU.getCurrentlyRunningServer().getRunDirectory().toPath().toAbsolutePath();
Path dataDumpDirectory = serverRootDirectory.resolve("minecraft-data").resolve(versionName);
DataGenerators.runDataGenerators(dataDumpDirectory);
Main.LOGGER.info("Done data generation!");
Runtime.getRuntime().halt(0);
MinecraftDataGenerator.start(
MinecraftVersion.CURRENT.getName(),
DGU.getCurrentlyRunningServer().getRunDirectory().toPath()
);
}
}
@@ -1,29 +0,0 @@
package dev.u9g.minecraftdatagenerator.mixin;
import net.fabricmc.fabric.impl.biome.TheEndBiomeData;
import net.fabricmc.fabric.impl.biome.WeightedPicker;
import net.minecraft.registry.RegistryKey;
import net.minecraft.world.biome.Biome;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
import java.util.Map;
@Mixin(TheEndBiomeData.class)
public interface TheEndBiomeDataAccessor {
@Accessor(value = "END_BIOMES_MAP", remap = false)
static Map<RegistryKey<Biome>, WeightedPicker<RegistryKey<Biome>>> END_BIOMES_MAP() {
throw new IllegalStateException("Should never be called.");
}
@Accessor(value = "END_MIDLANDS_MAP", remap = false)
static Map<RegistryKey<Biome>, WeightedPicker<RegistryKey<Biome>>> END_MIDLANDS_MAP() {
throw new IllegalStateException("Should never be called.");
}
@Accessor(value = "END_BARRENS_MAP", remap = false)
static Map<RegistryKey<Biome>, WeightedPicker<RegistryKey<Biome>>> END_BARRENS_MAP() {
throw new IllegalStateException("Should never be called.");
}
}
@@ -1,35 +0,0 @@
package dev.u9g.minecraftdatagenerator.mojangannoyances;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.BlockRenderView;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.ColorResolver;
@Environment(EnvType.CLIENT)
public class BiomeColors {
public static final ColorResolver GRASS_COLOR = Biome::getGrassColorAt;
public static final ColorResolver FOLIAGE_COLOR = (biome, x, z) -> biome.getFoliageColor();
public static final ColorResolver WATER_COLOR = (biome, x, z) -> biome.getWaterColor();
public BiomeColors() {
}
private static int getColor(BlockRenderView world, BlockPos pos, ColorResolver resolver) {
return world.getColor(pos, resolver);
}
public static int getGrassColor(BlockRenderView world, BlockPos pos) {
return getColor(world, pos, GRASS_COLOR);
}
public static int getFoliageColor(BlockRenderView world, BlockPos pos) {
return getColor(world, pos, FOLIAGE_COLOR);
}
public static int getWaterColor(BlockRenderView world, BlockPos pos) {
return getColor(world, pos, WATER_COLOR);
}
}
@@ -1,11 +0,0 @@
package dev.u9g.minecraftdatagenerator.mojangannoyances;
import net.minecraft.block.BlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.BlockRenderView;
import org.jetbrains.annotations.Nullable;
public interface BlockColorProvider {
int getColor(BlockState state, @Nullable BlockRenderView world, @Nullable BlockPos pos, int tintIndex);
}
@@ -1,94 +0,0 @@
package dev.u9g.minecraftdatagenerator.mojangannoyances;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import dev.u9g.minecraftdatagenerator.util.DGU;
import net.minecraft.block.*;
import net.minecraft.block.enums.DoubleBlockHalf;
import net.minecraft.client.color.world.FoliageColors;
import net.minecraft.client.color.world.GrassColors;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.state.property.Property;
import net.minecraft.util.collection.IdList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.BlockRenderView;
import net.minecraft.world.World;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
import java.util.Set;
public class BlockColors {
private static final int NO_COLOR = -1;
private final IdList<BlockColorProvider> providers = new IdList<>(32);
private final Map<Block, Set<Property<?>>> properties = Maps.newHashMap();
public BlockColors() {
}
public static BlockColors create() {
BlockColors blockColors = new BlockColors();
blockColors.registerColorProvider((state, world, pos, tintIndex) -> world != null && pos != null ? BiomeColors.getGrassColor(world, state.get(TallPlantBlock.HALF) == DoubleBlockHalf.UPPER ? pos.down() : pos) : -1, Blocks.LARGE_FERN, Blocks.TALL_GRASS);
blockColors.registerColorProperty(TallPlantBlock.HALF, Blocks.LARGE_FERN, Blocks.TALL_GRASS);
blockColors.registerColorProvider((state, world, pos, tintIndex) -> world != null && pos != null ? BiomeColors.getGrassColor(world, pos) : GrassColors.getColor(0.5, 1.0), Blocks.GRASS_BLOCK, Blocks.FERN, Blocks.GRASS, Blocks.POTTED_FERN);
blockColors.registerColorProvider((state, world, pos, tintIndex) -> FoliageColors.getSpruceColor(), Blocks.SPRUCE_LEAVES);
blockColors.registerColorProvider((state, world, pos, tintIndex) -> FoliageColors.getBirchColor(), Blocks.BIRCH_LEAVES);
blockColors.registerColorProvider((state, world, pos, tintIndex) -> world != null && pos != null ? BiomeColors.getFoliageColor(world, pos) : FoliageColors.getDefaultColor(), Blocks.OAK_LEAVES, Blocks.JUNGLE_LEAVES, Blocks.ACACIA_LEAVES, Blocks.DARK_OAK_LEAVES, Blocks.VINE, Blocks.MANGROVE_LEAVES);
blockColors.registerColorProvider((state, world, pos, tintIndex) -> world != null && pos != null ? BiomeColors.getWaterColor(world, pos) : -1, Blocks.WATER, Blocks.BUBBLE_COLUMN, Blocks.WATER_CAULDRON);
blockColors.registerColorProvider((state, world, pos, tintIndex) -> RedstoneWireBlock.getWireColor(state.get(RedstoneWireBlock.POWER)), Blocks.REDSTONE_WIRE);
blockColors.registerColorProperty(RedstoneWireBlock.POWER, Blocks.REDSTONE_WIRE);
blockColors.registerColorProvider((state, world, pos, tintIndex) -> world != null && pos != null ? BiomeColors.getGrassColor(world, pos) : -1, Blocks.SUGAR_CANE);
blockColors.registerColorProvider((state, world, pos, tintIndex) -> 14731036, Blocks.ATTACHED_MELON_STEM, Blocks.ATTACHED_PUMPKIN_STEM);
blockColors.registerColorProvider((state, world, pos, tintIndex) -> {
int i = state.get(StemBlock.AGE);
int j = i * 32;
int k = 255 - i * 8;
int l = i * 4;
return j << 16 | k << 8 | l;
}, Blocks.MELON_STEM, Blocks.PUMPKIN_STEM);
blockColors.registerColorProperty(StemBlock.AGE, Blocks.MELON_STEM, Blocks.PUMPKIN_STEM);
blockColors.registerColorProvider((state, world, pos, tintIndex) -> world != null && pos != null ? 2129968 : 7455580, Blocks.LILY_PAD);
return blockColors;
}
public int getParticleColor(BlockState state, World world, BlockPos pos) {
BlockColorProvider blockColorProvider = this.providers.get(DGU.getWorld().getRegistryManager().get(RegistryKeys.BLOCK).getRawId(state.getBlock()));
if (blockColorProvider != null) {
return blockColorProvider.getColor(state, null, null, 0);
} else {
MapColor mapColor = state.getMapColor(world, pos);
return mapColor != null ? mapColor.color : -1;
}
}
public int getColor(BlockState state, @Nullable BlockRenderView world, @Nullable BlockPos pos, int tintIndex) {
BlockColorProvider blockColorProvider = this.providers.get(DGU.getWorld().getRegistryManager().get(RegistryKeys.BLOCK).getRawId(state.getBlock()));
return blockColorProvider == null ? -1 : blockColorProvider.getColor(state, world, pos, tintIndex);
}
public void registerColorProvider(BlockColorProvider provider, Block... blocks) {
int var4 = blocks.length;
for (Block block : blocks) {
this.providers.set(provider, DGU.getWorld().getRegistryManager().get(RegistryKeys.BLOCK).getRawId(block));
}
}
private void registerColorProperties(Set<Property<?>> properties, Block... blocks) {
int var4 = blocks.length;
for (Block block : blocks) {
this.properties.put(block, properties);
}
}
private void registerColorProperty(Property<?> property, Block... blocks) {
this.registerColorProperties(ImmutableSet.of(property), blocks);
}
public Set<Property<?>> getProperties(Block block) {
return this.properties.getOrDefault(block, ImmutableSet.of());
}
}
@@ -6,24 +6,13 @@ import net.minecraft.util.Language;
import net.minecraft.world.World;
public class DGU {
private static final Language language = Language.getInstance();
@SuppressWarnings("deprecation")
private static MinecraftServer getCurrentlyRunningServerDedicated() {
public static MinecraftServer getCurrentlyRunningServer() {
return (MinecraftServer) FabricLoader.getInstance().getGameInstance();
}
public static MinecraftServer getCurrentlyRunningServer() {
return getCurrentlyRunningServerDedicated();
}
private static String translateTextFallback(String translationKey) {
return language.get(translationKey);
}
public static String translateText(String translationKey) {
return translateTextFallback(translationKey);
return Language.getInstance().get(translationKey);
}
public static World getWorld() {
+1 -8
View File
@@ -10,18 +10,11 @@
],
"contact": {},
"license": "MIT",
"environment": "server",
"entrypoints": {
"main": [
"dev.u9g.minecraftdatagenerator.Main"
]
},
"mixins": [
"minecraft-data-generator.mixins.json"
],
"depends": {
"fabricloader": ">=0.14.4",
"fabric": "*",
"fabricloader": "*",
"minecraft": "*"
}
}
@@ -4,11 +4,9 @@
"package": "dev.u9g.minecraftdatagenerator.mixin",
"compatibilityLevel": "JAVA_17",
"mixins": [
"EntityTypeAccessor",
"EULAMixin",
"MiningToolItemAccessor",
"ReadyMixin",
"TheEndBiomeDataAccessor"
"ReadyMixin"
],
"client": [
],