Skip to content

Commit

Permalink
Merge pull request #8 from WinExp/dev/main
Browse files Browse the repository at this point in the history
📕Dev Version 1.6.1
  • Loading branch information
WinExp authored Mar 31, 2024
2 parents 3ae876c + 7f6ed1e commit 0af8115
Show file tree
Hide file tree
Showing 35 changed files with 548 additions and 357 deletions.
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx8G

# Mod Properties
mod_id = battlegrounds
mod_version = 1.5.8
mod_version = 1.6.1
maven_group = com.github.winexp
archives_base_name = Battlegrounds

Expand Down
71 changes: 7 additions & 64 deletions src/main/java/com/github/winexp/battlegrounds/Battlegrounds.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,90 +8,32 @@
import com.github.winexp.battlegrounds.enchantment.Enchantments;
import com.github.winexp.battlegrounds.entity.EntityTypes;
import com.github.winexp.battlegrounds.game.GameManager;
import com.github.winexp.battlegrounds.game.GameProperties;
import com.github.winexp.battlegrounds.game.GameUtil;
import com.github.winexp.battlegrounds.item.ItemGroups;
import com.github.winexp.battlegrounds.item.Items;
import com.github.winexp.battlegrounds.loot.LootTableModifier;
import com.github.winexp.battlegrounds.network.ModServerConfigurationNetworkHandler;
import com.github.winexp.battlegrounds.network.ModServerPlayNetworkHandler;
import com.github.winexp.battlegrounds.resource.listener.DataPackResourceReloadListener;
import com.github.winexp.battlegrounds.sound.SoundEvents;
import com.github.winexp.battlegrounds.task.TaskScheduler;
import com.github.winexp.battlegrounds.util.Constants;
import com.github.winexp.battlegrounds.util.FileUtil;
import com.github.winexp.battlegrounds.util.Variables;
import com.google.gson.JsonElement;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.serialization.JsonOps;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.loot.v2.LootTableEvents;
import net.fabricmc.fabric.api.resource.ResourceManagerHelper;
import net.minecraft.command.CommandRegistryAccess;
import net.minecraft.resource.ResourceType;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.util.Identifier;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

