Update to NeoForge 20.2.88

This commit is contained in:
Stephen Seo 2023-12-29 17:20:14 +09:00
parent adb3a652f6
commit c9bf87271d
25 changed files with 568 additions and 548 deletions

View file

@ -2,168 +2,88 @@ plugins {
id 'eclipse' id 'eclipse'
id 'idea' id 'idea'
id 'maven-publish' id 'maven-publish'
id 'net.minecraftforge.gradle' version '[6.0,6.2)' id 'net.neoforged.gradle.userdev' version '7.0.57'
id 'com.github.johnrengelman.shadow' version '8.1.1'
} }
version = "1.23.1" version = "1.24.0"
group = "com.burnedkirby.TurnBasedMinecraft" group = "com.burnedkirby.TurnBasedMinecraft"
archivesBaseName = "TurnBasedMinecraft" archivesBaseName = "TurnBasedMinecraft-NeoForge"
java.toolchain.languageVersion = JavaLanguageVersion.of(17) java.toolchain.languageVersion = JavaLanguageVersion.of(17)
println('Java: ' + System.getProperty('java.version') + ' JVM: ' + System.getProperty('java.vm.version') + '(' + System.getProperty('java.vendor') + ') Arch: ' + System.getProperty('os.arch')) println('Java: ' + System.getProperty('java.version') + ' JVM: ' + System.getProperty('java.vm.version') + '(' + System.getProperty('java.vendor') + ') Arch: ' + System.getProperty('os.arch'))
minecraft { jarJar.enable()
// The mappings can be changed at any time, and must be in the following format.
// snapshot_YYYYMMDD Snapshot are built nightly.
// stable_# Stables are built at the discretion of the MCP team.
// Use non-default mappings at your own risk. they may not always work.
// Simply re-run your setup task after changing the mappings to update your workspace.
mappings channel: mapping_channel, version: mapping_version
// makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable.
// accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') // Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
// applies to all the run configs below
configureEach {
// Recommended logging data for a userdev environment
// The markers can be added/remove as needed separated by commas.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
systemProperty 'forge.logging.markers', 'REGISTRIES'
// This property allows configuring Gradle's ProcessResources task(s) to run on IDE output locations before launching the game. // Recommended logging level for the console
// It is REQUIRED to be set to true for this template to function. // You can set various levels here.
// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
copyIdeResources = true systemProperty 'forge.logging.console.level', 'debug'
// Default run configurations. modSource project.sourceSets.main
// These can be tweaked, removed, or duplicated as needed. }
runs {
client {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment client {
property 'forge.logging.markers', 'REGISTRIES' // Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
systemProperty 'forge.enabledGameTestNamespaces', project.mod_id
}
// Recommended logging level for the console server {
property 'forge.logging.console.level', 'debug' systemProperty 'forge.enabledGameTestNamespaces', project.mod_id
programArgument '--nogui'
}
// Comma-separated list of namespaces to load gametests from. Empty = all namespaces. // This run config launches GameTestServer and runs all registered gametests, then exits.
property 'forge.enabledGameTestNamespaces', 'TurnBasedMinecraftMod' // By default, the server will crash when no gametests are provided.
// The gametest system is also enabled by default for other run configs under the /test command.
gameTestServer {
systemProperty 'forge.enabledGameTestNamespaces', project.mod_id
}
mods { data {
TurnBasedMinecraftMod { // example of overriding the workingDirectory set in configureEach above, uncomment if you want to use it
source sourceSets.main // workingDirectory project.file('run-data')
}
}
}
server { // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
workingDirectory project.file('run') programArguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath()
// Recommended logging data for a userdev environment
property 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'
// Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
property 'forge.enabledGameTestNamespaces', 'TurnBasedMinecraftMod'
mods {
TurnBasedMinecraftMod {
source sourceSets.main
}
}
}
// This run config launches GameTestServer and runs all registered gametests, then exits.
// By default, the server will crash when no gametests are provided.
// The gametest system is also enabled by default for other run configs under the /test command.
gameTestServer {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
// The markers can be added/remove as needed separated by commas.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
property 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
// You can set various levels here.
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
property 'forge.logging.console.level', 'debug'
// Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
property 'forge.enabledGameTestNamespaces', 'TurnBasedMinecraftMod'
mods {
TurnBasedMinecraftMod {
source sourceSets.main
}
}
}
data {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
property 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'
args '--mod', 'TurnBasedMinecraftMod', '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources')
mods {
TurnBasedMinecraftMod {
source sourceSets.main
}
}
}
} }
} }
// Include resources generated by data generators. // Include resources generated by data generators.
sourceSets.main.resources { srcDir 'src/generated/resources' } sourceSets.main.resources { srcDir 'src/generated/resources' }
//repositories { repositories {
// // Put repositories for dependencies here flatDir {
// // ForgeGradle automatically adds the Forge maven and Maven Central for you dir 'libs'
// }
// // If you have mod jar dependencies in ./libs, you can declare them as a repository like so:
// // flatDir {
// // dir 'libs'
// // }
// mavenCentral()
// jcenter()
//
// dependencies {
// classpath 'com.github.jengelman.gradle.plugins:shadow:4.0.4'
// }
//}
apply plugin: 'com.github.johnrengelman.shadow'
configurations {
shade
impelmentation.extendsFrom shade
} }
dependencies { dependencies {
// Specify the version of Minecraft to use, If this is any group other then 'net.minecraft' it is assumed // Specify the version of Minecraft to use.
// that the dep is a ForgeGradle 'patcher' dependency. And it's patches will be applied. // Depending on the plugin applied there are several options. We will assume you applied the userdev plugin as shown above.
// The userdev artifact is a special name and will get all sorts of transformations applied to it. // The group for userdev is net.neoforged, the module name is neoforge, and the version is the same as the neoforge version.
minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" // You can however also use the vanilla plugin (net.neoforged.gradle.vanilla) to use a version of Minecraft without the neoforge loader.
// And its provides the option to then use net.minecraft as the group, and one of; client, server or joined as the module name, plus the game version as version.
// For all intends and purposes: You can treat this dependency as if it is a normal library you would use.
implementation "net.neoforged:neoforge:${neo_version}"
// Real mod deobf dependency examples - these get remapped to your current mappings // implementation files('libs/javamp3-1.0.3.jar')
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}:${jei_version}:api") // Adds JEI API as a compile dependency implementation 'fr.delthas:javamp3:1.0.3'
// runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}:${jei_version}") // Adds the full JEI mod as a runtime dependency
// implementation fg.deobf("com.tterrag.registrate:Registrate:MC${mc_version}-${registrate_version}") // Adds registrate as a dependency
// Examples using mod jars from ./libs jarJar(group: 'fr.delthas', name: 'javamp3', version: '[1.0.0,2.0.0)') {
// implementation fg.deobf("blank:coolmod-${mc_version}:${coolmod_version}") jarJar.pin(it, '1.0.3')
}
// For more info...
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
implementation files('libs/javamp3-1.0.3.jar')
shade files('libs/javamp3-1.0.3.jar')
} }
// This block of code expands all declared replace properties in the specified resource targets. // This block of code expands all declared replace properties in the specified resource targets.
@ -173,7 +93,7 @@ dependencies {
tasks.named('processResources', ProcessResources).configure { tasks.named('processResources', ProcessResources).configure {
var replaceProperties = [ var replaceProperties = [
minecraft_version: minecraft_version, minecraft_version_range: minecraft_version_range, minecraft_version: minecraft_version, minecraft_version_range: minecraft_version_range,
forge_version: forge_version, forge_version_range: forge_version_range, neo_version : neo_version, neo_version_range: neo_version_range,
loader_version_range: loader_version_range, loader_version_range: loader_version_range,
mod_id: mod_id, mod_name: mod_name, mod_license: mod_license, mod_version: mod_version, mod_id: mod_id, mod_name: mod_name, mod_license: mod_license, mod_version: mod_version,
mod_authors: mod_authors, mod_description: mod_description, mod_authors: mod_authors, mod_description: mod_description,
@ -203,26 +123,16 @@ jar {
} }
} }
shadowJar {
archiveClassifier = ''
//project.configurations.shadow.setTransitive(true);
configurations = [project.configurations.shade]
relocate 'fr.delthas', 'com.burnedkirby.tbm_repack.fr.delthas'
finalizedBy 'reobfShadowJar'
}
assemble.dependsOn shadowJar
reobf {
shadowJar {} // reobfuscate the shadowed jar
}
// Reproducible Builds // Reproducible Builds
tasks.withType(AbstractArchiveTask).configureEach { tasks.withType(AbstractArchiveTask).configureEach {
preserveFileTimestamps = false preserveFileTimestamps = false
reproducibleFileOrder = true reproducibleFileOrder = true
} }
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
}
// Example configuration to allow publishing using the maven-publish task // Example configuration to allow publishing using the maven-publish task
// we define a custom artifact that is sourced from the reobfJar output task // we define a custom artifact that is sourced from the reobfJar output task
// and then declare that to be published // and then declare that to be published

View file

@ -4,35 +4,17 @@ org.gradle.daemon=false
## Environment Properties ## Environment Properties
# The Minecraft version must agree with the Forge version to get a valid artifact # The Minecraft version must agree with the Forge version to get a valid artifact
minecraft_version=1.20.1 minecraft_version=1.20.2
# The Minecraft version range can use any release version of Minecraft as bounds. # The Minecraft version range can use any release version of Minecraft as bounds.
# Snapshots, pre-releases, and release candidates are not guaranteed to sort properly # Snapshots, pre-releases, and release candidates are not guaranteed to sort properly
# as they do not follow standard versioning conventions. # as they do not follow standard versioning conventions.
minecraft_version_range=[1.20.1,1.21) minecraft_version_range=[1.20.2,1.21)
# The Forge version must agree with the Minecraft version to get a valid artifact # The Neo version must agree with the Minecraft version to get a valid artifact
forge_version=47.1.0 neo_version=20.2.86
# The Forge version range can use any version of Forge as bounds or match the loader version range # The Neo version range can use any version of Neo as bounds or match the loader version range
forge_version_range=[47,) neo_version_range=[20.2,)
# The loader version range can only use the major version of Forge/FML as bounds # The loader version range can only use the major version of Neo/FML as bounds
loader_version_range=[47,) loader_version_range=[1,)
# The mapping channel to use for mappings.
# The default set of supported mapping channels are ["official", "snapshot", "snapshot_nodoc", "stable", "stable_nodoc"].
# Additional mapping channels can be registered through the "channelProviders" extension in a Gradle plugin.
#
# | Channel | Version | |
# |-----------|----------------------|--------------------------------------------------------------------------------|
# | official | MCVersion | Official field/method names from Mojang mapping files |
# | parchment | YYYY.MM.DD-MCVersion | Open community-sourced parameter names and javadocs layered on top of official |
#
# You must be aware of the Mojang license when using the 'official' or 'parchment' mappings.
# See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
#
# Parchment is an unofficial project maintained by ParchmentMC, separate from Minecraft Forge.
# Additional setup is needed to use their mappings, see https://parchmentmc.org/docs/getting-started
mapping_channel=official
# The mapping version to query from the mapping channel.
# This must match the format required by the mapping channel.
mapping_version=1.20.1
## Mod Properties ## Mod Properties
@ -44,7 +26,7 @@ mod_name=TurnBasedMinecraftMod
# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default. # The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default.
mod_license=MIT mod_license=MIT
# The mod version. See https://semver.org/ # The mod version. See https://semver.org/
mod_version=1.23.1 mod_version=1.24.0
# The group ID for the mod. It is only important when publishing as an artifact to a Maven repository. # The group ID for the mod. It is only important when publishing as an artifact to a Maven repository.
# This should match the base package used for the mod sources. # This should match the base package used for the mod sources.
# See https://maven.apache.org/guides/mini/guide-naming-conventions.html # See https://maven.apache.org/guides/mini/guide-naming-conventions.html
@ -53,3 +35,5 @@ mod_version=1.23.1
mod_authors=BurnedKirby a.k.a. Stephen Seo mod_authors=BurnedKirby a.k.a. Stephen Seo
# The description of the mod. This is a simple multiline text string that is used for display purposes in the mod list. # The description of the mod. This is a simple multiline text string that is used for display purposes in the mod list.
mod_description=Implements turn-based-battle in Minecraft. mod_description=Implements turn-based-battle in Minecraft.
# Pack version - this changes each minecraft release, in general.
pack_format_number=18

Binary file not shown.

7
gradlew vendored
View file

@ -85,6 +85,9 @@ done
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@ -194,10 +197,6 @@ if "$cygwin" || "$msys" ; then
done done
fi fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command; # Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in # shell script including quotes and variable substitutions, so put them in

View file

@ -2,8 +2,7 @@ pluginManagement {
repositories { repositories {
gradlePluginPortal() gradlePluginPortal()
maven { maven {
name = 'MinecraftForge' url = 'https://maven.neoforged.net/releases'
url = 'https://maven.minecraftforge.net/'
} }
jcenter() jcenter()
mavenCentral() mavenCentral()

View file

@ -368,4 +368,9 @@ public class BattleGui extends Screen {
public void setTurnTimerMax(int timerMax) { public void setTurnTimerMax(int timerMax) {
this.timerMax = timerMax; this.timerMax = timerMax;
} }
@Override
public void renderBackground(GuiGraphics p_283688_, int p_296369_, int p_296477_, float p_294317_) {
// Prevent graying of background.
}
} }

View file

@ -15,9 +15,7 @@ import net.minecraft.resources.ResourceKey;
import net.minecraft.sounds.SoundSource; import net.minecraft.sounds.SoundSource;
import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraftforge.network.NetworkEvent; import net.neoforged.neoforge.network.NetworkEvent;
import java.util.function.Supplier;
public class ClientProxy extends CommonProxy { public class ClientProxy extends CommonProxy {
private BattleGui battleGui = null; private BattleGui battleGui = null;
@ -224,7 +222,7 @@ public class ClientProxy extends CommonProxy {
} }
@Override @Override
public <MSG> void handlePacket(MSG msg, Supplier<NetworkEvent.Context> ctx) { public <MSG> void handlePacket(MSG msg, NetworkEvent.Context ctx) {
if (msg.getClass() == PacketBattleMessage.class) { if (msg.getClass() == PacketBattleMessage.class) {
PacketBattleMessage pkt = (PacketBattleMessage) msg; PacketBattleMessage pkt = (PacketBattleMessage) msg;
Entity fromEntity = getEntity(pkt.getEntityIDFrom(), pkt.getDimension()); Entity fromEntity = getEntity(pkt.getEntityIDFrom(), pkt.getDimension());
@ -435,6 +433,11 @@ public class ClientProxy extends CommonProxy {
parentComponent.getSiblings().add(message); parentComponent.getSiblings().add(message);
TurnBasedMinecraftMod.proxy.displayComponent(parentComponent); TurnBasedMinecraftMod.proxy.displayComponent(parentComponent);
} }
case CROSSBOW_NO_AMMO: {
parentComponent.getSiblings().add(from);
parentComponent.getSiblings().add(Component.literal(" tried to use their crossbow but ran out of ammo!"));
TurnBasedMinecraftMod.proxy.displayComponent(parentComponent);
}
break; break;
} }
} else if (msg.getClass() == PacketGeneralMessage.class) { } else if (msg.getClass() == PacketGeneralMessage.class) {

View file

@ -9,10 +9,10 @@ import com.burnedkirby.TurnBasedMinecraft.common.networking.PacketGeneralMessage
import net.minecraft.world.damagesource.DamageTypes; import net.minecraft.world.damagesource.DamageTypes;
import net.minecraft.world.entity.monster.Creeper; import net.minecraft.world.entity.monster.Creeper;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.event.entity.living.LivingAttackEvent; import net.neoforged.neoforge.event.entity.living.LivingAttackEvent;
import net.minecraftforge.event.entity.living.LivingChangeTargetEvent; import net.neoforged.neoforge.event.entity.living.LivingChangeTargetEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent; import net.neoforged.neoforge.network.PacketDistributor;
import net.minecraftforge.network.PacketDistributor; import net.neoforged.bus.api.SubscribeEvent;
public class AttackEventHandler public class AttackEventHandler
{ {

View file

@ -4,6 +4,7 @@ import com.burnedkirby.TurnBasedMinecraft.common.networking.PacketBattleInfo;
import com.burnedkirby.TurnBasedMinecraft.common.networking.PacketBattleMessage; import com.burnedkirby.TurnBasedMinecraft.common.networking.PacketBattleMessage;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.effect.MobEffects; import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity;
@ -13,8 +14,8 @@ import net.minecraft.world.entity.monster.Creeper;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.*; import net.minecraft.world.item.*;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraftforge.common.CreativeModeTabRegistry; import net.neoforged.neoforge.common.CreativeModeTabRegistry;
import net.minecraftforge.network.PacketDistributor; import net.neoforged.neoforge.network.PacketDistributor;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -793,6 +794,28 @@ public class Battle {
sendMessageToAllPlayers(PacketBattleMessage.MessageType.BOW_NO_AMMO, next.entity.getId(), 0, 0); sendMessageToAllPlayers(PacketBattleMessage.MessageType.BOW_NO_AMMO, next.entity.getId(), 0, 0);
} }
continue; continue;
} else if (heldItemStack.getItem() instanceof CrossbowItem) {
debugLog += " with crossbow";
if (Utility.doesPlayerHaveArrows((Player) next.entity)) {
final Entity nextEntity = next.entity;
final Entity targetEntity = target.entity;
final float yawDirection = Utility.yawDirection(next.entity.getX(), next.entity.getZ(), target.entity.getX(), target.entity.getZ());
final float pitchDirection = Utility.pitchDirection(next.entity.getX(), next.entity.getY(), next.entity.getZ(), target.entity.getX(), target.entity.getY(), target.entity.getZ());
if (TurnBasedMinecraftMod.proxy.getConfig().isFreezeCombatantsEnabled()) {
next.yaw = yawDirection;
next.pitch = pitchDirection;
}
// have player look at attack target
((ServerPlayer) nextEntity).connection.teleport(nextEntity.getX(), nextEntity.getY(), nextEntity.getZ(), yawDirection, pitchDirection);
CrossbowItem itemCrossbow = (CrossbowItem) heldItemStack.getItem();
TurnBasedMinecraftMod.proxy.getAttackerViaBowSet().add(new AttackerViaBow(nextEntity, getId()));
itemCrossbow.releaseUsing(heldItemStack, nextEntity.level(), (LivingEntity)nextEntity, -100);
itemCrossbow.use(nextEntity.level(), (Player)nextEntity, InteractionHand.MAIN_HAND);
sendMessageToAllPlayers(PacketBattleMessage.MessageType.FIRED_ARROW, nextEntity.getId(), targetEntity.getId(), 0);
} else {
sendMessageToAllPlayers(PacketBattleMessage.MessageType.CROSSBOW_NO_AMMO, next.entity.getId(), 0, 0);
}
continue;
} }
debugLog += " without bow"; debugLog += " without bow";
int hitChance = TurnBasedMinecraftMod.proxy.getConfig().getPlayerAttackProbability(); int hitChance = TurnBasedMinecraftMod.proxy.getConfig().getPlayerAttackProbability();

View file

@ -7,10 +7,10 @@ import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.monster.Creeper; import net.minecraft.world.entity.monster.Creeper;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraftforge.common.MinecraftForge; import net.neoforged.neoforge.common.NeoForge;
import net.minecraftforge.event.entity.living.LivingAttackEvent; import net.neoforged.neoforge.event.entity.living.LivingAttackEvent;
import net.minecraftforge.event.entity.living.LivingChangeTargetEvent; import net.neoforged.neoforge.event.entity.living.LivingChangeTargetEvent;
import net.minecraftforge.network.PacketDistributor; import net.neoforged.neoforge.network.PacketDistributor;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import java.util.*; import java.util.*;
@ -32,7 +32,7 @@ public class BattleManager
recentlyLeftBattle = new HashMap<Integer, Combatant>(); recentlyLeftBattle = new HashMap<Integer, Combatant>();
battleUpdater = new BattleUpdater(this); battleUpdater = new BattleUpdater(this);
entityToBattleMap = new HashMap<EntityIDDimPair, Integer>(); entityToBattleMap = new HashMap<EntityIDDimPair, Integer>();
MinecraftForge.EVENT_BUS.register(battleUpdater); NeoForge.EVENT_BUS.register(battleUpdater);
tempIDPair = new EntityIDDimPair(); tempIDPair = new EntityIDDimPair();
} }
@ -307,7 +307,7 @@ public class BattleManager
public void cleanup() public void cleanup()
{ {
battleUpdater.setRunning(false); battleUpdater.setRunning(false);
MinecraftForge.EVENT_BUS.unregister(battleUpdater); NeoForge.EVENT_BUS.unregister(battleUpdater);
battleMap.clear(); battleMap.clear();
battleUpdater = null; battleUpdater = null;
} }

View file

@ -1,8 +1,8 @@
package com.burnedkirby.TurnBasedMinecraft.common; package com.burnedkirby.TurnBasedMinecraft.common;
import net.minecraftforge.event.TickEvent; import net.neoforged.bus.api.SubscribeEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent; import net.neoforged.neoforge.event.TickEvent;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;

View file

@ -5,15 +5,14 @@ import net.minecraft.resources.ResourceKey;
import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraftforge.network.NetworkEvent; import net.neoforged.neoforge.network.NetworkEvent;
import net.minecraftforge.server.ServerLifecycleHooks; import net.neoforged.neoforge.server.ServerLifecycleHooks;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import java.util.HashSet; import java.util.HashSet;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.function.Supplier;
public class CommonProxy public class CommonProxy
{ {
@ -173,5 +172,5 @@ public class CommonProxy
return ServerLifecycleHooks.getCurrentServer().getLevel(dim).getEntity(id); return ServerLifecycleHooks.getCurrentServer().getLevel(dim).getEntity(id);
} }
public <MSG> void handlePacket(MSG msg, Supplier<NetworkEvent.Context> ctx) {} public <MSG> void handlePacket(MSG msg, NetworkEvent.Context ctx) {}
} }

