mirror of
https://github.com/MinecraftForge/MinecraftForge.git
synced 2026-11-19 11:59:25 +00:00
1.20.3 Initial Update
https://forums.minecraftforge.net/topic/139822-forge-490-minecraft-1203/
This commit is contained in:
456 files changed
+2432
-2933
No files matched your search
@@ -18,7 +18,6 @@ import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.multiplayer.ClientPacketListener;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.CommandRuntimeException;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.commands.synchronization.SuggestionProviders;
|
||||
@@ -156,16 +155,11 @@ public class ClientCommandHandler
|
||||
|
||||
ClientCommandSourceStack source = getSource();
|
||||
|
||||
try
|
||||
{
|
||||
try {
|
||||
commands.execute(reader, source);
|
||||
}
|
||||
catch (CommandRuntimeException execution)// Probably thrown by the command
|
||||
{
|
||||
Minecraft.getInstance().player.sendSystemMessage(Component.literal("").append(execution.getComponent()).withStyle(ChatFormatting.RED));
|
||||
}
|
||||
catch (CommandSyntaxException syntax)// Usually thrown by the CommandDispatcher
|
||||
{
|
||||
//} catch (CommandRuntimeException execution) { // Probably thrown by the command
|
||||
// Minecraft.getInstance().player.sendSystemMessage(Component.literal("").append(execution.getComponent()).withStyle(ChatFormatting.RED));
|
||||
} catch (CommandSyntaxException syntax) {
|
||||
if (syntax.getType() == CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand() || syntax.getType() == CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument())
|
||||
{
|
||||
// in case of unknown command, let the server try and handle it
|
||||
|
||||
@@ -89,7 +89,7 @@ public class LoadingErrorScreen extends ErrorScreen {
|
||||
|
||||
public static class LoadingEntryList extends ObjectSelectionList<LoadingEntryList.LoadingMessageEntry> {
|
||||
LoadingEntryList(final LoadingErrorScreen parent, final List<ModLoadingException> errors, final List<ModLoadingWarning> warnings) {
|
||||
super(Objects.requireNonNull(parent.minecraft), parent.width, parent.height, 35, parent.height - 50,
|
||||
super(Objects.requireNonNull(parent.minecraft), parent.width, parent.height, 35,
|
||||
Math.max(
|
||||
errors.stream().mapToInt(error -> parent.font.split(Component.literal(error.getMessage() != null ? error.getMessage() : ""), parent.width - 20).size()).max().orElse(0),
|
||||
warnings.stream().mapToInt(warning -> parent.font.split(Component.literal(warning.formatToString() != null ? warning.formatToString() : ""), parent.width - 20).size()).max().orElse(0)
|
||||
|
||||
@@ -270,7 +270,7 @@ public class ModListScreen extends Screen
|
||||
search = new EditBox(getFontRenderer(), PADDING + 1, y, listWidth - 2, 14, Component.translatable("fml.menu.mods.search"));
|
||||
|
||||
this.modList = new ModListWidget(this, listWidth, fullButtonHeight, search.getY() - getFontRenderer().lineHeight - PADDING);
|
||||
this.modList.setLeftPos(6);
|
||||
this.modList.setX(6);
|
||||
this.modInfo = new InfoPanel(this.minecraft, modInfoWidth, this.height - PADDING - fullButtonHeight, PADDING);
|
||||
|
||||
this.addRenderableWidget(modList);
|
||||
@@ -365,7 +365,7 @@ public class ModListScreen extends Screen
|
||||
this.modInfo.render(guiGraphics, mouseX, mouseY, partialTick);
|
||||
|
||||
Component text = Component.translatable("fml.menu.mods.search");
|
||||
int x = modList.getLeft() + ((modList.getRight() - modList.getLeft()) / 2) - (getFontRenderer().width(text) / 2);
|
||||
int x = modList.getX() + (modList.getWidth() / 2) - (getFontRenderer().width(text) / 2);
|
||||
this.search.render(guiGraphics, mouseX , mouseY, partialTick);
|
||||
super.render(guiGraphics, mouseX, mouseY, partialTick);
|
||||
guiGraphics.drawString(getFontRenderer(), text.getVisualOrderText(), x, search.getY() - getFontRenderer().lineHeight, 0xFFFFFF, false);
|
||||
|
||||
@@ -16,6 +16,7 @@ import net.minecraft.client.multiplayer.ClientPacketListener;
|
||||
import net.minecraft.client.renderer.GameRenderer;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.resources.language.I18n;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.util.StringUtil;
|
||||
@@ -351,7 +352,7 @@ public class ForgeGui extends Gui {
|
||||
if (time >= 120500L)
|
||||
listR.add(I18n.get("demo.demoExpired"));
|
||||
else
|
||||
listR.add(I18n.get("demo.remainingTime", StringUtil.formatTickDuration((int) (120500L - time))));
|
||||
listR.add(I18n.get("demo.remainingTime", StringUtil.formatTickDuration((int)(120500L - this.minecraft.level.getGameTime()), this.minecraft.level.tickRateManager().tickrate())));
|
||||
}
|
||||
|
||||
var forgeOverlay = (OverlayAccess)debugOverlay;
|
||||
|
||||
@@ -30,7 +30,7 @@ public class ModListWidget extends ObjectSelectionList<ModListWidget.ModEntry>
|
||||
|
||||
public ModListWidget(ModListScreen parent, int listWidth, int top, int bottom)
|
||||
{
|
||||
super(parent.getMinecraftInstance(), listWidth, parent.height, top, bottom, parent.getFontRenderer().lineHeight * 2 + 8);
|
||||
super(parent.getMinecraftInstance(), listWidth, parent.height, top, parent.getFontRenderer().lineHeight * 2 + 8);
|
||||
this.parent = parent;
|
||||
this.listWidth = listWidth;
|
||||
this.refreshList();
|
||||
@@ -53,11 +53,13 @@ public class ModListWidget extends ObjectSelectionList<ModListWidget.ModEntry>
|
||||
parent.buildModList(this::addEntry, mod->new ModEntry(mod, this.parent));
|
||||
}
|
||||
|
||||
/*
|
||||
@Override
|
||||
public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) {
|
||||
this.parent.renderBackground(guiGraphics, mouseX, mouseY, partialTicks);
|
||||
super.render(guiGraphics, mouseX, mouseY, partialTicks);
|
||||
}
|
||||
*/
|
||||
|
||||
public class ModEntry extends ObjectSelectionList.Entry<ModEntry> {
|
||||
private final IModInfo modInfo;
|
||||
@@ -87,7 +89,7 @@ public class ModListWidget extends ObjectSelectionList<ModListWidget.ModEntry>
|
||||
//TODO: Consider adding more icons for visualization
|
||||
RenderSystem.setShaderColor(1, 1, 1, 1);
|
||||
guiGraphics.pose().pushPose();
|
||||
guiGraphics.blit(VERSION_CHECK_ICONS, getLeft() + width - 12, top + entryHeight / 4, vercheck.status().getSheetOffset() * 8, (vercheck.status().isAnimated() && ((System.currentTimeMillis() / 800 & 1)) == 1) ? 8 : 0, 8, 8, 64, 16);
|
||||
guiGraphics.blit(VERSION_CHECK_ICONS, getX() + width - 12, top + entryHeight / 4, vercheck.status().getSheetOffset() * 8, (vercheck.status().isAnimated() && ((System.currentTimeMillis() / 800 & 1)) == 1) ? 8 : 0, 8, 8, 64, 16);
|
||||
guiGraphics.pose().popPose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.client.gui.widget;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
/**
|
||||
* This class provides a button that shows a string glyph at the beginning. The glyph can be scaled using the glyphScale parameter.
|
||||
*
|
||||
* @author bspkrs
|
||||
*/
|
||||
public class UnicodeGlyphButton extends ExtendedButton
|
||||
{
|
||||
public String glyph;
|
||||
public float glyphScale;
|
||||
|
||||
public UnicodeGlyphButton(int xPos, int yPos, int width, int height, Component displayString, String glyph, float glyphScale, OnPress handler)
|
||||
{
|
||||
super(xPos, yPos, width, height, displayString, handler);
|
||||
this.glyph = glyph;
|
||||
this.glyphScale = glyphScale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick)
|
||||
{
|
||||
if (this.visible)
|
||||
{
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
this.isHovered = mouseX >= this.getX() && mouseY >= this.getY() && mouseX < this.getX() + this.width && mouseY < this.getY() + this.height;
|
||||
guiGraphics.blitSprite(SPRITES.get(this.active, this.isHoveredOrFocused()), this.getX(), this.getY(), this.getWidth(), this.getHeight());
|
||||
|
||||
Component buttonText = this.createNarrationMessage();
|
||||
int glyphWidth = (int) (mc.font.width(glyph) * glyphScale);
|
||||
int strWidth = mc.font.width(buttonText);
|
||||
int ellipsisWidth = mc.font.width("...");
|
||||
int totalWidth = strWidth + glyphWidth;
|
||||
|
||||
if (totalWidth > width - 6 && totalWidth > ellipsisWidth)
|
||||
buttonText = Component.literal(mc.font.substrByWidth(buttonText, width - 6 - ellipsisWidth).getString().trim() + "...") ;
|
||||
|
||||
strWidth = mc.font.width(buttonText);
|
||||
totalWidth = glyphWidth + strWidth;
|
||||
|
||||
guiGraphics.pose().pushPose();
|
||||
guiGraphics.pose().scale(glyphScale, glyphScale, 1.0F);
|
||||
guiGraphics.drawCenteredString(mc.font, Component.literal(glyph),
|
||||
(int) (((this.getX() + (this.width / 2) - (strWidth / 2)) / glyphScale) - (glyphWidth / (2 * glyphScale)) + 2),
|
||||
(int) (((this.getY() + ((this.height - 8) / glyphScale) / 2) - 1) / glyphScale), getFGColor());
|
||||
guiGraphics.pose().popPose();
|
||||
|
||||
guiGraphics.drawCenteredString(mc.font, buttonText, (int) (this.getX() + (this.width / 2) + (glyphWidth / glyphScale)),
|
||||
this.getY() + (this.height - 8) / 2, getFGColor());
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,7 @@ import net.minecraft.network.chat.ClickEvent;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.MutableComponent;
|
||||
import net.minecraft.network.chat.TextColor;
|
||||
import net.minecraft.network.chat.contents.LiteralContents;
|
||||
import net.minecraft.network.chat.contents.PlainTextContents.LiteralContents;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.tags.BlockTags;
|
||||
import net.minecraft.tags.TagKey;
|
||||
@@ -103,6 +103,7 @@ import net.minecraft.world.Container;
|
||||
import net.minecraft.world.item.context.UseOnContext;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
import net.minecraft.nbt.NbtOps;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.syncher.EntityDataSerializer;
|
||||
import net.minecraft.network.protocol.game.ClientGamePacketListener;
|
||||
@@ -122,6 +123,7 @@ import net.minecraft.world.level.biome.BiomeSpecialEffects;
|
||||
import net.minecraft.world.level.biome.BiomeGenerationSettings;
|
||||
import net.minecraft.world.level.biome.MobSpawnSettings;
|
||||
import net.minecraftforge.common.crafting.conditions.ICondition;
|
||||
import net.minecraftforge.common.crafting.conditions.ICondition.IContext;
|
||||
import net.minecraftforge.common.crafting.ingredients.IIngredientSerializer;
|
||||
import net.minecraftforge.common.util.BlockSnapshot;
|
||||
import net.minecraftforge.common.util.BrainBuilder;
|
||||
@@ -977,7 +979,8 @@ public class ForgeHooks {
|
||||
}
|
||||
|
||||
@ApiStatus.Internal
|
||||
public static void readAdditionalLevelSaveData(CompoundTag rootTag, LevelStorageSource.LevelDirectory levelDirectory) {
|
||||
public static void readAdditionalLevelSaveData(Dynamic<?> data, LevelStorageSource.LevelDirectory levelDirectory) {
|
||||
CompoundTag rootTag = (CompoundTag)data.convert(NbtOps.INSTANCE).getValue();
|
||||
CompoundTag tag = rootTag.getCompound("fml");
|
||||
if (tag.contains("LoadingModList")) {
|
||||
ListTag modList = tag.getList("LoadingModList", net.minecraft.nbt.Tag.TAG_COMPOUND);
|
||||
@@ -1276,7 +1279,10 @@ public class ForgeHooks {
|
||||
}
|
||||
|
||||
@ApiStatus.Internal
|
||||
public static boolean readAndTestCondition(ICondition.IContext context, JsonObject json) {
|
||||
public static boolean readAndTestCondition(@Nullable ICondition.IContext context, JsonObject json) {
|
||||
if (context == null)
|
||||
context = IContext.EMPTY;
|
||||
|
||||
if (!json.has(ICondition.DEFAULT_FIELD))
|
||||
return true;
|
||||
|
||||
@@ -1294,7 +1300,9 @@ public class ForgeHooks {
|
||||
|
||||
@Nullable
|
||||
@ApiStatus.Internal
|
||||
public static JsonObject readConditionalAdvancement(ICondition.IContext context, JsonObject json) {
|
||||
public static JsonObject readConditionalAdvancement(@Nullable ICondition.IContext context, JsonObject json) {
|
||||
if (context == null)
|
||||
context = IContext.EMPTY;
|
||||
var entries = GsonHelper.getAsJsonArray(json, "advancements", null);
|
||||
if (entries == null)
|
||||
return readAndTestCondition(context, json) ? json : null;
|
||||
@@ -1305,7 +1313,7 @@ public class ForgeHooks {
|
||||
throw new JsonSyntaxException("Invalid advancement entry at index " + idx + " Must be JsonObject");
|
||||
|
||||
if (readAndTestCondition(context, ele.getAsJsonObject()))
|
||||
return GsonHelper.getAsJsonObject(ele.getAsJsonObject(), "advancement");
|
||||
return ele.getAsJsonObject();
|
||||
|
||||
idx++;
|
||||
}
|
||||
|
||||
@@ -10,9 +10,11 @@ import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.advancements.Advancement;
|
||||
import net.minecraft.advancements.AdvancementHolder;
|
||||
import net.minecraft.data.recipes.FinishedRecipe;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraftforge.common.ForgeHooks;
|
||||
import net.minecraftforge.common.crafting.conditions.ICondition;
|
||||
@@ -52,10 +54,6 @@ public class ConditionalAdvancement {
|
||||
return advancement(builder.build(DOESNT_MATTER).value());
|
||||
}
|
||||
|
||||
public Builder advancement(FinishedRecipe fromRecipe) {
|
||||
return advancement(fromRecipe.advancement());
|
||||
}
|
||||
|
||||
public Builder advancement(AdvancementHolder holder) {
|
||||
return advancement(holder.value());
|
||||
}
|
||||
@@ -73,17 +71,13 @@ public class ConditionalAdvancement {
|
||||
return this;
|
||||
}
|
||||
|
||||
public IResult build() {
|
||||
return new Result(List.copyOf(advancements));
|
||||
}
|
||||
|
||||
public JsonObject write() {
|
||||
public JsonObject build() {
|
||||
var json = new JsonObject();
|
||||
var array = new JsonArray();
|
||||
json.add("advancements", array);
|
||||
|
||||
for (var pair : advancements) {
|
||||
var holder = pair.adv().serializeToJson();
|
||||
JsonObject holder = (JsonObject)Util.getOrThrow(Advancement.CODEC.encodeStart(JsonOps.INSTANCE, pair.adv()), IllegalStateException::new);
|
||||
if (holder.has(ICondition.DEFAULT_FIELD))
|
||||
throw new IllegalStateException("Recipe already serialized conditions!");
|
||||
ForgeHooks.writeCondition(pair.condition(), holder);
|
||||
@@ -94,27 +88,5 @@ public class ConditionalAdvancement {
|
||||
}
|
||||
}
|
||||
|
||||
public interface IResult {
|
||||
JsonObject serializeToJson();
|
||||
}
|
||||
|
||||
private record Pair(ICondition condition, Advancement adv) {}
|
||||
private record Result(List<Pair> advancements) implements IResult {
|
||||
@Override
|
||||
public JsonObject serializeToJson() {
|
||||
var json = new JsonObject();
|
||||
var array = new JsonArray();
|
||||
json.add("advancements", array);
|
||||
|
||||
for (var pair : advancements) {
|
||||
var holder = pair.adv().serializeToJson();
|
||||
if (holder.has(ICondition.DEFAULT_FIELD))
|
||||
throw new IllegalStateException("Recipe already serialized conditions!");
|
||||
ForgeHooks.writeCondition(pair.condition(), holder);
|
||||
|
||||
array.add(holder);
|
||||
}
|
||||
return json;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,28 +8,36 @@ package net.minecraftforge.common.crafting;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import com.google.gson.JsonArray;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import com.mojang.datafixers.util.Pair;
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.DataResult;
|
||||
import com.mojang.serialization.Dynamic;
|
||||
import com.mojang.serialization.DynamicOps;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import com.mojang.serialization.MapDecoder;
|
||||
import com.mojang.serialization.MapEncoder;
|
||||
import com.mojang.serialization.MapLike;
|
||||
import com.mojang.serialization.RecordBuilder;
|
||||
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.advancements.Advancement;
|
||||
import net.minecraft.advancements.AdvancementHolder;
|
||||
import net.minecraft.data.recipes.FinishedRecipe;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.data.recipes.RecipeBuilder;
|
||||
import net.minecraft.data.recipes.RecipeOutput;
|
||||
import net.minecraft.world.Container;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.Recipe;
|
||||
import net.minecraft.world.item.crafting.RecipeSerializer;
|
||||
import net.minecraft.world.item.crafting.RecipeType;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.util.GsonHelper;
|
||||
import net.minecraftforge.common.ForgeHooks;
|
||||
import net.minecraftforge.common.crafting.conditions.ConditionCodec;
|
||||
import net.minecraftforge.common.crafting.conditions.ICondition;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
@@ -52,11 +60,13 @@ public class ConditionalRecipe {
|
||||
}
|
||||
|
||||
public static class Builder {
|
||||
private List<RecipePair> recipes = new ArrayList<>();
|
||||
private List<InnerRecipe> recipes = new ArrayList<>();
|
||||
private List<InnerAdvancement> advancements = new ArrayList<>();
|
||||
|
||||
private RecipeOutput bouncer = new RecipeOutput() {
|
||||
@Override
|
||||
public void accept(FinishedRecipe value) {
|
||||
recipe(value);
|
||||
public void accept(ResourceLocation id, Recipe<?> value, @Nullable AdvancementHolder advancement) {
|
||||
recipe(id, value, advancement);
|
||||
}
|
||||
|
||||
@SuppressWarnings("removal")
|
||||
@@ -64,6 +74,16 @@ public class ConditionalRecipe {
|
||||
public Advancement.Builder advancement() {
|
||||
return Advancement.Builder.recipeAdvancement().parent(RecipeBuilder.ROOT_RECIPE_ADVANCEMENT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(ResourceLocation id, Recipe<?> recipe, ResourceLocation advancementId, JsonElement advancement) {
|
||||
AdvancementHolder holder = null;
|
||||
if (advancement != null) {
|
||||
Advancement adv = Util.getOrThrow(Advancement.CODEC.parse(JsonOps.INSTANCE, advancement), JsonParseException::new);
|
||||
holder = new AdvancementHolder(advancementId, adv);
|
||||
}
|
||||
accept(id, recipe, holder);
|
||||
}
|
||||
};
|
||||
|
||||
@Nullable
|
||||
@@ -93,10 +113,12 @@ public class ConditionalRecipe {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder recipe(FinishedRecipe recipe) {
|
||||
public Builder recipe(ResourceLocation id, Recipe<?> recipe, @Nullable AdvancementHolder advancement) {
|
||||
if (condition == null)
|
||||
throw new IllegalStateException("Can not add a recipe with no conditions.");
|
||||
recipes.add(new RecipePair(this.condition, recipe));
|
||||
recipes.add(new InnerRecipe(this.condition, recipe));
|
||||
if (advancement != null)
|
||||
advancements.add(new InnerAdvancement(this.condition, advancement));
|
||||
condition = null;
|
||||
return this;
|
||||
}
|
||||
@@ -117,94 +139,91 @@ public class ConditionalRecipe {
|
||||
if (recipes.isEmpty())
|
||||
throw new IllegalStateException("Invalid ConditionalRecipe builder, No recipes");
|
||||
|
||||
var adv = ConditionalAdvancement.builder();
|
||||
var hasAdvancement = false;
|
||||
for (var pair : recipes) {
|
||||
if (pair.recipe().advancement() != null) {
|
||||
adv.condition(pair.condition())
|
||||
.advancement(pair.recipe().advancement());
|
||||
hasAdvancement = true;
|
||||
JsonElement advancement = null;
|
||||
if (!advancements.isEmpty()) {
|
||||
var adv = ConditionalAdvancement.builder();
|
||||
for (var data : advancements) {
|
||||
adv.condition(data.condition())
|
||||
.advancement(data.advancement());
|
||||
}
|
||||
if (advancementId == null)
|
||||
advancementId = id.withPrefix("recipes/");
|
||||
advancement = adv.build();
|
||||
} else {
|
||||
advancementId = null;
|
||||
}
|
||||
|
||||
if (advancementId == null)
|
||||
advancementId = id.withPrefix("recipes/");
|
||||
|
||||
out.accept(new Finished(id, mainCondition, recipes, advancementId, hasAdvancement ? adv.write() : null));
|
||||
out.accept(id, new Wrapper(mainCondition, recipes), advancementId, advancement);
|
||||
}
|
||||
}
|
||||
|
||||
private record Finished(
|
||||
ResourceLocation id,
|
||||
@Nullable
|
||||
ICondition mainCondition,
|
||||
List<RecipePair> recipes,
|
||||
ResourceLocation advId,
|
||||
JsonObject advData
|
||||
) implements FinishedRecipe {
|
||||
@Override
|
||||
public void serializeRecipeData(JsonObject json) {
|
||||
JsonArray array = new JsonArray();
|
||||
var main = mainCondition;
|
||||
if (main == null && recipes.size() == 1)
|
||||
main = recipes.get(0).condition();
|
||||
private record InnerRecipe(ICondition condition, Recipe<?> recipe) {}
|
||||
private record InnerAdvancement(ICondition condition, AdvancementHolder advancement) {}
|
||||
|
||||
ForgeHooks.writeCondition(main, json);
|
||||
private static class Wrapper implements Recipe<Container> {
|
||||
@Override public boolean matches(Container inv, Level level) { return false; }
|
||||
@Override public ItemStack assemble(Container inv, RegistryAccess reg) { return null; }
|
||||
@Override public boolean canCraftInDimensions(int width, int height) { return false; }
|
||||
@Override public ItemStack getResultItem(RegistryAccess reg) { return null; }
|
||||
@Override public RecipeSerializer<?> getSerializer() { return ConditionalRecipe.SERIALZIER; }
|
||||
@Override public RecipeType<?> getType() { throw new UnsupportedOperationException(); }
|
||||
|
||||
json.add("recipes", array);
|
||||
for (var pair : recipes) {
|
||||
var holder = pair.recipe().serializeRecipe();
|
||||
if (holder.has(ICondition.DEFAULT_FIELD))
|
||||
throw new IllegalStateException("Recipe already serialized conditions!");
|
||||
ForgeHooks.writeCondition(pair.condition(), holder);
|
||||
array.add(holder);
|
||||
}
|
||||
@Nullable private final ICondition main;
|
||||
private final List<InnerRecipe> recipes;
|
||||
private Wrapper(@Nullable ICondition main, List<InnerRecipe> recipes) {
|
||||
this.main = main;
|
||||
this.recipes = recipes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResourceLocation id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RecipeSerializer<?> type() {
|
||||
return ConditionalRecipe.SERIALZIER;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public AdvancementHolder advancement() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public AdvancementData advancementData() {
|
||||
return advData == null ? null : new AdvancementData(advId, advData);
|
||||
}
|
||||
}
|
||||
|
||||
private record RecipePair(ICondition condition, FinishedRecipe recipe) {}
|
||||
|
||||
private static Codec<Recipe<?>> CODEC = new Codec<Recipe<?>>() {
|
||||
private static final Codec<Recipe<?>> CODEC = Codec.of(new MapEncoder.Implementation<>() {
|
||||
@Override
|
||||
public <T> DataResult<T> encode(Recipe<?> input, DynamicOps<T> ops, T prefix) {
|
||||
throw new UnsupportedOperationException("ConditionRecipe.CODEC does not support encoding");
|
||||
public <T> RecordBuilder<T> encode(Recipe<?> input, DynamicOps<T> ops, RecordBuilder<T> prefix) {
|
||||
if (!(input instanceof Wrapper))
|
||||
new IllegalStateException("ConditionalRecipe.CODEC can only be used during data gen, how did you get here?");
|
||||
Wrapper wrapper = (Wrapper)input;
|
||||
|
||||
if (wrapper.main != null)
|
||||
prefix.add(ICondition.DEFAULT_FIELD, ICondition.CODEC.encodeStart(ops, wrapper.main));
|
||||
else if (wrapper.recipes.size() == 1)
|
||||
prefix.add(ICondition.DEFAULT_FIELD, ICondition.CODEC.encodeStart(ops, wrapper.recipes.get(0).condition()));
|
||||
|
||||
var recipes = new ArrayList<T>();
|
||||
for (var recipe : wrapper.recipes) {
|
||||
var json = (JsonObject)json(Recipe.CODEC, recipe.recipe());
|
||||
if (wrapper.recipes.size() > 1)
|
||||
json.add(ICondition.DEFAULT_FIELD, json(ICondition.CODEC, recipe.condition()));
|
||||
recipes.add(JsonOps.INSTANCE.convertTo(ops, json));
|
||||
}
|
||||
prefix.add("recipes", ops.createList(recipes.stream()));
|
||||
return prefix;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> DataResult<Pair<Recipe<?>, T>> decode(DynamicOps<T> ops, T input) {
|
||||
public <T> Stream<T> keys(DynamicOps<T> ops) {
|
||||
return Stream.of(ops.createString(ICondition.DEFAULT_FIELD), ops.createString("recipes"));
|
||||
}
|
||||
|
||||
|
||||
private static <T> JsonElement json(Codec<T> codec, T object) {
|
||||
return Util.getOrThrow(codec.encodeStart(JsonOps.INSTANCE, object), IllegalStateException::new);
|
||||
}
|
||||
}, new MapDecoder.Implementation<Recipe<?>>() {
|
||||
@Override
|
||||
public <T> DataResult<Recipe<?>> decode(DynamicOps<T> ops, MapLike<T> input) {
|
||||
var context = ConditionCodec.getContext(ops);
|
||||
var json = new Dynamic<>(ops, input).convert(JsonOps.INSTANCE).getValue();
|
||||
var json = ops.convertTo(JsonOps.INSTANCE, input.get("recipes"));
|
||||
try {
|
||||
var recipes = GsonHelper.getAsJsonArray(GsonHelper.convertToJsonObject(json.getAsJsonObject(), "root"), "recipes");
|
||||
var recipes = GsonHelper.convertToJsonArray(json, "recipes");
|
||||
int idx = 0;
|
||||
for (var entry : recipes) {
|
||||
var object = GsonHelper.convertToJsonObject(entry, "recipe[" + idx++ + "]");
|
||||
var conditionjson = GsonHelper.getAsJsonObject(object, ICondition.DEFAULT_FIELD);
|
||||
var condition = Util.getOrThrow(ICondition.SAFE_CODEC.parse(JsonOps.INSTANCE, conditionjson), JsonSyntaxException::new);
|
||||
if (!condition.test(context))
|
||||
continue;
|
||||
if (object.has(ICondition.DEFAULT_FIELD)) {
|
||||
var conditionjson = GsonHelper.getAsJsonObject(object, ICondition.DEFAULT_FIELD);
|
||||
var condition = Util.getOrThrow(ICondition.SAFE_CODEC.parse(JsonOps.INSTANCE, conditionjson), JsonSyntaxException::new);
|
||||
if (!condition.test(context))
|
||||
continue;
|
||||
}
|
||||
var type = new ResourceLocation(GsonHelper.getAsString(object, "type"));
|
||||
var serializer = ForgeRegistries.RECIPE_SERIALIZERS.getValue(type);
|
||||
if (serializer == null)
|
||||
@@ -215,14 +234,19 @@ public class ConditionalRecipe {
|
||||
else if (!parsed.result().isPresent())
|
||||
return DataResult.error(() -> "Recipe passed all conditions but did not parse a valid return");
|
||||
else
|
||||
return DataResult.success(Pair.of(parsed.result().get(), ops.empty()));
|
||||
return DataResult.success(parsed.result().get());
|
||||
}
|
||||
return DataResult.error(() -> "No recipe passed conditions, if this is the case, you should have an outer condition.");
|
||||
} catch (JsonSyntaxException e) {
|
||||
return DataResult.error(() -> e.getMessage());
|
||||
}
|
||||
}
|
||||
}.stable();
|
||||
|
||||
@Override
|
||||
public <T> Stream<T> keys(DynamicOps<T> ops) {
|
||||
return Stream.of(ops.createString(ICondition.DEFAULT_FIELD), ops.createString("recipes"));
|
||||
}
|
||||
}).codec();
|
||||
|
||||
public static final RecipeSerializer<Recipe<?>> SERIALZIER = new RecipeSerializer<Recipe<?>>() {
|
||||
@Override
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.common.data;
|
||||
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.core.RegistrySetBuilder;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.data.PackOutput;
|
||||
import net.minecraft.data.registries.RegistriesDatapackGenerator;
|
||||
import net.minecraftforge.registries.DataPackRegistriesHooks;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* An extension of the {@link RegistriesDatapackGenerator} which properly handles
|
||||
* referencing existing dynamic registry objects within another dynamic registry
|
||||
* object.
|
||||
*/
|
||||
public class DatapackBuiltinEntriesProvider extends RegistriesDatapackGenerator
|
||||
{
|
||||
|
||||
/**
|
||||
* Constructs a new datapack provider which generates all registry objects
|
||||
* from the provided mods using the holder.
|
||||
*
|
||||
* @param output the target directory of the data generator
|
||||
* @param registries a future of a lookup for registries and their objects
|
||||
* @param modIds a set of mod ids to generate the dynamic registry objects of
|
||||
*/
|
||||
public DatapackBuiltinEntriesProvider(PackOutput output, CompletableFuture<HolderLookup.Provider> registries, Set<String> modIds)
|
||||
{
|
||||
super(output, registries, modIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new datapack provider which generates all registry objects
|
||||
* from the provided mods using the holder. All entries that need to be
|
||||
* bootstrapped are provided within the {@link RegistrySetBuilder}.
|
||||
*
|
||||
* @param output the target directory of the data generator
|
||||
* @param registries a future of a lookup for registries and their objects
|
||||
* @param datapackEntriesBuilder a builder containing the dynamic registry objects added by this provider
|
||||
* @param modIds a set of mod ids to generate the dynamic registry objects of
|
||||
*/
|
||||
public DatapackBuiltinEntriesProvider(PackOutput output, CompletableFuture<HolderLookup.Provider> registries, RegistrySetBuilder datapackEntriesBuilder, Set<String> modIds)
|
||||
{
|
||||
this(output, registries.thenApply(r -> constructRegistries(r, datapackEntriesBuilder)), modIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* A method used to construct empty bootstraps for all registries this provider
|
||||
* did not touch such that existing dynamic registry objects do not get inlined.
|
||||
*
|
||||
* @param original a future of a lookup for registries and their objects
|
||||
* @param datapackEntriesBuilder a builder containing the dynamic registry objects added by this provider
|
||||
* @return a new lookup containing the existing and to be generated registries and their objects
|
||||
*/
|
||||
private static HolderLookup.Provider constructRegistries(HolderLookup.Provider original, RegistrySetBuilder datapackEntriesBuilder)
|
||||
{
|
||||
var builderKeys = new HashSet<>(datapackEntriesBuilder.getEntryKeys());
|
||||
DataPackRegistriesHooks.getDataPackRegistriesWithDimensions().filter(data -> !builderKeys.contains(data.key())).forEach(data -> datapackEntriesBuilder.add(data.key(), context -> {}));
|
||||
return datapackEntriesBuilder.buildPatch(RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY), original);
|
||||
}
|
||||
}
|
||||
@@ -5,15 +5,12 @@
|
||||
|
||||
package net.minecraftforge.common.data;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonElement;
|
||||
import net.minecraft.advancements.AdvancementHolder;
|
||||
import net.minecraft.advancements.Advancement.Builder;
|
||||
import net.minecraft.data.CachedOutput;
|
||||
import net.minecraft.data.PackOutput;
|
||||
import net.minecraft.data.recipes.FinishedRecipe;
|
||||
import net.minecraft.data.recipes.RecipeOutput;
|
||||
import net.minecraft.data.recipes.ShapedRecipeBuilder;
|
||||
import net.minecraft.data.recipes.ShapelessRecipeBuilder;
|
||||
import net.minecraft.data.recipes.packs.VanillaRecipeProvider;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.TagKey;
|
||||
@@ -24,6 +21,10 @@ import net.minecraft.world.item.crafting.Ingredient;
|
||||
import net.minecraft.world.item.crafting.Ingredient.ItemValue;
|
||||
import net.minecraft.world.item.crafting.Ingredient.TagValue;
|
||||
import net.minecraft.world.item.crafting.Ingredient.Value;
|
||||
import net.minecraft.world.item.crafting.Recipe;
|
||||
import net.minecraft.world.item.crafting.ShapedRecipe;
|
||||
import net.minecraft.world.item.crafting.ShapedRecipePattern;
|
||||
import net.minecraft.world.item.crafting.ShapelessRecipe;
|
||||
import net.minecraft.world.level.ItemLike;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraftforge.common.Tags;
|
||||
@@ -95,34 +96,38 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
|
||||
|
||||
super.buildRecipes(new RecipeOutput() {
|
||||
@Override
|
||||
public void accept(FinishedRecipe vanilla) {
|
||||
var modified = enhance(vanilla);
|
||||
public void accept(ResourceLocation id, Recipe<?> recipe, AdvancementHolder advancement) {
|
||||
var modified = enhance(id, recipe);
|
||||
if (modified != null)
|
||||
consumer.accept(modified);
|
||||
consumer.accept(id, modified, advancement);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Builder advancement() {
|
||||
return consumer.advancement();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(ResourceLocation id, Recipe<?> recipe, ResourceLocation advancementId, JsonElement advancement) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private FinishedRecipe enhance(FinishedRecipe vanilla) {
|
||||
if (vanilla instanceof ShapelessRecipeBuilder.Result shapeless)
|
||||
return enhance(shapeless);
|
||||
if (vanilla instanceof ShapedRecipeBuilder.Result shaped)
|
||||
return enhance(shaped);
|
||||
private Recipe<?> enhance(ResourceLocation id, Recipe<?> vanilla) {
|
||||
if (vanilla instanceof ShapelessRecipe shapeless)
|
||||
return enhance(id, shapeless);
|
||||
if (vanilla instanceof ShapedRecipe shaped)
|
||||
return enhance(id, shaped);
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private FinishedRecipe enhance(ShapelessRecipeBuilder.Result vanilla) {
|
||||
List<Ingredient> ingredients = getField(ShapelessRecipeBuilder.Result.class, vanilla, 4);
|
||||
private Recipe<?> enhance(ResourceLocation id, ShapelessRecipe vanilla) {
|
||||
List<Ingredient> ingredients = getField(ShapelessRecipe.class, vanilla, 3);
|
||||
boolean modified = false;
|
||||
for (int x = 0; x < ingredients.size(); x++) {
|
||||
Ingredient ing = enhance(vanilla.id(), ingredients.get(x));
|
||||
Ingredient ing = enhance(id, ingredients.get(x));
|
||||
if (ing != null) {
|
||||
ingredients.set(x, ing);
|
||||
modified = true;
|
||||
@@ -133,7 +138,7 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
protected CompletableFuture<?> saveAdvancement(CachedOutput output, ResourceLocation advancementId, JsonObject advancementJson, FinishedRecipe finishedRecipe) {
|
||||
protected CompletableFuture<?> saveAdvancement(CachedOutput output, ResourceLocation advancementId, JsonElement advancement) {
|
||||
// NOOP - We don't replace any of the advancement things yet...
|
||||
return null;
|
||||
}
|
||||
@@ -145,11 +150,13 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private FinishedRecipe enhance(ShapedRecipeBuilder.Result vanilla) {
|
||||
Map<Character, Ingredient> ingredients = getField(ShapedRecipeBuilder.Result.class, vanilla, 5);
|
||||
private Recipe<?> enhance(ResourceLocation id, ShapedRecipe vanilla) {
|
||||
ShapedRecipePattern pattern = getField(ShapedRecipe.class, vanilla, 2);
|
||||
var data = pattern.data().orElseThrow(() -> new IllegalStateException("Weird shaped recipe, data is missing? " + id + " " + vanilla));
|
||||
Map<Character, Ingredient> ingredients = data.key();
|
||||
boolean modified = false;
|
||||
for (Character x : ingredients.keySet()) {
|
||||
Ingredient ing = enhance(vanilla.id(), ingredients.get(x));
|
||||
Ingredient ing = enhance(id, ingredients.get(x));
|
||||
if (ing != null) {
|
||||
ingredients.put(x, ing);
|
||||
modified = true;
|
||||
|
||||
@@ -294,7 +294,7 @@ public interface IForgeBlock
|
||||
* @param target The full target the player is looking at
|
||||
* @return A ItemStack to add to the player's inventory, empty itemstack if nothing should be added.
|
||||
*/
|
||||
default ItemStack getCloneItemStack(BlockState state, HitResult target, BlockGetter level, BlockPos pos, Player player)
|
||||
default ItemStack getCloneItemStack(BlockState state, HitResult target, LevelReader level, BlockPos pos, Player player)
|
||||
{
|
||||
return self().getCloneItemStack(level, pos, state);
|
||||
}
|
||||
|
||||
@@ -102,44 +102,31 @@ public interface IForgeBlockEntity extends ICapabilitySerializable<CompoundTag>
|
||||
*
|
||||
* @return an appropriately size {@link AABB} for the {@link BlockEntity}
|
||||
*/
|
||||
default AABB getRenderBoundingBox()
|
||||
{
|
||||
default AABB getRenderBoundingBox() {
|
||||
AABB bb = INFINITE_EXTENT_AABB;
|
||||
BlockState state = self().getBlockState();
|
||||
Block block = state.getBlock();
|
||||
BlockPos pos = self().getBlockPos();
|
||||
if (block == Blocks.ENCHANTING_TABLE)
|
||||
{
|
||||
bb = new AABB(pos, pos.offset(1, 1, 1));
|
||||
}
|
||||
else if (block == Blocks.CHEST || block == Blocks.TRAPPED_CHEST)
|
||||
{
|
||||
bb = new AABB(pos.offset(-1, 0, -1), pos.offset(2, 2, 2));
|
||||
}
|
||||
else if (block == Blocks.STRUCTURE_BLOCK)
|
||||
{
|
||||
if (block == Blocks.ENCHANTING_TABLE) {
|
||||
bb = new AABB(pos);
|
||||
} else if (block == Blocks.CHEST || block == Blocks.TRAPPED_CHEST) {
|
||||
bb = AABB.encapsulatingFullBlocks(pos.offset(-1, 0, -1), pos.offset(1, 0, 1));
|
||||
} else if (block == Blocks.STRUCTURE_BLOCK) {
|
||||
bb = INFINITE_EXTENT_AABB;
|
||||
}
|
||||
else if (block != null && block != Blocks.BEACON)
|
||||
{
|
||||
} else if (block != null && block != Blocks.BEACON) {
|
||||
AABB cbb = null;
|
||||
try
|
||||
{
|
||||
try {
|
||||
VoxelShape collisionShape = state.getCollisionShape(self().getLevel(), pos);
|
||||
if (!collisionShape.isEmpty())
|
||||
{
|
||||
cbb = collisionShape.bounds().move(pos);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
} catch (Exception e) {
|
||||
// We have to capture any exceptions that may occur here because BUKKIT servers like to send
|
||||
// the tile entity data BEFORE the chunk data, you know, the OPPOSITE of what vanilla does!
|
||||
// So we can not GUARANTEE that the world state is the real state for the block...
|
||||
// So, once again in the long line of US having to accommodate BUKKIT breaking things,
|
||||
// here it is, assume that the TE is only 1 cubic block. Problem with this is that it may
|
||||
// cause the TileEntity renderer to error further down the line! But alas, nothing we can do.
|
||||
cbb = new net.minecraft.world.phys.AABB(pos.offset(-1, 0, -1), pos.offset(1, 1, 1));
|
||||
cbb = AABB.encapsulatingFullBlocks(pos.offset(-1, 0, -1), pos.offset(1, 1, 1));
|
||||
}
|
||||
if (cbb != null) bb = cbb;
|
||||
}
|
||||
|
||||
@@ -220,7 +220,7 @@ public interface IForgeBlockState
|
||||
* @param target The full target the player is looking at
|
||||
* @return A ItemStack to add to the player's inventory, empty itemstack if nothing should be added.
|
||||
*/
|
||||
default ItemStack getCloneItemStack(HitResult target, BlockGetter level, BlockPos pos, Player player)
|
||||
default ItemStack getCloneItemStack(HitResult target, LevelReader level, BlockPos pos, Player player)
|
||||
{
|
||||
return self().getBlock().getCloneItemStack(self(), target, level, pos, player);
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ public interface IForgeLivingEntity extends IForgeEntity {
|
||||
if (type == ForgeMod.WATER_TYPE.get())
|
||||
return !self().canBreatheUnderwater();
|
||||
return
|
||||
type.canDrownIn(self());
|
||||
type.canDrownIn(self());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -18,6 +18,7 @@ import com.mojang.brigadier.CommandDispatcher;
|
||||
|
||||
import net.minecraft.advancements.AdvancementHolder;
|
||||
import net.minecraft.advancements.AdvancementProgress;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
@@ -798,6 +799,14 @@ public class ForgeEventFactory {
|
||||
post(new ChunkEvent.Load(chunk, newChunk));
|
||||
}
|
||||
|
||||
public static void onLevelUnload(Level level) {
|
||||
post(new LevelEvent.Unload(level));
|
||||
}
|
||||
|
||||
public static void onLevelLoad(Level level) {
|
||||
post(new LevelEvent.Load(level));
|
||||
}
|
||||
|
||||
public static void onChunkDataSave(ChunkAccess chunk, LevelAccessor world, CompoundTag data) {
|
||||
post(new ChunkDataEvent.Save(chunk, world, data));
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import com.mojang.brigadier.arguments.IntegerArgumentType;
|
||||
import com.mojang.brigadier.builder.ArgumentBuilder;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
|
||||
import net.minecraft.commands.CommandRuntimeException;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
|
||||
@@ -18,10 +17,8 @@ import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraftforge.common.WorldWorkerManager;
|
||||
|
||||
class GenerateCommand
|
||||
{
|
||||
static ArgumentBuilder<CommandSourceStack, ?> register()
|
||||
{
|
||||
class GenerateCommand {
|
||||
static ArgumentBuilder<CommandSourceStack, ?> register() {
|
||||
return Commands.literal("generate")
|
||||
.requires(cs->cs.hasPermission(4)) //permission
|
||||
.then(Commands.argument("pos", BlockPosArgument.blockPos())
|
||||
@@ -37,13 +34,11 @@ class GenerateCommand
|
||||
);
|
||||
}
|
||||
|
||||
private static int getInt(CommandContext<CommandSourceStack> ctx, String name)
|
||||
{
|
||||
private static int getInt(CommandContext<CommandSourceStack> ctx, String name) {
|
||||
return IntegerArgumentType.getInteger(ctx, name);
|
||||
}
|
||||
|
||||
private static int execute(CommandSourceStack source, BlockPos pos, int count, ServerLevel dim, int interval) throws CommandRuntimeException
|
||||
{
|
||||
private static int execute(CommandSourceStack source, BlockPos pos, int count, ServerLevel dim, int interval) {
|
||||
BlockPos chunkpos = new BlockPos(pos.getX() >> 4, 0, pos.getZ() >> 4);
|
||||
|
||||
ChunkGenWorker worker = new ChunkGenWorker(source, chunkpos, count, dim, interval);
|
||||
|
||||
@@ -34,7 +34,7 @@ class TPSCommand
|
||||
sendTime(ctx.getSource(), dim);
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
double meanTickTime = mean(ctx.getSource().getServer().tickTimes) * 1.0E-6D;
|
||||
double meanTickTime = mean(ctx.getSource().getServer().tickTimesNanos) * 1.0E-6D;
|
||||
double meanTPS = Math.min(1000.0/meanTickTime, 20);
|
||||
ctx.getSource().sendSuccess(() -> Component.translatable("commands.forge.tps.summary.all", TIME_FORMATTER.format(meanTickTime), TIME_FORMATTER.format(meanTPS)), false);
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
import net.minecraft.commands.CommandRuntimeException;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
@@ -25,12 +24,10 @@ import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.server.timings.ForgeTimings;
|
||||
import net.minecraftforge.server.timings.TimeTracker;
|
||||
|
||||
class TrackCommand
|
||||
{
|
||||
class TrackCommand {
|
||||
private static final DecimalFormat TIME_FORMAT = new DecimalFormat("#####0.00");
|
||||
|
||||
static ArgumentBuilder<CommandSourceStack, ?> register()
|
||||
{
|
||||
static ArgumentBuilder<CommandSourceStack, ?> register() {
|
||||
return Commands.literal("track")
|
||||
.then(StartTrackingCommand.register())
|
||||
.then(ResetTrackingCommand.register())
|
||||
@@ -39,10 +36,8 @@ class TrackCommand
|
||||
.then(StartTrackingCommand.register());
|
||||
}
|
||||
|
||||
private static class StartTrackingCommand
|
||||
{
|
||||
static ArgumentBuilder<CommandSourceStack, ?> register()
|
||||
{
|
||||
private static class StartTrackingCommand {
|
||||
static ArgumentBuilder<CommandSourceStack, ?> register() {
|
||||
return Commands.literal("start")
|
||||
.requires(cs->cs.hasPermission(2)) //permission
|
||||
.then(Commands.literal("te")
|
||||
@@ -70,10 +65,8 @@ class TrackCommand
|
||||
}
|
||||
}
|
||||
|
||||
private static class ResetTrackingCommand
|
||||
{
|
||||
static ArgumentBuilder<CommandSourceStack, ?> register()
|
||||
{
|
||||
private static class ResetTrackingCommand {
|
||||
static ArgumentBuilder<CommandSourceStack, ?> register() {
|
||||
return Commands.literal("reset")
|
||||
.requires(cs->cs.hasPermission(2)) //permission
|
||||
.then(Commands.literal("te")
|
||||
@@ -93,15 +86,13 @@ class TrackCommand
|
||||
}
|
||||
}
|
||||
|
||||
private static class TrackResults
|
||||
{
|
||||
private static class TrackResults {
|
||||
/**
|
||||
* Returns the time objects recorded by the time tracker sorted by average time
|
||||
*
|
||||
* @return A list of time objects
|
||||
*/
|
||||
private static <T> List<ForgeTimings<T>> getSortedTimings(TimeTracker<T> tracker)
|
||||
{
|
||||
private static <T> List<ForgeTimings<T>> getSortedTimings(TimeTracker<T> tracker) {
|
||||
ArrayList<ForgeTimings<T>> list = new ArrayList<>();
|
||||
|
||||
list.addAll(tracker.getTimingData());
|
||||
@@ -111,61 +102,49 @@ class TrackCommand
|
||||
return list;
|
||||
}
|
||||
|
||||
private static <T> int execute(CommandSourceStack source, TimeTracker<T> tracker, Function<ForgeTimings<T>, Component> toString) throws CommandRuntimeException
|
||||
{
|
||||
private static <T> int execute(CommandSourceStack source, TimeTracker<T> tracker, Function<ForgeTimings<T>, Component> toString) {
|
||||
List<ForgeTimings<T>> timingsList = getSortedTimings(tracker);
|
||||
if (timingsList.isEmpty())
|
||||
{
|
||||
source.sendSuccess(() -> Component.translatable("commands.forge.tracking.no_data"), true);
|
||||
}
|
||||
else
|
||||
{
|
||||
else {
|
||||
timingsList.stream()
|
||||
.filter(timings -> timings.getObject().get() != null)
|
||||
.limit(10)
|
||||
.forEach(timings -> source.sendSuccess(() -> toString.apply(timings), true));
|
||||
.filter(timings -> timings.getObject().get() != null)
|
||||
.limit(10)
|
||||
.forEach(timings -> source.sendSuccess(() -> toString.apply(timings), true));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static class TrackResultsEntity
|
||||
{
|
||||
static ArgumentBuilder<CommandSourceStack, ?> register()
|
||||
{
|
||||
return Commands.literal("entity").executes(ctx -> TrackResults.execute(ctx.getSource(), TimeTracker.ENTITY_UPDATE, data ->
|
||||
{
|
||||
Entity entity = data.getObject().get();
|
||||
if (entity == null)
|
||||
return Component.translatable("commands.forge.tracking.invalid");
|
||||
private static class TrackResultsEntity {
|
||||
static ArgumentBuilder<CommandSourceStack, ?> register() {
|
||||
return Commands.literal("entity").executes(ctx -> TrackResults.execute(ctx.getSource(), TimeTracker.ENTITY_UPDATE, data -> {
|
||||
Entity entity = data.getObject().get();
|
||||
if (entity == null)
|
||||
return Component.translatable("commands.forge.tracking.invalid");
|
||||
|
||||
BlockPos pos = entity.blockPosition();
|
||||
double averageTimings = data.getAverageTimings();
|
||||
String tickTime = (averageTimings > 1000 ? TIME_FORMAT.format(averageTimings / 1000) : TIME_FORMAT.format(averageTimings)) + (averageTimings < 1000 ? "\u03bcs" : "ms");
|
||||
BlockPos pos = entity.blockPosition();
|
||||
double averageTimings = data.getAverageTimings();
|
||||
String tickTime = (averageTimings > 1000 ? TIME_FORMAT.format(averageTimings / 1000) : TIME_FORMAT.format(averageTimings)) + (averageTimings < 1000 ? "\u03bcs" : "ms");
|
||||
|
||||
return Component.translatable("commands.forge.tracking.timing_entry", ForgeRegistries.ENTITY_TYPES.getKey(entity.getType()), entity.level().dimension().location().toString(), pos.getX(), pos.getY(), pos.getZ(), tickTime);
|
||||
})
|
||||
);
|
||||
return Component.translatable("commands.forge.tracking.timing_entry", ForgeRegistries.ENTITY_TYPES.getKey(entity.getType()), entity.level().dimension().location().toString(), pos.getX(), pos.getY(), pos.getZ(), tickTime);
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
private static class TrackResultsBlockEntity
|
||||
{
|
||||
static ArgumentBuilder<CommandSourceStack, ?> register()
|
||||
{
|
||||
return Commands.literal("te").executes(ctx -> TrackResults.execute(ctx.getSource(), TimeTracker.BLOCK_ENTITY_UPDATE, data ->
|
||||
{
|
||||
BlockEntity be = data.getObject().get();
|
||||
if (be == null)
|
||||
return Component.translatable("commands.forge.tracking.invalid");
|
||||
private static class TrackResultsBlockEntity {
|
||||
static ArgumentBuilder<CommandSourceStack, ?> register() {
|
||||
return Commands.literal("te").executes(ctx -> TrackResults.execute(ctx.getSource(), TimeTracker.BLOCK_ENTITY_UPDATE, data -> {
|
||||
BlockEntity be = data.getObject().get();
|
||||
if (be == null)
|
||||
return Component.translatable("commands.forge.tracking.invalid");
|
||||
|
||||
BlockPos pos = be.getBlockPos();
|
||||
BlockPos pos = be.getBlockPos();
|
||||
|
||||
double averageTimings = data.getAverageTimings();
|
||||
String tickTime = (averageTimings > 1000 ? TIME_FORMAT.format(averageTimings / 1000) : TIME_FORMAT.format(averageTimings)) + (averageTimings < 1000 ? "\u03bcs" : "ms");
|
||||
return Component.translatable("commands.forge.tracking.timing_entry", ForgeRegistries.BLOCK_ENTITY_TYPES.getKey(be.getType()), be.getLevel().dimension().location().toString(), pos.getX(), pos.getY(), pos.getZ(), tickTime);
|
||||
})
|
||||
);
|
||||
double averageTimings = data.getAverageTimings();
|
||||
String tickTime = (averageTimings > 1000 ? TIME_FORMAT.format(averageTimings / 1000) : TIME_FORMAT.format(averageTimings)) + (averageTimings < 1000 ? "\u03bcs" : "ms");
|
||||
return Component.translatable("commands.forge.tracking.timing_entry", ForgeRegistries.BLOCK_ENTITY_TYPES.getKey(be.getType()), be.getLevel().dimension().location().toString(), pos.getX(), pos.getY(), pos.getZ(), tickTime);
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user