diff --git a/README.md b/README.md index 5fb486d..6e2aae7 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # ModularMCLib Utils -面向 Minecraft 26.1.2、NeoForge 26.1.2.126 与 Java 25 的通用工具库。模组标识为 `mmclutils`。 +面向 Minecraft 1.21.1、NeoForge 21.1.265 与 Java 21 的通用工具库。模组标识为 `mmclutils`。 ## 安装与构建 diff --git a/build.gradle b/build.gradle index d06d878..eb085c8 100644 --- a/build.gradle +++ b/build.gradle @@ -18,7 +18,11 @@ version = "${mod_version}" + (isSnapshot ? "-SNAPSHOT" : "") boolean isCI = System.getenv("CI") != null java { - toolchain.languageVersion = JavaLanguageVersion.of(25) + toolchain.languageVersion = JavaLanguageVersion.of(21) +} + +kotlin { + jvmToolchain(21) } sourceSets { @@ -32,6 +36,11 @@ sourceSets { runtimeClasspath += main.output + main.runtimeClasspath } + test { + compileClasspath += main.output + main.compileClasspath + runtimeClasspath += main.output + main.runtimeClasspath + } + extra { compileClasspath += main.output runtimeClasspath += main.output + main.runtimeClasspath diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 95277ed..7f0a15d 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,15 +1,16 @@ [versions] -minecraft = "26.1.2" -neoForge = "26.1.2.126" -lombok = "9.8.2" +minecraft = "1.21.1" +neoForge = "21.1.265" +lombok = "9.8.3" loader = "4" +parchment = "2024.11.17" # https://parchmentmc.org/docs/getting-started shadow = "9.6.1" spotless = "8.11.0" modDevGradle = "2.0.148" kotlin = "2.4.21" jetbrains-annotations = "26.1.0" -jspecify = "1.0.0" -fastutil = "8.5.18" +jspecify = "1.0.1" +fastutil = "8.5.12" renderNurse = "0.0.26" mixin = "0.8.7" diff --git a/gradle/scripts/moddevgradle.gradle b/gradle/scripts/moddevgradle.gradle index 2c0af81..7b98f6c 100644 --- a/gradle/scripts/moddevgradle.gradle +++ b/gradle/scripts/moddevgradle.gradle @@ -1,6 +1,11 @@ neoForge { version = libs.versions.neoForge.get() + parchment { + minecraftVersion = libs.versions.minecraft.get() + mappingsVersion = libs.versions.parchment.get() + } + accessTransformers { var file = project.file('src/main/resources/META-INF/accesstransformer.cfg') from(file) @@ -27,6 +32,13 @@ neoForge { sourceSet(sourceSets.extra) sourceSet(sourceSets.clientExtra) } + "${mod_id}_test" { + sourceSet(sourceSets.main) + sourceSet(sourceSets.client) + sourceSet(sourceSets.extra) + sourceSet(sourceSets.clientExtra) + sourceSet(sourceSets.test) + } } runs { @@ -48,18 +60,20 @@ neoForge { programArguments.addAll('--nogui', '--world', 'world-extra') } - // 让持续集成使用原版自带用例启动服务器、推进 Tick 并退出。 + // 用启动用例确认服务端已加载模组并开始推进 Tick。 gameTestServer { type = "gameTestServer" - sourceSet = sourceSets.extra + sourceSet = sourceSets.test + loadedMods = [mods["${mod_id}_test"]] ideName = "Game Tests" gameDirectory.set(file('run/gametest/server')) - programArguments.addAll('--tests', 'minecraft:always_pass') + systemProperty('neoforge.enabledGameTestNamespaces', 'minecraft') } // applies to all the run configs above configureEach { + loadedMods.convention([mods[project.mod_id]]) systemProperty 'forge.logging.markers', 'REGISTRIES' jvmArgument('-ea:com.modularmc.template...') logLevel = org.slf4j.event.Level.INFO diff --git a/gradle/scripts/resources.gradle b/gradle/scripts/resources.gradle index 52ba62c..9019055 100644 --- a/gradle/scripts/resources.gradle +++ b/gradle/scripts/resources.gradle @@ -35,7 +35,7 @@ var generateModMetadata = tasks.register("generateModMetadata", ProcessResources var replaceProperties = [ version : version_toml, mod_id : mod_id, - minecraft_version : "[26.1,)", + minecraft_version : "[${libs.versions.minecraft.get()}]", loader_version : libs.versions.loader.get(), neo_version : neoVersion, mod_license : mod_license, @@ -50,4 +50,4 @@ var generateModMetadata = tasks.register("generateModMetadata", ProcessResources into "build/generated/sources/modMetadata" } sourceSets.main.resources.srcDir generateModMetadata -neoForge.ideSyncTask generateModMetadata \ No newline at end of file +neoForge.ideSyncTask generateModMetadata diff --git a/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java b/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java index 1d087a4..2e81db6 100644 --- a/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java +++ b/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java @@ -3,7 +3,7 @@ import com.modularmc.mmclutils.api.input.SyncedKeyMappings; import com.modularmc.mmclutils.client.ModularMCLibUtilsClient; -import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.neoforged.bus.api.IEventBus; import net.neoforged.fml.ModList; @@ -46,8 +46,8 @@ public ModularMCLibUtils(IEventBus modBus) { * @param path 标识路径 * @return 属于 {@link #MOD_ID} 的标识 */ - public static Identifier id(String path) { - return Identifier.fromNamespaceAndPath(MOD_ID, path); + public static ResourceLocation id(String path) { + return ResourceLocation.fromNamespaceAndPath(MOD_ID, path); } /** 返回当前专用服或本地集成服。服务器尚未启动或已停止时返回空值。 */ @@ -72,7 +72,7 @@ public static Path getGameDir() { /** 判断当前运行是否为生产环境。 */ public static boolean isProd() { - return FMLEnvironment.isProduction(); + return FMLLoader.isProduction(); } /** 判断当前运行是否为开发环境。 */ @@ -93,12 +93,12 @@ public static boolean isDataGen() { */ public static boolean isModLoaded(String modId) { ModList mods = ModList.get(); - return mods == null ? FMLLoader.getCurrent().getLoadingModList().getModFileById(modId) != null : mods.isLoaded(modId); + return mods == null ? FMLLoader.getLoadingModList().getModFileById(modId) != null : mods.isLoaded(modId); } /** 判断物理运行端。集成服务器所在进程同样返回真。 */ public static boolean isClientSide() { - return FMLEnvironment.getDist().isClient(); + return FMLEnvironment.dist.isClient(); } /** 判断当前线程是否为物理客户端主线程。专用服务器上始终返回假。 */ diff --git a/src/main/java/com/modularmc/mmclutils/api/data/FastSavedData.java b/src/main/java/com/modularmc/mmclutils/api/data/FastSavedData.java index 56afa88..224663d 100644 --- a/src/main/java/com/modularmc/mmclutils/api/data/FastSavedData.java +++ b/src/main/java/com/modularmc/mmclutils/api/data/FastSavedData.java @@ -5,7 +5,7 @@ import com.modularmc.mmclutils.api.schedule.SerialTaskExecutor; import com.modularmc.mmclutils.utils.FileUtils; -import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.dimension.DimensionType; @@ -40,7 +40,7 @@ @EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID) public final class FastSavedData { - private static final LevelStore>> DATA = LevelStore.create(HashMap::new, entries -> entries.values().forEach(value -> value.save(true))); + private static final LevelStore>> DATA = LevelStore.create(HashMap::new, entries -> entries.values().forEach(value -> value.save(true))); private static final Map EXECUTORS = new IdentityHashMap<>(); private final Type type; @@ -83,7 +83,8 @@ public static FastSavedData get(ServerLevel level, Type type) throws I } Path worldRoot = level.getServer().getWorldPath(LevelResource.ROOT).toAbsolutePath().normalize(); Path directory = DimensionType.getStorageFolder(level.dimension(), worldRoot).resolve("data/mmclutils").normalize(); - Path path = type.id().withSuffix(".bin").resolveAgainst(directory).normalize(); + ResourceLocation file = type.id().withSuffix(".bin"); + Path path = directory.resolve(file.getNamespace()).resolve(file.getPath()).normalize(); if (!path.startsWith(directory)) throw new IllegalArgumentException("存档路径超出维度数据目录:" + type.id()); boolean imported = false; @@ -191,7 +192,7 @@ private static void checkOwner(ServerLevel level) { * @param legacy 仅在新文件缺失时使用的旧格式入口,可以为空 * @param 存档值的类型 */ - public record Type(Identifier id, Supplier factory, UnaryOperator copyForWrite, + public record Type(ResourceLocation id, Supplier factory, UnaryOperator copyForWrite, FileUtils.Reader reader, FileUtils.Writer writer, @Nullable LegacyFile legacy) { @@ -204,7 +205,7 @@ public record Type(Identifier id, Supplier factory, UnaryOperator copyF * @param reader 解码当前文件 * @param writer 在后台编码交付的数据 */ - public Type(Identifier id, Supplier factory, UnaryOperator copyForWrite, + public Type(ResourceLocation id, Supplier factory, UnaryOperator copyForWrite, FileUtils.Reader reader, FileUtils.Writer writer) { this(id, factory, copyForWrite, reader, writer, null); } diff --git a/src/main/java/com/modularmc/mmclutils/api/input/SyncedKeyMappings.java b/src/main/java/com/modularmc/mmclutils/api/input/SyncedKeyMappings.java index 9b12b07..63ead7a 100644 --- a/src/main/java/com/modularmc/mmclutils/api/input/SyncedKeyMappings.java +++ b/src/main/java/com/modularmc/mmclutils/api/input/SyncedKeyMappings.java @@ -5,7 +5,7 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; -import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.neoforged.bus.api.IEventBus; @@ -29,12 +29,12 @@ @EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID) public final class SyncedKeyMappings { - private static final ConcurrentHashMap KEYS = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap KEYS = new ConcurrentHashMap<>(); private SyncedKeyMappings() {} /** 在模组初始化时于两端声明一次。标识应使用调用方的命名空间,重复声明会抛出异常。 */ - public static Key define(Identifier id) { + public static Key define(ResourceLocation id) { var key = new Key(id); if (KEYS.putIfAbsent(id, key) != null) throw new IllegalArgumentException("同步按键已经声明 " + id); return key; @@ -51,7 +51,7 @@ private static void initPayload(RegisterPayloadHandlersEvent event) { (payload, context) -> apply((ServerPlayer) context.player(), payload.changes)); } - private static void apply(ServerPlayer player, Object2BooleanMap changes) { + private static void apply(ServerPlayer player, Object2BooleanMap changes) { var accepted = new Object2BooleanLinkedOpenHashMap(); for (var change : changes.object2BooleanEntrySet()) { Key key = KEYS.get(change.getKey()); @@ -98,17 +98,17 @@ private static void release(ServerPlayer player) { /** 一个可被客户端绑定并由服务端读取的按键。状态和玩家监听仅在服务端线程访问。 */ public static final class Key { - private final Identifier id; + private final ResourceLocation id; private final ReferenceOpenHashSet pressed = new ReferenceOpenHashSet<>(); private final CopyOnWriteArrayList listeners = new CopyOnWriteArrayList<>(); private final Reference2ObjectOpenHashMap> playerListeners = new Reference2ObjectOpenHashMap<>(); - private Key(Identifier id) { + private Key(ResourceLocation id) { this.id = id; } /** 返回两端共享的按键标识。 */ - public Identifier id() { + public ResourceLocation id() { return id; } @@ -171,7 +171,7 @@ public interface Listener { * @param changes 已登记按键的标识及其按下状态 */ @ApiStatus.Internal - public record ChangeSet(Object2BooleanMap changes) implements CustomPacketPayload { + public record ChangeSet(Object2BooleanMap changes) implements CustomPacketPayload { /** 单个载荷允许的最大变化条目数。 */ public static final int MAX_CHANGES = 64; @@ -182,9 +182,9 @@ public record ChangeSet(Object2BooleanMap changes) implements Custom private static ChangeSet read(FriendlyByteBuf buffer) { int count = buffer.readVarInt(); if (count < 1 || count > MAX_CHANGES) throw new DecoderException("同步按键数量超出范围 " + count); - var changes = new Object2BooleanLinkedOpenHashMap(count); + var changes = new Object2BooleanLinkedOpenHashMap(count); for (int i = 0; i < count; i++) { - Identifier id = Identifier.STREAM_CODEC.decode(buffer); + ResourceLocation id = ResourceLocation.STREAM_CODEC.decode(buffer); if (changes.containsKey(id)) throw new DecoderException("同步按键标识重复 " + id); changes.put(id, buffer.readBoolean()); } @@ -194,7 +194,7 @@ private static ChangeSet read(FriendlyByteBuf buffer) { private static void write(FriendlyByteBuf buffer, ChangeSet state) { buffer.writeVarInt(state.changes.size()); for (var change : state.changes.object2BooleanEntrySet()) { - Identifier.STREAM_CODEC.encode(buffer, change.getKey()); + ResourceLocation.STREAM_CODEC.encode(buffer, change.getKey()); buffer.writeBoolean(change.getBooleanValue()); } } diff --git a/src/main/java/com/modularmc/mmclutils/api/inventory/ResourceTransferSimulation.java b/src/main/java/com/modularmc/mmclutils/api/inventory/ResourceTransferSimulation.java index 2e901da..83d1c90 100644 --- a/src/main/java/com/modularmc/mmclutils/api/inventory/ResourceTransferSimulation.java +++ b/src/main/java/com/modularmc/mmclutils/api/inventory/ResourceTransferSimulation.java @@ -1,99 +1,118 @@ package com.modularmc.mmclutils.api.inventory; -import net.neoforged.neoforge.transfer.ResourceHandler; -import net.neoforged.neoforge.transfer.resource.Resource; -import net.neoforged.neoforge.transfer.transaction.Transaction; -import net.neoforged.neoforge.transfer.transaction.TransactionContext; - -import org.jspecify.annotations.Nullable; +import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.items.IItemHandlerModifiable; +import net.neoforged.neoforge.items.ItemHandlerHelper; /** - * 在所属线程中仿真连续插入和提取,复用存储自身的规则。 - * 在关闭或重置前,同一线程通过原始存储能看到仿真中的数量。使用 try-with-resources 限定作用范围。 - * - * @param 存储的资源类型 + * 保存物品槽位,在库存的所属线程执行连续插入和提取。 + * 阶段性值会被原库存读到并触发库存的变更通知。关闭前未提交时,按槽位恢复原值。 */ -public final class ResourceTransferSimulation implements AutoCloseable { - - private final ResourceHandler storage; - private final @Nullable TransactionContext parent; - private @Nullable Transaction transaction; +public final class ResourceTransferSimulation implements AutoCloseable { - /** 在独立的事务中打开仿真,仿真结束时回滚。 */ - public ResourceTransferSimulation(ResourceHandler storage) { - this(storage, null); - } + private final IItemHandlerModifiable storage; + private final ItemStack[] original; + private boolean closed; - /** 在指定外层事务的当前状态上开始仿真。外层为空时使用独立事务。 */ - public ResourceTransferSimulation(ResourceHandler storage, @Nullable TransactionContext parent) { + /** 在槽位布局固定的库存上开始一轮仿真。 */ + public ResourceTransferSimulation(IItemHandlerModifiable storage) { this.storage = storage; - this.parent = parent; - transaction = Transaction.open(parent); + original = new ItemStack[storage.getSlots()]; + for (int slot = 0; slot < original.length; slot++) { + original[slot] = storage.getStackInSlot(slot).copy(); + } } /** 返回存储的槽位数。 */ public int size() { - return storage.size(); + return original.length; } - /** 查询指定槽位当前的资源,空槽由存储返回空资源。 */ - public R resource(int index) { - return storage.getResource(index); + /** 取得槽位物品的副本,包含本轮仿真的改动。 */ + public ItemStack resource(int index) { + return storage.getStackInSlot(index).copy(); } /** 返回指定槽位的当前数量,包含本轮仿真的改动。 */ public long amount(int index) { - return storage.getAmountAsLong(index); + return storage.getStackInSlot(index).getCount(); } - /** - * 查询指定资源在此槽位的容量。该值由存储提供,可用于估算,实际插入仍由事务验证。 - * - * @param index 槽位索引 - * @param resource 待查询的资源,空资源查询槽位通用容量 - * @return 槽位容量 - */ - public long capacity(int index, R resource) { - return storage.getCapacityAsLong(index, resource); + /** 查询指定物品在此槽位的容量。空栈用于查询槽位通用容量。 */ + public long capacity(int index, ItemStack resource) { + int limit = storage.getSlotLimit(index); + return resource.isEmpty() ? limit : Math.min(limit, resource.getMaxStackSize()); } - /** 按存储的插入顺序尝试插入,返回成功量。 */ - public int insert(R resource, int amount) { - return storage.insert(resource, amount, active()); + /** 优先插入已有同类物品的槽位,返回成功量。 */ + public int insert(ItemStack resource, int amount) { + checkActive(resource, amount); + return amount - ItemHandlerHelper.insertItemStacked(storage, resource.copyWithCount(amount), false).getCount(); } - /** 尝试向指定槽位插入非空资源,并返回本轮实际接受的数量。 */ - public int insert(int index, R resource, int amount) { - return storage.insert(index, resource, amount, active()); + /** 尝试向指定槽位插入非空物品,并返回接受的数量。 */ + public int insert(int index, ItemStack resource, int amount) { + checkActive(resource, amount); + return amount - storage.insertItem(index, resource.copyWithCount(amount), false).getCount(); } - /** 按存储的提取顺序提取指定资源,并返回本轮实际提取的数量。 */ - public int extract(R resource, int amount) { - return storage.extract(resource, amount, active()); + /** 按槽位顺序提取指定物品,并返回提取的数量。 */ + public int extract(ItemStack resource, int amount) { + checkActive(resource, amount); + int remaining = amount; + for (int slot = 0; slot < size() && remaining > 0; slot++) { + remaining -= extract(slot, resource, remaining); + } + return amount - remaining; } - /** 从指定槽位提取资源,并返回本轮实际提取的数量。 */ - public int extract(int index, R resource, int amount) { - return storage.extract(index, resource, amount, active()); + /** 从指定槽位提取物品,并返回提取的数量。 */ + public int extract(int index, ItemStack resource, int amount) { + checkActive(resource, amount); + int remaining = amount; + while (remaining > 0 && ItemStack.isSameItemSameComponents(storage.getStackInSlot(index), resource)) { + int removed = storage.extractItem(index, remaining, false).getCount(); + if (removed == 0) break; + remaining -= removed; + } + return amount - remaining; } - /** 回滚仿真中的所有改动,开启新一轮。 */ + /** 保留本轮对槽位的改动并结束仿真。 */ + public void commit() { + ensureOpen(); + closed = true; + } + + /** 恢复槽位,开启新一轮。 */ public void reset() { - active().close(); - transaction = Transaction.open(parent); + ensureOpen(); + restore(); + } + + private void checkActive(ItemStack resource, int amount) { + ensureOpen(); + if (resource.isEmpty() || amount < 0) throw new IllegalArgumentException("物品应为非空且转移数量应为非负数"); } - private Transaction active() { - if (transaction == null) throw new IllegalStateException("转移仿真已关闭"); - return transaction; + private void ensureOpen() { + if (closed) throw new IllegalStateException("转移仿真已关闭"); + } + + private void restore() { + for (int slot = 0; slot < original.length; slot++) { + if (!ItemStack.matches(original[slot], storage.getStackInSlot(slot))) { + storage.setStackInSlot(slot, original[slot].copy()); + } + } } - /** 关闭事务,恢复仿真开始前的存储状态。 */ + /** 结束仿真,未提交时恢复原库存。 */ @Override public void close() { - if (transaction != null) { - transaction.close(); - transaction = null; + if (!closed) { + restore(); + closed = true; } } } diff --git a/src/main/java/com/modularmc/mmclutils/api/level/AreaBlockActions.java b/src/main/java/com/modularmc/mmclutils/api/level/AreaBlockActions.java index 1bd0d5e..a62afc1 100644 --- a/src/main/java/com/modularmc/mmclutils/api/level/AreaBlockActions.java +++ b/src/main/java/com/modularmc/mmclutils/api/level/AreaBlockActions.java @@ -26,8 +26,8 @@ public static long box(ServerLevel level, BlockPos first, BlockPos second, Actio /** 两角按区块坐标传入,覆盖其间所有区块的完整高度。 */ public static long chunks(ServerLevel level, int firstX, int firstZ, int secondX, int secondZ, Action action) { - return visit(level, Math.multiplyExact(Math.min(firstX, secondX), 16), level.getMinY(), Math.multiplyExact(Math.min(firstZ, secondZ), 16), - Math.multiplyExact(Math.max(firstX, secondX), 16) + 15, level.getMaxY(), Math.multiplyExact(Math.max(firstZ, secondZ), 16) + 15, pos -> true, action); + return visit(level, Math.multiplyExact(Math.min(firstX, secondX), 16), level.getMinBuildHeight(), Math.multiplyExact(Math.min(firstZ, secondZ), 16), + Math.multiplyExact(Math.max(firstX, secondX), 16) + 15, level.getMaxBuildHeight() - 1, Math.multiplyExact(Math.max(firstZ, secondZ), 16) + 15, pos -> true, action); } /** 按水平方向的圆形距离筛选指定高度区间的方块。负半径将被拒绝。 */ @@ -90,8 +90,8 @@ public static Task schedule(ServerLevel level, LongIterator positions, int limit private static long visit(ServerLevel level, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, LongPredicate contains, Action action) { checkThread(level); - minY = Math.max(minY, level.getMinY()); - maxY = Math.min(maxY, level.getMaxY()); + minY = Math.max(minY, level.getMinBuildHeight()); + maxY = Math.min(maxY, level.getMaxBuildHeight() - 1); if (minY > maxY) return 0; if (BlockPos.getX(BlockPos.asLong(minX, 0, 0)) != minX || BlockPos.getX(BlockPos.asLong(maxX, 0, 0)) != maxX || BlockPos.getZ(BlockPos.asLong(0, 0, minZ)) != minZ || BlockPos.getZ(BlockPos.asLong(0, 0, maxZ)) != maxZ) { throw new IllegalArgumentException("区域超出可编码的方块坐标"); diff --git a/src/main/java/com/modularmc/mmclutils/api/level/BlockRange.java b/src/main/java/com/modularmc/mmclutils/api/level/BlockRange.java index 687f78f..cf61d82 100644 --- a/src/main/java/com/modularmc/mmclutils/api/level/BlockRange.java +++ b/src/main/java/com/modularmc/mmclutils/api/level/BlockRange.java @@ -202,8 +202,8 @@ public AABB bounds() { /** 将包围盒裁切到世界的建造高度。完全落在世界外时,返回贴在相邻边界的零高包围盒。 */ public AABB bounds(LevelHeightAccessor height) { int y = BlockPos.getY(center); - int minY = height.getMinY(); - double endY = (double) height.getMaxY() + 1; + int minY = height.getMinBuildHeight(); + double endY = height.getMaxBuildHeight(); return bounds(Math.clamp((double) y - below, minY, endY), Math.clamp((double) y + above + 1, minY, endY)); } diff --git a/src/main/java/com/modularmc/mmclutils/api/recipe/ShapedRecipePatterns.java b/src/main/java/com/modularmc/mmclutils/api/recipe/ShapedRecipePatterns.java index ff1267c..0b7d843 100644 --- a/src/main/java/com/modularmc/mmclutils/api/recipe/ShapedRecipePatterns.java +++ b/src/main/java/com/modularmc/mmclutils/api/recipe/ShapedRecipePatterns.java @@ -25,7 +25,10 @@ private ShapedRecipePatterns() {} * @return 按材料首次出现顺序分配字符的图案 */ public static Pattern of(ShapedRecipePattern pattern) { - return of(pattern.ingredients(), pattern.width(), pattern.height()); + var ingredients = pattern.ingredients().stream() + .map(ingredient -> ingredient.isEmpty() ? Optional.empty() : Optional.of(ingredient)) + .toList(); + return of(ingredients, pattern.width(), pattern.height()); } /** diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/ServerExecutors.java b/src/main/java/com/modularmc/mmclutils/api/schedule/ServerExecutors.java index aef11b0..2c05e97 100644 --- a/src/main/java/com/modularmc/mmclutils/api/schedule/ServerExecutors.java +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/ServerExecutors.java @@ -2,7 +2,7 @@ import com.modularmc.mmclutils.ModularMCLibUtils; -import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.neoforged.bus.api.SubscribeEvent; import net.neoforged.fml.common.EventBusSubscriber; @@ -15,12 +15,12 @@ @EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID) public final class ServerExecutors { - private static final Reference2ObjectOpenHashMap> SERVERS = new Reference2ObjectOpenHashMap<>(); + private static final Reference2ObjectOpenHashMap> SERVERS = new Reference2ObjectOpenHashMap<>(); private ServerExecutors() {} /** 在所属服务器线程上取得执行器。后台只应使用与游戏线程分离的数据。 */ - public static synchronized PriorityTaskExecutor priority(MinecraftServer server, Identifier id) { + public static synchronized PriorityTaskExecutor priority(MinecraftServer server, ResourceLocation id) { if (!server.isSameThread()) throw new IllegalStateException("须在所属服务器线程取得执行器"); return SERVERS.computeIfAbsent(server, ignored -> new Object2ObjectOpenHashMap<>()) .computeIfAbsent(id, key -> new PriorityTaskExecutor(key.toString())); @@ -28,7 +28,7 @@ public static synchronized PriorityTaskExecutor priority(MinecraftServer server, @SubscribeEvent private static void release(ServerStoppedEvent event) { - Object2ObjectOpenHashMap executors; + Object2ObjectOpenHashMap executors; synchronized (ServerExecutors.class) { executors = SERVERS.remove(event.getServer()); } diff --git a/src/main/java/com/modularmc/mmclutils/client/gui/GuiUtils.java b/src/main/java/com/modularmc/mmclutils/client/gui/GuiUtils.java index b26cfe2..5b35fd9 100644 --- a/src/main/java/com/modularmc/mmclutils/client/gui/GuiUtils.java +++ b/src/main/java/com/modularmc/mmclutils/client/gui/GuiUtils.java @@ -1,16 +1,9 @@ package com.modularmc.mmclutils.client.gui; -import net.minecraft.client.gui.GuiGraphicsExtractor; -import net.minecraft.client.gui.navigation.ScreenRectangle; -import net.minecraft.client.gui.render.TextureSetup; -import net.minecraft.client.renderer.RenderPipelines; -import net.minecraft.client.renderer.state.gui.GuiElementRenderState; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.renderer.RenderType; -import com.mojang.blaze3d.pipeline.RenderPipeline; import com.mojang.blaze3d.vertex.VertexConsumer; -import org.joml.Matrix3x2f; -import org.joml.Matrix3x2fc; -import org.jspecify.annotations.Nullable; /** 绘制原版界面中的渐变矩形并计算列表行和滚动条布局。 */ public final class GuiUtils { @@ -19,47 +12,29 @@ public final class GuiUtils { private GuiUtils() {} - /** 用原版 GUI 管线提交从左到右的 ARGB 渐变。矩形使用当前姿态和裁剪范围。 */ - public static void fillHorizontalGradient(GuiGraphicsExtractor graphics, int left, int top, int right, int bottom, + /** 用原版 GUI 渲染类型绘制从左到右的 ARGB 渐变,沿用当前姿态和裁剪范围。 */ + public static void fillHorizontalGradient(GuiGraphics graphics, int left, int top, int right, int bottom, int leftColor, int rightColor) { - fillGradient(graphics, RenderPipelines.GUI, left, top, right, bottom, leftColor, leftColor, rightColor, rightColor); + fillGradient(graphics, RenderType.gui(), left, top, right, bottom, leftColor, leftColor, rightColor, rightColor); } - /** 使用指定的位置和颜色管线提交水平渐变。调用方传入两侧的 ARGB 颜色。 */ - public static void fillHorizontalGradient(GuiGraphicsExtractor graphics, RenderPipeline pipeline, int left, int top, + /** 使用指定的位置和颜色渲染类型绘制水平渐变。调用方传入两侧的 ARGB 颜色。 */ + public static void fillHorizontalGradient(GuiGraphics graphics, RenderType layer, int left, int top, int right, int bottom, int leftColor, int rightColor) { - fillGradient(graphics, pipeline, left, top, right, bottom, leftColor, leftColor, rightColor, rightColor); + fillGradient(graphics, layer, left, top, right, bottom, leftColor, leftColor, rightColor, rightColor); } - /** 管线须使用位置和颜色顶点格式。颜色依次对应左上、左下、右下和右上。 */ - public static void fillGradient(GuiGraphicsExtractor graphics, RenderPipeline pipeline, int left, int top, int right, int bottom, + /** 渲染类型须使用位置和颜色顶点格式。颜色依次对应左上、左下、右下和右上。 */ + public static void fillGradient(GuiGraphics graphics, RenderType layer, int left, int top, int right, int bottom, int topLeft, int bottomLeft, int bottomRight, int topRight) { if (left >= right || top >= bottom) return; - var pose = new Matrix3x2f(graphics.pose()); - ScreenRectangle scissor = graphics.peekScissorStack(); - ScreenRectangle bounds = new ScreenRectangle(left, top, right - left, bottom - top).transformMaxBounds(pose); - if (scissor != null) bounds = bounds.intersection(scissor); - if (bounds == null) return; - graphics.submitGuiElementRenderState( - new Gradient(pipeline, pose, scissor, bounds, left, top, right, bottom, topLeft, bottomLeft, bottomRight, topRight)); - } - - private record Gradient(RenderPipeline pipeline, Matrix3x2fc pose, @Nullable ScreenRectangle scissorArea, ScreenRectangle bounds, - int left, int top, int right, int bottom, int topLeft, int bottomLeft, int bottomRight, int topRight) - implements GuiElementRenderState { - - @Override - public TextureSetup textureSetup() { - return TextureSetup.noTexture(); - } - - @Override - public void buildVertices(VertexConsumer vertices) { - vertices.addVertexWith2DPose(pose, left, top).setColor(topLeft); - vertices.addVertexWith2DPose(pose, left, bottom).setColor(bottomLeft); - vertices.addVertexWith2DPose(pose, right, bottom).setColor(bottomRight); - vertices.addVertexWith2DPose(pose, right, top).setColor(topRight); - } + var pose = graphics.pose().last().pose(); + VertexConsumer vertices = graphics.bufferSource().getBuffer(layer); + vertices.addVertex(pose, left, top, 0).setColor(topLeft); + vertices.addVertex(pose, left, bottom, 0).setColor(bottomLeft); + vertices.addVertex(pose, right, bottom, 0).setColor(bottomRight); + vertices.addVertex(pose, right, top, 0).setColor(topRight); + graphics.flush(); } /** 把零到一的列表进度换算成整像素宽度,最大值比行宽少一像素以保留行边界。 */ diff --git a/src/main/java/com/modularmc/mmclutils/client/input/ClientInput.java b/src/main/java/com/modularmc/mmclutils/client/input/ClientInput.java index e9e2c77..d540a06 100644 --- a/src/main/java/com/modularmc/mmclutils/client/input/ClientInput.java +++ b/src/main/java/com/modularmc/mmclutils/client/input/ClientInput.java @@ -1,7 +1,7 @@ package com.modularmc.mmclutils.client.input; import net.minecraft.client.KeyMapping; -import net.minecraft.client.input.InputQuirks; +import net.minecraft.client.Minecraft; import net.neoforged.neoforge.client.settings.KeyConflictContext; import net.neoforged.neoforge.client.settings.KeyModifier; @@ -28,14 +28,19 @@ private ClientInput() {} /** 读取当前按下的全部修饰键并组成位掩码。请在客户端线程调用。 */ public static int modifiers() { - return (KeyModifier.CONTROL.isActive(KeyConflictContext.UNIVERSAL) ? CONTROL : 0) | (KeyModifier.SHIFT.isActive(KeyConflictContext.UNIVERSAL) ? SHIFT : 0) | (KeyModifier.ALT.isActive(KeyConflictContext.UNIVERSAL) ? ALT : 0) | (InputQuirks.REPLACE_CTRL_KEY_WITH_CMD_KEY && KeyModifier.CONTROL_OR_COMMAND.isActive(KeyConflictContext.UNIVERSAL) ? COMMAND : 0); + long window = Minecraft.getInstance().getWindow().getWindow(); + boolean control = InputConstants.isKeyDown(window, GLFW.GLFW_KEY_LEFT_CONTROL) || + InputConstants.isKeyDown(window, GLFW.GLFW_KEY_RIGHT_CONTROL); + boolean command = Minecraft.ON_OSX && KeyModifier.CONTROL.isActive(KeyConflictContext.UNIVERSAL); + return (control ? CONTROL : 0) | (command ? COMMAND : 0) | + (KeyModifier.SHIFT.isActive(KeyConflictContext.UNIVERSAL) ? SHIFT : 0) | + (KeyModifier.ALT.isActive(KeyConflictContext.UNIVERSAL) ? ALT : 0); } /** 将 NeoForge 修饰键转换成当前平台的掩码位。无修饰键则返回零。 */ public static int modifierBit(KeyModifier modifier) { return switch (modifier) { - case CONTROL -> CONTROL; - case CONTROL_OR_COMMAND -> InputQuirks.REPLACE_CTRL_KEY_WITH_CMD_KEY ? COMMAND : CONTROL; + case CONTROL -> Minecraft.ON_OSX ? COMMAND : CONTROL; case SHIFT -> SHIFT; case ALT -> ALT; case NONE -> 0; @@ -44,11 +49,12 @@ public static int modifierBit(KeyModifier modifier) { /** 把输入键转换成对应修饰位。普通输入键或不受支持的 Command 键返回零。 */ public static int keyModifierBit(InputConstants.Key key) { - int code = key.getValue(); - if (key.getType() == InputConstants.Type.KEYSYM && (code == GLFW.GLFW_KEY_LEFT_SUPER || code == GLFW.GLFW_KEY_RIGHT_SUPER)) { - return InputQuirks.REPLACE_CTRL_KEY_WITH_CMD_KEY ? COMMAND : 0; - } - return modifierBit(KeyModifier.getKeyModifier(key)); + if (key.getType() != InputConstants.Type.KEYSYM) return 0; + return switch (key.getValue()) { + case GLFW.GLFW_KEY_LEFT_CONTROL, GLFW.GLFW_KEY_RIGHT_CONTROL -> CONTROL; + case GLFW.GLFW_KEY_LEFT_SUPER, GLFW.GLFW_KEY_RIGHT_SUPER -> Minecraft.ON_OSX ? COMMAND : 0; + default -> modifierBit(KeyModifier.getKeyModifier(key)); + }; } /** 直接读取主键。扫描码使用原版记录的状态,当前输入事件可以提供更早的状态变化。 */ @@ -57,8 +63,8 @@ public static boolean mainKeyDown(Window window, KeyMapping mapping, InputConsta InputConstants.Key key = mapping.getKey(); if (key.equals(changed)) return down; return switch (key.getType()) { - case KEYSYM -> InputConstants.isKeyDown(window, key.getValue()); - case MOUSE -> GLFW.glfwGetMouseButton(window.handle(), key.getValue()) == GLFW.GLFW_PRESS; + case KEYSYM -> InputConstants.isKeyDown(window.getWindow(), key.getValue()); + case MOUSE -> GLFW.glfwGetMouseButton(window.getWindow(), key.getValue()) == GLFW.GLFW_PRESS; case SCANCODE -> mapping.isDown(); }; } diff --git a/src/main/java/com/modularmc/mmclutils/client/input/ClientKeyBindings.java b/src/main/java/com/modularmc/mmclutils/client/input/ClientKeyBindings.java index 8cbc16f..9f9fb97 100644 --- a/src/main/java/com/modularmc/mmclutils/client/input/ClientKeyBindings.java +++ b/src/main/java/com/modularmc/mmclutils/client/input/ClientKeyBindings.java @@ -9,7 +9,7 @@ import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.options.controls.KeyBindsScreen; import net.minecraft.client.player.LocalPlayer; -import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceLocation; import net.neoforged.api.distmarker.Dist; import net.neoforged.bus.api.EventPriority; import net.neoforged.bus.api.IEventBus; @@ -87,7 +87,7 @@ private static void sampleTick(ClientTickEvent.Pre event) { @SubscribeEvent private static void sampleKeyboard(InputEvent.Key event) { if (event.getAction() != GLFW.GLFW_REPEAT) { - sample(InputConstants.getKey(event.getKeyEvent()), event.getAction() == GLFW.GLFW_PRESS); + sample(InputConstants.getKey(event.getKey(), event.getScanCode()), event.getAction() == GLFW.GLFW_PRESS); } } @@ -112,7 +112,7 @@ private static void onScreenKey(ScreenEvent.KeyPressed.Pre event) { Minecraft client = Minecraft.getInstance(); double x = client.mouseHandler.xpos() * event.getScreen().width / client.getWindow().getScreenWidth(); double y = client.mouseHandler.ypos() * event.getScreen().height / client.getWindow().getScreenHeight(); - if (dispatchScreen(event.getScreen(), InputConstants.getKey(event.getKeyEvent()), x, y)) event.setCanceled(true); + if (dispatchScreen(event.getScreen(), InputConstants.getKey(event.getKeyCode(), event.getScanCode()), x, y)) event.setCanceled(true); } @SubscribeEvent @@ -180,7 +180,7 @@ private static void sample(InputConstants.@Nullable Key changed, boolean down) { } private static void send(ObjectArrayList changes, Consumer send) { - var payload = new Object2BooleanLinkedOpenHashMap(Math.min(changes.size(), ChangeSet.MAX_CHANGES)); + var payload = new Object2BooleanLinkedOpenHashMap(Math.min(changes.size(), ChangeSet.MAX_CHANGES)); for (Binding binding : changes) { payload.put(binding.key.id(), binding.down); if (payload.size() == ChangeSet.MAX_CHANGES) { diff --git a/src/main/java/com/modularmc/mmclutils/client/input/KeyChordMapping.java b/src/main/java/com/modularmc/mmclutils/client/input/KeyChordMapping.java index abab894..56c1340 100644 --- a/src/main/java/com/modularmc/mmclutils/client/input/KeyChordMapping.java +++ b/src/main/java/com/modularmc/mmclutils/client/input/KeyChordMapping.java @@ -3,6 +3,7 @@ import com.modularmc.mmclutils.ModularMCLibUtils; import net.minecraft.client.KeyMapping; +import net.minecraft.client.Minecraft; import net.minecraft.client.Options; import net.minecraft.network.chat.Component; import net.neoforged.neoforge.client.settings.IKeyConflictContext; @@ -18,8 +19,7 @@ /** 可在控制设置中编辑和保存的组合键。只在客户端线程读写。 */ public final class KeyChordMapping extends KeyMapping { - private static final KeyModifier[] DISPLAY_ORDER = { KeyModifier.ALT, KeyModifier.SHIFT, KeyModifier.CONTROL, - KeyModifier.CONTROL_OR_COMMAND }; + private static final KeyModifier[] DISPLAY_ORDER = { KeyModifier.ALT, KeyModifier.SHIFT, KeyModifier.CONTROL }; private final int defaultModifiers; /** 当前组合要求的完整修饰键掩码。 */ @Getter @@ -28,14 +28,14 @@ public final class KeyChordMapping extends KeyMapping { private @Nullable LegacyOptions legacyOptions; /** 用主键和修饰掩码创建绑定,自动去掉掩码中与主键重复的修饰位。 */ - public KeyChordMapping(String name, Category category, IKeyConflictContext context, InputConstants.Key key, int modifiers) { + public KeyChordMapping(String name, String category, IKeyConflictContext context, InputConstants.Key key, int modifiers) { super(name, context, primary(normalize(key, modifiers)), key, category); defaultModifiers = normalize(key, modifiers); this.modifiers = defaultModifiers; } /** 用输入类型和按键编号创建组合。编号的解释遵循对应的原版输入类型。 */ - public KeyChordMapping(String name, Category category, IKeyConflictContext context, InputConstants.Type type, int key, int modifiers) { + public KeyChordMapping(String name, String category, IKeyConflictContext context, InputConstants.Type type, int key, int modifiers) { this(name, category, context, type.getOrCreate(key), modifiers); } @@ -91,12 +91,12 @@ public void setToDefault() { public Component getTranslatedKeyMessage() { Component result = getKey().getDisplayName(); for (KeyModifier modifier : DISPLAY_ORDER) { - if (modifier == KeyModifier.CONTROL_OR_COMMAND && ClientInput.modifierBit(modifier) != ClientInput.COMMAND) continue; if ((modifiers & ClientInput.modifierBit(modifier)) == 0) continue; Component suffix = result; result = modifier.getCombinedName(getKey(), () -> suffix); } - return result; + return Minecraft.ON_OSX && (modifiers & ClientInput.CONTROL) != 0 ? + Component.translatable("neoforge.controlsgui.control", result) : result; } @Override @@ -151,7 +151,9 @@ private String optionPrefix() { private void readModifiers(String saved) { String prefix = optionPrefix(); - if (!saved.startsWith(prefix) || saved.equals(prefix + modifiers)) return; + String legacyPrefix = getKey().getName() + ":CONTROL_OR_COMMAND:"; + if (saved.startsWith(legacyPrefix)) prefix = legacyPrefix; + if (!saved.startsWith(prefix) || saved.equals(optionPrefix() + modifiers)) return; try { setChord(getKey(), Integer.parseInt(saved.substring(prefix.length()))); } catch (IllegalArgumentException failure) { @@ -169,8 +171,7 @@ private static int normalize(InputConstants.Key key, int modifiers) { } private static KeyModifier primary(int modifiers) { - if ((modifiers & ClientInput.CONTROL) != 0) return KeyModifier.CONTROL; - if ((modifiers & ClientInput.COMMAND) != 0) return KeyModifier.CONTROL_OR_COMMAND; + if ((modifiers & (Minecraft.ON_OSX ? ClientInput.COMMAND : ClientInput.CONTROL)) != 0) return KeyModifier.CONTROL; if ((modifiers & ClientInput.SHIFT) != 0) return KeyModifier.SHIFT; return (modifiers & ClientInput.ALT) != 0 ? KeyModifier.ALT : KeyModifier.NONE; } diff --git a/src/main/java/com/modularmc/mmclutils/client/level/ClientChunkVisibility.java b/src/main/java/com/modularmc/mmclutils/client/level/ClientChunkVisibility.java index 8c716ea..df1fb09 100644 --- a/src/main/java/com/modularmc/mmclutils/client/level/ClientChunkVisibility.java +++ b/src/main/java/com/modularmc/mmclutils/client/level/ClientChunkVisibility.java @@ -56,7 +56,7 @@ public static void sync(View view) { LevelChunk chunk = chunks.get(i); if (chunk == null) continue; ChunkPos pos = chunk.getPos(); - BlockEntityTracking.setVisible(chunk, view.mmclutils$inRange(pos.x(), pos.z())); + BlockEntityTracking.setVisible(chunk, view.mmclutils$inRange(pos.x, pos.z)); } } } diff --git a/src/main/java/com/modularmc/mmclutils/client/model/BlockModelRotation.java b/src/main/java/com/modularmc/mmclutils/client/model/BlockModelRotation.java index 53cb216..4175c99 100644 --- a/src/main/java/com/modularmc/mmclutils/client/model/BlockModelRotation.java +++ b/src/main/java/com/modularmc/mmclutils/client/model/BlockModelRotation.java @@ -1,13 +1,12 @@ package com.modularmc.mmclutils.client.model; -import net.minecraft.client.renderer.block.dispatch.Variant; -import net.minecraft.client.renderer.block.dispatch.Variant.SimpleModelState; +import net.minecraft.client.renderer.block.model.Variant; import net.minecraft.core.Direction; +import net.minecraft.util.Mth; -import com.mojang.math.OctahedralGroup; -import com.mojang.math.Quadrant; import com.mojang.math.Transformation; import lombok.Getter; +import org.joml.Quaternionf; /** * 记录可定向方块的 24 种正交旋转。每个枚举值的前缀是世界前向,后缀是用水平方向编码的滚转。 @@ -52,7 +51,6 @@ public enum BlockModelRotation { /** 按原版方向编号和水平旋转编号索引的旋转表。调用方应将数组视为只读。 */ public static final BlockModelRotation[] VALUES = values(); - private static final SimpleModelState[] VARIANT_STATES = createVariantStates(); /** 模型绕 X 轴旋转的角度,以度为单位。 */ @Getter @@ -107,7 +105,11 @@ public Variant rotate(Variant variant) { * @throws IllegalArgumentException 任一轴的角度不是 0、90、180 或 270 度 */ public static Transformation transformation(int x, int y, int z) { - return rotationState(x, y, z).asModelState().transformation(); + checkAngle(x); + checkAngle(y); + checkAngle(z); + var rotation = new Quaternionf().rotateY(-y * Mth.DEG_TO_RAD).rotateX(-x * Mth.DEG_TO_RAD).rotateZ(-z * Mth.DEG_TO_RAD); + return new Transformation(null, rotation, null, null); } /** @@ -121,36 +123,12 @@ public static Transformation transformation(int x, int y, int z) { * @throws IllegalArgumentException 任一轴的角度不是 0、90、180 或 270 度 */ public static Variant rotate(Variant variant, int x, int y, int z) { - return variant.withState(rotationState(x, y, z).withUvLock(variant.modelState().uvLock())); + return new Variant(variant.getModelLocation(), transformation(x, y, z), variant.isUvLocked(), variant.getWeight()); } - private static SimpleModelState rotationState(int x, int y, int z) { - OctahedralGroup group = Quadrant.fromXYAngles(quadrant(x), quadrant(y)).compose(quadrant(z).rotationZ); - return VARIANT_STATES[group.ordinal()]; - } - - private static SimpleModelState[] createVariantStates() { - var states = new SimpleModelState[OctahedralGroup.values().length]; - Quadrant[] angles = Quadrant.values(); - // 原版变体最后绕世界 Z 轴旋转,按变换结果查出等价的原版角度以沿用 UV 锁定和序列化。 - for (Quadrant z : angles) { - for (Quadrant y : angles) { - for (Quadrant x : angles) { - int index = Quadrant.fromXYZAngles(x, y, z).ordinal(); - if (states[index] == null) states[index] = new SimpleModelState(x, y, z, false); - } - } + private static void checkAngle(int angle) { + if (angle != 0 && angle != 90 && angle != 180 && angle != 270) { + throw new IllegalArgumentException("模型旋转角度无效 " + angle); } - return states; - } - - private static Quadrant quadrant(int angle) { - return switch (angle) { - case 0 -> Quadrant.R0; - case 90 -> Quadrant.R90; - case 180 -> Quadrant.R180; - case 270 -> Quadrant.R270; - default -> throw new IllegalArgumentException("模型旋转角度无效 " + angle); - }; } } diff --git a/src/main/java/com/modularmc/mmclutils/client/model/BlockTintView.java b/src/main/java/com/modularmc/mmclutils/client/model/BlockTintView.java index dc94e96..e218be2 100644 --- a/src/main/java/com/modularmc/mmclutils/client/model/BlockTintView.java +++ b/src/main/java/com/modularmc/mmclutils/client/model/BlockTintView.java @@ -1,8 +1,8 @@ package com.modularmc.mmclutils.client.model; -import net.minecraft.client.renderer.block.BlockAndTintGetter; import net.minecraft.core.BlockPos; -import net.minecraft.world.level.CardinalLighting; +import net.minecraft.core.Direction; +import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.ColorResolver; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; @@ -21,8 +21,8 @@ public BlockTintView(BlockAndTintGetter parent, BlockPos position, BlockState st } @Override - public CardinalLighting cardinalLighting() { - return parent.cardinalLighting(); + public float getShade(Direction direction, boolean shade) { + return parent.getShade(direction, shade); } @Override @@ -56,7 +56,7 @@ public int getHeight() { } @Override - public int getMinY() { - return parent.getMinY(); + public int getMinBuildHeight() { + return parent.getMinBuildHeight(); } } diff --git a/src/main/java/com/modularmc/mmclutils/client/model/ConnectedTextureUtils.java b/src/main/java/com/modularmc/mmclutils/client/model/ConnectedTextureUtils.java index 59fd156..c536da6 100644 --- a/src/main/java/com/modularmc/mmclutils/client/model/ConnectedTextureUtils.java +++ b/src/main/java/com/modularmc/mmclutils/client/model/ConnectedTextureUtils.java @@ -1,21 +1,20 @@ package com.modularmc.mmclutils.client.model; import com.modularmc.mmclutils.client.model.QuadUtils.Face; +import com.modularmc.mmclutils.client.model.QuadView.MaterialInfo; -import net.minecraft.client.renderer.block.BlockAndTintGetter; -import net.minecraft.client.renderer.block.dispatch.BlockStateModel; -import net.minecraft.client.renderer.block.dispatch.BlockStateModelPart; -import net.minecraft.client.resources.model.geometry.BakedQuad; -import net.minecraft.client.resources.model.geometry.BakedQuad.MaterialInfo; -import net.minecraft.client.resources.model.geometry.QuadCollection; -import net.minecraft.client.resources.model.sprite.Material; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.resources.model.BakedModel; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.util.Mth; import net.minecraft.util.RandomSource; -import net.minecraft.util.TriState; +import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.block.state.BlockState; -import net.neoforged.neoforge.client.model.DelegateBlockStateModel; +import net.neoforged.neoforge.client.model.BakedModelWrapper; +import net.neoforged.neoforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.data.ModelProperty; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectImmutableList; @@ -36,13 +35,12 @@ private ConnectedTextureUtils() {} /** * 包装能根据相邻方块更换表面的模型。无世界上下文的渲染沿用父模型。 * - * @param parent 提供基础几何和粒子材质的模型 - * @param replacementFlags 所有候选替换材质的 {@link MaterialInfo#flags()} 按位或 - * @param rule 根据世界上下文确定每个面的输出 + * @param parent 提供基础几何和粒子材质的模型 + * @param rule 根据世界上下文确定每个面的输出 * @return 保留父模型随机变体和光照行为的方块模型 */ - public static BlockStateModel wrap(BlockStateModel parent, @BakedQuad.MaterialFlags int replacementFlags, FaceRule rule) { - return new ConnectedModel(parent, replacementFlags, rule); + public static BakedModel wrap(BakedModel parent, FaceRule rule) { + return new ConnectedModel(parent, rule); } /** 四份材质按从左到右、从上到下排列。每个子面映射整个新贴图。 */ @@ -195,80 +193,50 @@ private static void moveVertex(MutableQuadView quad, int vertex, Direction face, } } - private static final class ConnectedModel extends DelegateBlockStateModel { + private static final class ConnectedModel extends BakedModelWrapper { - private final int replacementFlags; + private static final ModelProperty CONTEXT = new ModelProperty<>(); private final FaceRule rule; - private ConnectedModel(BlockStateModel parent, int replacementFlags, FaceRule rule) { + private ConnectedModel(BakedModel parent, FaceRule rule) { super(parent); - this.replacementFlags = replacementFlags; this.rule = rule; } @Override - public void collectParts(BlockAndTintGetter level, BlockPos pos, BlockState state, RandomSource random, - List parts) { - var source = new ObjectArrayList(); - delegate.collectParts(level, pos, state, random, source); - var geometry = new ObjectArrayList(); - for (BlockStateModelPart part : source) { - geometry.clear(); - boolean changed = collectFaces(level, pos, state, part, null, geometry); - for (Direction direction : DIRECTIONS) { - changed |= collectFaces(level, pos, state, part, direction, geometry); - } - parts.add(changed ? new ConnectedPart(part, QuadUtils.collect(geometry)) : part); - } + public ModelData getModelData(BlockAndTintGetter level, BlockPos pos, BlockState state, ModelData data) { + return super.getModelData(level, pos, state, data).derive().with(CONTEXT, new Context(level, pos.immutable())).build(); } - private boolean collectFaces(BlockAndTintGetter level, BlockPos pos, BlockState state, BlockStateModelPart part, - @Nullable Direction direction, ObjectList geometry) { - boolean changed = false; - for (BakedQuad quad : part.getQuads(direction)) { - var face = new Face(quad, direction); - Iterable replacement = rule.replace(level, pos, state, face); - if (replacement == null) geometry.add(face); - else { - changed = true; - replacement.forEach(geometry::add); - } + @Override + public List getQuads(@Nullable BlockState state, @Nullable Direction direction, RandomSource random, + ModelData data, @Nullable RenderType layer) { + Context context = data.get(CONTEXT); + if (context == null || state == null) return super.getQuads(state, direction, random, data, layer); + var output = new ObjectArrayList(); + // 同一个方块的各剔除组使用同一个加权变体,替换规则可以改变面的剔除方向。 + long seed = state.getSeed(context.pos()); + RandomSource sample = RandomSource.create(seed); + append(context, state, null, direction, sample, data, layer, output); + for (Direction side : DIRECTIONS) { + sample.setSeed(seed); + append(context, state, side, direction, sample, data, layer, output); } - return changed; + return output; } - @Override - public int materialFlags(BlockAndTintGetter level, BlockPos pos, BlockState state) { - return delegate.materialFlags(level, pos, state) | replacementFlags; + private void append(Context context, BlockState state, @Nullable Direction source, @Nullable Direction requested, + RandomSource random, ModelData data, @Nullable RenderType layer, List output) { + for (BakedQuad quad : originalModel.getQuads(state, source, random, data, layer)) { + Iterable replacement = rule.replace(context.level(), context.pos(), state, new Face(quad, source)); + if (replacement == null) { + if (source == requested) output.add(quad); + } else { + for (Face face : replacement) if (face.cullFace() == requested) output.add(face.quad()); + } + } } } - private record ConnectedPart(BlockStateModelPart parent, QuadCollection quads) implements BlockStateModelPart { - - @Override - public List getQuads(@Nullable Direction direction) { - return quads.getQuads(direction); - } - - @Override - public Material.Baked particleMaterial() { - return parent.particleMaterial(); - } - - @Override - @Deprecated - public boolean useAmbientOcclusion() { - return parent.useAmbientOcclusion(); - } - - @Override - public TriState ambientOcclusion() { - return parent.ambientOcclusion(); - } - - @Override - public int materialFlags() { - return quads.materialFlags(); - } - } + private record Context(BlockAndTintGetter level, BlockPos pos) {} } diff --git a/src/main/java/com/modularmc/mmclutils/client/model/ItemModelGenerator.java b/src/main/java/com/modularmc/mmclutils/client/model/ItemModelGenerator.java index 0ddcc2d..c147b9c 100644 --- a/src/main/java/com/modularmc/mmclutils/client/model/ItemModelGenerator.java +++ b/src/main/java/com/modularmc/mmclutils/client/model/ItemModelGenerator.java @@ -1,40 +1,42 @@ package com.modularmc.mmclutils.client.model; -import net.minecraft.client.color.item.ItemTintSource; -import net.minecraft.client.data.models.ItemModelOutput; -import net.minecraft.client.data.models.model.ItemModelUtils; -import net.minecraft.client.data.models.model.ModelInstance; -import net.minecraft.client.data.models.model.ModelTemplate; -import net.minecraft.client.data.models.model.ModelTemplates; -import net.minecraft.client.data.models.model.TextureMapping; -import net.minecraft.client.data.models.model.TextureSlot; -import net.minecraft.client.resources.model.sprite.Material; -import net.minecraft.resources.Identifier; +import net.minecraft.client.color.item.ItemColor; +import net.minecraft.data.models.model.ModelLocationUtils; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; +import net.neoforged.neoforge.client.event.RegisterColorHandlersEvent; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; import java.util.function.BiConsumer; +import java.util.function.Supplier; /** 生成多层原版物品模型并按图层次序绑定染色来源。 */ public final class ItemModelGenerator { private ItemModelGenerator() {} - /** 向数据生成输出登记带逐层染色的平面物品模型。材质和染色源按图层顺序一一对应。 */ - public static Identifier generated(Item item, ItemModelOutput items, BiConsumer models, - Material[] materials, ItemTintSource... tints) { - if (materials.length == 0 || materials.length != tints.length) { - throw new IllegalArgumentException("每一层图案须对应一个染色来源"); - } - var mapping = new TextureMapping(); - var slots = new TextureSlot[materials.length]; - for (int index = 0; index < materials.length; index++) { - TextureSlot slot = TextureSlot.create("layer" + index); - slots[index] = slot; - mapping.put(slot, materials[index]); - } - var template = new ModelTemplate(ModelTemplates.FLAT_ITEM.model, ModelTemplates.FLAT_ITEM.suffix, slots); - Identifier model = template.create(item, mapping, models); - items.accept(item, ItemModelUtils.tintedModel(model, tints)); + /** 登记原版平面物品模型,贴图按从底层到顶层排列。原版生成器支持一至五层。 */ + public static ResourceLocation generated(Item item, BiConsumer> models, + ResourceLocation... textures) { + if (textures.length == 0 || textures.length > 5) throw new IllegalArgumentException("物品模型须包含一至五层贴图"); + ResourceLocation model = ModelLocationUtils.getModelLocation(item); + ResourceLocation[] layers = textures.clone(); + models.accept(model, () -> { + var output = new JsonObject(); + output.addProperty("parent", "minecraft:item/generated"); + var mapping = new JsonObject(); + for (int index = 0; index < layers.length; index++) mapping.addProperty("layer" + index, layers[index].toString()); + output.add("textures", mapping); + return output; + }); return model; } + + /** 在客户端颜色注册时按图层登记染色回调。未登记染色的图层保持原色。 */ + public static void registerTints(RegisterColorHandlersEvent.Item event, Item item, ItemColor... tints) { + ItemColor[] layers = tints.clone(); + event.register((stack, index) -> index >= 0 && index < layers.length ? layers[index].getColor(stack, index) : -1, item); + } } diff --git a/src/main/java/com/modularmc/mmclutils/client/model/ModelUtils.java b/src/main/java/com/modularmc/mmclutils/client/model/ModelUtils.java index 104b74c..137b507 100644 --- a/src/main/java/com/modularmc/mmclutils/client/model/ModelUtils.java +++ b/src/main/java/com/modularmc/mmclutils/client/model/ModelUtils.java @@ -1,28 +1,29 @@ package com.modularmc.mmclutils.client.model; import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.SubmitNodeCollector; -import net.minecraft.client.renderer.block.BlockAndTintGetter; -import net.minecraft.client.renderer.block.BlockModelRenderState; -import net.minecraft.client.renderer.block.dispatch.BlockStateModel; -import net.minecraft.client.renderer.block.dispatch.BlockStateModelPart; -import net.minecraft.client.renderer.block.dispatch.SingleVariant; -import net.minecraft.client.renderer.block.model.BlockDisplayContext; -import net.minecraft.client.renderer.item.ItemModel; -import net.minecraft.client.renderer.item.ItemStackRenderState; -import net.minecraft.client.resources.model.geometry.BakedQuad; -import net.minecraft.client.resources.model.sprite.Material; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.ItemOverrides; +import net.minecraft.client.renderer.block.model.ItemTransforms; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.client.resources.model.SimpleBakedModel; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceLocation; import net.minecraft.util.RandomSource; -import net.minecraft.world.entity.ItemOwner; -import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.neoforged.neoforge.client.model.DelegateBlockStateModel; -import net.neoforged.neoforge.client.model.standalone.StandaloneModelKey; +import net.neoforged.neoforge.client.ChunkRenderTypeSet; +import net.neoforged.neoforge.client.RenderTypeGroup; +import net.neoforged.neoforge.client.model.BakedModelWrapper; +import net.neoforged.neoforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.data.ModelProperty; import com.mojang.blaze3d.vertex.PoseStack; import it.unimi.dsi.fastutil.objects.ObjectArrayList; @@ -30,9 +31,10 @@ import it.unimi.dsi.fastutil.objects.ObjectList; import org.jspecify.annotations.Nullable; +import java.util.EnumMap; import java.util.List; -/** 通过当前资源版本的原版模型解析器和提交器操作模型。 */ +/** 通过当前资源版本的原版烘焙模型解析器和渲染器操作模型。 */ public final class ModelUtils { private static final Direction[] DIRECTIONS = Direction.values(); @@ -40,141 +42,125 @@ public final class ModelUtils { private ModelUtils() {} /** 取得当前资源版本的方块状态模型。资源重载后应重新获取。 */ - public static BlockStateModel block(BlockState state) { - return Minecraft.getInstance().getModelManager().getBlockStateModelSet().get(state); + public static BakedModel block(BlockState state) { + return Minecraft.getInstance().getBlockRenderer().getBlockModel(state); } - /** 按物品模型标识查找当前已加载的模型。 */ - public static ItemModel item(Identifier model) { - return Minecraft.getInstance().getModelManager().getItemModel(model); + /** 按物品注册标识查找当前已加载的模型。 */ + public static BakedModel item(ResourceLocation model) { + return Minecraft.getInstance().getModelManager().getModel(ModelResourceLocation.inventory(model)); } - /** 按已注册键取得独立烘焙模型。键应已参与当前资源版本的模型加载。 */ - public static T standalone(StandaloneModelKey key) { - return Minecraft.getInstance().getModelManager().getStandaloneModel(key); + /** 取得通过 ModelEvent.RegisterAdditional 登记的独立模型。 */ + public static BakedModel standalone(ResourceLocation model) { + return Minecraft.getInstance().getModelManager().getModel(ModelResourceLocation.standalone(model)); } - /** 为该栈分配渲染状态并解析显示上下文、世界和持有者驱动的模型。 */ - public static ItemStackRenderState resolveItem(ItemStack stack, ItemDisplayContext context, - @Nullable Level level, @Nullable ItemOwner owner, int seed) { - var state = new ItemStackRenderState(); - resolveItem(state, stack, context, level, owner, seed); - return state; + /** 解析物品及其世界、持有者驱动的模型覆盖。世界和持有者可以为空。 */ + public static BakedModel resolveItem(ItemStack stack, @Nullable Level level, @Nullable LivingEntity owner, int seed) { + return Minecraft.getInstance().getItemRenderer().getModel(stack, level, owner, seed); } - /** 用当前模型解析器更新调用方提供的物品渲染状态。世界和持有者可以为空。 */ - public static void resolveItem(ItemStackRenderState output, ItemStack stack, ItemDisplayContext context, - @Nullable Level level, @Nullable ItemOwner owner, int seed) { - Minecraft.getInstance().getItemModelResolver().updateForTopItem(output, stack, context, level, owner, seed); - } - - /** 以指定显示上下文、姿态及亮度提交方块模型,提交器负责后续绘制。 */ - public static void submitBlock(BlockState block, BlockDisplayContext context, PoseStack poses, SubmitNodeCollector output, - int light, int overlay, int outlineColor) { - var state = new BlockModelRenderState(); - Minecraft.getInstance().getBlockModelResolver().update(state, block, context); - state.submit(poses, output, light, overlay, outlineColor); + /** 以指定姿态、亮度和覆盖层向渲染缓冲区绘制方块模型。 */ + public static void renderBlock(BlockState block, PoseStack poses, MultiBufferSource output, int light, int overlay) { + Minecraft.getInstance().getBlockRenderer().renderSingleBlock(block, poses, output, light, overlay); } /** 采集一次加权模型选择的全部通用面和各方向剔除面。 */ - public static ObjectList quads(BlockStateModel model, RandomSource random) { - var parts = new ObjectArrayList(); - model.collectParts(random, parts); - return quads(parts); + public static ObjectList quads(BakedModel model, RandomSource random) { + return quads(model, null, random, ModelData.EMPTY); } /** 使用当前方块视图读取模型。连接纹理等上下文相关模型从视图获取数据。 */ - public static ObjectList quads(BlockStateModel model, BlockAndTintGetter level, BlockPos pos, + public static ObjectList quads(BakedModel model, BlockAndTintGetter level, BlockPos pos, BlockState state, RandomSource random) { - var parts = new ObjectArrayList(); - model.collectParts(level, pos, state, random, parts); - return quads(parts); + return quads(model, state, random, model.getModelData(level, pos, state, ModelData.EMPTY)); } - /** 收集所有部件的通用面及六个方向的剔除分组。 */ - public static ObjectList quads(List parts) { + /** 收集模型的通用面及六个方向的剔除分组,各方向使用同一个变体种子。 */ + public static ObjectList quads(BakedModel model, @Nullable BlockState state, RandomSource random, + ModelData data) { var result = new ObjectArrayList(); - for (BlockStateModelPart part : parts) { - for (var quad : part.getQuads(null)) result.add(new QuadUtils.Face(quad, null)); - for (Direction direction : DIRECTIONS) { - for (var quad : part.getQuads(direction)) result.add(new QuadUtils.Face(quad, direction)); - } + long seed = random.nextLong(); + RandomSource sample = RandomSource.create(seed); + for (BakedQuad quad : model.getQuads(state, null, sample, data, null)) result.add(new QuadUtils.Face(quad, null)); + for (Direction direction : DIRECTIONS) { + sample.setSeed(seed); + for (BakedQuad quad : model.getQuads(state, direction, sample, data, null)) result.add(new QuadUtils.Face(quad, direction)); } return new ObjectImmutableList<>(result); } - /** 给由方块实体渲染器负责提交几何的方块提供粒子材质。 */ - public static BlockStateModel particleOnly(Material.Baked material) { - return new SingleVariant(new ParticlePart(material)); + /** 给由方块实体渲染器绘制几何的方块提供粒子贴图。 */ + public static BakedModel particleOnly(TextureAtlasSprite sprite) { + var culled = new EnumMap>(Direction.class); + for (Direction direction : DIRECTIONS) culled.put(direction, List.of()); + return new SimpleBakedModel(List.of(), culled, false, false, false, sprite, + ItemTransforms.NO_TRANSFORMS, ItemOverrides.EMPTY, RenderTypeGroup.EMPTY); } - /** 按输入顺序组合已烘焙模型。各部分共享随机变体种子,粒子材质取第一项。 */ - public static BlockStateModel combine(List parts) { + /** 按输入顺序组合已烘焙模型。各部分共享随机变体种子,粒子贴图取第一项。 */ + public static BakedModel combine(List parts) { if (parts.isEmpty()) throw new IllegalArgumentException("模型组合需要至少一个部件"); if (parts.size() == 1) return parts.getFirst(); return new CombinedModel(List.copyOf(parts)); } - private record ParticlePart(Material.Baked particleMaterial) implements BlockStateModelPart { - - @Override - public List getQuads(@Nullable Direction direction) { - return List.of(); - } + private static final class CombinedModel extends BakedModelWrapper { - @Override - public boolean useAmbientOcclusion() { - return false; - } + private final ModelProperty> partData = new ModelProperty<>(); + private final List parts; - @Override - public int materialFlags() { - return 0; - } - } - - private static final class CombinedModel extends DelegateBlockStateModel { - - private final List parts; - - private CombinedModel(List parts) { + private CombinedModel(List parts) { super(parts.getFirst()); this.parts = parts; } @Override @Deprecated - public void collectParts(RandomSource random, List output) { - long seed = random.nextLong(); - for (BlockStateModel model : parts) { - random.setSeed(seed); - model.collectParts(random, output); - } + public List getQuads(@Nullable BlockState state, @Nullable Direction direction, RandomSource random) { + return getQuads(state, direction, random, ModelData.EMPTY, null); } @Override - public void collectParts(BlockAndTintGetter level, BlockPos pos, BlockState state, - RandomSource random, List output) { + public List getQuads(@Nullable BlockState state, @Nullable Direction direction, RandomSource random, + ModelData data, @Nullable RenderType layer) { + var output = new ObjectArrayList(); long seed = random.nextLong(); - for (BlockStateModel model : parts) { - random.setSeed(seed); - model.collectParts(level, pos, state, random, output); + RandomSource sample = RandomSource.create(seed); + var dataByPart = data.get(partData); + for (int index = 0; index < parts.size(); index++) { + BakedModel part = parts.get(index); + ModelData modelData = dataByPart == null ? data : dataByPart.get(index); + if (layer != null && state != null && !part.getRenderTypes(state, sample, modelData).contains(layer)) { + sample.setSeed(seed); + continue; + } + sample.setSeed(seed); + output.addAll(part.getQuads(state, direction, sample, modelData, layer)); + sample.setSeed(seed); } + return output; } @Override - @Deprecated - public int materialFlags() { - int flags = 0; - for (BlockStateModel model : parts) flags |= model.materialFlags(); - return flags; + public ModelData getModelData(BlockAndTintGetter level, BlockPos pos, BlockState state, ModelData data) { + var byPart = new ObjectArrayList(parts.size()); + for (BakedModel part : parts) byPart.add(part.getModelData(level, pos, state, data)); + return byPart.getFirst().derive().with(partData, byPart).build(); } @Override - public int materialFlags(BlockAndTintGetter level, BlockPos pos, BlockState state) { - int flags = 0; - for (BlockStateModel model : parts) flags |= model.materialFlags(level, pos, state); - return flags; + public ChunkRenderTypeSet getRenderTypes(BlockState state, RandomSource random, ModelData data) { + long seed = random.nextLong(); + RandomSource sample = RandomSource.create(seed); + var types = new ObjectArrayList(parts.size()); + var dataByPart = data.get(partData); + for (int index = 0; index < parts.size(); index++) { + sample.setSeed(seed); + types.add(parts.get(index).getRenderTypes(state, sample, dataByPart == null ? data : dataByPart.get(index))); + } + return ChunkRenderTypeSet.union(types); } } } diff --git a/src/main/java/com/modularmc/mmclutils/client/model/MutableQuadView.java b/src/main/java/com/modularmc/mmclutils/client/model/MutableQuadView.java index a715350..f39d88c 100644 --- a/src/main/java/com/modularmc/mmclutils/client/model/MutableQuadView.java +++ b/src/main/java/com/modularmc/mmclutils/client/model/MutableQuadView.java @@ -1,11 +1,10 @@ package com.modularmc.mmclutils.client.model; -import net.minecraft.client.model.geom.builders.UVPair; -import net.minecraft.client.resources.model.geometry.BakedQuad; -import net.minecraft.client.resources.model.geometry.BakedQuad.MaterialInfo; +import com.modularmc.mmclutils.utils.ColorUtils; + +import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.Direction; -import net.neoforged.neoforge.client.model.quad.BakedColors; -import net.neoforged.neoforge.client.model.quad.BakedNormals; +import net.neoforged.neoforge.client.model.IQuadTransformer; import org.joml.Vector3f; import org.joml.Vector3fc; @@ -20,6 +19,7 @@ public final class MutableQuadView implements QuadView { private final long[] uv = new long[VERTEX_COUNT]; private final int[] normals = new int[VERTEX_COUNT]; private final int[] colors = new int[VERTEX_COUNT]; + private final int[] light = new int[VERTEX_COUNT]; private Direction lightFace = Direction.UP; private @Nullable Direction cullFace; private MaterialInfo material; @@ -42,6 +42,7 @@ public MutableQuadView copyFrom(QuadView source) { uv[vertex] = source.packedUv(vertex); normals[vertex] = source.packedNormal(vertex); colors[vertex] = source.color(vertex); + light[vertex] = source.packedLight(vertex); } lightFace = source.lightFace(); cullFace = source.cullFace(); @@ -55,6 +56,7 @@ public MutableQuadView clear(MaterialInfo material) { Arrays.fill(uv, 0); Arrays.fill(normals, 0); Arrays.fill(colors, -1); + Arrays.fill(light, 0); lightFace = Direction.UP; cullFace = null; this.material = material; @@ -91,7 +93,7 @@ public MutableQuadView packedUv(int vertex, long packedUv) { /** 写入 UV。烘焙时以当前值为图集坐标,使用局部 UV 时须事先映射到材质精灵。 */ public MutableQuadView uv(int vertex, float u, float v) { - return packedUv(vertex, UVPair.pack(u, v)); + return packedUv(vertex, (long) Float.floatToIntBits(u) << 32 | Integer.toUnsignedLong(Float.floatToIntBits(v))); } @Override @@ -107,7 +109,7 @@ public MutableQuadView packedNormal(int vertex, int normal) { /** 将单位向量打包为指定顶点的法线。 */ public MutableQuadView normal(int vertex, Vector3fc normal) { - return packedNormal(vertex, BakedNormals.pack(normal)); + return packedNormal(vertex, QuadUtils.packNormal(normal)); } /** 用几何面法线填充未设置的顶点法线。退化面沿用光照方向。 */ @@ -116,7 +118,7 @@ public MutableQuadView populateMissingNormals() { if (flags == (1 << VERTEX_COUNT) - 1) return this; var normal = QuadUtils.normal(this, new Vector3f()); if (normal.lengthSquared() == 0) normal.set(lightFace.getStepX(), lightFace.getStepY(), lightFace.getStepZ()); - int packed = BakedNormals.pack(normal); + int packed = QuadUtils.packNormal(normal); for (int vertex = 0; vertex < VERTEX_COUNT; vertex++) { if ((flags & (1 << vertex)) == 0) normals[vertex] = packed; } @@ -128,6 +130,17 @@ public int color(int vertex) { return colors[vertex]; } + @Override + public int packedLight(int vertex) { + return light[vertex]; + } + + /** 设置顶点的打包光照。 */ + public MutableQuadView packedLight(int vertex, int value) { + light[vertex] = value; + return this; + } + /** 设置单个顶点的 ARGB 调制色。 */ public MutableQuadView color(int vertex, int argb) { colors[vertex] = argb; @@ -175,8 +188,19 @@ public MutableQuadView material(MaterialInfo value) { /** 产生可直接提交给原版的四边形。剔除分组仍由调用者维护。 */ public BakedQuad bake() { - return new BakedQuad(new Vector3f(positions[0]), new Vector3f(positions[1]), new Vector3f(positions[2]), new Vector3f(positions[3]), - uv[0], uv[1], uv[2], uv[3], lightFace, material, - BakedNormals.of(normals[0], normals[1], normals[2], normals[3]), BakedColors.of(colors[0], colors[1], colors[2], colors[3])); + int[] data = new int[VERTEX_COUNT * IQuadTransformer.STRIDE]; + for (int vertex = 0; vertex < VERTEX_COUNT; vertex++) { + int offset = vertex * IQuadTransformer.STRIDE; + Vector3f position = positions[vertex]; + data[offset + IQuadTransformer.POSITION] = Float.floatToRawIntBits(position.x); + data[offset + IQuadTransformer.POSITION + 1] = Float.floatToRawIntBits(position.y); + data[offset + IQuadTransformer.POSITION + 2] = Float.floatToRawIntBits(position.z); + data[offset + IQuadTransformer.UV0] = (int) (uv[vertex] >>> 32); + data[offset + IQuadTransformer.UV0 + 1] = (int) uv[vertex]; + data[offset + IQuadTransformer.COLOR] = ColorUtils.swapRedBlue(colors[vertex]); + data[offset + IQuadTransformer.UV2] = light[vertex]; + data[offset + IQuadTransformer.NORMAL] = normals[vertex]; + } + return new BakedQuad(data, material.tintIndex(), lightFace, material.sprite(), material.shade(), material.ambientOcclusion()); } } diff --git a/src/main/java/com/modularmc/mmclutils/client/model/QuadTransforms.java b/src/main/java/com/modularmc/mmclutils/client/model/QuadTransforms.java index 8a56018..5b3ad8e 100644 --- a/src/main/java/com/modularmc/mmclutils/client/model/QuadTransforms.java +++ b/src/main/java/com/modularmc/mmclutils/client/model/QuadTransforms.java @@ -1,10 +1,10 @@ package com.modularmc.mmclutils.client.model; -import net.minecraft.client.resources.model.geometry.BakedQuad.MaterialInfo; +import com.modularmc.mmclutils.client.model.QuadView.MaterialInfo; + import net.minecraft.core.Direction; import net.minecraft.util.Mth; import net.minecraft.world.phys.AABB; -import net.neoforged.neoforge.client.model.quad.BakedNormals; import org.joml.Matrix3f; import org.joml.Matrix4f; @@ -45,7 +45,7 @@ public static Transform transform(Matrix4fc matrix) { quad.position(vertex, position); int packed = quad.packedNormal(vertex); if (packed != 0) { - BakedNormals.unpack(packed, normal); + QuadUtils.unpackNormal(packed, normal); normal.mul(normalMatrix).normalize(); quad.normal(vertex, normal); } @@ -85,14 +85,13 @@ public static Transform color(int argb, boolean clearTint) { quad.colorAll(argb); if (clearTint) { MaterialInfo material = quad.material(); - quad.material(new MaterialInfo(material.sprite(), material.layer(), material.itemRenderType(), -1, - material.shade(), material.lightEmission(), material.ambientOcclusion())); + quad.material(new MaterialInfo(material.sprite(), -1, material.shade(), material.ambientOcclusion())); } return true; }; } - /** 重映射图集 UV。新材质同时提供与图集匹配的渲染层。 */ + /** 将 UV 重映射到新材质精灵。 */ public static Transform retexture(MaterialInfo replacement) { return quad -> { QuadUtils.replace(quad, replacement); diff --git a/src/main/java/com/modularmc/mmclutils/client/model/QuadUtils.java b/src/main/java/com/modularmc/mmclutils/client/model/QuadUtils.java index ef029c0..34dc2f8 100644 --- a/src/main/java/com/modularmc/mmclutils/client/model/QuadUtils.java +++ b/src/main/java/com/modularmc/mmclutils/client/model/QuadUtils.java @@ -1,13 +1,12 @@ package com.modularmc.mmclutils.client.model; +import com.modularmc.mmclutils.client.model.QuadView.MaterialInfo; + +import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.geometry.BakedQuad; -import net.minecraft.client.resources.model.geometry.BakedQuad.MaterialInfo; -import net.minecraft.client.resources.model.geometry.QuadCollection; import net.minecraft.core.Direction; -import net.minecraft.util.ARGB; +import net.minecraft.util.FastColor.ARGB32; import net.minecraft.world.phys.AABB; -import net.neoforged.neoforge.client.model.quad.BakedNormals; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectImmutableList; @@ -16,6 +15,8 @@ import org.joml.Vector3fc; import org.jspecify.annotations.Nullable; +import java.util.EnumMap; + /** 构造和变换原版四边形,处理顶点法线、光照方向、颜色插值和图集 UV。 */ public final class QuadUtils { @@ -45,14 +46,7 @@ public static ObjectList forFace(Iterable source, @Nullable Dir /** 将烘焙面按剔除方向收集为可交给原版模型的四边形集合。各组内保持输入顺序。 */ public static QuadCollection collect(Iterable faces) { - var output = new QuadCollection.Builder(); - for (Face face : faces) add(output, face.quad(), face.cullFace()); - return output.build(); - } - - private static void add(QuadCollection.Builder output, BakedQuad quad, @Nullable Direction cullFace) { - if (cullFace == null) output.addUnculledFace(quad); - else output.addCulledFace(cullFace, quad); + return new QuadCollection(faces); } /** 以方块单位构造盒子一面。盒子内侧的面不参与邻方块剔除。 */ @@ -104,7 +98,7 @@ public record Face(BakedQuad quad, @Nullable Direction cullFace) {} public static final class Builder { private final MutableQuadView editor; - private final QuadCollection.Builder faces = new QuadCollection.Builder(); + private final ObjectList faces = new ObjectArrayList<>(); /** 创建构建器并指定首个面的材质。 */ public Builder(MaterialInfo material) { @@ -128,27 +122,62 @@ public MutableQuadView begin(QuadView source) { /** 烘焙当前视图并追加到相应剔除组。 */ public Builder emit() { - QuadUtils.add(faces, editor.bake(), editor.cullFace()); + faces.add(new Face(editor.bake(), editor.cullFace())); return this; } /** 追加已经烘焙的面,保留剔除分组。 */ public Builder add(Face face) { - QuadUtils.add(faces, face.quad(), face.cullFace()); + faces.add(face); return this; } /** 返回已提交的原版四边形集合。当前视图须先经 {@link #emit()} 提交。 */ public QuadCollection build() { - return faces.build(); + return collect(faces); + } + } + + /** 按相邻面遮挡方向索引的不可变四边形列表。 */ + public static final class QuadCollection { + + private final ObjectList unculled; + private final EnumMap> culled = new EnumMap<>(Direction.class); + + private QuadCollection(Iterable faces) { + var unculled = new ObjectArrayList(); + for (Face face : faces) { + Direction direction = face.cullFace(); + if (direction == null) unculled.add(face.quad()); + else culled.computeIfAbsent(direction, ignored -> new ObjectArrayList<>()).add(face.quad()); + } + this.unculled = new ObjectImmutableList<>(unculled); + culled.replaceAll((direction, group) -> new ObjectImmutableList<>(group)); + } + + /** 返回指定方向的剔除组。空值选择通用面。 */ + public ObjectList getQuads(@Nullable Direction direction) { + return direction == null ? unculled : culled.getOrDefault(direction, ObjectList.of()); } } + static int packNormal(Vector3fc normal) { + return normalByte(normal.x()) | normalByte(normal.y()) << 8 | normalByte(normal.z()) << 16; + } + + private static int normalByte(float value) { + return Math.round(Math.clamp(value, -1, 1) * 127) & 255; + } + + static void unpackNormal(int packed, Vector3f output) { + output.set((byte) packed / 127f, (byte) (packed >>> 8) / 127f, (byte) (packed >>> 16) / 127f); + } + /** 将顶点法线写入调用方的向量。缺少独立法线时使用光照朝向。 */ public static Vector3f vertexNormal(QuadView quad, int vertex, Vector3f output) { int packed = quad.packedNormal(vertex); if (packed != 0) { - BakedNormals.unpack(packed, output); + unpackNormal(packed, output); return output; } Direction face = quad.lightFace(); @@ -209,9 +238,12 @@ private static boolean sample(QuadView source, MutableQuadView target, int index target.uv(index, w0 * source.u(0) + w1 * source.u(b) + w2 * source.u(c), w0 * source.v(0) + w1 * source.v(b) + w2 * source.v(c)); int aColor = source.color(0), bColor = source.color(b), cColor = source.color(c); - target.color(index, ARGB.color(channel(aColor, bColor, cColor, 24, w0, w1, w2), + target.color(index, ARGB32.color(channel(aColor, bColor, cColor, 24, w0, w1, w2), channel(aColor, bColor, cColor, 16, w0, w1, w2), channel(aColor, bColor, cColor, 8, w0, w1, w2), channel(aColor, bColor, cColor, 0, w0, w1, w2))); + int aLight = source.packedLight(0), bLight = source.packedLight(b), cLight = source.packedLight(c); + target.packedLight(index, channel(aLight, bLight, cLight, 0, w0, w1, w2) | + channel(aLight, bLight, cLight, 16, w0, w1, w2) << 16); if (normal != null) { vertexNormal(source, 0, normal).mul(w0); float nx = normal.x, ny = normal.y, nz = normal.z; diff --git a/src/main/java/com/modularmc/mmclutils/client/model/QuadView.java b/src/main/java/com/modularmc/mmclutils/client/model/QuadView.java index 4d65c81..f72920d 100644 --- a/src/main/java/com/modularmc/mmclutils/client/model/QuadView.java +++ b/src/main/java/com/modularmc/mmclutils/client/model/QuadView.java @@ -1,10 +1,13 @@ package com.modularmc.mmclutils.client.model; -import net.minecraft.client.model.geom.builders.UVPair; -import net.minecraft.client.resources.model.geometry.BakedQuad; -import net.minecraft.client.resources.model.geometry.BakedQuad.MaterialInfo; +import com.modularmc.mmclutils.utils.ColorUtils; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; +import net.neoforged.neoforge.client.model.IQuadTransformer; +import org.joml.Vector3f; import org.joml.Vector3fc; import org.jspecify.annotations.Nullable; @@ -12,12 +15,12 @@ public interface QuadView { /** 一个四边形的顶点数。 */ - int VERTEX_COUNT = BakedQuad.VERTEX_COUNT; + int VERTEX_COUNT = 4; /** 返回只读顶点坐标,索引范围为零至三。 */ Vector3fc position(int vertex); - /** 返回使用原版 UVPair 编码的图集坐标。 */ + /** 返回打包的图集坐标,高位为 U,低位为 V。 */ long packedUv(int vertex); /** 返回 NeoForge 编码的法线。零值表示使用面朝向。 */ @@ -26,6 +29,11 @@ public interface QuadView { /** 返回顶点的 ARGB 调制色。 */ int color(int vertex); + /** 返回原版打包的顶点光照。 */ + default int packedLight(int vertex) { + return 0; + } + /** 返回用于光照的面朝向。 */ Direction lightFace(); @@ -38,12 +46,12 @@ public interface QuadView { /** 返回指定顶点的图集横坐标,范围取决于材质精灵。 */ default float u(int vertex) { - return UVPair.unpackU(packedUv(vertex)); + return Float.intBitsToFloat((int) (packedUv(vertex) >>> 32)); } /** 返回指定顶点的图集纵坐标,范围取决于材质精灵。 */ default float v(int vertex) { - return UVPair.unpackV(packedUv(vertex)); + return Float.intBitsToFloat((int) packedUv(vertex)); } /** 返回显式顶点法线的位掩码,第零位至第三位按顶点顺序排列。 */ @@ -65,37 +73,50 @@ static QuadView of(BakedQuad quad, @Nullable Direction cullFace) { return new Baked(quad, cullFace); } + /** 1.21.1 中随四边形保存的精灵、染色和光照选项。渲染层由所属模型提供。 */ + record MaterialInfo(TextureAtlasSprite sprite, int tintIndex, boolean shade, boolean ambientOcclusion) {} + /** 提供原版烘焙面的只读视图,保留调用者指定的剔除分组。 */ record Baked(BakedQuad quad, @Nullable Direction cullFace) implements QuadView { @Override public Vector3fc position(int vertex) { - return quad.position(vertex); + int offset = vertex * IQuadTransformer.STRIDE + IQuadTransformer.POSITION; + int[] data = quad.getVertices(); + return new Vector3f(Float.intBitsToFloat(data[offset]), Float.intBitsToFloat(data[offset + 1]), + Float.intBitsToFloat(data[offset + 2])); } @Override public long packedUv(int vertex) { - return quad.packedUV(vertex); + int offset = vertex * IQuadTransformer.STRIDE + IQuadTransformer.UV0; + int[] data = quad.getVertices(); + return (long) data[offset] << 32 | Integer.toUnsignedLong(data[offset + 1]); } @Override public int packedNormal(int vertex) { - return quad.bakedNormals().normal(vertex); + return quad.getVertices()[vertex * IQuadTransformer.STRIDE + IQuadTransformer.NORMAL] & 0xFFFFFF; } @Override public int color(int vertex) { - return quad.bakedColors().color(vertex); + return ColorUtils.swapRedBlue(quad.getVertices()[vertex * IQuadTransformer.STRIDE + IQuadTransformer.COLOR]); + } + + @Override + public int packedLight(int vertex) { + return quad.getVertices()[vertex * IQuadTransformer.STRIDE + IQuadTransformer.UV2]; } @Override public Direction lightFace() { - return quad.direction(); + return quad.getDirection(); } @Override public MaterialInfo material() { - return quad.materialInfo(); + return new MaterialInfo(quad.getSprite(), quad.getTintIndex(), quad.isShade(), quad.hasAmbientOcclusion()); } } } diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectQuadBuffer.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectQuadBuffer.java index 15bb4b6..21ee6a2 100644 --- a/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectQuadBuffer.java +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectQuadBuffer.java @@ -1,93 +1,169 @@ package com.modularmc.mmclutils.client.render.effect; -import com.modularmc.mmclutils.mixin.mc.client.GlBufferAccessor; +import com.modularmc.mmclutils.client.render.effect.EffectRenderPipelines.Blend; +import com.modularmc.mmclutils.client.render.effect.EffectRenderPipelines.Pass; import net.minecraft.client.Minecraft; -import net.minecraft.resources.Identifier; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.resources.ResourceLocation; -import com.mojang.blaze3d.buffers.GpuBuffer; -import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.VertexFormat; import org.joml.Matrix4f; import org.joml.Matrix4fc; -import org.joml.Vector3f; import org.joml.Vector4f; import org.joml.Vector4fc; -import org.jspecify.annotations.Nullable; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL14; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; import java.nio.ByteBuffer; -import java.util.OptionalDouble; -import java.util.OptionalInt; /** 变换反馈和普通顶点写入共享相同的缓冲布局。 */ final class EffectQuadBuffer implements AutoCloseable { static final int VERTEX_BYTES = 9 * Float.BYTES; private static final Vector4f WHITE = new Vector4f(1); - private static final Vector3f ZERO = new Vector3f(); - private static final Matrix4f IDENTITY = new Matrix4f(); + private static final Matrix4f POSE = new Matrix4f(); - private @Nullable GpuBuffer verticesBuffer; + private int array; + private long capacity; int buffer; int vertices; void reserve(int vertexCapacity) { long bytes = (long) vertexCapacity * VERTEX_BYTES; - if (verticesBuffer != null && verticesBuffer.size() >= bytes) return; - close(); - verticesBuffer = RenderSystem.getDevice().createBuffer( - () -> "mmclutils-effects", GpuBuffer.USAGE_VERTEX | GpuBuffer.USAGE_COPY_DST, Math.max(bytes, VERTEX_BYTES)); - if (verticesBuffer instanceof GlBufferAccessor accessor) buffer = accessor.mmclutils$handle(); + if (buffer != 0 && capacity >= bytes) return; + RenderSystem.assertOnRenderThread(); + if (buffer == 0) buffer = GL15.glGenBuffers(); + int previous = GL11.glGetInteger(GL15.GL_ARRAY_BUFFER_BINDING); + GlStateManager._glBindBuffer(GL15.GL_ARRAY_BUFFER, buffer); + try { + GL15.glBufferData(GL15.GL_ARRAY_BUFFER, Math.max(bytes, VERTEX_BYTES), GL15.GL_DYNAMIC_DRAW); + capacity = Math.max(bytes, VERTEX_BYTES); + } finally { + GlStateManager._glBindBuffer(GL15.GL_ARRAY_BUFFER, previous); + } } void upload(ByteBuffer bytes) { int count = bytes.remaining() / VERTEX_BYTES; if (count != 0) { reserve(count); - RenderSystem.getDevice().createCommandEncoder().writeToBuffer(verticesBuffer.slice(0, bytes.remaining()), bytes); + int previous = GL11.glGetInteger(GL15.GL_ARRAY_BUFFER_BINDING); + GlStateManager._glBindBuffer(GL15.GL_ARRAY_BUFFER, buffer); + try { + GL15.glBufferSubData(GL15.GL_ARRAY_BUFFER, 0, bytes); + } finally { + GlStateManager._glBindBuffer(GL15.GL_ARRAY_BUFFER, previous); + } } vertices = count; } - void draw(RenderPipeline pipeline, Identifier textureId) { - draw(pipeline, textureId, EffectRenderer.modelView(), WHITE); + void draw(Pass pass, ResourceLocation textureId) { + draw(pass, textureId, EffectRenderer.modelView(), WHITE); } - void draw(RenderPipeline pipeline, Identifier textureId, Matrix4fc pose) { - draw(pipeline, textureId, pose, WHITE); + void draw(Pass pass, ResourceLocation textureId, Matrix4fc pose) { + draw(pass, textureId, pose, WHITE); } - void draw(RenderPipeline pipeline, Identifier textureId, Matrix4fc pose, Vector4fc tint) { + void draw(Pass pass, ResourceLocation textureId, Matrix4fc pose, Vector4fc tint) { if (vertices == 0) return; + RenderSystem.assertOnRenderThread(); var mc = Minecraft.getInstance(); - var target = mc.getMainRenderTarget(); - var color = RenderSystem.outputColorTextureOverride != null ? RenderSystem.outputColorTextureOverride : target.getColorTextureView(); - var depth = RenderSystem.outputDepthTextureOverride != null ? RenderSystem.outputDepthTextureOverride : target.getDepthTextureView(); - var texture = mc.getTextureManager().getTexture(textureId); - int indexCount = vertices / 4 * 6; - var indices = RenderSystem.getSequentialBuffer(VertexFormat.Mode.QUADS); - var indexBuffer = indices.getBuffer(indexCount); - var transform = RenderSystem.getDynamicUniforms().writeTransform(pose, tint, ZERO, IDENTITY); - try (var pass = RenderSystem.getDevice().createCommandEncoder() - .createRenderPass(() -> "mmclutils-effects", color, OptionalInt.empty(), depth, OptionalDouble.empty())) { - pass.setPipeline(pipeline); - RenderSystem.bindDefaultUniforms(pass); - pass.setUniform("DynamicTransforms", transform); - pass.bindTexture("Sampler0", texture.getTextureView(), texture.getSampler()); - pass.setVertexBuffer(0, verticesBuffer); - pass.setIndexBuffer(indexBuffer, indices.type()); - pass.drawIndexed(0, 0, indexCount, 1); + var shader = GameRenderer.getPositionTexColorShader(); + int previousArray = GL11.glGetInteger(GL30.GL_VERTEX_ARRAY_BINDING); + int previousBuffer = GL11.glGetInteger(GL15.GL_ARRAY_BUFFER_BINDING); + int activeTexture = GlStateManager._getActiveTexture(); + GlStateManager._activeTexture(GL13.GL_TEXTURE0); + int previousTexture = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); + GlStateManager._activeTexture(activeTexture); + boolean depth = GL11.glIsEnabled(GL11.GL_DEPTH_TEST); + boolean depthWrite = GL11.glGetBoolean(GL11.GL_DEPTH_WRITEMASK); + int depthFunction = GL11.glGetInteger(GL11.GL_DEPTH_FUNC); + boolean cull = GL11.glIsEnabled(GL11.GL_CULL_FACE); + boolean blend = GL11.glIsEnabled(GL11.GL_BLEND); + int sourceRgb = GL11.glGetInteger(GL14.GL_BLEND_SRC_RGB), targetRgb = GL11.glGetInteger(GL14.GL_BLEND_DST_RGB); + int sourceAlpha = GL11.glGetInteger(GL14.GL_BLEND_SRC_ALPHA), targetAlpha = GL11.glGetInteger(GL14.GL_BLEND_DST_ALPHA); + + try { + configure(pass); + shader.setDefaultUniforms(VertexFormat.Mode.QUADS, POSE.set(pose), EffectRenderer.projection(), mc.getWindow()); + shader.setSampler("Sampler0", mc.getTextureManager().getTexture(textureId)); + shader.COLOR_MODULATOR.set(tint.x(), tint.y(), tint.z(), tint.w()); + shader.apply(); + bind(); + int indexCount = vertices / 4 * 6; + var indices = RenderSystem.getSequentialBuffer(VertexFormat.Mode.QUADS); + indices.bind(indexCount); + RenderSystem.drawElements(GL11.GL_TRIANGLES, indexCount, indices.type().asGLType); + } finally { + shader.clear(); + GlStateManager._activeTexture(GL13.GL_TEXTURE0); + GlStateManager._bindTexture(previousTexture); + GlStateManager._activeTexture(activeTexture); + GlStateManager._glBindVertexArray(previousArray); + GlStateManager._glBindBuffer(GL15.GL_ARRAY_BUFFER, previousBuffer); + if (depth) RenderSystem.enableDepthTest(); + else RenderSystem.disableDepthTest(); + RenderSystem.depthFunc(depthFunction); + RenderSystem.depthMask(depthWrite); + if (cull) RenderSystem.enableCull(); + else RenderSystem.disableCull(); + if (blend) RenderSystem.enableBlend(); + else RenderSystem.disableBlend(); + RenderSystem.blendFuncSeparate(sourceRgb, targetRgb, sourceAlpha, targetAlpha); + } + } + + private void bind() { + if (array != 0) { + GlStateManager._glBindVertexArray(array); + return; + } + array = GL30.glGenVertexArrays(); + GlStateManager._glBindVertexArray(array); + GlStateManager._glBindBuffer(GL15.GL_ARRAY_BUFFER, buffer); + // 原版着色器的属性顺序是 Position、UV0、Color。反馈缓冲的颜色使用四个浮点数。 + GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, VERTEX_BYTES, 0); + GL20.glVertexAttribPointer(1, 2, GL11.GL_FLOAT, false, VERTEX_BYTES, 7L * Float.BYTES); + GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, VERTEX_BYTES, 3L * Float.BYTES); + GL20.glEnableVertexAttribArray(0); + GL20.glEnableVertexAttribArray(1); + GL20.glEnableVertexAttribArray(2); + } + + private static void configure(Pass pass) { + if (pass.depthTest()) { + RenderSystem.enableDepthTest(); + RenderSystem.depthFunc(GL11.GL_LEQUAL); + } else { + RenderSystem.disableDepthTest(); + } + RenderSystem.depthMask(pass.writeDepth()); + RenderSystem.disableCull(); + if (pass.blend() == Blend.OPAQUE) { + RenderSystem.disableBlend(); + } else { + RenderSystem.enableBlend(); + if (pass.blend() == Blend.ADDITIVE) RenderSystem.blendFuncSeparate(GL11.GL_ONE, GL11.GL_ONE, GL11.GL_ONE, GL11.GL_ONE); + else RenderSystem.defaultBlendFunc(); } } @Override public void close() { - if (verticesBuffer != null) { - verticesBuffer.close(); - verticesBuffer = null; - } + if (array != 0) GlStateManager._glDeleteVertexArrays(array); + if (buffer != 0) GlStateManager._glDeleteBuffers(buffer); + array = 0; buffer = 0; vertices = 0; + capacity = 0; } } diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderPipelines.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderPipelines.java index 0ab2ca9..7f4eac4 100644 --- a/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderPipelines.java +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderPipelines.java @@ -3,80 +3,52 @@ import com.modularmc.mmclutils.ModularMCLibUtils; import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.RenderPipelines; import net.minecraft.client.renderer.texture.DynamicTexture; -import net.minecraft.resources.Identifier; -import net.neoforged.neoforge.client.event.RegisterRenderPipelinesEvent; +import net.minecraft.resources.ResourceLocation; -import com.mojang.blaze3d.pipeline.BlendFunction; -import com.mojang.blaze3d.pipeline.ColorTargetState; -import com.mojang.blaze3d.pipeline.DepthStencilState; -import com.mojang.blaze3d.pipeline.RenderPipeline; -import com.mojang.blaze3d.platform.CompareOp; import com.mojang.blaze3d.platform.NativeImage; -import com.mojang.blaze3d.vertex.VertexFormat; -import com.mojang.blaze3d.vertex.VertexFormatElement; -import org.jspecify.annotations.Nullable; - -import java.util.Optional; /** 环、光点和实体附着共用的原版绘制状态与纹理。 */ public final class EffectRenderPipelines { /** 渐隐的环形光带纹理。 */ - public static final Identifier GLOW_TEXTURE = ModularMCLibUtils.id("effect/glow"); + public static final ResourceLocation GLOW_TEXTURE = ModularMCLibUtils.id("effect/glow"); /** 绘制纯色几何时使用的白色纹理。 */ - public static final Identifier WHITE_TEXTURE = ModularMCLibUtils.id("effect/white"); + public static final ResourceLocation WHITE_TEXTURE = ModularMCLibUtils.id("effect/white"); /** RGB 已按透明度渐变的光点纹理,供加法混合使用。 */ - public static final Identifier MOTE_TEXTURE = ModularMCLibUtils.id("effect/mote"); - - private static final VertexFormat FORMAT = VertexFormat.builder() - .add("Position", VertexFormatElement.POSITION) - .add("Color", VertexFormatElement.register( - VertexFormatElement.findNextId(), 0, VertexFormatElement.Type.FLOAT, false, 4)) - .add("UV0", VertexFormatElement.UV0) - .build(); + public static final ResourceLocation MOTE_TEXTURE = ModularMCLibUtils.id("effect/mote"); /** 使用场景深度测试与深度写入绘制实体四边形。 */ - public static final RenderPipeline VOXEL = program("voxel", null, true, false); + public static final Pass VOXEL = new Pass(Blend.OPAQUE, true, true); /** 使用场景深度测试,以加法混合写入颜色。 */ - public static final RenderPipeline GLOW = program("glow", BlendFunction.ADDITIVE, false, false); + public static final Pass GLOW = new Pass(Blend.ADDITIVE, true, false); /** 以透明度混合绘制穿过场景的高亮。 */ - public static final RenderPipeline HIGHLIGHT = program("highlight", BlendFunction.TRANSLUCENT, false, true); - private static final RenderPipeline GLOW_THROUGH = program("glow_through", BlendFunction.ADDITIVE, false, true); - private static final RenderPipeline ATLAS = program("particle", BlendFunction.TRANSLUCENT, false, false); - private static final RenderPipeline ATLAS_THROUGH = program("particle_through", BlendFunction.TRANSLUCENT, false, true); + public static final Pass HIGHLIGHT = new Pass(Blend.TRANSLUCENT, false, false); + private static final Pass GLOW_THROUGH = new Pass(Blend.ADDITIVE, false, false); + private static final Pass ATLAS = new Pass(Blend.TRANSLUCENT, true, false); + private static final Pass ATLAS_THROUGH = new Pass(Blend.TRANSLUCENT, false, false); private static boolean texturesReady; private EffectRenderPipelines() {} - static void init(RegisterRenderPipelinesEvent event) { - for (RenderPipeline pipeline : new RenderPipeline[] { VOXEL, GLOW, HIGHLIGHT, GLOW_THROUGH, ATLAS, ATLAS_THROUGH }) { - event.registerPipeline(pipeline); - } - } - - /** 选择对应遮挡规则的加法混合管线。传入真时跳过场景深度测试。 */ - public static RenderPipeline glow(boolean throughWalls) { + /** 选择对应遮挡规则的加法混合状态。传入真时跳过场景深度测试。 */ + public static Pass glow(boolean throughWalls) { return throughWalls ? GLOW_THROUGH : GLOW; } - /** 选择对应遮挡规则的粒子图集管线,颜色按透明度混合。 */ - public static RenderPipeline atlas(boolean throughWalls) { + /** 选择对应遮挡规则的粒子图集状态,颜色按透明度混合。 */ + public static Pass atlas(boolean throughWalls) { return throughWalls ? ATLAS_THROUGH : ATLAS; } - private static RenderPipeline program(String path, @Nullable BlendFunction blend, boolean writeDepth, boolean throughWalls) { - return RenderPipeline.builder(RenderPipelines.MATRICES_PROJECTION_SNIPPET) - .withLocation(ModularMCLibUtils.id("pipeline/effect/" + path)) - .withVertexShader("core/position_tex_color") - .withFragmentShader("core/position_tex_color") - .withSampler("Sampler0") - .withCull(false) - .withDepthStencilState(throughWalls ? Optional.empty() : Optional.of(new DepthStencilState(CompareOp.LESS_THAN_OR_EQUAL, writeDepth))) - .withColorTargetState(blend == null ? ColorTargetState.DEFAULT : new ColorTargetState(blend)) - .withVertexFormat(FORMAT, VertexFormat.Mode.QUADS) - .build(); + /** 1.21.1 位置、贴图、颜色着色器的绘制状态。 */ + public record Pass(Blend blend, boolean depthTest, boolean writeDepth) {} + + /** 场景颜色与效果颜色的合成规则。 */ + public enum Blend { + OPAQUE, + ADDITIVE, + TRANSLUCENT } static void ensureTextures() { @@ -91,16 +63,16 @@ static void ensureTextures() { float dy = (y - center) / (size / 2f); float fade = Math.max(0, 1 - (float) Math.sqrt(dx * dx + dy * dy)); int alpha = Math.round((float) Math.ceil(fade * fade * 5) * 51); - glow.setPixel(x, y, alpha << 24 | 0xFFFFFF); - mote.setPixel(x, y, alpha * 0x01010101); + glow.setPixelRGBA(x, y, alpha << 24 | 0xFFFFFF); + mote.setPixelRGBA(x, y, alpha * 0x01010101); } } var white = new NativeImage(1, 1, false); - white.setPixel(0, 0, -1); + white.setPixelRGBA(0, 0, -1); var textures = Minecraft.getInstance().getTextureManager(); - textures.register(GLOW_TEXTURE, new DynamicTexture(GLOW_TEXTURE::toString, glow)); - textures.register(MOTE_TEXTURE, new DynamicTexture(MOTE_TEXTURE::toString, mote)); - textures.register(WHITE_TEXTURE, new DynamicTexture(WHITE_TEXTURE::toString, white)); + textures.register(GLOW_TEXTURE, new DynamicTexture(glow)); + textures.register(MOTE_TEXTURE, new DynamicTexture(mote)); + textures.register(WHITE_TEXTURE, new DynamicTexture(white)); texturesReady = true; } diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderer.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderer.java index 848498c..91ce626 100644 --- a/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderer.java +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderer.java @@ -10,17 +10,15 @@ import net.minecraft.core.Direction; import net.minecraft.server.packs.resources.ResourceManagerReloadListener; import net.minecraft.util.Mth; -import net.minecraft.util.context.ContextKey; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.neoforged.api.distmarker.Dist; import net.neoforged.bus.api.IEventBus; import net.neoforged.bus.api.SubscribeEvent; import net.neoforged.fml.common.EventBusSubscriber; -import net.neoforged.neoforge.client.event.AddClientReloadListenersEvent; import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent; import net.neoforged.neoforge.client.event.ClientTickEvent; -import net.neoforged.neoforge.client.event.ExtractLevelRenderStateEvent; +import net.neoforged.neoforge.client.event.RegisterClientReloadListenersEvent; import net.neoforged.neoforge.client.event.RenderLevelStageEvent; import net.neoforged.neoforge.event.GameShuttingDownEvent; @@ -37,12 +35,11 @@ @EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID, value = Dist.CLIENT) public final class EffectRenderer { - private static final ContextKey FRAME = new ContextKey<>(ModularMCLibUtils.id("effect_frame")); private static final ObjectArrayList RINGS = new ObjectArrayList<>(); private static final ObjectArrayList SOURCES = new ObjectArrayList<>(); private static final Matrix4f MODEL_VIEW = new Matrix4f(); + private static final Matrix4f PROJECTION = new Matrix4f(); private static int ringCount; - private static long frame; private static @Nullable ClientLevel collectingLevel; private static double frameTime; private static long clientTicks; @@ -106,7 +103,7 @@ public static void removeSource(Source source) { */ public static double now() { Minecraft client = Minecraft.getInstance(); - return client.level == null ? Double.NaN : clientTicks + client.getDeltaTracker().getGameTimeDeltaPartialTick(false); + return client.level == null ? Double.NaN : clientTicks + client.getTimer().getGameTimeDeltaPartialTick(false); } /** 返回最近一次世界帧采集使用的效果时间,单位为 Tick。 */ @@ -174,7 +171,7 @@ public static void ring(ParticleRing ring, RingStyle style, RingShape shape, dou if (palette.length < EffectPalette.SIZE) throw new IllegalArgumentException("环的色板长度不足"); if (ringCount == RINGS.size()) RINGS.add(new RingCommand()); RingCommand command = RINGS.get(ringCount++); - Vec3 eye = camera.position(); + Vec3 eye = camera.getPosition(); float scale = intensity * intensity * (3 - 2 * intensity); command.ring = ring; command.x = (float) (worldX - eye.x); @@ -193,15 +190,37 @@ public static void ring(ParticleRing ring, RingStyle style, RingShape shape, dou } @SubscribeEvent - private static void collectFrame(ExtractLevelRenderStateEvent event) { + private static void renderStage(RenderLevelStageEvent event) { + var stage = event.getStage(); + if (stage == RenderLevelStageEvent.Stage.AFTER_SKY) { + collectFrame(event.getCamera()); + } else if (camera != null && stage == RenderLevelStageEvent.Stage.AFTER_BLOCK_ENTITIES) { + EffectRenderPipelines.ensureTextures(); + MODEL_VIEW.set(event.getModelViewMatrix()); + PROJECTION.set(event.getProjectionMatrix()); + if (ringCount != 0) { + RingRenderer.draw(RINGS, ringCount, camera); + ringCount = 0; + } + GpuParticleRenderer.flush(frameTime, camera); + } else if (camera != null && stage == RenderLevelStageEvent.Stage.AFTER_PARTICLES) { + MODEL_VIEW.set(event.getModelViewMatrix()); + PROJECTION.set(event.getProjectionMatrix()); + PlayerAttachmentRenderer.drawPending(); + SphereHighlight.draw(camera.getPosition(), MODEL_VIEW); + camera = null; + } + } + + private static void collectFrame(Camera currentCamera) { + ClientLevel level = Minecraft.getInstance().level; + if (level == null) return; frameTime = now(); - camera = event.getCamera(); + camera = currentCamera; ringCount = 0; - PlayerAttachmentRenderer.beginFrame(event.getRenderState().cameraRenderState.pos); + Vec3 eye = camera.getPosition(); + PlayerAttachmentRenderer.beginFrame(eye); GpuParticleRenderer.beginFrame(); - event.getRenderState().setRenderData(FRAME, ++frame); - Vec3 eye = camera.position(); - ClientLevel level = event.getLevel(); collectingLevel = level; try { for (int index = 0; index < SOURCES.size(); index++) { @@ -212,28 +231,8 @@ private static void collectFrame(ExtractLevelRenderStateEvent event) { } } - private static boolean matchesFrame(RenderLevelStageEvent event) { - Long extracted = event.getLevelRenderState().getRenderData(FRAME); - return extracted != null && extracted.longValue() == frame && camera != null; - } - - @SubscribeEvent - private static void drawWorldEffects(RenderLevelStageEvent.AfterOpaqueFeatures event) { - if (!matchesFrame(event)) return; - EffectRenderPipelines.ensureTextures(); - MODEL_VIEW.set(event.getModelViewMatrix()); - if (ringCount != 0) { - RingRenderer.draw(RINGS, ringCount, camera); - ringCount = 0; - } - GpuParticleRenderer.flush(frameTime, camera); - } - - @SubscribeEvent - private static void drawAttachmentsAndHighlights(RenderLevelStageEvent.AfterTranslucentParticles event) { - if (!matchesFrame(event)) return; - PlayerAttachmentRenderer.drawPending(); - SphereHighlight.draw(camera.position(), MODEL_VIEW); + static Matrix4f projection() { + return PROJECTION; } @SubscribeEvent @@ -261,16 +260,15 @@ private static void clearWorldEffects() { ringCount = 0; } - /** 将管线、资源重载和玩家模型层接入客户端模组总线。 */ + /** 将资源重载和玩家模型层接入客户端模组总线。 */ @ApiStatus.Internal public static void init(IEventBus modBus) { - modBus.addListener(EffectRenderPipelines::init); modBus.addListener(EffectRenderer::initResourceReload); modBus.addListener(PlayerAttachmentRenderer::initLayers); } - private static void initResourceReload(AddClientReloadListenersEvent event) { - event.addListener(ModularMCLibUtils.id("effects"), (ResourceManagerReloadListener) manager -> releaseRenderBuffers()); + private static void initResourceReload(RegisterClientReloadListenersEvent event) { + event.registerReloadListener((ResourceManagerReloadListener) manager -> releaseRenderBuffers()); } private static void releaseRenderBuffers() { @@ -295,7 +293,7 @@ private static void releaseOnShutdown(GameShuttingDownEvent event) { } /** - * 在世界状态提取时提交一帧的绘制指令。 + * 在世界绘制阶段采集一帧的效果指令。 * 回调在客户端渲染线程执行,可利用世界和相机状态决定要提交的效果。 */ @FunctionalInterface diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/GpuParticleRenderer.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/GpuParticleRenderer.java index 40374e0..6bda38f 100644 --- a/src/main/java/com/modularmc/mmclutils/client/render/effect/GpuParticleRenderer.java +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/GpuParticleRenderer.java @@ -6,7 +6,7 @@ import net.minecraft.client.Camera; import net.minecraft.client.renderer.texture.TextureAtlas; -import com.mojang.blaze3d.opengl.GlStateManager; +import com.mojang.blaze3d.platform.GlStateManager; import org.joml.Vector3f; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; @@ -350,7 +350,7 @@ static void flush(double frameTime, Camera camera) { } return; } - var cam = camera.position(); + var cam = camera.getPosition(); double hx = Math.floor(cam.x / 1024) * 1024, hy = Math.floor(cam.y / 1024) * 1024, hz = Math.floor(cam.z / 1024) * 1024; var left = new Vector3f(-1, 0, 0).rotate(camera.rotation()); var up = new Vector3f(0, 1, 0).rotate(camera.rotation()); diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleEmitters.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleEmitters.java index d1d747e..72c85b4 100644 --- a/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleEmitters.java +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleEmitters.java @@ -99,15 +99,15 @@ private static void remove(int i) { private static void spawn(ClientLevel level, ParticleOptions particle, double x, double y, double z, int count, double dx, double dy, double dz, double speed) { - var eye = Minecraft.getInstance().gameRenderer.getMainCamera().position(); + var eye = Minecraft.getInstance().gameRenderer.getMainCamera().getPosition(); if (eye.distanceToSqr(x, y, z) > ParticleEffects.SPAWN_DISTANCE * ParticleEffects.SPAWN_DISTANCE) return; var random = level.getRandom(); if (count == 0) { - level.addParticle(particle, true, false, x, y, z, speed * dx, speed * dy, speed * dz); + level.addParticle(particle, true, x, y, z, speed * dx, speed * dy, speed * dz); return; } for (int i = 0; i < count; i++) { - level.addParticle(particle, true, false, x + random.nextGaussian() * dx, y + random.nextGaussian() * dy, z + random.nextGaussian() * dz, + level.addParticle(particle, true, x + random.nextGaussian() * dx, y + random.nextGaussian() * dy, z + random.nextGaussian() * dz, random.nextGaussian() * speed, random.nextGaussian() * speed, random.nextGaussian() * speed); } } diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleGeometry.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleGeometry.java index 8505a8a..b38edd6 100644 --- a/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleGeometry.java +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleGeometry.java @@ -26,7 +26,7 @@ static void release() { static void generate(GpuParticleRenderer.Pool pool, double now, double epoch, Camera camera, ByteBuffer frames, int frameColumns) { int size = pool.stream ? pool.count : pool.highWater; - var eye = camera.position(); + var eye = camera.getPosition(); LEFT.set(-1, 0, 0).rotate(camera.rotation()); UP.set(0, 1, 0).rotate(camera.rotation()); HALOS.begin(size); diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/PlayerAttachmentRenderer.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/PlayerAttachmentRenderer.java index 7363af2..92f37bb 100644 --- a/src/main/java/com/modularmc/mmclutils/client/render/effect/PlayerAttachmentRenderer.java +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/PlayerAttachmentRenderer.java @@ -1,11 +1,12 @@ package com.modularmc.mmclutils.client.render.effect; -import net.minecraft.client.model.player.PlayerModel; -import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.model.PlayerModel; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.entity.RenderLayerParent; import net.minecraft.client.renderer.entity.layers.RenderLayer; -import net.minecraft.client.renderer.entity.state.AvatarRenderState; -import net.minecraft.util.ARGB; +import net.minecraft.client.renderer.entity.player.PlayerRenderer; +import net.minecraft.util.FastColor.ARGB32; import net.minecraft.util.Mth; import net.minecraft.world.phys.Vec3; import net.neoforged.neoforge.client.event.EntityRenderersEvent; @@ -31,6 +32,7 @@ public final class PlayerAttachmentRenderer { private static final ObjectArrayList PENDING = new ObjectArrayList<>(); private static final ReferenceOpenHashSet UPLOADED_SHEETS = new ReferenceOpenHashSet<>(); private static final Vector3f TRANSFORMED_POSITION = new Vector3f(); + private static final Matrix4f DRAW_MATRIX = new Matrix4f(); private static @Nullable Vec3 cameraOrigin; private static int count; @@ -56,7 +58,7 @@ public static void remove(Attachment attachment) { static void initLayers(EntityRenderersEvent.AddLayers event) { for (var skin : event.getSkins()) { - var renderer = event.getPlayerRenderer(skin); + PlayerRenderer renderer = event.getSkin(skin); if (renderer != null) renderer.addLayer(new Layer(renderer)); } } @@ -81,7 +83,7 @@ static void drawPending() { try { for (int i = 0; i < count; i++) { var draw = PENDING.get(i); - draw.sheet.draw(draw.transform, draw.tint); + draw.sheet.draw(DRAW_MATRIX.set(EffectRenderer.modelView()).mul(draw.transform), draw.tint); } } finally { clearFrame(); @@ -156,24 +158,24 @@ public interface Attachment { /** * 采集单个玩家的附着效果。 * - * @param state 原版提取的玩家渲染状态 - * @param model 已应用动画的玩家模型 - * @param pose 实体相对相机的姿态栈 + * @param player 当前正在渲染的客户端玩家 + * @param model 已应用动画的玩家模型 + * @param pose 实体相对相机的姿态栈 */ - void collect(AvatarRenderState state, PlayerModel model, PoseStack pose); + void collect(AbstractClientPlayer player, PlayerModel model, PoseStack pose); } - private static final class Layer extends RenderLayer { + private static final class Layer extends RenderLayer> { - private Layer(RenderLayerParent parent) { + private Layer(RenderLayerParent> parent) { super(parent); } @Override - public void submit(PoseStack pose, SubmitNodeCollector collector, int light, AvatarRenderState state, - float yaw, float pitch) { + public void render(PoseStack pose, MultiBufferSource buffers, int light, AbstractClientPlayer player, + float limbSwing, float limbSwingAmount, float partialTick, float ageInTicks, float yaw, float pitch) { if (!inLevel()) return; - for (int i = 0; i < LISTENERS.size(); i++) LISTENERS.get(i).collect(state, getParentModel(), pose); + for (int i = 0; i < LISTENERS.size(); i++) LISTENERS.get(i).collect(player, getParentModel(), pose); } } @@ -290,9 +292,9 @@ private void upload(EffectVertices vertices, EffectQuadBuffer output, float size int color = Float.floatToRawIntBits(pixels[i + 2]); float alpha = pixels[i + 3]; // 加法混合直接累加 RGB,由顶点颜色携带像素亮度。 - float r = Mth.lerp(whiten, ARGB.redFloat(color), 1) * alpha; - float g = Mth.lerp(whiten, ARGB.greenFloat(color), 1) * alpha; - float b = Mth.lerp(whiten, ARGB.blueFloat(color), 1) * alpha; + float r = Mth.lerp(whiten, ARGB32.red(color) / 255f, 1) * alpha; + float g = Mth.lerp(whiten, ARGB32.green(color) / 255f, 1) * alpha; + float b = Mth.lerp(whiten, ARGB32.blue(color) / 255f, 1) * alpha; vertices.writeVertex(x - half, y - half, 0, r, g, b, alpha, 0, 0); vertices.writeVertex(x - half, y + half, 0, r, g, b, alpha, 0, 1); vertices.writeVertex(x + half, y + half, 0, r, g, b, alpha, 1, 1); diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/RingGeometry.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/RingGeometry.java index 57b2784..cfdb913 100644 --- a/src/main/java/com/modularmc/mmclutils/client/render/effect/RingGeometry.java +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/RingGeometry.java @@ -2,7 +2,7 @@ import net.minecraft.client.Camera; import net.minecraft.core.Direction; -import net.minecraft.util.ARGB; +import net.minecraft.util.FastColor.ARGB32; import net.minecraft.util.Mth; import org.joml.Matrix3f; @@ -78,7 +78,7 @@ private static void particles(EffectRenderer.RingCommand command) { if (fade == 0) continue; point(command, angle, radial, height, CENTER); int rgb = command.palette[ring.tone(i)]; - float red = ARGB.redFloat(rgb), green = ARGB.greenFloat(rgb), blue = ARGB.blueFloat(rgb); + float red = ARGB32.red(rgb) / 255f, green = ARGB32.green(rgb) / 255f, blue = ARGB32.blue(rgb) / 255f; if (half > 0) { ring.spin(i, time, ROTATION); voxel(half * fade, red, green, blue); @@ -111,9 +111,9 @@ private static void voxel(float half, float red, float green, float blue) { private static void ribbon(EffectRenderer.RingCommand command, float width, int strength) { if (width <= 0 || strength <= 0) return; - float red = ARGB.red(command.baseColor) * strength / 65025f; - float green = ARGB.green(command.baseColor) * strength / 65025f; - float blue = ARGB.blue(command.baseColor) * strength / 65025f; + float red = ARGB32.red(command.baseColor) * strength / 65025f; + float green = ARGB32.green(command.baseColor) * strength / 65025f; + float blue = ARGB32.blue(command.baseColor) * strength / 65025f; int strands = Math.max(1, command.shape.strands()); for (int strand = 0; strand < strands; strand++) { int pieces = RingRenderer.RIBBON_SEGMENTS / strands + (strand < RingRenderer.RIBBON_SEGMENTS % strands ? 1 : 0); diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/RingRenderer.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/RingRenderer.java index 6a6a1b0..f475fbb 100644 --- a/src/main/java/com/modularmc/mmclutils/client/render/effect/RingRenderer.java +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/RingRenderer.java @@ -4,7 +4,7 @@ import net.minecraft.client.Camera; -import com.mojang.blaze3d.opengl.GlStateManager; +import com.mojang.blaze3d.platform.GlStateManager; import it.unimi.dsi.fastutil.objects.Reference2IntLinkedOpenHashMap; import org.joml.Vector3f; import org.lwjgl.opengl.GL11; diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/TransformFeedbackProgram.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/TransformFeedbackProgram.java index 57b6db9..4302ce1 100644 --- a/src/main/java/com/modularmc/mmclutils/client/render/effect/TransformFeedbackProgram.java +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/TransformFeedbackProgram.java @@ -4,7 +4,6 @@ import net.minecraft.client.Minecraft; -import com.mojang.blaze3d.systems.RenderSystem; import org.jspecify.annotations.Nullable; import org.lwjgl.opengl.GL; import org.lwjgl.opengl.GL20; @@ -32,7 +31,7 @@ int uniform(String name) { } static boolean supported() { - return RenderSystem.getDevice().getBackendName().equalsIgnoreCase("OpenGL") && GL.getCapabilities().OpenGL33; + return GL.getCapabilities().OpenGL33; } private static String source(String name) throws IOException { diff --git a/src/main/java/com/modularmc/mmclutils/client/render/geometry/SectionGeometryCapture.java b/src/main/java/com/modularmc/mmclutils/client/render/geometry/SectionGeometryCapture.java index b8320e3..e1df59b 100644 --- a/src/main/java/com/modularmc/mmclutils/client/render/geometry/SectionGeometryCapture.java +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/SectionGeometryCapture.java @@ -101,7 +101,7 @@ private int exposedFaces(ClientLevel level, BlockPos position, BlockState state) if (chunk == null) faces |= DirectionUtils.mask(direction); else { BlockState adjacent = chunk.getBlockState(neighbor); - if ((fluid.isEmpty() || !fluid.getType().isSame(adjacent.getFluidState().getType())) && Block.shouldRenderFace(level, position, state, adjacent, direction)) faces |= DirectionUtils.mask(direction); + if ((fluid.isEmpty() || !fluid.getType().isSame(adjacent.getFluidState().getType())) && Block.shouldRenderFace(state, level, position, direction, neighbor)) faces |= DirectionUtils.mask(direction); } } return faces; diff --git a/src/main/java/com/modularmc/mmclutils/client/render/geometry/StaticMesh.java b/src/main/java/com/modularmc/mmclutils/client/render/geometry/StaticMesh.java index 33766a5..576aed2 100644 --- a/src/main/java/com/modularmc/mmclutils/client/render/geometry/StaticMesh.java +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/StaticMesh.java @@ -1,20 +1,28 @@ package com.modularmc.mmclutils.client.render.geometry; -import com.mojang.blaze3d.buffers.GpuBuffer; -import com.mojang.blaze3d.systems.RenderPass; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.ShaderInstance; + +import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.MeshData; import com.mojang.blaze3d.vertex.VertexFormat; -import org.jspecify.annotations.Nullable; +import org.joml.Matrix4f; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL30; -/** 保存能跨帧使用的 GPU 顶点和索引。上传、提交及释放都在渲染线程完成。 */ +/** 保存能跨帧使用的 GPU 顶点和索引。上传、绘制及释放都在渲染线程完成。 */ public final class StaticMesh implements AutoCloseable { - private final GpuBuffer vertices; - private final @Nullable GpuBuffer indices; + private final int array; + private final int vertices; + private final int indices; private final MeshData.DrawState state; + private boolean closed; - private StaticMesh(GpuBuffer vertices, @Nullable GpuBuffer indices, MeshData.DrawState state) { + private StaticMesh(int array, int vertices, int indices, MeshData.DrawState state) { + this.array = array; this.vertices = vertices; this.indices = indices; this.state = state; @@ -23,15 +31,32 @@ private StaticMesh(GpuBuffer vertices, @Nullable GpuBuffer indices, MeshData.Dra /** 复制网格数据。调用方仍负责关闭传入的网格。 */ public static StaticMesh upload(String label, MeshData mesh) { RenderSystem.assertOnRenderThread(); - var device = RenderSystem.getDevice(); - GpuBuffer vertices = device.createBuffer(() -> label + " vertices", GpuBuffer.USAGE_VERTEX, mesh.vertexBuffer()); + int previousArray = GL11.glGetInteger(GL30.GL_VERTEX_ARRAY_BINDING); + int previousBuffer = GL11.glGetInteger(GL15.GL_ARRAY_BUFFER_BINDING); + var indexBytes = mesh.indexBuffer(); + int array = GL30.glGenVertexArrays(); + int vertices = GL15.glGenBuffers(); + int indices = indexBytes == null ? 0 : GL15.glGenBuffers(); + var output = new StaticMesh(array, vertices, indices, mesh.drawState()); try { - var bytes = mesh.indexBuffer(); - GpuBuffer indices = bytes == null ? null : device.createBuffer(() -> label + " indices", GpuBuffer.USAGE_INDEX, bytes); - return new StaticMesh(vertices, indices, mesh.drawState()); + if (array == 0 || vertices == 0 || indexBytes != null && indices == 0) { + throw new IllegalStateException("无法为网格 " + label + " 分配缓冲"); + } + GlStateManager._glBindVertexArray(array); + GlStateManager._glBindBuffer(GL15.GL_ARRAY_BUFFER, vertices); + GL15.glBufferData(GL15.GL_ARRAY_BUFFER, mesh.vertexBuffer(), GL15.GL_STATIC_DRAW); + output.format().setupBufferState(); + if (indices != 0) { + GlStateManager._glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, indices); + GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, indexBytes, GL15.GL_STATIC_DRAW); + } + return output; } catch (RuntimeException | Error failure) { - vertices.close(); + output.close(); throw failure; + } finally { + GlStateManager._glBindVertexArray(previousArray); + GlStateManager._glBindBuffer(GL15.GL_ARRAY_BUFFER, previousBuffer); } } @@ -40,31 +65,41 @@ public VertexFormat format() { return state.format(); } - /** 返回网格的图元模式,供调用方选择绘制管线。 */ + /** 返回网格的图元模式,供调用方配置渲染状态。 */ public VertexFormat.Mode mode() { return state.mode(); } - /** 在已设置管线、变换及贴图的 pass 中提交。管线的顶点格式和图元须与网格一致。 */ - public void draw(RenderPass pass) { - pass.setVertexBuffer(0, vertices); - if (indices == null) { - var sequential = RenderSystem.getSequentialBuffer(state.mode()); - pass.setIndexBuffer(sequential.getBuffer(state.indexCount()), sequential.type()); - } else { - pass.setIndexBuffer(indices, state.indexType()); + /** 用匹配的着色器绘制网格。混合、深度和贴图由调用方配置。 */ + public void draw(Matrix4f modelView, Matrix4f projection, ShaderInstance shader) { + RenderSystem.assertOnRenderThread(); + if (closed) throw new IllegalStateException("网格已关闭"); + int previousArray = GL11.glGetInteger(GL30.GL_VERTEX_ARRAY_BINDING); + try { + GlStateManager._glBindVertexArray(array); + VertexFormat.IndexType indexType = state.indexType(); + if (indices == 0) { + var sequential = RenderSystem.getSequentialBuffer(state.mode()); + sequential.bind(state.indexCount()); + indexType = sequential.type(); + } + shader.setDefaultUniforms(state.mode(), modelView, projection, Minecraft.getInstance().getWindow()); + shader.apply(); + RenderSystem.drawElements(state.mode().asGLMode, state.indexCount(), indexType.asGLType); + } finally { + shader.clear(); + GlStateManager._glBindVertexArray(previousArray); } - pass.drawIndexed(0, 0, state.indexCount(), 1); } - /** 在渲染线程释放网格的顶点缓冲和独立索引缓冲。 */ + /** 在渲染线程释放网格的顶点和索引。 */ @Override public void close() { RenderSystem.assertOnRenderThread(); - try { - if (indices != null) indices.close(); - } finally { - vertices.close(); - } + if (closed) return; + GlStateManager._glDeleteVertexArrays(array); + GlStateManager._glDeleteBuffers(vertices); + if (indices != 0) GlStateManager._glDeleteBuffers(indices); + closed = true; } } diff --git a/src/main/java/com/modularmc/mmclutils/client/render/geometry/VertexWriters.java b/src/main/java/com/modularmc/mmclutils/client/render/geometry/VertexWriters.java index e641ab3..7f60e2f 100644 --- a/src/main/java/com/modularmc/mmclutils/client/render/geometry/VertexWriters.java +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/VertexWriters.java @@ -18,7 +18,8 @@ private VertexWriters() {} /** 按指定姿态写出位置和法线,其余属性使用传入的图集 UV、ARGB、覆盖层与打包光照。 */ public static void vertex(VertexConsumer vertices, PoseStack.Pose pose, Vector3fc position, int color, float u, float v, int overlay, int light, Vector3fc normal) { - vertices.addVertex(pose, position).setColor(color).setUv(u, v).setOverlay(overlay).setLight(light).setNormal(pose, normal); + vertices.addVertex(pose, position.x(), position.y(), position.z()).setColor(color).setUv(u, v) + .setOverlay(overlay).setLight(light).setNormal(pose, normal.x(), normal.y(), normal.z()); } /** 按四边形顶点顺序写入,同一打包光照应用于四点。 */ diff --git a/src/main/java/com/modularmc/mmclutils/client/texture/ImageTextures.java b/src/main/java/com/modularmc/mmclutils/client/texture/ImageTextures.java index 65743c1..f77eb96 100644 --- a/src/main/java/com/modularmc/mmclutils/client/texture/ImageTextures.java +++ b/src/main/java/com/modularmc/mmclutils/client/texture/ImageTextures.java @@ -2,7 +2,7 @@ import net.minecraft.client.renderer.texture.DynamicTexture; import net.minecraft.client.renderer.texture.TextureManager; -import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceLocation; import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.systems.RenderSystem; @@ -22,7 +22,7 @@ public final class ImageTextures implements AutoCloseable { private final TextureManager textures; private final int capacity; - private final Object2ObjectLinkedOpenHashMap entries = new Object2ObjectLinkedOpenHashMap<>(); + private final Object2ObjectLinkedOpenHashMap entries = new Object2ObjectLinkedOpenHashMap<>(); /** 创建渲染线程使用的动态贴图缓存。容量为同时保留的贴图数,须为正数。缓存占有登记的标识。 */ public ImageTextures(TextureManager textures, int capacity) { @@ -32,33 +32,33 @@ public ImageTextures(TextureManager textures, int capacity) { } /** 查询缓存并更新最近使用顺序。缺失时返回空值,返回的贴图由缓存持有。 */ - public @Nullable DynamicTexture get(Identifier id) { + public @Nullable DynamicTexture get(ResourceLocation id) { RenderSystem.assertOnRenderThread(); return entries.getAndMoveToLast(id); } /** 在渲染线程从文件解码并登记 PNG,方法返回或抛出异常时关闭文件流。 */ - public DynamicTexture load(Identifier id, Path path, Limits limits) throws IOException { + public DynamicTexture load(ResourceLocation id, Path path, Limits limits) throws IOException { try (InputStream input = Files.newInputStream(path)) { return load(id, input, limits); } } /** 在渲染线程读取和上传。输入流由调用方关闭。 */ - public DynamicTexture load(Identifier id, InputStream input, Limits limits) throws IOException { + public DynamicTexture load(ResourceLocation id, InputStream input, Limits limits) throws IOException { RenderSystem.assertOnRenderThread(); return load(id, input.readNBytes(limits.bytes() + 1), limits); } /** 读取 PNG 数据。解码前限制文件大小和像素数。 */ - public DynamicTexture load(Identifier id, byte[] bytes, Limits limits) throws IOException { + public DynamicTexture load(ResourceLocation id, byte[] bytes, Limits limits) throws IOException { RenderSystem.assertOnRenderThread(); if (bytes.length > limits.bytes()) throw new IOException("贴图数据超出字节上限 " + id); checkHeader(id, bytes, limits); NativeImage image = NativeImage.read(bytes); DynamicTexture texture; try { - texture = new DynamicTexture(id::toString, image); + texture = new DynamicTexture(image); } catch (RuntimeException | Error failure) { image.close(); throw failure; @@ -75,7 +75,7 @@ public DynamicTexture load(Identifier id, byte[] bytes, Limits limits) throws IO } /** 释放匹配标识的 GPU 贴图,并将其从缓存移除。 */ - public void invalidate(Identifier id) { + public void invalidate(ResourceLocation id) { RenderSystem.assertOnRenderThread(); if (entries.remove(id) != null) textures.release(id); } @@ -92,7 +92,7 @@ public void close() { clear(); } - private static void checkHeader(Identifier id, byte[] bytes, Limits limits) throws IOException { + private static void checkHeader(ResourceLocation id, byte[] bytes, Limits limits) throws IOException { if (bytes.length < 33 || readInt(bytes, 0) != 0x89504e47 || readInt(bytes, 4) != 0x0d0a1a0a || readInt(bytes, 8) != 13 || readInt(bytes, 12) != 0x49484452) { throw new IOException("贴图缺少有效的 PNG 标头 " + id); } diff --git a/src/main/java/com/modularmc/mmclutils/client/texture/SpriteLookup.java b/src/main/java/com/modularmc/mmclutils/client/texture/SpriteLookup.java index 648069f..903ebe4 100644 --- a/src/main/java/com/modularmc/mmclutils/client/texture/SpriteLookup.java +++ b/src/main/java/com/modularmc/mmclutils/client/texture/SpriteLookup.java @@ -2,6 +2,7 @@ import com.modularmc.mmclutils.client.model.QuadView; +import net.minecraft.client.renderer.texture.MissingTextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureAtlas; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -19,7 +20,7 @@ public final class SpriteLookup { /** 在当前图集上建立查询索引。资源重载后,须使用新图集重新创建。 */ public SpriteLookup(TextureAtlas atlas) { - this(atlas.getTextures().values(), atlas.missingSprite()); + this(atlas.getTextures().values(), atlas.getSprite(MissingTextureAtlasSprite.getLocation())); } /** 以给定的精灵集合建立索引,未命中时返回指定的缺失纹理。 */ diff --git a/src/main/java/com/modularmc/mmclutils/client/texture/TextureMetadata.java b/src/main/java/com/modularmc/mmclutils/client/texture/TextureMetadata.java index 010bf5d..fa2cc26 100644 --- a/src/main/java/com/modularmc/mmclutils/client/texture/TextureMetadata.java +++ b/src/main/java/com/modularmc/mmclutils/client/texture/TextureMetadata.java @@ -1,8 +1,8 @@ package com.modularmc.mmclutils.client.texture; import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.resources.Identifier; -import net.minecraft.server.packs.metadata.MetadataSectionType; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.metadata.MetadataSectionSerializer; import net.minecraft.server.packs.resources.ResourceManager; import java.io.IOException; @@ -14,18 +14,18 @@ public final class TextureMetadata { private TextureMetadata() {} /** 将精灵标识映射为资源包内的 PNG 文件标识。 */ - public static Identifier textureFile(Identifier id) { + public static ResourceLocation textureFile(ResourceLocation id) { return id.withPath(path -> "textures/" + path + ".png"); } /** 按精灵的源贴图查找指定元数据,资源或元数据段缺失时返回空结果。 */ - public static Optional readSprite(ResourceManager resources, TextureAtlasSprite sprite, MetadataSectionType type) - throws IOException { + public static Optional readSprite(ResourceManager resources, TextureAtlasSprite sprite, MetadataSectionSerializer type) + throws IOException { return read(resources, textureFile(sprite.contents().name()), type); } /** 读取当前资源优先级下的贴图元数据。资源缺失时返回空结果,读取失败时传播 I/O 异常。 */ - public static Optional read(ResourceManager resources, Identifier file, MetadataSectionType type) throws IOException { + public static Optional read(ResourceManager resources, ResourceLocation file, MetadataSectionSerializer type) throws IOException { var resource = resources.getResource(file); return resource.isPresent() ? resource.get().metadata().getSection(type) : Optional.empty(); } diff --git a/src/main/java/com/modularmc/mmclutils/mixin/mc/client/GlBufferAccessor.java b/src/main/java/com/modularmc/mmclutils/mixin/mc/client/GlBufferAccessor.java deleted file mode 100644 index 11f044f..0000000 --- a/src/main/java/com/modularmc/mmclutils/mixin/mc/client/GlBufferAccessor.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.modularmc.mmclutils.mixin.mc.client; - -import com.mojang.blaze3d.opengl.GlBuffer; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -/** 为渲染后端读取原版 GL 缓冲对象的驱动句柄。 */ -@Mixin(GlBuffer.class) -public interface GlBufferAccessor { - - /** 返回原版缓冲包装所持有的 OpenGL 缓冲标识。 */ - @Accessor("handle") - int mmclutils$handle(); -} diff --git a/src/main/java/com/modularmc/mmclutils/mixin/mc/client/KeyBindsScreenMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/mc/client/KeyBindsScreenMixin.java index 882985f..b91b10b 100644 --- a/src/main/java/com/modularmc/mmclutils/mixin/mc/client/KeyBindsScreenMixin.java +++ b/src/main/java/com/modularmc/mmclutils/mixin/mc/client/KeyBindsScreenMixin.java @@ -3,15 +3,14 @@ import com.modularmc.mmclutils.client.input.ClientInput; import com.modularmc.mmclutils.client.input.KeyChordMapping; +import net.minecraft.Util; import net.minecraft.client.KeyMapping; import net.minecraft.client.gui.screens.options.controls.KeyBindsList; import net.minecraft.client.gui.screens.options.controls.KeyBindsScreen; -import net.minecraft.client.input.KeyEvent; -import net.minecraft.client.input.MouseButtonEvent; -import net.minecraft.util.Util; import com.mojang.blaze3d.platform.InputConstants; import org.jspecify.annotations.Nullable; +import org.lwjgl.glfw.GLFW; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; @@ -31,26 +30,26 @@ public abstract class KeyBindsScreenMixin { private KeyBindsList keyBindsList; @Inject(method = "keyPressed", at = @At("HEAD"), cancellable = true) - private void mmclutils$captureKey(KeyEvent event, CallbackInfoReturnable callback) { + private void mmclutils$captureKey(int keyCode, int scanCode, int modifiers, CallbackInfoReturnable callback) { if (!(selectedKey instanceof KeyChordMapping chord)) return; - InputConstants.Key key = InputConstants.getKey(event); - if (event.isEscape()) mmclutils$finish(chord, InputConstants.UNKNOWN, 0); + InputConstants.Key key = InputConstants.getKey(keyCode, scanCode); + if (keyCode == GLFW.GLFW_KEY_ESCAPE) mmclutils$finish(chord, InputConstants.UNKNOWN, 0); else if (ClientInput.keyModifierBit(key) == 0) mmclutils$finish(chord, key, ClientInput.modifiers()); callback.setReturnValue(true); } @Inject(method = "keyReleased", at = @At("HEAD"), cancellable = true) - private void mmclutils$releaseKey(KeyEvent event, CallbackInfoReturnable callback) { + private void mmclutils$releaseKey(int keyCode, int scanCode, int modifiers, CallbackInfoReturnable callback) { if (!(selectedKey instanceof KeyChordMapping chord)) return; - InputConstants.Key key = InputConstants.getKey(event); + InputConstants.Key key = InputConstants.getKey(keyCode, scanCode); if (ClientInput.keyModifierBit(key) != 0) mmclutils$finish(chord, key, ClientInput.modifiers()); callback.setReturnValue(true); } @Inject(method = "mouseClicked", at = @At("HEAD"), cancellable = true) - private void mmclutils$captureMouse(MouseButtonEvent event, boolean doubleClick, CallbackInfoReturnable callback) { + private void mmclutils$captureMouse(double mouseX, double mouseY, int button, CallbackInfoReturnable callback) { if (!(selectedKey instanceof KeyChordMapping chord)) return; - mmclutils$finish(chord, InputConstants.Type.MOUSE.getOrCreate(event.button()), ClientInput.modifiers()); + mmclutils$finish(chord, InputConstants.Type.MOUSE.getOrCreate(button), ClientInput.modifiers()); callback.setReturnValue(true); } diff --git a/src/main/java/com/modularmc/mmclutils/mixin/mc/client/OptionsMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/mc/client/OptionsMixin.java index 05778de..49fa46d 100644 --- a/src/main/java/com/modularmc/mmclutils/mixin/mc/client/OptionsMixin.java +++ b/src/main/java/com/modularmc/mmclutils/mixin/mc/client/OptionsMixin.java @@ -13,6 +13,8 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import java.util.function.Consumer; + /** 在选项序列化流程中读写组合键的主键与修饰键。 */ @Mixin(Options.class) public abstract class OptionsMixin { @@ -27,9 +29,12 @@ public abstract class OptionsMixin { } } - @WrapOperation(method = "load", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Options;processOptions(Lnet/minecraft/client/Options$FieldAccess;)V")) - private void mmclutils$readLegacyChords(Options options, Options.FieldAccess access, Operation original) { - original.call(options, access); + @WrapOperation(method = "load(Z)V", at = @At(value = "INVOKE", target = "Ljava/util/function/Consumer;accept(Ljava/lang/Object;)V")) + private void mmclutils$readLegacyChords(Consumer processor, Object value, Operation original, + boolean limited) { + original.call(processor, value); + if (limited) return; + var access = (Options.FieldAccess) value; for (KeyMapping mapping : keyMappings) { if (mapping instanceof KeyChordMapping chord) chord.readLegacyOptions(access); } diff --git a/src/main/java/com/modularmc/mmclutils/mixin/mc/world/ServerChunkCacheMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/mc/world/ServerChunkCacheMixin.java index 1efbda3..6eedd7e 100644 --- a/src/main/java/com/modularmc/mmclutils/mixin/mc/world/ServerChunkCacheMixin.java +++ b/src/main/java/com/modularmc/mmclutils/mixin/mc/world/ServerChunkCacheMixin.java @@ -39,7 +39,7 @@ public abstract class ServerChunkCacheMixin implements Source { @Override public @Nullable LevelChunk mmclutils$loadedChunk(int chunkX, int chunkZ) { if (Thread.currentThread() == mainThread) return getChunkNow(chunkX, chunkZ); - long key = ChunkPos.pack(chunkX, chunkZ); + long key = ChunkPos.asLong(chunkX, chunkZ); LevelChunk cached = mmclutils$recent.get(key); if (cached != null) return cached; ChunkHolder holder = mmclutils$visibleChunk(key); diff --git a/src/main/java/com/modularmc/mmclutils/utils/BlockPosUtils.java b/src/main/java/com/modularmc/mmclutils/utils/BlockPosUtils.java index afa577a..1debcb7 100644 --- a/src/main/java/com/modularmc/mmclutils/utils/BlockPosUtils.java +++ b/src/main/java/com/modularmc/mmclutils/utils/BlockPosUtils.java @@ -3,8 +3,8 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.GlobalPos; import net.minecraft.core.registries.Registries; -import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; import java.util.Arrays; import java.util.Comparator; @@ -151,7 +151,7 @@ public static double distance(long first, long second) { } /** 用维度标识和原版打包坐标构建全局位置。坐标为零时表示该维度的原点。 */ - public static GlobalPos globalPos(Identifier dimension, long packedPos) { + public static GlobalPos globalPos(ResourceLocation dimension, long packedPos) { return GlobalPos.of(ResourceKey.create(Registries.DIMENSION, dimension), BlockPos.of(packedPos)); } } diff --git a/src/main/java/com/modularmc/mmclutils/utils/ColorUtils.java b/src/main/java/com/modularmc/mmclutils/utils/ColorUtils.java index b7b1bd9..3f3e8b9 100644 --- a/src/main/java/com/modularmc/mmclutils/utils/ColorUtils.java +++ b/src/main/java/com/modularmc/mmclutils/utils/ColorUtils.java @@ -1,6 +1,7 @@ package com.modularmc.mmclutils.utils; -import net.minecraft.util.ARGB; +import net.minecraft.util.FastColor.ABGR32; +import net.minecraft.util.FastColor.ARGB32; import net.minecraft.util.Mth; import net.minecraft.world.item.DyeColor; import net.minecraft.world.level.material.MapColor; @@ -16,26 +17,26 @@ private ColorUtils() {} /** 将给定透明度和低 24 位的 RGB 合成为 ARGB。 */ public static int withAlpha(int rgb, int alpha) { - return ARGB.color(alpha, rgb); + return ARGB32.color(alpha, rgb); } /** 输入只含 RGB 分量时补上透明度,已有非零透明度的颜色直接返回。 */ public static int withDefaultAlpha(int color, int alpha) { - return ARGB.alpha(color) == 0 ? withAlpha(color, alpha) : color; + return ARGB32.alpha(color) == 0 ? withAlpha(color, alpha) : color; } /** 以 0~1 的比例逐通道插值 ARGB,并四舍五入到整数分量。 */ public static int interpolate(int from, int to, float amount) { - return ARGB.color( - Math.round(Mth.lerp(amount, ARGB.alpha(from), ARGB.alpha(to))), - Math.round(Mth.lerp(amount, ARGB.red(from), ARGB.red(to))), - Math.round(Mth.lerp(amount, ARGB.green(from), ARGB.green(to))), - Math.round(Mth.lerp(amount, ARGB.blue(from), ARGB.blue(to)))); + return ARGB32.color( + Math.round(Mth.lerp(amount, ARGB32.alpha(from), ARGB32.alpha(to))), + Math.round(Mth.lerp(amount, ARGB32.red(from), ARGB32.red(to))), + Math.round(Mth.lerp(amount, ARGB32.green(from), ARGB32.green(to))), + Math.round(Mth.lerp(amount, ARGB32.blue(from), ARGB32.blue(to)))); } /** 交换红色与蓝色通道,保持透明度和绿色通道。 */ public static int swapRedBlue(int argb) { - return ARGB.toABGR(argb); + return ABGR32.fromArgb32(argb); } /** 将最高字节的透明度移到最低字节。 */ @@ -45,12 +46,12 @@ public static int argbToRgba(int argb) { /** 返回归一化到 0~1 的红、绿、蓝三个分量。 */ public static float[] rgb(int argb) { - return new float[] { ARGB.redFloat(argb), ARGB.greenFloat(argb), ARGB.blueFloat(argb) }; + return new float[] { ARGB32.red(argb) / 255f, ARGB32.green(argb) / 255f, ARGB32.blue(argb) / 255f }; } /** 两个 RGBA 值中位置相同的分量相乘,结果仍按 RGBA 排列。 */ public static int multiplyRgba(int first, int second) { - return ARGB.multiply(first, second); + return ARGB32.multiply(first, second); } /** 以 RGB 分量的平方距离匹配最接近的染料文字颜色。 */ @@ -74,7 +75,7 @@ public static MapColor nearestMapColor(int rgb) { for (int id = 1; id < 64; id++) { MapColor color = MapColor.byId(id); if (color == MapColor.NONE) continue; - int distance = rgbDistanceSquared(rgb, color.calculateARGBColor(MapColor.Brightness.NORMAL)); + int distance = rgbDistanceSquared(rgb, swapRedBlue(color.calculateRGBColor(MapColor.Brightness.NORMAL))); if (distance < bestDistance) { bestDistance = distance; nearest = color; @@ -84,9 +85,9 @@ public static MapColor nearestMapColor(int rgb) { } private static int rgbDistanceSquared(int first, int second) { - int red = ARGB.red(first) - ARGB.red(second); - int green = ARGB.green(first) - ARGB.green(second); - int blue = ARGB.blue(first) - ARGB.blue(second); + int red = ARGB32.red(first) - ARGB32.red(second); + int green = ARGB32.green(first) - ARGB32.green(second); + int blue = ARGB32.blue(first) - ARGB32.blue(second); return red * red + green * green + blue * blue; } @@ -96,10 +97,10 @@ public static int[] stepGradient(int from, int to, int alpha, int steps) { int[] result = new int[steps]; for (int index = 0; index < steps; index++) { float amount = (float) index / (steps - 1); - result[index] = ARGB.color(alpha, - Math.round(Mth.lerp(amount, ARGB.red(from), ARGB.red(to))), - Math.round(Mth.lerp(amount, ARGB.green(from), ARGB.green(to))), - Math.round(Mth.lerp(amount, ARGB.blue(from), ARGB.blue(to)))); + result[index] = ARGB32.color(alpha, + Math.round(Mth.lerp(amount, ARGB32.red(from), ARGB32.red(to))), + Math.round(Mth.lerp(amount, ARGB32.green(from), ARGB32.green(to))), + Math.round(Mth.lerp(amount, ARGB32.blue(from), ARGB32.blue(to)))); } return result; } @@ -118,7 +119,7 @@ public static int fromHsl(float hue, float saturation, float lightness, int alph float sat = Mth.clamp(saturation, 0f, 1f); float light = Mth.clamp(lightness, 0f, 1f); float chroma = (1 - Math.abs(2 * light - 1)) * sat; - return ARGB.color(alpha, hslChannel(turn, chroma, light, 0), hslChannel(turn, chroma, light, 8), + return ARGB32.color(alpha, hslChannel(turn, chroma, light, 0), hslChannel(turn, chroma, light, 8), hslChannel(turn, chroma, light, 4)); } @@ -129,9 +130,9 @@ public static int fromHsl(Hsl hsl, int alpha) { /** 取得归一化的 HSL 分量。灰阶的色相与饱和度均为零。 */ public static Hsl toHsl(int argb) { - int red = ARGB.red(argb); - int green = ARGB.green(argb); - int blue = ARGB.blue(argb); + int red = ARGB32.red(argb); + int green = ARGB32.green(argb); + int blue = ARGB32.blue(argb); int maximum = Math.max(red, Math.max(green, blue)); int minimum = Math.min(red, Math.min(green, blue)); int chroma = maximum - minimum; @@ -155,7 +156,7 @@ public static Hsl toHsl(int argb) { public static IntIntPair lightnessGradient(int argb, float difference) { if (!(difference >= 0)) throw new IllegalArgumentException("亮度偏移量须为非负数"); Hsl hsl = toHsl(argb); - int alpha = ARGB.alpha(argb); + int alpha = ARGB32.alpha(argb); int dark = fromHsl(hsl.hue(), hsl.saturation(), hsl.lightness() - difference, alpha); int light = fromHsl(hsl.hue(), hsl.saturation(), hsl.lightness() + difference, alpha); return IntIntPair.of(dark, light); diff --git a/src/main/java/com/modularmc/mmclutils/utils/ComponentUtils.java b/src/main/java/com/modularmc/mmclutils/utils/ComponentUtils.java index 2028e39..5aa6639 100644 --- a/src/main/java/com/modularmc/mmclutils/utils/ComponentUtils.java +++ b/src/main/java/com/modularmc/mmclutils/utils/ComponentUtils.java @@ -1,11 +1,11 @@ package com.modularmc.mmclutils.utils; import net.minecraft.ChatFormatting; +import net.minecraft.Util; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.Style; import net.minecraft.network.chat.contents.PlainTextContents; -import net.minecraft.util.Util; import net.minecraft.world.level.block.state.properties.Property; import it.unimi.dsi.fastutil.objects.ObjectArrayList; diff --git a/src/main/java/com/modularmc/mmclutils/utils/DirectionUtils.java b/src/main/java/com/modularmc/mmclutils/utils/DirectionUtils.java index 898dfd0..786c498 100644 --- a/src/main/java/com/modularmc/mmclutils/utils/DirectionUtils.java +++ b/src/main/java/com/modularmc/mmclutils/utils/DirectionUtils.java @@ -31,7 +31,7 @@ public static long offset(long packedPosition, Direction side) { /** 以方块中心为起点,用指向世界坐标的向量选择最近世界方向。 */ public static Direction nearestSide(Vec3 point, BlockPos position) { - return Direction.getApproximateNearest(point.x - position.getX() - .5, + return Direction.getNearest(point.x - position.getX() - .5, point.y - position.getY() - .5, point.z - position.getZ() - .5); } @@ -72,7 +72,7 @@ private static Direction gridSide(Direction face, @Nullable Direction first, @Nu int x = BlockPos.getX(neighbor) - BlockPos.getX(source); int y = BlockPos.getY(neighbor) - BlockPos.getY(source); int z = BlockPos.getZ(neighbor) - BlockPos.getZ(source); - return Math.abs(x) + Math.abs(y) + Math.abs(z) == 1 ? Direction.getNearest(x, y, z, null) : null; + return Math.abs(x) + Math.abs(y) + Math.abs(z) == 1 ? Direction.getNearest(x, y, z) : null; } /** 取得两个接壤方块之间的方向。两个位置重合或不共享方块面时返回空值。 */ @@ -196,7 +196,7 @@ public static Orientation fromRoll(Direction front, Direction roll, boolean mirr /** 返回局部左侧在世界坐标中的方向,镜像时交换左右。 */ public Direction left() { - Direction side = Direction.getApproximateNearest( + Direction side = Direction.getNearest( up.getStepY() * front.getStepZ() - up.getStepZ() * front.getStepY(), up.getStepZ() * front.getStepX() - up.getStepX() * front.getStepZ(), up.getStepX() * front.getStepY() - up.getStepY() * front.getStepX()); diff --git a/src/main/java/com/modularmc/mmclutils/utils/EntityUtils.java b/src/main/java/com/modularmc/mmclutils/utils/EntityUtils.java index 2d5c4d6..e2dd721 100644 --- a/src/main/java/com/modularmc/mmclutils/utils/EntityUtils.java +++ b/src/main/java/com/modularmc/mmclutils/utils/EntityUtils.java @@ -8,7 +8,7 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -import net.minecraft.world.level.portal.TeleportTransition; +import net.minecraft.world.level.portal.DimensionTransition; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; @@ -54,7 +54,7 @@ public static List within(Level level, Class type, Vec3 * @throws IllegalArgumentException 指定类型与索引组合不存在 */ public static EquipmentSlot equipmentSlotByTypeAndIndex(EquipmentSlot.Type type, int index) { - for (EquipmentSlot slot : EquipmentSlot.VALUES) { + for (EquipmentSlot slot : EquipmentSlot.values()) { if (slot.getType() == type && slot.getIndex() == index) return slot; } throw new IllegalArgumentException("无对应装备槽 " + type + " " + index); @@ -82,8 +82,8 @@ public static int matchingArmorPieces(LivingEntity entity, Predicate /** 在服务端线程传送实体,保留既有速度。返回原版传送后的实体,失败时返回空值。 */ public static @Nullable Entity teleport(Entity entity, ServerLevel level, Vec3 position, float yaw, float pitch) { - return entity.teleport(new TeleportTransition(level, position, entity.getDeltaMovement(), yaw, - pitch, TeleportTransition.DO_NOTHING)); + return entity.changeDimension(new DimensionTransition(level, position, entity.getDeltaMovement(), yaw, + pitch, DimensionTransition.DO_NOTHING)); } /** 按维度键定位目标维度。维度尚未加载时返回空值。 */ diff --git a/src/main/java/com/modularmc/mmclutils/utils/FileUtils.java b/src/main/java/com/modularmc/mmclutils/utils/FileUtils.java index ea1b988..034299b 100644 --- a/src/main/java/com/modularmc/mmclutils/utils/FileUtils.java +++ b/src/main/java/com/modularmc/mmclutils/utils/FileUtils.java @@ -1,6 +1,6 @@ package com.modularmc.mmclutils.utils; -import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceLocation; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; @@ -468,18 +468,18 @@ public record Serializer(Reader reader, Writer writer) implements Reade }, (output, value) -> output.writeUTF(value.toString())); /** 将完整标识作为一个 UTF 字段写入。 */ - public static final Serializer IDENTIFIER = new Serializer<>(input -> { + public static final Serializer IDENTIFIER = new Serializer<>(input -> { String text = input.readUTF(); - Identifier id = Identifier.tryParse(text); + ResourceLocation id = ResourceLocation.tryParse(text); if (id == null) throw new IOException("无效的资源标识:" + text); return id; }, (output, value) -> output.writeUTF(value.toString())); /** 兼容先写命名空间、再写路径的双 UTF 布局。 */ - public static final Serializer IDENTIFIER_PARTS = new Serializer<>(input -> { + public static final Serializer IDENTIFIER_PARTS = new Serializer<>(input -> { String namespace = input.readUTF(); String path = input.readUTF(); - Identifier id = Identifier.tryBuild(namespace, path); + ResourceLocation id = ResourceLocation.tryBuild(namespace, path); if (id == null) throw new IOException("无效的资源标识:" + namespace + ":" + path); return id; }, (output, id) -> { diff --git a/src/main/java/com/modularmc/mmclutils/utils/FluidContainerUtils.java b/src/main/java/com/modularmc/mmclutils/utils/FluidContainerUtils.java index b821aa0..fcf31e9 100644 --- a/src/main/java/com/modularmc/mmclutils/utils/FluidContainerUtils.java +++ b/src/main/java/com/modularmc/mmclutils/utils/FluidContainerUtils.java @@ -4,164 +4,93 @@ import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.inventory.AbstractContainerMenu; -import net.neoforged.neoforge.capabilities.Capabilities; +import net.minecraft.world.item.ItemStack; import net.neoforged.neoforge.common.SoundActions; -import net.neoforged.neoforge.fluids.FluidType; -import net.neoforged.neoforge.transfer.RangedResourceHandler; -import net.neoforged.neoforge.transfer.ResourceHandler; -import net.neoforged.neoforge.transfer.ResourceHandlerUtil; -import net.neoforged.neoforge.transfer.access.ItemAccess; -import net.neoforged.neoforge.transfer.fluid.FluidResource; -import net.neoforged.neoforge.transfer.item.CarriedSlotWrapper; -import net.neoforged.neoforge.transfer.item.ItemResource; -import net.neoforged.neoforge.transfer.item.ItemStacksResourceHandler; -import net.neoforged.neoforge.transfer.item.PlayerInventoryWrapper; -import net.neoforged.neoforge.transfer.transaction.Transaction; -import net.neoforged.neoforge.transfer.transaction.TransactionContext; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidUtil; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.capability.IFluidHandlerItem; -import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap; -import org.jspecify.annotations.Nullable; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; -/** 通过 NeoForge 的物品访问修改容器,流体与原物品的替换在同一个事务中完成。 */ +/** 通过 NeoForge 的流体能力装入或倒空物品容器。 */ public final class FluidContainerUtils { private FluidContainerUtils() {} - /** - * 将指定储罐中的流体装入单个物品容器。 - * - * @param item 持有待装填容器的物品访问器 - * @param source 流体来源 - * @param tank 来源中的储罐索引 - * @param maximum 最多转移的毫桶数 - * @param parent 可选的外层事务 - * @return 实际装入容器的毫桶数 - */ - public static int fill(ItemAccess item, ResourceHandler source, int tank, int maximum, - @Nullable TransactionContext parent) { - var access = item.oneByOne(); - var target = access.getCapability(Capabilities.Fluid.ITEM); - return target == null ? 0 : InventoryUtils.move(source, tank, target, maximum, parent); + /** 从来源装入容器。调用方持有容器能力,并负责应用变化后的物品栈。 */ + public static int fill(IFluidHandlerItem item, IFluidHandler source, int maximum) { + return transfer(source, item, maximum).getAmount(); } - /** - * 将单个物品容器中的流体排入指定储罐。 - * - * @param item 持有待排空容器的物品访问器 - * @param tank 目标中的储罐索引 - * @param target 流体目标 - * @param maximum 最多转移的毫桶数 - * @param parent 可选的外层事务 - * @return 实际排入储罐的毫桶数 - */ - public static int drain(ItemAccess item, int tank, ResourceHandler target, int maximum, - @Nullable TransactionContext parent) { - var access = item.oneByOne(); - var source = access.getCapability(Capabilities.Fluid.ITEM); - return source == null ? 0 : InventoryUtils.move(source, tank, target, maximum, parent); + /** 将单个物品容器排入流体处理器。调用方负责应用变化后的物品栈。 */ + public static int drain(IFluidHandlerItem item, IFluidHandler target, int maximum) { + return transfer(item, target, maximum).getAmount(); } - /** - * 在服务端处理菜单光标上的容器。普通点击处理一个,批量点击最多处理整组。 - * - * @param player 发起操作的玩家 - * @param handler 目标流体处理器 - * @param tank 要操作的储罐索引 - * @param batch 是否处理光标堆叠中的全部容器 - * @param allowFill 是否允许将储罐流体装入容器 - * @param allowDrain 是否允许将容器流体排入储罐 - * @return 成功操作的容器数量 - */ - public static int click(ServerPlayer player, ResourceHandler handler, int tank, - boolean batch, boolean allowFill, boolean allowDrain) { - return click(player, player.containerMenu, handler, tank, batch ? Integer.MAX_VALUE : 1, allowFill, allowDrain); + /** 在服务端处理光标上的容器。普通点击处理一个,批量点击至多处理整组。 */ + public static int click(ServerPlayer player, IFluidHandler handler, boolean batch, boolean allowFill, boolean allowDrain) { + return click(player, player.containerMenu, handler, batch ? Integer.MAX_VALUE : 1, allowFill, allowDrain); } /** - * 只操作指定储罐。装入容器成功后按同一方向继续,无法装入时可尝试倒空。 - * 光标空出后放回一组结果,其余交给玩家库存。声音和菜单同步发生在提交后。 - * - * @param player 发起操作的玩家 - * @param menu 持有光标物品的菜单 - * @param handler 目标流体处理器 - * @param tank 要操作的储罐索引 - * @param maximumContainers 最多处理的容器数量 - * @param allowFill 是否允许将储罐流体装入容器 - * @param allowDrain 是否允许将容器流体排入储罐 - * @return 成功装入或倒空的容器数量 - * @throws IllegalArgumentException 容器数量上限为负数 + * 操作代表指定储罐的流体处理器。装入成功后按同一方向继续,无法装入时可尝试倒空。 + * 光标空出后放回同类结果,其余交给玩家库存。 */ - public static int click(ServerPlayer player, AbstractContainerMenu menu, ResourceHandler handler, - int tank, int maximumContainers, boolean allowFill, boolean allowDrain) { + public static int click(ServerPlayer player, AbstractContainerMenu menu, IFluidHandler handler, + int maximumContainers, boolean allowFill, boolean allowDrain) { if (maximumContainers < 0) throw new IllegalArgumentException("容器数量应为非负数"); - var cursor = CarriedSlotWrapper.of(menu); - int count = Math.min(maximumContainers, cursor.getAmountAsInt(0)); - if (count == 0 || (!allowFill && !allowDrain)) return 0; + ItemStack carried = menu.getCarried(); + int maximum = Math.min(carried.getCount(), maximumContainers); + if (maximum == 0 || (!allowFill && !allowDrain)) return 0; - var tankAccess = RangedResourceHandler.ofSingleIndex(handler, tank); - BatchResult result; + var products = new ObjectArrayList(); + FluidStack firstFluid = FluidStack.EMPTY; + int containers = 0; boolean fill = allowFill; - try (var transaction = Transaction.openRoot()) { - result = fill ? transferContainers(cursor, tankAccess, count, true, player, transaction) : null; - if (result == null && allowDrain) { + for (; containers < maximum; containers++) { + var item = FluidUtil.getFluidHandler(carried.copyWithCount(1)).orElse(null); + if (item == null) break; + FluidStack moved = fill ? transfer(handler, item, Integer.MAX_VALUE) : FluidStack.EMPTY; + if (moved.isEmpty() && (allowDrain && containers == 0 || !fill)) { + moved = transfer(item, handler, Integer.MAX_VALUE); fill = false; - result = transferContainers(cursor, tankAccess, count, false, player, transaction); } - if (result == null) return 0; - transaction.commit(); - } + if (moved.isEmpty()) break; - var fluid = result.fluid(); - var stack = fluid.toStack(FluidType.BUCKET_VOLUME); - var sound = fluid.getFluidType().getSound(stack, fill ? SoundActions.BUCKET_FILL : SoundActions.BUCKET_EMPTY); - if (sound == null) sound = fill ? SoundEvents.BUCKET_FILL : SoundEvents.BUCKET_EMPTY; - player.level().playSound(null, player, sound, SoundSource.BLOCKS, 1, 1); - menu.broadcastChanges(); - return result.containers(); - } - - private static @Nullable BatchResult transferContainers(ResourceHandler cursor, ResourceHandler tank, - int count, boolean fill, ServerPlayer player, TransactionContext parent) { - var original = cursor.getResource(0); - var single = new ItemStacksResourceHandler(1); - var access = ItemAccess.forHandlerIndexStrict(single, 0); - var results = new Object2IntLinkedOpenHashMap(); - FluidResource firstFluid = FluidResource.EMPTY; - int containers = 0; - for (; containers < count; containers++) { - // 每次仅从光标取原始容器,产物在本批结束后回填。 - try (var attempt = Transaction.open(parent)) { - if (cursor.extract(0, original, 1, attempt) != 1) break; - if (single.insert(0, original, 1, attempt) != 1) break; - var container = access.getCapability(Capabilities.Fluid.ITEM); - if (container == null) break; - var moved = ResourceHandlerUtil.moveFirst(fill ? tank : container, fill ? container : tank, - resource -> true, Integer.MAX_VALUE, attempt); - if (moved == null) break; + ItemStack product = item.getContainer(); + if (!product.isEmpty()) products.add(product); + carried.shrink(1); + if (firstFluid.isEmpty()) firstFluid = moved; + } + if (containers == 0) return 0; - var product = single.getResource(0); - if (!product.isEmpty()) { - int amount = single.extract(0, product, single.getAmountAsInt(0), attempt); - results.addTo(product, amount); + ItemStack cursor = carried; + for (ItemStack product : products) { + if (cursor.isEmpty()) { + cursor = product; + } else if (ItemStack.isSameItemSameComponents(cursor, product)) { + int stackable = Math.min(cursor.getMaxStackSize() - cursor.getCount(), product.getCount()); + if (stackable > 0) { + cursor.grow(stackable); + product.shrink(stackable); } - attempt.commit(); - if (firstFluid.isEmpty()) firstFluid = moved.resource(); + if (!product.isEmpty()) player.getInventory().placeItemBackInInventory(product); + } else { + player.getInventory().placeItemBackInInventory(product); } } - if (containers == 0) return null; + menu.setCarried(cursor); - if (!results.isEmpty() && cursor.getResource(0).isEmpty()) { - ItemResource last = results.lastKey(); - int inserted = cursor.insert(0, last, results.getInt(last), parent); - results.addTo(last, -inserted); - } - var inventory = PlayerInventoryWrapper.of(player); - for (var entry : results.object2IntEntrySet()) { - int amount = entry.getIntValue(); - if (amount > 0) inventory.placeItemBackInInventory(entry.getKey(), amount, parent); - } - return new BatchResult(containers, firstFluid); + var sound = firstFluid.getFluidType().getSound(firstFluid, fill ? SoundActions.BUCKET_FILL : SoundActions.BUCKET_EMPTY); + if (sound == null) sound = fill ? SoundEvents.BUCKET_FILL : SoundEvents.BUCKET_EMPTY; + player.level().playSound(null, player, sound, SoundSource.BLOCKS, 1, 1); + menu.broadcastChanges(); + return containers; } - private record BatchResult(int containers, FluidResource fluid) {} + private static FluidStack transfer(IFluidHandler source, IFluidHandler target, int maximum) { + if (maximum < 0) throw new IllegalArgumentException("转移数量应为非负数"); + return maximum == 0 || source == target ? FluidStack.EMPTY : FluidUtil.tryFluidTransfer(target, source, maximum, true); + } } diff --git a/src/main/java/com/modularmc/mmclutils/utils/FluidUtils.java b/src/main/java/com/modularmc/mmclutils/utils/FluidUtils.java index 5ed6792..19375a7 100644 --- a/src/main/java/com/modularmc/mmclutils/utils/FluidUtils.java +++ b/src/main/java/com/modularmc/mmclutils/utils/FluidUtils.java @@ -3,7 +3,7 @@ import com.modularmc.mmclutils.api.inventory.FluidStackStrategy; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.material.Fluid; import net.neoforged.neoforge.fluids.FluidStack; @@ -20,12 +20,12 @@ public final class FluidUtils { private FluidUtils() {} /** 返回流体栈的注册表标识。 */ - public static Identifier id(FluidStack stack) { + public static ResourceLocation id(FluidStack stack) { return id(stack.getFluid()); } /** 返回已注册流体的标识。 */ - public static Identifier id(Fluid fluid) { + public static ResourceLocation id(Fluid fluid) { return BuiltInRegistries.FLUID.getKey(fluid); } @@ -36,7 +36,7 @@ public static String formatAmount(long amount) { /** 生成包含毫桶数量和流体标识的调试文本。 */ public static String formatStack(FluidStack stack) { - Identifier id = id(stack); + ResourceLocation id = id(stack); return stack.getAmount() + "x_" + id.getNamespace() + "_" + id.getPath(); } diff --git a/src/main/java/com/modularmc/mmclutils/utils/InventoryUtils.java b/src/main/java/com/modularmc/mmclutils/utils/InventoryUtils.java index 6658704..f0daf53 100644 --- a/src/main/java/com/modularmc/mmclutils/utils/InventoryUtils.java +++ b/src/main/java/com/modularmc/mmclutils/utils/InventoryUtils.java @@ -1,169 +1,123 @@ package com.modularmc.mmclutils.utils; -import net.neoforged.neoforge.transfer.ResourceHandler; -import net.neoforged.neoforge.transfer.ResourceHandlerUtil; -import net.neoforged.neoforge.transfer.TransferPreconditions; -import net.neoforged.neoforge.transfer.item.ItemResource; -import net.neoforged.neoforge.transfer.resource.Resource; -import net.neoforged.neoforge.transfer.transaction.Transaction; -import net.neoforged.neoforge.transfer.transaction.TransactionContext; +import com.modularmc.mmclutils.api.inventory.ItemStackStrategy; +import com.modularmc.mmclutils.api.inventory.ResourceTransferSimulation; -import it.unimi.dsi.fastutil.objects.Object2LongLinkedOpenHashMap; +import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.items.IItemHandler; +import net.neoforged.neoforge.items.IItemHandlerModifiable; +import net.neoforged.neoforge.items.ItemHandlerHelper; + +import it.unimi.dsi.fastutil.objects.Object2LongLinkedOpenCustomHashMap; import it.unimi.dsi.fastutil.objects.Object2LongMap; -import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2LongOpenCustomHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import org.jspecify.annotations.Nullable; import java.util.Comparator; -/** - * 汇总、排序及转移 NeoForge 库存资源。调用方须在库存的所属线程访问。 - * 跨槽筛选转移和优先填充同类槽位可直接使用 {@link ResourceHandlerUtil}。 - */ +/** 汇总、排序及转移 NeoForge 物品库存。调用方须在库存的所属线程访问。 */ public final class InventoryUtils { private InventoryUtils() {} /** - * 从一个槽位向目标尝试转移,按双方都能接受的数量提交改动。 - * - * @param source 提供资源的库存 - * @param sourceSlot 提取的槽位 - * @param target 接收资源的库存 - * @param maximum 允许转移的最大数量 - * @param parent 外层事务,空值表示本次调用自行提交 - * @param 资源类型 - * @return 实际转移的数量 - * @throws IllegalArgumentException 最大数量为负数 + * 从一个槽位向目标尝试转移,优先填充目标中已有的同类堆叠。 + * 实际插入量与预览不一致时,恢复两个库存。 */ - public static int move(ResourceHandler source, int sourceSlot, ResourceHandler target, - int maximum, @Nullable TransactionContext parent) { + public static int move(IItemHandlerModifiable source, int sourceSlot, IItemHandlerModifiable target, int maximum) { if (maximum < 0) throw new IllegalArgumentException("转移数量应为非负数"); if (source == target || maximum == 0) return 0; - R resource = source.getResource(sourceSlot); - if (resource.isEmpty()) return 0; - try (Transaction transaction = Transaction.open(parent)) { - int removed; - int accepted; - try (Transaction attempt = Transaction.open(transaction)) { - removed = source.extract(sourceSlot, resource, maximum, attempt); - if (removed == 0) return 0; - accepted = target.insert(resource, removed, attempt); - if (accepted == removed) { - attempt.commit(); - } - } - if (accepted == 0) return 0; - if (accepted < removed) { - if (source.extract(sourceSlot, resource, accepted, transaction) != accepted) return 0; - if (target.insert(resource, accepted, transaction) != accepted) return 0; - } - transaction.commit(); + ItemStack available = source.extractItem(sourceSlot, maximum, true); + if (available.isEmpty()) return 0; + int accepted = available.getCount() - ItemHandlerHelper.insertItemStacked(target, available, true).getCount(); + if (accepted == 0) return 0; + + try (var sourceState = new ResourceTransferSimulation(source); + var targetState = new ResourceTransferSimulation(target)) { + ItemStack removed = source.extractItem(sourceSlot, accepted, false); + if (removed.getCount() != accepted || !ItemStack.isSameItemSameComponents(available, removed)) return 0; + if (!ItemHandlerHelper.insertItemStacked(target, removed, false).isEmpty()) return 0; + sourceState.commit(); + targetState.commit(); return accepted; } } /** - * 从多个槽位提取指定资源,并完整转移相应数量。任一侧未达到指定数量时回滚。 - * - * @param source 提供资源的库存 - * @param target 接收资源的库存 - * @param resource 要转移的非空资源,包含其数据组件 - * @param amount 必须完整转移的非负数量 - * @param parent 外层事务,空值表示本次调用自行提交 - * @param 资源类型 - * @return 是否转移了指定的完整数量。零数量直接成功 - * @throws IllegalArgumentException 资源为空或数量为负数 + * 从多个槽位提取指定物品及组件,并完整转移相应数量。任一侧未达到指定数量时恢复槽位。 + * 使用可写槽位以便恢复库存,调用期间库存的槽位结构须保持稳定。 */ - public static boolean moveExact(ResourceHandler source, ResourceHandler target, - R resource, int amount, @Nullable TransactionContext parent) { - TransferPreconditions.checkNonEmptyNonNegative(resource, amount); + public static boolean moveExact(IItemHandlerModifiable source, IItemHandlerModifiable target, ItemStack resource, int amount) { + checkResource(resource, amount); if (amount == 0) return true; if (source == target) return false; - try (Transaction transaction = Transaction.open(parent)) { - if (source.extract(resource, amount, transaction) != amount || target.insert(resource, amount, transaction) != amount) return false; - transaction.commit(); + ItemStack stack = resource.copyWithCount(amount); + if (!ItemHandlerHelper.insertItemStacked(target, stack, true).isEmpty()) return false; + try (var sourceState = new ResourceTransferSimulation(source); + var targetState = new ResourceTransferSimulation(target)) { + if (sourceState.extract(resource, amount) != amount) return false; + if (!ItemHandlerHelper.insertItemStacked(target, stack, false).isEmpty()) return false; + sourceState.commit(); + targetState.commit(); return true; } } - /** - * 按槽位顺序尝试插入资源,只使用尚未占用的槽位。目标库存的插入限制照常生效。 - * - * @param target 接收资源的库存 - * @param resource 要插入的非空资源 - * @param amount 尝试插入的非负数量 - * @param parent 外层事务,空值表示本次调用自行提交 - * @param 资源类型 - * @return 实际插入的数量 - * @throws IllegalArgumentException 资源为空或数量为负数 - */ - public static int insertIntoEmpty(ResourceHandler target, R resource, int amount, - @Nullable TransactionContext parent) { - TransferPreconditions.checkNonEmptyNonNegative(resource, amount); - if (amount == 0) return 0; - int inserted = 0; - try (Transaction transaction = Transaction.open(parent)) { - for (int slot = 0, slots = target.size(); slot < slots && inserted < amount; slot++) { - if (target.getResource(slot).isEmpty()) inserted += target.insert(slot, resource, amount - inserted, transaction); + /** 按槽位顺序尝试插入,只使用尚未占用的槽位,目标库存的插入限制照常生效。 */ + public static int insertIntoEmpty(IItemHandler target, ItemStack resource, int amount) { + checkResource(resource, amount); + int remaining = amount; + for (int slot = 0, slots = target.getSlots(); slot < slots && remaining > 0; slot++) { + if (target.getStackInSlot(slot).isEmpty()) { + remaining = target.insertItem(slot, resource.copyWithCount(remaining), false).getCount(); } - transaction.commit(); } - return inserted; + return amount - remaining; } - /** 按槽位顺序统计资源总量,保留各类资源首次出现的顺序。 */ - public static Object2LongMap count(ResourceHandler storage) { + /** 按槽位顺序统计物品总量,保留各类物品首次出现的顺序。 */ + public static Object2LongMap count(IItemHandler storage) { return count(storage, true); } - /** 汇总同类资源的数量,可保留资源首次出现的顺序。总量超出 long 范围时抛出算术异常。 */ - public static Object2LongMap count(ResourceHandler storage, boolean ordered) { - Object2LongMap counts = ordered ? new Object2LongLinkedOpenHashMap<>() : new Object2LongOpenHashMap<>(); - for (int i = 0, slots = storage.size(); i < slots; i++) { - long amount = storage.getAmountAsLong(i); - if (amount == 0) continue; - R resource = storage.getResource(i); - counts.put(resource, Math.addExact(counts.getLong(resource), amount)); + /** 按物品与组件统计数量,键为数量一的副本,可保留资源首次出现的顺序。 */ + public static Object2LongMap count(IItemHandler storage, boolean ordered) { + var strategy = ItemStackStrategy.comparingAllButCount(); + Object2LongMap counts = ordered ? new Object2LongLinkedOpenCustomHashMap<>(strategy) : + new Object2LongOpenCustomHashMap<>(strategy); + for (int slot = 0, slots = storage.getSlots(); slot < slots; slot++) { + ItemStack stack = storage.getStackInSlot(slot); + if (!stack.isEmpty()) counts.mergeLong(stack.copyWithCount(1), stack.getCount(), Math::addExact); } return counts; } /** - * 尝试按给定顺序重新填充所有物品槽位。库存拒绝提取或重新插入时回滚整次排序。 - * - * @param inventory 待整理的物品库存 - * @param order 含数据组件的物品资源排序规则 - * @param parent 外层事务,空值表示本次调用自行提交 - * @return 是否完成整理 + * 尝试按给定顺序重新填充所有物品槽位。库存拒绝提取或重新插入时恢复槽位。 + * 比较器接收包含组件、数量为一的物品栈。 */ - public static boolean sort(ResourceHandler inventory, Comparator order, - @Nullable TransactionContext parent) { - var amounts = new Object2LongLinkedOpenHashMap(); - try (Transaction transaction = Transaction.open(parent)) { - for (int slot = 0; slot < inventory.size(); slot++) { - ItemResource resource = inventory.getResource(slot); - long remaining = inventory.getAmountAsLong(slot); - if (resource.isEmpty() || remaining == 0) continue; - amounts.addTo(resource, remaining); - while (remaining > 0) { - int amount = (int) Math.min(Integer.MAX_VALUE, remaining); - if (inventory.extract(slot, resource, amount, transaction) != amount) return false; - remaining -= amount; - } + public static boolean sort(IItemHandlerModifiable inventory, Comparator order) { + var amounts = count(inventory); + var resources = new ObjectArrayList<>(amounts.keySet()); + resources.sort(order); + try (var state = new ResourceTransferSimulation(inventory)) { + for (int slot = 0; slot < state.size(); slot++) { + ItemStack stack = state.resource(slot); + if (!stack.isEmpty() && state.extract(slot, stack, stack.getCount()) != stack.getCount()) return false; } - var resources = new ObjectArrayList<>(amounts.keySet()); - resources.sort(order); - for (ItemResource resource : resources) { + for (ItemStack resource : resources) { long remaining = amounts.getLong(resource); - for (int slot = 0; slot < inventory.size() && remaining > 0; slot++) { - int inserted = inventory.insert(slot, resource, (int) Math.min(Integer.MAX_VALUE, remaining), transaction); - remaining -= inserted; + for (int slot = 0; slot < state.size() && remaining > 0; slot++) { + remaining -= state.insert(slot, resource, (int) Math.min(Integer.MAX_VALUE, remaining)); } if (remaining != 0) return false; } - transaction.commit(); + state.commit(); return true; } } + + private static void checkResource(ItemStack resource, int amount) { + if (resource.isEmpty() || amount < 0) throw new IllegalArgumentException("物品应为非空且转移数量应为非负数"); + } } diff --git a/src/main/java/com/modularmc/mmclutils/utils/ItemUtils.java b/src/main/java/com/modularmc/mmclutils/utils/ItemUtils.java index 5b2155c..c7cab7c 100644 --- a/src/main/java/com/modularmc/mmclutils/utils/ItemUtils.java +++ b/src/main/java/com/modularmc/mmclutils/utils/ItemUtils.java @@ -4,7 +4,7 @@ import com.modularmc.mmclutils.utils.FileUtils.Serializer; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; @@ -23,7 +23,7 @@ public final class ItemUtils { /** 旧文件格式依次写入命名空间、路径和数量。读取时也接受单个 UTF 字段的完整标识。 */ public static final Serializer SERIALIZER = new Serializer<>(input -> { - Identifier id = readLegacyItemId(input); + ResourceLocation id = readLegacyItemId(input); int count = input.readInt(); if (count < 0) throw new IOException("无效的物品数量:" + count); if (count == 0) return ItemStack.EMPTY; @@ -36,25 +36,25 @@ public final class ItemUtils { private ItemUtils() {} - private static Identifier readLegacyItemId(DataInputStream input) throws IOException { + private static ResourceLocation readLegacyItemId(DataInputStream input) throws IOException { String first = input.readUTF(); - Identifier id = first.indexOf(':') >= 0 ? Identifier.tryParse(first) : Identifier.tryBuild(first, input.readUTF()); + ResourceLocation id = first.indexOf(':') >= 0 ? ResourceLocation.tryParse(first) : ResourceLocation.tryBuild(first, input.readUTF()); if (id == null) throw new IOException("无效的物品标识,以 " + first + " 开头"); return id; } /** 返回栈中物品的注册表标识,空栈使用空气物品的标识。 */ - public static Identifier id(ItemStack stack) { + public static ResourceLocation id(ItemStack stack) { return id(stack.getItem()); } /** 返回已注册物品的标识。 */ - public static Identifier id(Item item) { + public static ResourceLocation id(Item item) { return BuiltInRegistries.ITEM.getKey(item); } /** 返回方块对应的物品标识。 */ - public static Identifier id(Block block) { + public static ResourceLocation id(Block block) { return id(block.asItem()); } diff --git a/src/main/java/com/modularmc/mmclutils/utils/LevelUtils.java b/src/main/java/com/modularmc/mmclutils/utils/LevelUtils.java index 994d8e7..9d8dccf 100644 --- a/src/main/java/com/modularmc/mmclutils/utils/LevelUtils.java +++ b/src/main/java/com/modularmc/mmclutils/utils/LevelUtils.java @@ -25,7 +25,7 @@ private LevelUtils() {} /** 判断当前位置是否处于晴朗日照下。区块未加载或维度无天空光时返回假。 */ public static boolean canSeeSunClearly(Level level, BlockPos pos) { - return level.dimensionType().hasSkyLight() && level.isBrightOutside() && !level.isRaining() && !level.isThundering() && LoadedChunks.isLoaded(level, pos) && level.canSeeSky(pos); + return level.dimensionType().hasSkyLight() && level.isDay() && !level.isRaining() && !level.isThundering() && LoadedChunks.isLoaded(level, pos) && level.canSeeSky(pos); } /** 将世界日时映射成 0~1 的日照系数。白天沿正弦曲线变化,夜间为零。 */ diff --git a/src/main/java/com/modularmc/mmclutils/utils/MatrixUtils.java b/src/main/java/com/modularmc/mmclutils/utils/MatrixUtils.java index 2c5fdf2..5f255ae 100644 --- a/src/main/java/com/modularmc/mmclutils/utils/MatrixUtils.java +++ b/src/main/java/com/modularmc/mmclutils/utils/MatrixUtils.java @@ -1,8 +1,8 @@ package com.modularmc.mmclutils.utils; +import net.minecraft.Util; import net.minecraft.core.Direction; import net.minecraft.util.Mth; -import net.minecraft.util.Util; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; diff --git a/src/main/java/com/modularmc/mmclutils/utils/RegistriesUtils.java b/src/main/java/com/modularmc/mmclutils/utils/RegistriesUtils.java index c5ce2fc..a122352 100644 --- a/src/main/java/com/modularmc/mmclutils/utils/RegistriesUtils.java +++ b/src/main/java/com/modularmc/mmclutils/utils/RegistriesUtils.java @@ -4,8 +4,8 @@ import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; @@ -25,28 +25,28 @@ public final class RegistriesUtils { private RegistriesUtils() {} /** 按完整标识查询原版物品注册表。 */ - public static Item getItem(Identifier id) { + public static Item getItem(ResourceLocation id) { return getValue(BuiltInRegistries.ITEM, id); } /** 解析文本标识后查询物品。省略命名空间时使用原版的默认命名空间。 */ public static Item getItem(String id) { - return getItem(Identifier.parse(id)); + return getItem(ResourceLocation.parse(id)); } /** 由命名空间和路径构造标识后查询物品。 */ public static Item getItem(String namespace, String path) { - return getItem(Identifier.fromNamespaceAndPath(namespace, path)); + return getItem(ResourceLocation.fromNamespaceAndPath(namespace, path)); } /** 创建指定物品和数量的新栈。标识须已注册。 */ - public static ItemStack getItemStack(Identifier id, int count) { + public static ItemStack getItemStack(ResourceLocation id, int count) { return new ItemStack(getItem(id), count); } /** 解析后用指定数量创建物品栈。 */ public static ItemStack getItemStack(String id, int count) { - return getItemStack(Identifier.parse(id), count); + return getItemStack(ResourceLocation.parse(id), count); } /** 解析后创建数量为一的物品栈。 */ @@ -55,51 +55,51 @@ public static ItemStack getItemStack(String id) { } /** 按完整标识查询原版方块注册表。 */ - public static Block getBlock(Identifier id) { + public static Block getBlock(ResourceLocation id) { return getValue(BuiltInRegistries.BLOCK, id); } /** 解析文本标识后查询方块。 */ public static Block getBlock(String id) { - return getBlock(Identifier.parse(id)); + return getBlock(ResourceLocation.parse(id)); } /** 首次取值时查找方块,成功后复用同一结果。 */ public static Supplier getSupplierBlock(String id) { - Identifier blockId = Identifier.parse(id); + ResourceLocation blockId = ResourceLocation.parse(id); return Memoization.memoize(() -> getBlock(blockId)); } /** 按完整标识查询原版流体注册表。 */ - public static Fluid getFluid(Identifier id) { + public static Fluid getFluid(ResourceLocation id) { return getValue(BuiltInRegistries.FLUID, id); } /** 解析文本标识后查询流体。 */ public static Fluid getFluid(String id) { - return getFluid(Identifier.parse(id)); + return getFluid(ResourceLocation.parse(id)); } /** amount 以毫桶计量。 */ - public static FluidStack getFluidStack(Identifier id, int amount) { + public static FluidStack getFluidStack(ResourceLocation id, int amount) { return new FluidStack(getFluid(id), amount); } /** 解析标识后创建指定毫桶数的流体栈。 */ public static FluidStack getFluidStack(String id, int amount) { - return getFluidStack(Identifier.parse(id), amount); + return getFluidStack(ResourceLocation.parse(id), amount); } /** 按给定顺序构造注册键,调用方可在对应注册表中查询。 */ public static List> resolveResourceKeys(ResourceKey> registryKey, String... locations) { return Arrays.stream(locations) - .map(location -> ResourceKey.create(registryKey, Identifier.parse(location))) + .map(location -> ResourceKey.create(registryKey, ResourceLocation.parse(location))) .toList(); } - private static T getValue(Registry registry, Identifier id) { + private static T getValue(Registry registry, ResourceLocation id) { return registry.getOptional(id) - .orElseThrow(() -> new IllegalArgumentException("注册表 " + registry.key().identifier() + " 缺少标识 " + id)); + .orElseThrow(() -> new IllegalArgumentException("注册表 " + registry.key().location() + " 缺少标识 " + id)); } } diff --git a/src/main/java/com/modularmc/mmclutils/utils/ResourceUtils.java b/src/main/java/com/modularmc/mmclutils/utils/ResourceUtils.java index f707f82..f15f6c2 100644 --- a/src/main/java/com/modularmc/mmclutils/utils/ResourceUtils.java +++ b/src/main/java/com/modularmc/mmclutils/utils/ResourceUtils.java @@ -1,12 +1,12 @@ package com.modularmc.mmclutils.utils; -import net.minecraft.resources.Identifier; +import net.minecraft.FileUtil; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.PackLocationInfo; import net.minecraft.server.packs.PackResources; import net.minecraft.server.packs.PackType; import net.minecraft.server.packs.PathPackResources; import net.minecraft.server.packs.resources.ResourceProvider; -import net.minecraft.util.FileUtil; import java.nio.file.Files; import java.nio.file.Path; @@ -29,37 +29,37 @@ public static PathPackResources openPath(PackLocationInfo pack, Path root) { } /** 查询资源包中是否存在指定资源,不打开资源流。 */ - public static boolean exists(PackResources pack, PackType type, Identifier id) { + public static boolean exists(PackResources pack, PackType type, ResourceLocation id) { return pack.getResource(type, id) != null; } /** 从当前资源提供器查询标识是否可读。 */ - public static boolean exists(ResourceProvider provider, Identifier id) { + public static boolean exists(ResourceProvider provider, ResourceLocation id) { return provider.getResource(id).isPresent(); } /** 查询资源标识对应的普通文件是否存在,根目录包含资源类型子目录。 */ - public static boolean exists(Path root, PackType type, Identifier id) { + public static boolean exists(Path root, PackType type, ResourceLocation id) { return Files.isRegularFile(resolve(root, type, id)); } /** 以包含资源类型子目录的包根目录解析完整资源路径。 */ - public static Path resolve(Path root, PackType type, Identifier id) { + public static Path resolve(Path root, PackType type, ResourceLocation id) { return resolve(root.resolve(type.getDirectory()), id); } /** 以资源类型目录为根,按命名空间和标识中的各路径片段解析。非法路径会抛出异常。 */ - public static Path resolve(Path root, Identifier id) { + public static Path resolve(Path root, ResourceLocation id) { return FileUtil.resolvePath(root.resolve(id.getNamespace()), resourcePath(id)); } /** 将标识拆为命名空间和路径片段,可用于资源索引。 */ - public static String[] pathSegments(Identifier id) { + public static String[] pathSegments(ResourceLocation id) { return pathSegments(id, 1); } /** 在命名空间前附加资源包类型对应的目录。 */ - public static String[] pathSegments(PackType type, Identifier id) { + public static String[] pathSegments(PackType type, ResourceLocation id) { String[] segments = pathSegments(id, 2); segments[0] = type.getDirectory(); return segments; @@ -70,12 +70,12 @@ public static boolean isValidResourcePath(Path path) { if (path.getRoot() != null || path.getNameCount() == 0) return false; for (Path segment : path) { String name = segment.toString(); - if (name.isEmpty() || !FileUtil.isValidPathSegment(name)) return false; + if (name.equals(".") || name.equals("..") || !FileUtil.isValidStrictPathSegment(name)) return false; } return true; } - private static String[] pathSegments(Identifier id, int prefixLength) { + private static String[] pathSegments(ResourceLocation id, int prefixLength) { List parts = resourcePath(id); String[] result = new String[prefixLength + parts.size()]; result[prefixLength - 1] = id.getNamespace(); @@ -83,7 +83,7 @@ private static String[] pathSegments(Identifier id, int prefixLength) { return result; } - private static List resourcePath(Identifier id) { + private static List resourcePath(ResourceLocation id) { FileUtil.validatePath(id.getNamespace()); return FileUtil.decomposePath(id.getPath()).getOrThrow(); } diff --git a/src/main/java/com/modularmc/mmclutils/utils/TagUtils.java b/src/main/java/com/modularmc/mmclutils/utils/TagUtils.java index 17d07bb..d8ac7b6 100644 --- a/src/main/java/com/modularmc/mmclutils/utils/TagUtils.java +++ b/src/main/java/com/modularmc/mmclutils/utils/TagUtils.java @@ -3,7 +3,7 @@ import com.modularmc.mmclutils.utils.FileUtils.Serializer; import net.minecraft.core.registries.Registries; -import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagEntry; import net.minecraft.tags.TagKey; import net.minecraft.tags.TagLoader.EntryWithSource; @@ -30,7 +30,7 @@ public final class TagUtils { * 此格式没有来源包名称字段,读取时将来源设为空字符串。 */ public static final Serializer ENTRY_WITH_SOURCE_SERIALIZER = new Serializer<>(input -> { - Identifier id = Serializer.IDENTIFIER_PARTS.read(input); + ResourceLocation id = Serializer.IDENTIFIER_PARTS.read(input); boolean tag = input.readBoolean(); boolean required = input.readBoolean(); TagEntry entry; @@ -51,17 +51,17 @@ public final class TagUtils { private TagUtils() {} /** 构造指定标识的方块标签键,不查询注册表。 */ - public static TagKey block(Identifier id) { + public static TagKey block(ResourceLocation id) { return TagKey.create(Registries.BLOCK, id); } /** 构造指定标识的物品标签键,不查询注册表。 */ - public static TagKey item(Identifier id) { + public static TagKey item(ResourceLocation id) { return TagKey.create(Registries.ITEM, id); } /** 构造指定标识的流体标签键,不查询注册表。 */ - public static TagKey fluid(Identifier id) { + public static TagKey fluid(ResourceLocation id) { return TagKey.create(Registries.FLUID, id); } @@ -329,9 +329,9 @@ private List tokenize(String expr) { */ public static boolean tagsMatch(TagExprParser.@Nullable MatchExpr expr, ItemStack stack) { if (expr == null) return false; - Set tags = stack.typeHolder().tags() + Set tags = stack.getItemHolder().tags() .map(TagKey::location) - .map(Identifier::toString) + .map(ResourceLocation::toString) .collect(Collectors.toCollection(ObjectOpenHashSet::new)); return expr.matches(tags); @@ -342,7 +342,7 @@ public static boolean tagsMatch(TagExprParser.@Nullable MatchExpr expr, FluidSta if (expr == null) return false; Set tags = stack.getFluid().builtInRegistryHolder().tags() .map(TagKey::location) - .map(Identifier::toString) + .map(ResourceLocation::toString) .collect(Collectors.toCollection(ObjectOpenHashSet::new)); return expr.matches(tags); diff --git a/src/main/resources/mmclutils.mixins.json b/src/main/resources/mmclutils.mixins.json index 3e638da..f039561 100644 --- a/src/main/resources/mmclutils.mixins.json +++ b/src/main/resources/mmclutils.mixins.json @@ -2,7 +2,7 @@ "required": true, "minVersion": "0.8", "package": "com.modularmc.mmclutils.mixin", - "compatibilityLevel": "JAVA_25", + "compatibilityLevel": "JAVA_21", "mixins": [ "mc.VoxelShapeAccessor", "mc.world.BlockEntityMixin", @@ -12,7 +12,6 @@ "mc.world.ServerLevelMixin" ], "client": [ - "mc.client.GlBufferAccessor", "mc.client.KeyBindsScreenMixin", "mc.client.OptionsMixin", "mc.world.ClientChunkCacheMixin", diff --git a/src/test/java/com/modularmc/mmclutils/gametest/ServerStartupGameTest.java b/src/test/java/com/modularmc/mmclutils/gametest/ServerStartupGameTest.java new file mode 100644 index 0000000..99a17ab --- /dev/null +++ b/src/test/java/com/modularmc/mmclutils/gametest/ServerStartupGameTest.java @@ -0,0 +1,18 @@ +package com.modularmc.mmclutils.gametest; + +import com.modularmc.mmclutils.ModularMCLibUtils; + +import net.minecraft.gametest.framework.GameTest; +import net.minecraft.gametest.framework.GameTestHelper; +import net.neoforged.neoforge.gametest.GameTestHolder; +import net.neoforged.neoforge.gametest.PrefixGameTestTemplate; + +@GameTestHolder(ModularMCLibUtils.MOD_ID) +@PrefixGameTestTemplate(false) +public final class ServerStartupGameTest { + + @GameTest(templateNamespace = "minecraft", template = "bastion/mobs/empty") + public static void serverReachesGameTest(GameTestHelper helper) { + helper.succeed(); + } +}