View file

@ -1521,7 +1521,7 @@ public class Config
possibleIgnoreHurtDamageSources.clear(); possibleIgnoreHurtDamageSources.clear();
try { try {
VanillaRegistries.createLookup().lookupOrThrow(Registries.DAMAGE_TYPE).listElements().forEach(dt -> possibleIgnoreHurtDamageSources.add(dt.get().msgId())); VanillaRegistries.createLookup().lookupOrThrow(Registries.DAMAGE_TYPE).listElements().forEach(dt -> possibleIgnoreHurtDamageSources.add(dt.value().msgId()));
} catch (Exception e) { } catch (Exception e) {
logger.warn("Config failed to load possible DamageSources! Undesired things may happen, like Zombies dying from Fire during battle!"); logger.warn("Config failed to load possible DamageSources! Undesired things may happen, like Zombies dying from Fire during battle!");
logger.warn(e); logger.warn(e);

View file

@ -2,9 +2,9 @@ package com.burnedkirby.TurnBasedMinecraft.common;
import com.burnedkirby.TurnBasedMinecraft.common.networking.PacketGeneralMessage; import com.burnedkirby.TurnBasedMinecraft.common.networking.PacketGeneralMessage;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.event.entity.EntityTravelToDimensionEvent; import net.neoforged.neoforge.event.entity.EntityTravelToDimensionEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent; import net.neoforged.bus.api.SubscribeEvent;
import net.minecraftforge.network.PacketDistributor; import net.neoforged.neoforge.network.PacketDistributor;
public class DimensionChangedHandler { public class DimensionChangedHandler {
@SubscribeEvent @SubscribeEvent

View file

@ -1,7 +1,7 @@
package com.burnedkirby.TurnBasedMinecraft.common; package com.burnedkirby.TurnBasedMinecraft.common;
import net.minecraftforge.event.entity.living.LivingHurtEvent; import net.neoforged.bus.api.SubscribeEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent; import net.neoforged.neoforge.event.entity.living.LivingHurtEvent;
public class HurtEventHandler { public class HurtEventHandler {
@SubscribeEvent @SubscribeEvent

View file

@ -1,8 +1,8 @@
package com.burnedkirby.TurnBasedMinecraft.common; package com.burnedkirby.TurnBasedMinecraft.common;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraftforge.event.entity.EntityJoinLevelEvent; import net.neoforged.bus.api.SubscribeEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent; import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent;
public class PlayerJoinEventHandler public class PlayerJoinEventHandler
{ {

View file

@ -1,5 +1,6 @@
package com.burnedkirby.TurnBasedMinecraft.common; package com.burnedkirby.TurnBasedMinecraft.common;
import ca.weblite.objc.Client;
import com.burnedkirby.TurnBasedMinecraft.client.ClientProxy; import com.burnedkirby.TurnBasedMinecraft.client.ClientProxy;
import com.burnedkirby.TurnBasedMinecraft.common.networking.*; import com.burnedkirby.TurnBasedMinecraft.common.networking.*;
import com.mojang.brigadier.LiteralMessage; import com.mojang.brigadier.LiteralMessage;
@ -18,20 +19,20 @@ import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.MutableComponent;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.common.MinecraftForge; import net.neoforged.bus.api.SubscribeEvent;
import net.minecraftforge.event.RegisterCommandsEvent; import net.neoforged.fml.loading.FMLEnvironment;
import net.minecraftforge.event.server.ServerStartingEvent; import net.neoforged.neoforge.common.NeoForge;
import net.minecraftforge.event.server.ServerStoppingEvent; import net.neoforged.neoforge.event.RegisterCommandsEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent; import net.neoforged.neoforge.event.server.ServerStartingEvent;
import net.minecraftforge.fml.DistExecutor; import net.neoforged.neoforge.event.server.ServerStoppingEvent;
import net.minecraftforge.fml.common.Mod; import net.neoforged.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLDedicatedServerSetupEvent; import net.neoforged.fml.event.lifecycle.FMLDedicatedServerSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.neoforged.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.network.NetworkRegistry; import net.neoforged.neoforge.network.NetworkRegistry;
import net.minecraftforge.network.PacketDistributor; import net.neoforged.neoforge.network.PacketDistributor;
import net.minecraftforge.network.simple.SimpleChannel; import net.neoforged.neoforge.network.simple.SimpleChannel;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@ -39,7 +40,7 @@ import org.apache.logging.log4j.Logger;
public class TurnBasedMinecraftMod { public class TurnBasedMinecraftMod {
public static final String MODID = "com_burnedkirby_turnbasedminecraft"; public static final String MODID = "com_burnedkirby_turnbasedminecraft";
public static final String NAME = "Turn Based Minecraft Mod"; public static final String NAME = "Turn Based Minecraft Mod";
public static final String VERSION = "1.23.1"; public static final String VERSION = "1.24.0";
public static final String CONFIG_FILENAME = "TBM_Config.toml"; public static final String CONFIG_FILENAME = "TBM_Config.toml";
public static final String DEFAULT_CONFIG_FILENAME = "TBM_Config_DEFAULT.toml"; public static final String DEFAULT_CONFIG_FILENAME = "TBM_Config_DEFAULT.toml";
public static final String CONFIG_DIRECTORY = "config/TurnBasedMinecraft/"; public static final String CONFIG_DIRECTORY = "config/TurnBasedMinecraft/";
@ -50,7 +51,7 @@ public class TurnBasedMinecraftMod {
public static final String MUSIC_SILLY = MUSIC_ROOT + "silly/"; public static final String MUSIC_SILLY = MUSIC_ROOT + "silly/";
public static final String MUSIC_BATTLE = MUSIC_ROOT + "battle/"; public static final String MUSIC_BATTLE = MUSIC_ROOT + "battle/";
private static final String PROTOCOL_VERSION = Integer.toString(2); private static final String PROTOCOL_VERSION = Integer.toString(3);
private static final ResourceLocation HANDLER_ID = new ResourceLocation(MODID, "main_channel"); private static final ResourceLocation HANDLER_ID = new ResourceLocation(MODID, "main_channel");
private static final SimpleChannel HANDLER = NetworkRegistry.ChannelBuilder private static final SimpleChannel HANDLER = NetworkRegistry.ChannelBuilder
.named(HANDLER_ID) .named(HANDLER_ID)
@ -75,11 +76,15 @@ public class TurnBasedMinecraftMod {
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::secondInitClient); FMLJavaModLoadingContext.get().getModEventBus().addListener(this::secondInitClient);
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::secondInitServer); FMLJavaModLoadingContext.get().getModEventBus().addListener(this::secondInitServer);
MinecraftForge.EVENT_BUS.register(this); NeoForge.EVENT_BUS.register(this);
} }
private void firstInit(final FMLCommonSetupEvent event) { private void firstInit(final FMLCommonSetupEvent event) {
proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); if (FMLEnvironment.dist.isClient()) {
proxy = new ClientProxy();
} else {
proxy = new CommonProxy();
}
proxy.setLogger(logger); proxy.setLogger(logger);
proxy.initialize(); proxy.initialize();
@ -88,45 +93,45 @@ public class TurnBasedMinecraftMod {
HANDLER.registerMessage( HANDLER.registerMessage(
packetHandlerID++, packetHandlerID++,
PacketBattleInfo.class, PacketBattleInfo.class,
PacketBattleInfo::encode, new PacketBattleInfo.Encoder(),
PacketBattleInfo::decode, new PacketBattleInfo.Decoder(),
PacketBattleInfo::handle); new PacketBattleInfo.Consumer());
HANDLER.registerMessage( HANDLER.registerMessage(
packetHandlerID++, packetHandlerID++,
PacketBattleRequestInfo.class, PacketBattleRequestInfo.class,
PacketBattleRequestInfo::encode, new PacketBattleRequestInfo.Encoder(),
PacketBattleRequestInfo::decode, new PacketBattleRequestInfo.Decoder(),
PacketBattleRequestInfo::handle); new PacketBattleRequestInfo.Consumer());
HANDLER.registerMessage( HANDLER.registerMessage(
packetHandlerID++, packetHandlerID++,
PacketBattleDecision.class, PacketBattleDecision.class,
PacketBattleDecision::encode, new PacketBattleDecision.Encoder(),
PacketBattleDecision::decode, new PacketBattleDecision.Decoder(),
PacketBattleDecision::handle); new PacketBattleDecision.Consumer());
HANDLER.registerMessage( HANDLER.registerMessage(
packetHandlerID++, packetHandlerID++,
PacketBattleMessage.class, PacketBattleMessage.class,
PacketBattleMessage::encode, new PacketBattleMessage.Encoder(),
PacketBattleMessage::decode, new PacketBattleMessage.Decoder(),
PacketBattleMessage::handle); new PacketBattleMessage.Consumer());
HANDLER.registerMessage( HANDLER.registerMessage(
packetHandlerID++, packetHandlerID++,
PacketGeneralMessage.class, PacketGeneralMessage.class,
PacketGeneralMessage::encode, new PacketGeneralMessage.Encoder(),
PacketGeneralMessage::decode, new PacketGeneralMessage.Decoder(),
PacketGeneralMessage::handle); new PacketGeneralMessage.Consumer());
HANDLER.registerMessage( HANDLER.registerMessage(
packetHandlerID++, packetHandlerID++,
PacketEditingMessage.class, PacketEditingMessage.class,
PacketEditingMessage::encode, new PacketEditingMessage.Encoder(),
PacketEditingMessage::decode, new PacketEditingMessage.Decoder(),
PacketEditingMessage::handle); new PacketEditingMessage.Consumer());
// register event handler(s) // register event handler(s)
MinecraftForge.EVENT_BUS.register(new AttackEventHandler()); NeoForge.EVENT_BUS.register(new AttackEventHandler());
MinecraftForge.EVENT_BUS.register(new PlayerJoinEventHandler()); NeoForge.EVENT_BUS.register(new PlayerJoinEventHandler());
MinecraftForge.EVENT_BUS.register(new DimensionChangedHandler()); NeoForge.EVENT_BUS.register(new DimensionChangedHandler());
MinecraftForge.EVENT_BUS.register(new HurtEventHandler()); NeoForge.EVENT_BUS.register(new HurtEventHandler());
logger.debug("Init com_burnedkirby_turnbasedminecraft"); logger.debug("Init com_burnedkirby_turnbasedminecraft");
} }

View file

@ -1,14 +1,13 @@
package com.burnedkirby.TurnBasedMinecraft.common.networking; package com.burnedkirby.TurnBasedMinecraft.common.networking;
import java.util.function.Supplier;
import com.burnedkirby.TurnBasedMinecraft.common.Battle; import com.burnedkirby.TurnBasedMinecraft.common.Battle;
import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod; import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod;
import com.burnedkirby.TurnBasedMinecraft.common.Battle.Decision; import com.burnedkirby.TurnBasedMinecraft.common.Battle.Decision;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent; import net.neoforged.neoforge.network.NetworkEvent;
import net.neoforged.neoforge.network.simple.MessageFunctions;
public class PacketBattleDecision public class PacketBattleDecision
{ {
@ -25,25 +24,40 @@ public class PacketBattleDecision
this.targetIDOrItemID = targetIDOrItemID; this.targetIDOrItemID = targetIDOrItemID;
} }
public static void encode(PacketBattleDecision pkt, FriendlyByteBuf buf) { public static class Encoder implements MessageFunctions.MessageEncoder<PacketBattleDecision> {
buf.writeInt(pkt.battleID); public Encoder() {}
buf.writeInt(pkt.decision.getValue());
buf.writeInt(pkt.targetIDOrItemID); @Override
public void encode(PacketBattleDecision pkt, FriendlyByteBuf buf) {
buf.writeInt(pkt.battleID);
buf.writeInt(pkt.decision.getValue());
buf.writeInt(pkt.targetIDOrItemID);
}
} }
public static PacketBattleDecision decode(FriendlyByteBuf buf) { public static class Decoder implements MessageFunctions.MessageDecoder<PacketBattleDecision> {
return new PacketBattleDecision(buf.readInt(), Decision.valueOf(buf.readInt()), buf.readInt()); public Decoder() {}
@Override
public PacketBattleDecision decode(FriendlyByteBuf buf) {
return new PacketBattleDecision(buf.readInt(), Decision.valueOf(buf.readInt()), buf.readInt());
}
} }
public static void handle(final PacketBattleDecision pkt, Supplier<NetworkEvent.Context> ctx) { public static class Consumer implements MessageFunctions.MessageConsumer<PacketBattleDecision> {
ctx.get().enqueueWork(() -> { public Consumer() {}
Battle b = TurnBasedMinecraftMod.proxy.getBattleManager().getBattleByID(pkt.battleID);
if(b != null) @Override
{ public void handle(PacketBattleDecision pkt, NetworkEvent.Context ctx) {
ServerPlayer player = ctx.get().getSender(); ctx.enqueueWork(() -> {
b.setDecision(player.getId(), pkt.decision, pkt.targetIDOrItemID); Battle b = TurnBasedMinecraftMod.proxy.getBattleManager().getBattleByID(pkt.battleID);
} if(b != null)
}); {
ctx.get().setPacketHandled(true); ServerPlayer player = ctx.getSender();
b.setDecision(player.getId(), pkt.decision, pkt.targetIDOrItemID);
}
});
ctx.setPacketHandled(true);
}
} }
} }

View file

@ -2,14 +2,14 @@ package com.burnedkirby.TurnBasedMinecraft.common.networking;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.function.Supplier;
import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod; import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent; import net.neoforged.neoforge.network.NetworkEvent;
import net.neoforged.neoforge.network.simple.MessageFunctions;
public class PacketBattleInfo public class PacketBattleInfo
{ {
@ -38,65 +38,80 @@ public class PacketBattleInfo
this.turnTimerEnabled = turnTimerEnabled; this.turnTimerEnabled = turnTimerEnabled;
} }
public static void encode(PacketBattleInfo msg, FriendlyByteBuf buf) { public static class Encoder implements MessageFunctions.MessageEncoder<PacketBattleInfo> {
buf.writeInt(msg.sideA.size()); public Encoder() {}
buf.writeInt(msg.sideB.size());
for(Integer id : msg.sideA) { @Override
buf.writeInt(id); public void encode(PacketBattleInfo msg, FriendlyByteBuf buf) {
} buf.writeInt(msg.sideA.size());
for(Integer id : msg.sideB) { buf.writeInt(msg.sideB.size());
buf.writeInt(id); for(Integer id : msg.sideA) {
} buf.writeInt(id);
buf.writeLong(msg.decisionNanos); }
buf.writeLong(msg.maxDecisionNanos); for(Integer id : msg.sideB) {
buf.writeBoolean(msg.turnTimerEnabled); buf.writeInt(id);
}
buf.writeLong(msg.decisionNanos);
buf.writeLong(msg.maxDecisionNanos);
buf.writeBoolean(msg.turnTimerEnabled);
}
} }
public static PacketBattleInfo decode(FriendlyByteBuf buf) { public static class Decoder implements MessageFunctions.MessageDecoder<PacketBattleInfo> {
int sideACount = buf.readInt(); public Decoder() {}
int sideBCount = buf.readInt();
Collection<Integer> sideA = new ArrayList<Integer>(sideACount); @Override
Collection<Integer> sideB = new ArrayList<Integer>(sideBCount); public PacketBattleInfo decode(FriendlyByteBuf buf) {
for(int i = 0; i < sideACount; ++i) { int sideACount = buf.readInt();
sideA.add(buf.readInt()); int sideBCount = buf.readInt();
} Collection<Integer> sideA = new ArrayList<Integer>(sideACount);
for(int i = 0; i < sideBCount; ++i) { Collection<Integer> sideB = new ArrayList<Integer>(sideBCount);
sideB.add(buf.readInt()); for(int i = 0; i < sideACount; ++i) {
} sideA.add(buf.readInt());
long decisionNanos = buf.readLong(); }
long maxDecisionNanos = buf.readLong(); for(int i = 0; i < sideBCount; ++i) {
boolean turnTimerEnabled = buf.readBoolean(); sideB.add(buf.readInt());
return new PacketBattleInfo(sideA, sideB, decisionNanos, maxDecisionNanos, turnTimerEnabled); }
long decisionNanos = buf.readLong();
long maxDecisionNanos = buf.readLong();
boolean turnTimerEnabled = buf.readBoolean();
return new PacketBattleInfo(sideA, sideB, decisionNanos, maxDecisionNanos, turnTimerEnabled);
}
} }
public static void handle(final PacketBattleInfo pkt, Supplier<NetworkEvent.Context> ctx) { public static class Consumer implements MessageFunctions.MessageConsumer<PacketBattleInfo> {
ctx.get().enqueueWork(() -> { public Consumer() {}
if(TurnBasedMinecraftMod.proxy.getLocalBattle() == null)
{ @Override
return; public void handle(PacketBattleInfo pkt, NetworkEvent.Context ctx) {
} ctx.enqueueWork(() -> {
TurnBasedMinecraftMod.proxy.getLocalBattle().clearCombatants(); if(TurnBasedMinecraftMod.proxy.getLocalBattle() == null)
for(Integer id : pkt.sideA)
{
Entity e = Minecraft.getInstance().level.getEntity(id);
if(e != null)
{ {
TurnBasedMinecraftMod.proxy.getLocalBattle().addCombatantToSideA(e); return;
} }
} TurnBasedMinecraftMod.proxy.getLocalBattle().clearCombatants();
for(Integer id : pkt.sideB) for(Integer id : pkt.sideA)
{
Entity e = Minecraft.getInstance().level.getEntity(id);
if(e != null)
{ {
TurnBasedMinecraftMod.proxy.getLocalBattle().addCombatantToSideB(e); Entity e = Minecraft.getInstance().level.getEntity(id);
if(e != null)
{
TurnBasedMinecraftMod.proxy.getLocalBattle().addCombatantToSideA(e);
}
} }
} for(Integer id : pkt.sideB)
TurnBasedMinecraftMod.proxy.setBattleGuiTime((int)(pkt.decisionNanos / 1000000000L)); {
TurnBasedMinecraftMod.proxy.setBattleGuiBattleChanged(); Entity e = Minecraft.getInstance().level.getEntity(id);
TurnBasedMinecraftMod.proxy.setBattleGuiTurnTimerEnabled(pkt.turnTimerEnabled); if(e != null)
TurnBasedMinecraftMod.proxy.setBattleGuiTurnTimerMax((int)(pkt.maxDecisionNanos / 1000000000L)); {
}); TurnBasedMinecraftMod.proxy.getLocalBattle().addCombatantToSideB(e);
ctx.get().setPacketHandled(true); }
}
TurnBasedMinecraftMod.proxy.setBattleGuiTime((int)(pkt.decisionNanos / 1000000000L));
TurnBasedMinecraftMod.proxy.setBattleGuiBattleChanged();
TurnBasedMinecraftMod.proxy.setBattleGuiTurnTimerEnabled(pkt.turnTimerEnabled);
TurnBasedMinecraftMod.proxy.setBattleGuiTurnTimerMax((int)(pkt.maxDecisionNanos / 1000000000L));
});
ctx.setPacketHandled(true);
}
} }
} }

View file

@ -2,7 +2,6 @@ package com.burnedkirby.TurnBasedMinecraft.common.networking;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.function.Supplier;
import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod; import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod;
@ -10,9 +9,9 @@ import com.burnedkirby.TurnBasedMinecraft.common.Utility;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraftforge.api.distmarker.Dist; import net.neoforged.fml.loading.FMLEnvironment;
import net.minecraftforge.fml.DistExecutor; import net.neoforged.neoforge.network.NetworkEvent;
import net.minecraftforge.network.NetworkEvent; import net.neoforged.neoforge.network.simple.MessageFunctions;
public class PacketBattleMessage public class PacketBattleMessage
{ {
@ -39,7 +38,8 @@ public class PacketBattleMessage
BOW_NO_AMMO(18), BOW_NO_AMMO(18),
CREEPER_WAIT(19), CREEPER_WAIT(19),
CREEPER_WAIT_FINAL(20), CREEPER_WAIT_FINAL(20),
CREEPER_EXPLODE(21); CREEPER_EXPLODE(21),
CROSSBOW_NO_AMMO(22);
private int value; private int value;
private static Map<Integer, MessageType> map = new HashMap<Integer, MessageType>(); private static Map<Integer, MessageType> map = new HashMap<Integer, MessageType>();
@ -154,30 +154,47 @@ public class PacketBattleMessage
this.custom = custom; this.custom = custom;
} }
public static void encode(PacketBattleMessage pkt, FriendlyByteBuf buf) { public static class Encoder implements MessageFunctions.MessageEncoder<PacketBattleMessage> {
buf.writeInt(pkt.messageType.getValue()); public Encoder() {}
buf.writeInt(pkt.entityIDFrom);
buf.writeInt(pkt.entityIDTo); @Override
buf.writeUtf(Utility.serializeDimension(pkt.dimension)); public void encode(PacketBattleMessage pkt, FriendlyByteBuf buf) {
buf.writeInt(pkt.amount); buf.writeInt(pkt.messageType.getValue());
buf.writeUtf(pkt.custom); buf.writeInt(pkt.entityIDFrom);
buf.writeInt(pkt.entityIDTo);
buf.writeUtf(Utility.serializeDimension(pkt.dimension));
buf.writeInt(pkt.amount);
buf.writeUtf(pkt.custom);
}
} }
public static PacketBattleMessage decode(FriendlyByteBuf buf) { public static class Decoder implements MessageFunctions.MessageDecoder<PacketBattleMessage> {
return new PacketBattleMessage( public Decoder() {}
MessageType.valueOf(
buf.readInt()), @Override
buf.readInt(), public PacketBattleMessage decode(FriendlyByteBuf buf) {
buf.readInt(), return new PacketBattleMessage(
Utility.deserializeDimension(buf.readUtf()), MessageType.valueOf(
buf.readInt(), buf.readInt()),
buf.readUtf()); buf.readInt(),
buf.readInt(),
Utility.deserializeDimension(buf.readUtf()),
buf.readInt(),
buf.readUtf());
}
} }
public static void handle(final PacketBattleMessage pkt, Supplier<NetworkEvent.Context> ctx) { public static class Consumer implements MessageFunctions.MessageConsumer<PacketBattleMessage> {
ctx.get().enqueueWork(() -> { public Consumer() {}
DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> TurnBasedMinecraftMod.proxy.handlePacket(pkt, ctx));
}); @Override
ctx.get().setPacketHandled(true); public void handle(PacketBattleMessage pkt, NetworkEvent.Context ctx) {
ctx.enqueueWork(() -> {
if (FMLEnvironment.dist.isClient()) {
TurnBasedMinecraftMod.proxy.handlePacket(pkt, ctx);
}
});
ctx.setPacketHandled(true);
}
} }
} }

View file

@ -1,12 +1,11 @@
package com.burnedkirby.TurnBasedMinecraft.common.networking; package com.burnedkirby.TurnBasedMinecraft.common.networking;
import java.util.function.Supplier;
import com.burnedkirby.TurnBasedMinecraft.common.Battle; import com.burnedkirby.TurnBasedMinecraft.common.Battle;
import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod; import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent; import net.neoforged.neoforge.network.NetworkEvent;
import net.neoforged.neoforge.network.simple.MessageFunctions;
public class PacketBattleRequestInfo public class PacketBattleRequestInfo
{ {
@ -19,22 +18,37 @@ public class PacketBattleRequestInfo
this.battleID = battleID; this.battleID = battleID;
} }
public static void encode(PacketBattleRequestInfo pkt, FriendlyByteBuf buf) { public static class Encoder implements MessageFunctions.MessageEncoder<PacketBattleRequestInfo> {
buf.writeInt(pkt.battleID); public Encoder() {}
@Override
public void encode(PacketBattleRequestInfo pkt, FriendlyByteBuf buf) {
buf.writeInt(pkt.battleID);
}
} }
public static PacketBattleRequestInfo decode(FriendlyByteBuf buf) { public static class Decoder implements MessageFunctions.MessageDecoder<PacketBattleRequestInfo> {
return new PacketBattleRequestInfo(buf.readInt()); public Decoder() {}
@Override
public PacketBattleRequestInfo decode(FriendlyByteBuf buf) {
return new PacketBattleRequestInfo(buf.readInt());
}
} }
public static void handle(final PacketBattleRequestInfo pkt, Supplier<NetworkEvent.Context> ctx) { public static class Consumer implements MessageFunctions.MessageConsumer<PacketBattleRequestInfo> {
ctx.get().enqueueWork(() -> { public Consumer() {}
Battle b = TurnBasedMinecraftMod.proxy.getBattleManager().getBattleByID(pkt.battleID);
if(b == null) { @Override
return; public void handle(PacketBattleRequestInfo pkt, NetworkEvent.Context ctx) {
} ctx.enqueueWork(() -> {
TurnBasedMinecraftMod.getHandler().reply(new PacketBattleInfo(b.getSideAIDs(), b.getSideBIDs(), b.getTimerNanos(), TurnBasedMinecraftMod.proxy.getConfig().getDecisionDurationNanos(), !TurnBasedMinecraftMod.proxy.getConfig().isBattleDecisionDurationForever()), ctx.get()); Battle b = TurnBasedMinecraftMod.proxy.getBattleManager().getBattleByID(pkt.battleID);
}); if(b == null) {
ctx.get().setPacketHandled(true); return;
}
TurnBasedMinecraftMod.getHandler().reply(new PacketBattleInfo(b.getSideAIDs(), b.getSideBIDs(), b.getTimerNanos(), TurnBasedMinecraftMod.proxy.getConfig().getDecisionDurationNanos(), !TurnBasedMinecraftMod.proxy.getConfig().isBattleDecisionDurationForever()), ctx);
});
ctx.setPacketHandled(true);
}
} }
} }