public class Battlegrounds implements ModInitializer {
public static Battlegrounds INSTANCE;
public static final HashMap<Identifier, GameProperties> GAME_PRESETS = new HashMap<>();

public void loadGameProperties() {
this.saveGameProperties();
GAME_PRESETS.clear();
try {
for (File directory : FileUtil.listFiles(Constants.GAME_PROPERTIES_PATH)) {
if (directory.isDirectory()) {
for (File file : FileUtil.listFiles(directory.toPath())) {
if (file.isFile() && file.getName().endsWith(".json")) {
try {
JsonElement json = Constants.GSON.fromJson(FileUtil.readString(file), JsonElement.class);
GameProperties properties = GameProperties.CODEC.parse(JsonOps.INSTANCE, json).result().orElseThrow();
GAME_PRESETS.put(properties.id(), properties);
} catch (Exception e) {
Constants.LOGGER.warn("无法将 %s 转换为游戏配置:".formatted(file.toString()), e);
}
}
}
}
}
} catch (Exception e) {
Constants.LOGGER.warn("无法加载游戏配置:", e);
}
}

public void saveGameProperties() {
List<GameProperties> properties = List.of(
GameProperties.NORMAL_PRESET
);
for (GameProperties preset : properties) {
Identifier id = preset.id();
File file = Constants.GAME_PROPERTIES_PATH
.resolve(id.getNamespace())
.resolve(id.getPath() + ".json").toFile();
try {
Optional<GameProperties> parseResult = Optional.empty();
if (file.exists()) {
JsonElement jsonFrom = Constants.GSON.fromJson(FileUtil.readString(file), JsonElement.class);
parseResult = GameProperties.CODEC.parse(JsonOps.INSTANCE, jsonFrom).result();
}
if (parseResult.isEmpty()) {
JsonElement json = GameProperties.CODEC.encodeStart(JsonOps.INSTANCE, preset)
.getOrThrow(false, Constants.LOGGER::error);
String jsonStr = Constants.GSON.toJson(json);
FileUtil.writeString(file, jsonStr);
}
} catch (Exception e) {
Constants.LOGGER.error("无法将游戏配置写入文件 %s:".formatted(file.toString()), e);
}
}
}

public void loadConfigs() {
Variables.config = ConfigUtil.readOrCreateConfig(
Expand All @@ -102,7 +44,6 @@ public void loadConfigs() {

public void reload() {
this.loadConfigs();
this.loadGameProperties();

Items.addCustomRecipes();
}
Expand Down Expand Up @@ -143,7 +84,6 @@ public void onInitialize() {
Constants.LOGGER.info("Loading {}", Constants.MOD_NAME);
// 加载配置
this.loadConfigs();
this.loadGameProperties(); // 加载游戏预设
// 注册事件
// 指令
CommandRegistrationCallback.EVENT.register(this::registerCommands);
Expand All @@ -154,8 +94,11 @@ public void onInitialize() {
ServerLifecycleEvents.AFTER_SAVE.register(this::onSaving);
LootTableEvents.MODIFY.register(new LootTableModifier());
// 注册网络包相关
ModServerConfigurationNetworkHandler.registerReceivers();
ModServerConfigurationNetworkHandler.register();
ModServerPlayNetworkHandler.register();
// 注册数据包
ResourceManagerHelper resourceManagerHelper = ResourceManagerHelper.get(ResourceType.SERVER_DATA);
resourceManagerHelper.registerReloadListener(new DataPackResourceReloadListener());
// 注册物品
Items.registerItems();
// 注册物品组
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
import com.github.winexp.battlegrounds.client.gui.screen.vote.VoteScreen;
import com.github.winexp.battlegrounds.client.network.ModClientConfigurationNetworkHandler;
import com.github.winexp.battlegrounds.client.network.ModClientPlayNetworkHandler;
import com.github.winexp.battlegrounds.client.render.FlashRenderer;
import com.github.winexp.battlegrounds.client.render.entity.ChannelingArrowEntityRenderer;
import com.github.winexp.battlegrounds.client.toast.vote.PlayerVotedToast;
import com.github.winexp.battlegrounds.client.toast.vote.VoteClosedToast;
import com.github.winexp.battlegrounds.client.toast.vote.VoteOpenedToast;
import com.github.winexp.battlegrounds.client.util.ClientConstants;
import com.github.winexp.battlegrounds.entity.EntityTypes;
import com.github.winexp.battlegrounds.event.ClientApplyFogCallback;
import com.github.winexp.battlegrounds.event.ClientVoteEvents;
Expand All @@ -20,7 +20,7 @@
import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.render.entity.FlyingItemEntityRenderer;
import net.minecraft.sound.SoundCategory;
import net.minecraft.client.sound.PositionedSoundInstance;
import net.minecraft.sound.SoundEvents;

@Environment(EnvType.CLIENT)
Expand All @@ -32,9 +32,8 @@ private void registerRenderer() {
EntityRendererRegistry.register(EntityTypes.MOLOTOV, FlyingItemEntityRenderer::new);

// 自定义渲染器
FlashRenderer flashRenderer = new FlashRenderer();
HudRenderCallback.EVENT.register(flashRenderer);
ClientApplyFogCallback.EVENT.register(flashRenderer);
HudRenderCallback.EVENT.register(ClientConstants.FLASH_RENDERER);
ClientApplyFogCallback.EVENT.register(ClientConstants.FLASH_RENDERER);
}

@Override
Expand All @@ -43,32 +42,26 @@ public void onInitializeClient() {
ClientVoteEvents.OPENED.register(voteInfo -> {
MinecraftClient client = MinecraftClient.getInstance();
client.getToastManager().add(new VoteOpenedToast(voteInfo));
if (client.player != null) {
client.player.playSound(SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, SoundCategory.NEUTRAL, 0.3F, 1.0F);
}
client.getSoundManager().play(PositionedSoundInstance.master(SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, 1.0F));
VoteScreen.onVoteOpened(client, voteInfo);
});
ClientVoteEvents.CLOSED.register((voteInfo, reason) -> {
MinecraftClient client = MinecraftClient.getInstance();
client.getToastManager().add(new VoteClosedToast(voteInfo, reason));
if (client.player != null) {
client.player.playSound(SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, SoundCategory.NEUTRAL, 0.3F, 1.0F);
}
client.getSoundManager().play(PositionedSoundInstance.master(SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, 1.0F));
VoteScreen.onVoteClosed(client, voteInfo);
});
ClientVoteEvents.PLAYER_VOTED.register((playerName, voteInfo, result) -> {
MinecraftClient client = MinecraftClient.getInstance();
client.getToastManager().add(new PlayerVotedToast(playerName, voteInfo, result));
if (client.player != null) {
client.player.playSound(SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, SoundCategory.NEUTRAL, 0.3F, 1.0F);
}
client.getSoundManager().play(PositionedSoundInstance.master(SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, 1.0F));
});
ClientTickEvents.END_CLIENT_TICK.register(VoteScreen::globalTick);
// 注册实体渲染器
this.registerRenderer();
// 注册网络包相关
ModClientConfigurationNetworkHandler.register();
ModClientPlayNetworkHandler.registerReceivers();
ModClientPlayNetworkHandler.register();
// 注册按键绑定
KeyBindings.registerKeyBindings();
// 注册物品模型谓词
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.github.winexp.battlegrounds.client.network;

import com.github.winexp.battlegrounds.client.gui.screen.vote.VoteScreen;
import com.github.winexp.battlegrounds.client.util.ClientVariables;
import com.github.winexp.battlegrounds.client.util.ClientConstants;
import com.github.winexp.battlegrounds.entity.projectile.FlashBangEntity;
import com.github.winexp.battlegrounds.event.ClientVoteEvents;
import com.github.winexp.battlegrounds.network.packet.s2c.play.FlashS2CPacket;
Expand All @@ -17,7 +17,7 @@

@Environment(EnvType.CLIENT)
public final class ModClientPlayNetworkHandler {
public static void registerReceivers() {
public static void register() {
ClientPlayNetworking.registerGlobalReceiver(FlashS2CPacket.TYPE, ModClientPlayNetworkHandler::onFlash);
ClientPlayNetworking.registerGlobalReceiver(SyncVoteInfosS2CPacket.TYPE, ModClientPlayNetworkHandler::onSyncVoteInfos);
ClientPlayNetworking.registerGlobalReceiver(UpdateVoteInfoS2CPacket.TYPE, ModClientPlayNetworkHandler::onUpdateVoteInfo);
Expand All @@ -33,8 +33,7 @@ private static void onFlash(FlashS2CPacket packet, ClientPlayerEntity player, Pa
Entity entity = client.getCameraEntity();
if (entity != null) {
float tickDelta = client.getTickDelta();
ClientVariables.flashStrength = Math.max(ClientVariables.flashStrength,
FlashBangEntity.getFlashStrength(entity, pos, distance, tickDelta));
ClientConstants.FLASH_RENDERER.setFlashStrength(FlashBangEntity.getFlashStrength(entity, pos, distance, tickDelta));
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package com.github.winexp.battlegrounds.client.render;

import com.github.winexp.battlegrounds.client.util.ClientVariables;
import com.github.winexp.battlegrounds.entity.projectile.FlashBangEntity;
import com.github.winexp.battlegrounds.event.ClientApplyFogCallback;
import com.mojang.blaze3d.systems.RenderSystem;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.render.BackgroundRenderer;
import net.minecraft.client.render.FogShape;
Expand All @@ -16,9 +17,31 @@

@Environment(EnvType.CLIENT)
public class FlashRenderer implements HudRenderCallback, ClientApplyFogCallback {
private float flashStrength;

public FlashRenderer() {
ClientTickEvents.END_CLIENT_TICK.register(this::tick);
}

private void tick(MinecraftClient client) {
if (this.flashStrength > 0) {
this.flashStrength -= FlashBangEntity.STRENGTH_LEFT_SPEED;
} else if (this.flashStrength < 0){
this.flashStrength = 0;
}
}

public float getFlashStrength() {
return this.flashStrength;
}

public void setFlashStrength(float flashStrength) {
this.flashStrength = Math.max(flashStrength, this.flashStrength);
}

@Override
public void onHudRender(DrawContext context, float tickDelta) {
float strength = ClientVariables.flashStrength;
float strength = this.flashStrength;
if (strength > 0) {
RenderSystem.enableBlend();
if (strength > 1.0F) strength = 1.0F;
Expand All @@ -32,7 +55,7 @@ public void onHudRender(DrawContext context, float tickDelta) {

@Override
public void onApplyFog(float viewDistance, BackgroundRenderer.FogData fogData) {
float flashStrength = ClientVariables.flashStrength;
float flashStrength = this.flashStrength;
float flashLeftSpeed = FlashBangEntity.STRENGTH_LEFT_SPEED;
if (flashStrength > 0) {
fogData.fogShape = FogShape.SPHERE;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.github.winexp.battlegrounds.client.util;


import com.github.winexp.battlegrounds.client.render.FlashRenderer;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;

@Environment(EnvType.CLIENT)
public class ClientConstants {
public static final FlashRenderer FLASH_RENDERER = new FlashRenderer();
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public static void registerRoot(CommandDispatcher<ServerCommandSource> dispatche
public static ArgumentBuilder<ServerCommandSource, ?> registerStart() {
var cStart = literal("start");
var aProp = argument("gameProperties", IdentifierArgumentType.identifier()).suggests(((context, builder) ->
CommandSource.suggestMatching(Battlegrounds.GAME_PRESETS.keySet().stream().map(Identifier::toString), builder)))
CommandSource.suggestMatching(Constants.GAME_PROPERTIES.keySet().stream().map(Identifier::toString), builder)))
.executes(BattlegroundsCommand::executeStart);
return cStart.then(aProp);
}
Expand Down Expand Up @@ -79,8 +79,11 @@ private static int executeSummonFlash(CommandContext<ServerCommandSource> contex
}

public static ArgumentBuilder<ServerCommandSource, ?> registerGameMode() {
var cRoot = literal("gamemode");
var aMode = argument("gamemode", GameModeArgumentType.gameMode()).executes((context) ->
var cRoot = literal("gamemode").requires(source ->
source.hasPermissionLevel(2));
var aMode = argument("gamemode", GameModeArgumentType.gameMode())
.requires(ServerCommandSource::isExecutedByPlayer)
.executes((context) ->
executeChangeGameMode(context, true));
var aPlayer = argument("players", EntityArgumentType.players()).executes((context ->
executeChangeGameMode(context, false)));
Expand All @@ -90,11 +93,9 @@ private static int executeSummonFlash(CommandContext<ServerCommandSource> contex

private static int executeChangeGameMode(CommandContext<ServerCommandSource> context, boolean isSelf) throws CommandSyntaxException {
GameMode gameMode = GameModeArgumentType.getGameMode(context, "gamemode");
if (isSelf && context.getSource().isExecutedByPlayer()) {
if (isSelf) {
ServerPlayerEntity player = context.getSource().getPlayerOrThrow();
PlayerUtil.changeGameMode(player, gameMode);
} else if (isSelf && !context.getSource().isExecutedByPlayer()) {
throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument().create();
} else {
Collection<ServerPlayerEntity> players = EntityArgumentType.getPlayers(context, "players");
for (ServerPlayerEntity player : players) {
Expand All @@ -107,10 +108,10 @@ private static int executeChangeGameMode(CommandContext<ServerCommandSource> con
private static int executeStart(CommandContext<ServerCommandSource> context) throws CommandSyntaxException {
ServerCommandSource source = context.getSource();
Identifier id = IdentifierArgumentType.getIdentifier(context, "gameProperties");
if (!Battlegrounds.GAME_PRESETS.containsKey(id)) {
if (!Constants.GAME_PROPERTIES.containsKey(id)) {
throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument().create();
}
GameProperties gameProperties = Battlegrounds.GAME_PRESETS.get(id);
GameProperties gameProperties = Constants.GAME_PROPERTIES.get(id);
if (VoteManager.INSTANCE.containsVote(VotePreset.START_GAME.identifier())) {
source.sendFeedback(() -> Text.translatable("vote.battlegrounds.already_voting.feedback")
.formatted(Formatting.RED), false);
Expand All @@ -126,15 +127,15 @@ private static int executeStop(CommandContext<ServerCommandSource> context) {
VoteManager.INSTANCE.closeAllVotes();
TaskScheduler.INSTANCE.cancelAllTasks();
Variables.gameManager.stopGame();
context.getSource().sendFeedback(() -> Text.translatable("battlegrounds.command.stop.feedback")
context.getSource().sendFeedback(() -> Text.translatable("commands.battlegrounds.stop.feedback")
.formatted(Formatting.GREEN), true);

return 1;
}

private static int executeReload(CommandContext<ServerCommandSource> context) {
Battlegrounds.INSTANCE.reload();
context.getSource().sendFeedback(() -> Text.translatable("battlegrounds.command.reload.feedback")
context.getSource().sendFeedback(() -> Text.translatable("commands.battlegrounds.reload.feedback")
.formatted(Formatting.GREEN), true);

return 1;
Expand Down
Loading

0 comments on commit 0af8115

Please sign in to comment.