View file

@ -3,13 +3,12 @@ package com.burnedkirby.TurnBasedMinecraft.common.networking;
import com.burnedkirby.TurnBasedMinecraft.common.EntityInfo; import com.burnedkirby.TurnBasedMinecraft.common.EntityInfo;
import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod; import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.api.distmarker.Dist; import net.neoforged.fml.loading.FMLEnvironment;
import net.minecraftforge.fml.DistExecutor; import net.neoforged.neoforge.network.NetworkEvent;
import net.minecraftforge.network.NetworkEvent; import net.neoforged.neoforge.network.simple.MessageFunctions;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.function.Supplier;
public class PacketEditingMessage public class PacketEditingMessage
{ {
@ -88,58 +87,75 @@ public class PacketEditingMessage
} }
} }
public static void encode(PacketEditingMessage pkt, FriendlyByteBuf buf) { public static class Encoder implements MessageFunctions.MessageEncoder<PacketEditingMessage> {
buf.writeInt(pkt.type.getValue()); public Encoder() {}
if(pkt.entityInfo.classType != null) {
buf.writeUtf(pkt.entityInfo.classType.getName()); @Override
} else { public void encode(PacketEditingMessage pkt, FriendlyByteBuf buf) {
buf.writeUtf("unknown"); buf.writeInt(pkt.type.getValue());
} if(pkt.entityInfo.classType != null) {
buf.writeBoolean(pkt.entityInfo.ignoreBattle); buf.writeUtf(pkt.entityInfo.classType.getName());
buf.writeInt(pkt.entityInfo.attackPower); } else {
buf.writeInt(pkt.entityInfo.attackProbability); buf.writeUtf("unknown");
buf.writeInt(pkt.entityInfo.attackVariance); }
buf.writeUtf(pkt.entityInfo.attackEffect.toString()); buf.writeBoolean(pkt.entityInfo.ignoreBattle);
buf.writeInt(pkt.entityInfo.attackEffectProbability); buf.writeInt(pkt.entityInfo.attackPower);
buf.writeInt(pkt.entityInfo.defenseDamage); buf.writeInt(pkt.entityInfo.attackProbability);
buf.writeInt(pkt.entityInfo.defenseDamageProbability); buf.writeInt(pkt.entityInfo.attackVariance);
buf.writeInt(pkt.entityInfo.evasion); buf.writeUtf(pkt.entityInfo.attackEffect.toString());
buf.writeInt(pkt.entityInfo.speed); buf.writeInt(pkt.entityInfo.attackEffectProbability);
buf.writeUtf(pkt.entityInfo.category); buf.writeInt(pkt.entityInfo.defenseDamage);
buf.writeInt(pkt.entityInfo.decisionAttack); buf.writeInt(pkt.entityInfo.defenseDamageProbability);
buf.writeInt(pkt.entityInfo.decisionDefend); buf.writeInt(pkt.entityInfo.evasion);
buf.writeInt(pkt.entityInfo.decisionFlee); buf.writeInt(pkt.entityInfo.speed);
buf.writeUtf(pkt.entityInfo.customName); buf.writeUtf(pkt.entityInfo.category);
buf.writeInt(pkt.entityInfo.decisionAttack);
buf.writeInt(pkt.entityInfo.decisionDefend);
buf.writeInt(pkt.entityInfo.decisionFlee);
buf.writeUtf(pkt.entityInfo.customName);
}
} }
public static PacketEditingMessage decode(FriendlyByteBuf buf) { public static class Decoder implements MessageFunctions.MessageDecoder<PacketEditingMessage> {
Type type = Type.valueOf(buf.readInt()); public Decoder() {}
EntityInfo einfo = new EntityInfo();
try { @Override
einfo.classType = einfo.getClass().getClassLoader().loadClass(buf.readUtf()); public PacketEditingMessage decode(FriendlyByteBuf buf) {
} catch (ClassNotFoundException e) { /* ignored */ } Type type = Type.valueOf(buf.readInt());
einfo.ignoreBattle = buf.readBoolean(); EntityInfo einfo = new EntityInfo();
einfo.attackPower = buf.readInt(); try {
einfo.attackProbability = buf.readInt(); einfo.classType = einfo.getClass().getClassLoader().loadClass(buf.readUtf());
einfo.attackVariance = buf.readInt(); } catch (ClassNotFoundException e) { /* ignored */ }
einfo.attackEffect = EntityInfo.Effect.fromString(buf.readUtf()); einfo.ignoreBattle = buf.readBoolean();
einfo.attackEffectProbability = buf.readInt(); einfo.attackPower = buf.readInt();
einfo.defenseDamage = buf.readInt(); einfo.attackProbability = buf.readInt();
einfo.defenseDamageProbability = buf.readInt(); einfo.attackVariance = buf.readInt();
einfo.evasion = buf.readInt(); einfo.attackEffect = EntityInfo.Effect.fromString(buf.readUtf());
einfo.speed = buf.readInt(); einfo.attackEffectProbability = buf.readInt();
einfo.category = buf.readUtf(); einfo.defenseDamage = buf.readInt();
einfo.decisionAttack = buf.readInt(); einfo.defenseDamageProbability = buf.readInt();
einfo.decisionDefend = buf.readInt(); einfo.evasion = buf.readInt();
einfo.decisionFlee = buf.readInt(); einfo.speed = buf.readInt();
einfo.customName = buf.readUtf(); einfo.category = buf.readUtf();
return new PacketEditingMessage(type, einfo); einfo.decisionAttack = buf.readInt();
einfo.decisionDefend = buf.readInt();
einfo.decisionFlee = buf.readInt();
einfo.customName = buf.readUtf();
return new PacketEditingMessage(type, einfo);
}
} }
public static void handle(final PacketEditingMessage pkt, Supplier<NetworkEvent.Context> ctx) { public static class Consumer implements MessageFunctions.MessageConsumer<PacketEditingMessage> {
ctx.get().enqueueWork(() -> { public Consumer() {}
DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> TurnBasedMinecraftMod.proxy.handlePacket(pkt, ctx));
}); @Override
ctx.get().setPacketHandled(true); public void handle(PacketEditingMessage pkt, NetworkEvent.Context ctx) {
ctx.enqueueWork(() -> {
if (FMLEnvironment.dist.isClient()) {
TurnBasedMinecraftMod.proxy.handlePacket(pkt, ctx);
}
});
ctx.setPacketHandled(true);
}
} }
} }

View file

@ -1,13 +1,13 @@
package com.burnedkirby.TurnBasedMinecraft.common.networking; package com.burnedkirby.TurnBasedMinecraft.common.networking;
import java.util.function.Supplier;
import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod; import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.api.distmarker.Dist; import net.neoforged.api.distmarker.Dist;
import net.minecraftforge.fml.DistExecutor; import net.neoforged.fml.DistExecutor;
import net.minecraftforge.network.NetworkEvent; import net.neoforged.fml.loading.FMLEnvironment;
import net.neoforged.neoforge.network.NetworkEvent;
import net.neoforged.neoforge.network.simple.MessageFunctions;
public class PacketGeneralMessage public class PacketGeneralMessage
{ {
@ -27,18 +27,35 @@ public class PacketGeneralMessage
this.message = message; this.message = message;
} }
public static void encode(PacketGeneralMessage pkt, FriendlyByteBuf buf) { public static class Encoder implements MessageFunctions.MessageEncoder<PacketGeneralMessage> {
buf.writeUtf(pkt.message); public Encoder() {}
@Override
public void encode(PacketGeneralMessage pkt, FriendlyByteBuf buf) {
buf.writeUtf(pkt.message);
}
} }
public static PacketGeneralMessage decode(FriendlyByteBuf buf) { public static class Decoder implements MessageFunctions.MessageDecoder<PacketGeneralMessage> {
return new PacketGeneralMessage(buf.readUtf()); public Decoder() {}
@Override
public PacketGeneralMessage decode(FriendlyByteBuf buf) {
return new PacketGeneralMessage(buf.readUtf());
}
} }
public static void handle(final PacketGeneralMessage pkt, Supplier<NetworkEvent.Context> ctx) { public static class Consumer implements MessageFunctions.MessageConsumer<PacketGeneralMessage> {
ctx.get().enqueueWork(() -> { public Consumer() {}
DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> TurnBasedMinecraftMod.proxy.handlePacket(pkt, ctx));
}); @Override
ctx.get().setPacketHandled(true); public void handle(PacketGeneralMessage pkt, NetworkEvent.Context ctx) {
ctx.enqueueWork(() -> {
if (FMLEnvironment.dist.isClient()) {
TurnBasedMinecraftMod.proxy.handlePacket(pkt, ctx);
}
});
ctx.setPacketHandled(true);
}
} }
} }

View file

@ -35,11 +35,11 @@ Implements turn-based-battle in Minecraft.
# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional. # A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional.
[[dependencies.com_burnedkirby_turnbasedminecraft]] #optional [[dependencies.com_burnedkirby_turnbasedminecraft]] #optional
# the modid of the dependency # the modid of the dependency
modId="forge" #mandatory modId="neoforge" #mandatory
# Does this dependency have to exist - if not, ordering below must be specified # Does this dependency have to exist - if not, ordering below must be specified
mandatory=true #mandatory mandatory=true #mandatory
# The version range of the dependency # The version range of the dependency
versionRange="${forge_version_range}" #mandatory versionRange="${neo_version_range}" #mandatory
# An ordering relationship for the dependency - BEFORE or AFTER required if the relationship is not mandatory # An ordering relationship for the dependency - BEFORE or AFTER required if the relationship is not mandatory
ordering="NONE" ordering="NONE"
# Side this dependency is applied on - BOTH, CLIENT or SERVER # Side this dependency is applied on - BOTH, CLIENT or SERVER